{"version":3,"sources":["/home/runner/work/kora/kora/packages/store/dist/chunk-CLNXN3TF.cjs","../src/store/store.ts","../src/collection/collection.ts","../src/compaction/compact-operation-log.ts","../src/fold/compact-folded-log.ts","../src/fold/legacy-bodies.ts","../src/fold/rematerialize.ts","../src/fold/remote-batch-prefetch.ts","../src/migrations/run-migrations.ts","../src/overlay/write-order.ts","../src/overlay/pending-writes.ts","../src/overlay/overlay-controller.ts","../src/query/query-builder.ts","../src/subscription/result-equality.ts","../src/query/pluralize.ts","../src/relations/relation-enforcer.ts","../src/relations/relation-lookup.ts","../src/replay/replay-to.ts","../src/seed/seed-store.ts","../src/sequences/sequence-manager.ts","../src/serialization/stored-text-migration.ts","../src/staging/staging-replica.ts","../src/staging/staging-merge.ts","../src/overlay/query-eval.ts","../src/overlay/apply.ts","../src/subscription/bloom-filter.ts","../src/subscription/subscription-manager.ts","../src/sync/offline-pins.ts","../src/sync/rebase-unsynced-operations.ts","../src/sync/rotate-node-id.ts","../src/transaction/transaction-context.ts","../src/store/legacy-indexes.ts","../src/store/node-lock.ts","../src/store/relax-constraints.ts","../src/store/tab-node-id.ts"],"names":["quoteIdent","HybridLogicalClock","createVersionVector","encodeStoredText","createSnapshotState","run","KoraError","validateRecord","rowVersion"],"mappings":"AAAA;AACE;AACA;AACA;AACA;AACF,wDAA6B;AAC7B;AACE;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACF,wDAA6B;AAC7B;AACE;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACF,wDAA6B;AAC7B;AACE;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACF,wDAA6B;AAC7B;AACE;AACF,wDAA6B;AAC7B;AACE;AACF,wDAA6B;AAC7B;AACE;AACF,wDAA6B;AAC7B;AACE;AACA;AACA;AACA;AACA;AACA;AACF,wDAA6B;AAC7B;AACE;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACF,wDAA6B;AAC7B;AACE;AACA;AACF,wDAA6B;AAC7B;AACA;ACtKA;AACC;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AAAA,oCACM;AAgBP;AACC;AACA;AACA;AAAA,iDACM;ADyJP;AACA;AEzLA;AA4BO,IAAM,WAAA,EAAN,MAAiB;AAAA,EACvB,WAAA,CACkB,IAAA,EACA,UAAA,EACA,MAAA,EACA,OAAA,EACT,KAAA,EACA,MAAA,EACS,UAAA,EACT,gBAAA,EACA,eAAA,EACA,aAAA,EACS,iBAAA,EACA,cAAA,EACA,sBAAA,EAIA,cAAA,EACA,IAAA,EACA,iBAAA,EACA,uBAAA,EACA,YAAA,EACA,OAAA,EAChB;AAtBgB,IAAA,IAAA,CAAA,KAAA,EAAA,IAAA;AACA,IAAA,IAAA,CAAA,WAAA,EAAA,UAAA;AACA,IAAA,IAAA,CAAA,OAAA,EAAA,MAAA;AACA,IAAA,IAAA,CAAA,QAAA,EAAA,OAAA;AACT,IAAA,IAAA,CAAA,MAAA,EAAA,KAAA;AACA,IAAA,IAAA,CAAA,OAAA,EAAA,MAAA;AACS,IAAA,IAAA,CAAA,WAAA,EAAA,UAAA;AACT,IAAA,IAAA,CAAA,iBAAA,EAAA,gBAAA;AACA,I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AqCyD;AACxC,EAAA;AAC0C,EAAA;AACJ,IAAA;AACtD,EAAA;AACO,EAAA;AACR;AAcC;AAEa,EAAA;AACC,IAAA;AACuC,MAAA;AAC1C,MAAA;AACV,IAAA;AACU,IAAA;AAC4B,MAAA;AACrC,MAAA;AACA,MAAA;AACD,IAAA;AACD,EAAA;AAG+E,EAAA;AAEhD,EAAA;AACP,EAAA;AAC4B,IAAA;AACzB,IAAA;AACuB,MAAA;AAC7B,QAAA;AACnB,MAAA;AACA,MAAA;AACD,IAAA;AACqC,IAAA;AACkB,IAAA;AACxC,MAAA;AACf,IAAA;AACD,EAAA;AACkC,EAAA;AACgB,EAAA;AACnD;AAsCC;AAEsB,EAAA;AACrB,IAAA;AAC2B,IAAA;AAC5B,EAAA;AACqB,EAAA;AACY,EAAA;AACyB,EAAA;AAGtD,EAAA;AAEe,EAAA;AACF,EAAA;AACb,IAAA;AACA,IAAA;AACH,EAAA;AACM,EAAA;AACR;AAG4B;AAG2B;AACT,EAAA;AAC9C;ADinJ4D;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA","file":"/home/runner/work/kora/kora/packages/store/dist/chunk-CLNXN3TF.cjs","sourcesContent":[null,"import {\n\tCausalTracker,\n\tHybridLogicalClock,\n\tKORA_STORAGE_FORMAT,\n\tKoraError,\n\tassertOperationTransformCoverage,\n\tcreateVersionVector,\n\tderiveSideEffectOpId,\n\tdeserializeFoldState,\n\texpandFieldVersionedOperations,\n\tfinalizeSchema,\n\tfoldPlanFingerprints,\n\tgenerateUUIDv7,\n\tisReservedNodeId,\n\tisServerNodeId,\n\tmismatchedFoldFields,\n\toperationSchemaView,\n\tquoteIdent,\n\treplayOperationsForRecord,\n} from '@korajs/core'\nimport type {\n\tFoldState,\n\tHLCTimestamp,\n\tKoraEventEmitter,\n\tMergeTrace,\n\tOfflineCompletion,\n\tOfflineMarksSnapshot,\n\tOfflineUnitKey,\n\tOperation,\n\tOperationLog,\n\tOperationTransform,\n\tSchemaDefinition,\n\tSecretKeyProvider,\n\tVersionVector,\n} from '@korajs/core'\nimport {\n\tcurrentWriteObserver,\n\tnotifyWriteObserver,\n\trecordMatchesCollectionScope,\n} from '@korajs/core/internal'\nimport { DDL_STATE_TABLE_SQL } from '../adapters/ddl-state'\nimport { readBackupManifest as readManifest } from '../backup/backup'\nimport type { BackupManifest, BackupOptions, RestoreOptions, RestoreResult } from '../backup/types'\nimport { Collection } from '../collection/collection'\nimport { compactOperationLog } from '../compaction/compact-operation-log'\nimport type { CompactionResult, CompactionStrategy } from '../compaction/types'\nimport {\n\tNodeOwnedByAnotherUserError,\n\tOptimisticLockError,\n\tSchemaVersionAheadError,\n\tStorageFormatAheadError,\n\tStoreNotOpenError,\n\tStoreReadOnlyError,\n\tWriteNotDurableError,\n} from '../errors'\nimport { compactFoldedLog } from '../fold/compact-folded-log'\nimport { LEGACY_BODIES_META_KEY, canonicalizeLegacyLogBodies } from '../fold/legacy-bodies'\nimport {\n\tCOMPACTED_THROUGH_TABLE,\n\ttype DeferredPrior,\n\tFOLD_MATERIALIZATION_CURRENT,\n\tFOLD_MATERIALIZATION_LEGACY,\n\tFOLD_MATERIALIZATION_META_KEY,\n\tFOLD_STATE_TABLE,\n\tFOLD_TABLES_DDL,\n\tRecordFolder,\n\tisCompacted,\n} from '../fold/record-folder'\nimport {\n\ttype KeptRecords,\n\ttype RematerializationMode,\n\trematerializeDatabase,\n} from '../fold/rematerialize'\nimport { RemoteBatchPrefetch } from '../fold/remote-batch-prefetch'\nimport {\n\tLOG_QUARANTINE_TABLE,\n\ttype LogIntegrityReport,\n\tscanLogIntegrity,\n} from '../log-integrity/log-integrity'\nimport {\n\ttype FieldVersions,\n\teffectiveFieldVersion,\n\tfieldVersionsForFields,\n\tparseFieldVersions,\n\tresolvePerFieldLww,\n\tserializeFieldVersions,\n} from '../lww/field-versions'\nimport { isIncomingNewerThanRow, serializeRowVersion } from '../lww/row-version'\nimport { runSchemaMigrations } from '../migrations/run-migrations'\nimport {\n\tSTORAGE_FORMAT_META_KEY,\n\tSTORED_FORMAT_SQL,\n\tSTORED_SCHEMA_VERSION_SQL,\n\tparseFormatAhead,\n\tparseSchemaAhead,\n\tstoredSchemaVersion,\n} from '../migrations/schema-ceiling'\nimport type { VersionGate } from '../multi-tab/version-gate'\nimport { WriteGate, type WriteScope } from '../multi-tab/write-gate'\nimport type { LocalMutationContext } from '../mutations/types'\nimport { isStorageFullError } from '../mutations/write-context'\nimport { OverlayController } from '../overlay/overlay-controller'\nimport type { ForeignApply } from '../overlay/pending-writes'\nimport { groupOrderKeys, readGroupBasesIfNeeded, trackGroup } from '../overlay/write-overlay'\nimport { QueryBuilder } from '../query/query-builder'\nimport {\n\tbuildFieldFastForwardUpdateQuery,\n\tbuildInsertQuery,\n\tbuildLwwSoftDeleteQuery,\n} from '../query/sql-builder'\nimport { RelationEnforcer } from '../relations/relation-enforcer'\nimport { buildReplaySnapshot } from '../replay/replay-to'\nimport type { ReplaySnapshot } from '../replay/replay-to'\nimport {\n\ttype PurgeOutcome,\n\tSEED_TABLE_DDL,\n\ttype SeedInput,\n\ttype SeedMeta,\n\ttype SeedOutcome,\n\ttype SeedRow,\n\tlistSeedsInTx,\n\tpurgeSeedsInTx,\n\tseedRecordsInTx,\n} from '../seed/seed-store'\nimport { SequenceManager } from '../sequences/sequence-manager'\nimport {\n\tdeserializeOperationWithCollection,\n\tdeserializeRecord,\n\tserializeOperation,\n\tserializeRecord,\n} from '../serialization/serializer'\nimport { ensureStoredTextCodec } from '../serialization/stored-text-migration'\nimport type { StagingMergeHost } from '../staging/staging-merge'\nimport { ReplicaEventBuffer, StagingReplica } from '../staging/staging-replica'\nimport {\n\ttype RecordsChangeListener,\n\tSubscriptionManager,\n} from '../subscription/subscription-manager'\nimport {\n\ttype AdoptionSchedule,\n\ttype LocalNodeRecord,\n\ttype TerminalRejection,\n\tassignLocalNodePrincipal,\n\tconfirmLocalNodePrincipal,\n\tdropLocalNode,\n\tensureLocalSyncRecordTables,\n\tfindAuthoredHere,\n\tfindTerminalRejections,\n\tforgetLocalNode,\n\tlistLocalNodes,\n\tloadAcceptedCycle,\n\tloadAdoptionSchedule,\n\tmarkLocalNodeAccepted,\n\tmarkLocalNodeRefused,\n\tnoteReceivedUnderLocalNode,\n\trecordLocalNodeRefusedFor,\n\trecordTerminalRejections,\n\tregisterLocalNode,\n\tretireLocalNode,\n\treviveLocalNode,\n\tsaveAdoptionSchedule,\n\tseedTerminalRejectionsOnce,\n\tsetLocalNodePrincipal,\n} from '../sync/local-sync-records'\nimport {\n\tclearOfflineMarks,\n\tdeleteOfflineViewMarks,\n\tloadOfflineMarks,\n\topenOfflineUnit,\n} from '../sync/offline-marks'\nimport {\n\ttype NewOfflinePin,\n\ttype OfflinePinWriteResult,\n\ttype StoredOfflinePin,\n\ttype StoredOfflinePinHold,\n\taddOfflinePinHold,\n\tensureOfflinePin,\n\tensureOfflinePinTables,\n\tkeepOfflinePin,\n\tloadOfflinePinHolds,\n\tloadOfflinePins,\n\tmarkOfflinePinCompleted,\n\tpruneOfflinePinHolds,\n\treleaseOfflinePin,\n\tremoveOfflinePinHold,\n} from '../sync/offline-pins'\nimport type { ClockRebaseResult } from '../sync/rebase-unsynced-operations'\nimport { rebaseUnsyncedOperationsInLog } from '../sync/rebase-unsynced-operations'\nimport { renumberOperationRow, rewriteDependentsInTx } from '../sync/rehash-operation'\nimport type { ResequenceResult } from '../sync/rehash-operation'\nimport { dropRewrittenQueueEntries } from '../sync/rotate-node-id'\nimport type { NodeRotationResult } from '../sync/rotate-node-id'\nimport { rotateUnsyncedOperationsInLog } from '../sync/rotate-node-id'\nimport type { UnappliedOperation } from '../sync/sync-durability'\nimport { rebaseUnappliedOperations } from '../sync/sync-durability'\nimport {\n\tensureUnappliedTable,\n\tloadAcceptedDownlinkScope,\n\tloadOwnAckedThrough,\n\tloadUnappliedOperations,\n\tremoveUnappliedOperations,\n\tsaveAcceptedDownlinkScope,\n\tsaveOwnAckedThrough,\n\tsaveUnappliedOperations,\n\tsaveUnappliedOperationsInTx,\n} from '../sync/sync-durability'\nimport {\n\tDELIVERY_WATERMARK_META_KEY,\n\tDELTA_CURSOR_META_KEY,\n\tNODE_TOKEN_META_KEY,\n\tcollectOperationsAheadOfServer,\n\tdeleteDeliveryWatermark,\n\tloadAllDeliveryWatermarks,\n\tloadAuthoritativeNodeIds,\n\tloadDeliveryWatermark,\n\tloadDeltaCursor,\n\tloadLastAckedServerVector,\n\tloadNodeToken,\n\tloadRevokedAuthoritativeNodeIds,\n\tmergeVersionVectors,\n\tnodeTokenKey,\n\tsaveAuthoritativeNodeIds,\n\tsaveDeliveryWatermark,\n\tsaveDeliveryWatermarkInTx,\n\tsaveDeltaCursor,\n\tsaveLastAckedServerVector,\n\tsaveNodeToken,\n\tsaveRevokedAuthoritativeNodeIds,\n} from '../sync/sync-state'\nimport {\n\ttype TransactionCommitOptions,\n\tTransactionContext,\n\ttype TransactionRegistrar,\n} from '../transaction/transaction-context'\nimport { WriteBehindTransaction } from '../transaction/write-behind'\nimport type { WriteDurabilityState, WriteOptions } from '../types'\nimport type {\n\tApplyRemoteOptions,\n\tApplyResult,\n\tLocalMutationHandler,\n\tMaterializedRowSnapshot,\n\tMetaRow,\n\tOperationRow,\n\tProvisionalSideEffect,\n\tRawCollectionRow,\n\tRemoteApplyBatch,\n\tRemoteBatchCollectionReader,\n\tRowVersionState,\n\tStorageAdapter,\n\tStoreConfig,\n\tStoreIsolation,\n\tTransaction,\n\tVersionVectorRow,\n} from '../types'\nimport { dropLegacyIndexes } from './legacy-indexes'\nimport {\n\tacquireNodeLock,\n\tacquireNodeLockGranted,\n\tisNodeLockHeld,\n\tnodeLockName,\n\ttryAcquireNodeLock,\n} from './node-lock'\nimport { relaxValueDomainConstraints } from './relax-constraints'\nimport { allocateNextSequenceInTransaction } from './sequence-allocator'\nimport {\n\tSEQ_CONFLICTS_TABLE,\n\tinsertConflictRow,\n\tisOperationLogged,\n\tloadRetainedConflictRows,\n\trepairSequenceUniqueness,\n} from './sequence-repair'\nimport { savePerTabNodeId } from './tab-node-id'\nimport { resolvePerTabNodeId } from './tab-node-id'\n\n/**\n * Store is the main orchestrator. It owns a schema, a storage adapter,\n * a clock, and a subscription manager. It creates Collection instances\n * for each schema collection, and provides the sync contract via\n * applyRemoteOperation and getOperationRange.\n *\n * @example\n * ```typescript\n * const store = new Store({ schema, adapter })\n * await store.open()\n * const todo = await store.collection('todos').insert({ title: 'Hello' })\n * await store.close()\n * ```\n */\n/** `_kora_meta` key: per-collection fold plan fingerprints the rows were folded with (RT-63). */\nconst FOLD_PLAN_META_KEY = 'fold_plan_fingerprints'\n/** Parse a stored eviction report; anything unreadable is no report. */\nfunction parseStoredEviction(\n\traw: string | null,\n): import('../adapters/storage-evidence').StorageEviction | null {\n\tif (raw === null) return null\n\ttry {\n\t\tconst parsed = JSON.parse(raw) as Partial<\n\t\t\timport('../adapters/storage-evidence').StorageEviction\n\t\t> | null\n\t\tif (\n\t\t\tparsed === null ||\n\t\t\ttypeof parsed !== 'object' ||\n\t\t\ttypeof parsed.dbName !== 'string' ||\n\t\t\ttypeof parsed.detectedAt !== 'number' ||\n\t\t\t!Array.isArray(parsed.evidence) ||\n\t\t\ttypeof parsed.lostWrites?.count !== 'number'\n\t\t) {\n\t\t\treturn null\n\t\t}\n\t\treturn {\n\t\t\tdbName: parsed.dbName,\n\t\t\tdetectedAt: parsed.detectedAt,\n\t\t\tlastOpenedAt: typeof parsed.lastOpenedAt === 'number' ? parsed.lastOpenedAt : null,\n\t\t\tevidence: parsed.evidence.filter(\n\t\t\t\t(item): item is 'manifest' | 'localStorage' =>\n\t\t\t\t\titem === 'manifest' || item === 'localStorage',\n\t\t\t),\n\t\t\tlostWrites: { count: parsed.lostWrites.count, certain: parsed.lostWrites.certain === true },\n\t\t}\n\t} catch {\n\t\treturn null\n\t}\n}\n\n/** `_kora_meta` key: this database's epoch, written once its first durable open completed. */\nconst DB_EPOCH_META_KEY = 'db_epoch'\n/** `_kora_meta` key: a detected storage loss the app has not acknowledged yet (JSON). */\nconst STORAGE_EVICTED_META_KEY = 'storage_evicted'\n/** `_kora_meta` key: a full resync was requested to settle row snapshots (RT-68). */\nconst SNAPSHOT_RESYNC_META_KEY = 'fold_snapshot_resync'\n/**\n * Node id of provisional side effects (RT-69). In the reserved `kora:` namespace: no\n * device authors under it, and its effects never enter the log or the upload queue.\n */\nconst PROVISIONAL_NODE_ID = 'kora:provisional'\n\n/** How long opening a store on a pinned node waits for a repair of that node to finish. */\nconst PINNED_NODE_LOCK_WAIT_MS = 60_000\n\n/** A node id this client must never author under (RT-61): Kora's reserved namespace. */\nexport class ReservedNodeIdError extends KoraError {\n\tconstructor(nodeId: string, source: string) {\n\t\tsuper(\n\t\t\t`Node id \"${nodeId}\" (${source}) is in Kora's reserved \"kora:\" namespace; devices never author under it.`,\n\t\t\t'RESERVED_NODE_ID',\n\t\t\t{ nodeId, source, fix: 'Configure a node id that does not start with \"kora:\".' },\n\t\t)\n\t\tthis.name = 'ReservedNodeIdError'\n\t}\n}\n\n/**\n * Per collection, the record ids that own quarantined log rows (RT-68); a\n * quarantined row whose record id cannot be read keeps its whole collection.\n */\nasync function loadQuarantinedRecords(adapter: StorageAdapter): Promise<KeptRecords> {\n\tconst records = new Map<string, Set<string>>()\n\tconst collections = new Set<string>()\n\tconst exists = await adapter.query<{ name: string }>(\n\t\t\"SELECT name FROM sqlite_master WHERE type = 'table' AND name = ?\",\n\t\t[LOG_QUARANTINE_TABLE],\n\t)\n\tif (exists.length === 0) return { records, collections }\n\tconst rows = await adapter.query<{ collection: string; row_json: string }>(\n\t\t`SELECT collection, row_json FROM ${LOG_QUARANTINE_TABLE}`,\n\t)\n\tfor (const row of rows) {\n\t\tlet recordId: unknown = null\n\t\ttry {\n\t\t\trecordId = (JSON.parse(row.row_json) as { record_id?: unknown }).record_id\n\t\t} catch {\n\t\t\trecordId = null\n\t\t}\n\t\tif (typeof recordId === 'string' && recordId.length > 0) {\n\t\t\tconst set = records.get(row.collection) ?? new Set<string>()\n\t\t\tset.add(recordId)\n\t\t\trecords.set(row.collection, set)\n\t\t} else {\n\t\t\tcollections.add(row.collection)\n\t\t}\n\t}\n\treturn { records, collections }\n}\n\n/** Collections whose stored fold states hold a field of another fold kind than the schema's. */\nasync function collectionsWithMismatchedStates(\n\tadapter: StorageAdapter,\n\tschema: SchemaDefinition,\n): Promise<string[]> {\n\tconst out: string[] = []\n\tfor (const collection of Object.keys(schema.collections)) {\n\t\tconst rows = await adapter.query<{ state: string }>(\n\t\t\t`SELECT state FROM ${FOLD_STATE_TABLE} WHERE collection = ?`,\n\t\t\t[collection],\n\t\t)\n\t\tfor (const row of rows) {\n\t\t\tlet state: FoldState\n\t\t\ttry {\n\t\t\t\tstate = deserializeFoldState(row.state)\n\t\t\t} catch {\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\tif (mismatchedFoldFields(state, schema).length > 0) {\n\t\t\t\tout.push(collection)\n\t\t\t\tbreak\n\t\t\t}\n\t\t}\n\t}\n\treturn out\n}\n\n/**\n * Make `nodeId` the database's node id (`_kora_meta.node_id`). The unkeyed legacy node\n * token belongs to the node id it replaces, so it moves to that node's own key first:\n * it must never be presented as the new node's token.\n */\n/** Parent ids looked up per query by a delivery batch (under SQLite's variable limit). */\nconst PARENT_LOOKUP_CHUNK = 400\n\nasync function moveDatabaseNodeId(tx: Transaction, nodeId: string): Promise<void> {\n\tconst meta = await tx.query<MetaRow>(\"SELECT value FROM _kora_meta WHERE key = 'node_id'\")\n\tconst previous = meta[0]?.value\n\tif (previous === nodeId) return\n\tconst legacy = await tx.query<MetaRow>('SELECT value FROM _kora_meta WHERE key = ?', [\n\t\tNODE_TOKEN_META_KEY,\n\t])\n\tif (legacy[0] && previous) {\n\t\tawait tx.execute('INSERT OR IGNORE INTO _kora_meta (key, value) VALUES (?, ?)', [\n\t\t\tnodeTokenKey(previous),\n\t\t\tlegacy[0].value,\n\t\t])\n\t}\n\tawait tx.execute('DELETE FROM _kora_meta WHERE key = ?', [NODE_TOKEN_META_KEY])\n\tawait tx.execute(\"INSERT OR REPLACE INTO _kora_meta (key, value) VALUES ('node_id', ?)\", [nodeId])\n}\n\n/** Result of {@link Store.bindPrincipal} (RT-42). */\nexport interface PrincipalBinding {\n\t/** The node id local writes use from now on. */\n\tnodeId: string\n\t/** The node id in use before the call. */\n\tpreviousNodeId: string\n\t/** The store moved to another node id. */\n\tswitched: boolean\n\t/** The node id is pinned and belongs to another user: nothing may upload it now. */\n\tconflict: boolean\n}\n\n/** `_kora_meta` key prefix of the records an access narrowing kept (per collection). */\nconst ACCESS_NARROWING_META_PREFIX = 'access_narrowing_kept:'\n\n/** What an access narrowing remembers of a collection: its scope, the records it kept and those a server retracted. */\ninterface KeptOutsideNarrowing {\n\tscope: Record<string, unknown> | null\n\tkept: string[]\n\tretracted?: string[]\n\t/**\n\t * The delivery view (signature) the narrowing was for. A list is judged only under that view:\n\t * under another, its records may be inside the scope. Absent: stored before views were tagged.\n\t */\n\tview?: string\n}\n\n/** Thrown inside a transaction to roll it back when the delivery it is for no longer stands. */\nclass StaleStoreWrite extends KoraError {\n\tconstructor() {\n\t\tsuper('The delivery position moved before the write committed', 'STALE_STORE_WRITE')\n\t\tthis.name = 'StaleStoreWrite'\n\t}\n}\n\n/** `_kora_meta` key of the access read rules' key the device was last re-scoped under. */\nconst ACCESS_RULES_KEY_META_KEY = 'access_rules_key'\n\n/** What the transactional part of a W7 remote apply did (published after commit). */\ninterface FoldedApplyOutcome {\n\tduplicate: boolean\n\trevived: boolean\n\ttraces: MergeTrace[]\n}\n\n/** Whether an IndexedDB durability failure permanently retired this store's lineage. */\nfunction isSnapshotSuperseded(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\tconst candidate = current as { context?: unknown; cause?: unknown }\n\t\tif (\n\t\t\ttypeof candidate.context === 'object' &&\n\t\t\tcandidate.context !== null &&\n\t\t\t'code' in candidate.context &&\n\t\t\t(candidate.context as { code?: unknown }).code === 'SNAPSHOT_SUPERSEDED'\n\t\t) {\n\t\t\treturn true\n\t\t}\n\t\tcurrent = candidate.cause\n\t}\n\treturn false\n}\n\n/** `_kora_meta` key prefix of a view's delivery anchor; the view signature follows it. */\nconst DELIVERY_ANCHOR_META_PREFIX = 'delivery_anchor:'\n\n/** Meta key: every collection table was relaxed (RT-101); later opens skip the check. */\nconst VALUE_DOMAIN_RELAXED_META_KEY = 'value_domain_relaxed'\n\nexport class Store implements OperationLog {\n\tprivate writeDurabilityFailing = false\n\tprivate writeDurabilitySince = 0\n\tprivate writeDurabilityMessage = ''\n\t/** A superseded IndexedDB lineage can never become durable in this store instance. */\n\tprivate writeDurabilityPermanentlyFailed = false\n\tprivate opened = false\n\tprivate nodeId = ''\n\t/** Records an access narrowing kept for their unsent writes (loaded lazily). */\n\tprivate keptOutsideNarrowing: Map<\n\t\tstring,\n\t\t{ scope: Record<string, unknown> | null; kept: string[]; retracted?: string[] }\n\t> | null = null\n\tprivate sequenceNumber = 0\n\tprivate versionVector: VersionVector = createVersionVector()\n\tprivate clock: HybridLogicalClock | null = null\n\tprivate collections = new Map<string, Collection>()\n\tprivate subscriptionManager: SubscriptionManager\n\tprivate sequenceManager: SequenceManager | null = null\n\n\tprivate readonly schema: SchemaDefinition\n\tprivate readonly adapter: StorageAdapter\n\t/**\n\t * Admits this store's writes until the tab is superseded by a newer build of the app\n\t * (version gate, section 5): then every write entry point refuses with\n\t * `BuildSupersededError` and retirement waits for every write it admitted.\n\t */\n\tprivate readonly writeGate = new WriteGate()\n\tprivate readonly configNodeId: string | undefined\n\t/** The one user this database belongs to (`StoreConfig.databaseOwner`), or null. */\n\tprivate readonly databaseOwner: string | null\n\t/** The owner of the pinned node while it belongs to another user than the signed-in one (F9). */\n\tprivate pinnedNodeOwnedBy: string | null = null\n\t/** The sync server refused the pinned node as another user's (F9). */\n\tprivate pinnedNodeRefusedByServer = false\n\t/** Set while the app must not write locally ({@link setReadOnly}). */\n\tprivate readOnlyReason: string | null = null\n\t/** The user of the last {@link bindPrincipal}. */\n\tprivate signedInPrincipal: string | null = null\n\t/**\n\t * Delivery positions of operations the sync engine is about to apply, by operation id\n\t * (see {@link noteDeliveryPosition}); `replay` marks a quarantine replay.\n\t */\n\tprivate readonly deliveryPositions = new Map<\n\t\tstring,\n\t\t{ position?: number; replay: boolean; isCurrent?: () => boolean }\n\t>()\n\t/** Who `stamp('userId')` fields are filled with: the signed-in user, null when signed out. */\n\tprivate stampingUser: string | null = null\n\tprivate readonly dbName: string\n\tprivate readonly isolation: StoreIsolation\n\tprivate readonly emitter: KoraEventEmitter | null\n\tprivate localMutationHandler: LocalMutationHandler | null\n\t/**\n\t * The instant-updates overlay of this store (S4), or null (the default). It is created\n\t * here, per store, from `StoreConfig.instantUpdates`; nothing outside the store holds a\n\t * process-wide one.\n\t */\n\tprivate readonly overlayController: OverlayController | null\n\tprivate relationEnforcer: RelationEnforcer | null = null\n\tprivate causalTracker: CausalTracker | null = null\n\tprivate readonly secretKeyProvider: SecretKeyProvider | undefined\n\t/** Releases the per-tab node lock (RT-40); null when none is held. */\n\tprivate releaseNodeLock: (() => Promise<void>) | null = null\n\t/** How rows are materialized ({@link StoreConfig.materialization}). */\n\tprivate readonly materialization: 'fold' | 'legacy'\n\t/** The W7 record fold; null under legacy materialization. */\n\tprivate readonly folder: RecordFolder | null\n\t/** True once every row of the database is a materialization of its fold state. */\n\tprivate foldActive = false\n\tprivate foreignKeyIndex: Map<string, Array<{ field: string; to: string }>> | null = null\n\t/**\n\t * How many seeds the database holds (0 almost always). The remote-apply path asks only when\n\t * it is not zero, so a database without seeds pays nothing per operation.\n\t */\n\tprivate seedCount = 0\n\t/** Schema transforms applied at fold time (RT-84); never to stored operations. */\n\tprivate readonly operationTransforms: readonly OperationTransform[]\n\t/** Largest operation a local write may produce (RT-86); default in the write path. */\n\tprivate readonly maxOperationBytes: number | undefined\n\t/** The version gate this store's writes follow (configured, or the adapter's). */\n\tprivate readonly versionGate: VersionGate | null\n\n\tconstructor(config: StoreConfig) {\n\t\t// A schema from the first-paint `defineSchema` is completed and validated here.\n\t\tfinalizeSchema(config.schema)\n\t\tthis.materialization = config.materialization ?? 'fold'\n\t\tthis.operationTransforms = config.operationTransforms ?? []\n\t\tthis.maxOperationBytes = config.maxOperationBytes\n\t\tthis.folder =\n\t\t\tthis.materialization === 'fold'\n\t\t\t\t? new RecordFolder(config.schema, this.operationTransforms)\n\t\t\t\t: null\n\t\tthis.schema = config.schema\n\t\tthis.adapter = config.adapter\n\t\tconst versionGate = config.versionGate ?? config.adapter.getVersionGate?.() ?? null\n\t\t// The same instance the write gate follows decides close-time draining (an injected\n\t\t// gate on an adapter that does not expose one, e.g. better-sqlite3 or Tauri).\n\t\tthis.versionGate = versionGate\n\t\tif (versionGate) {\n\t\t\tversionGate.onSuperseded(({ current, newer }) =>\n\t\t\t\tthis.writeGate.close({ currentBuild: current.build, newerBuild: newer.build }),\n\t\t\t)\n\t\t\tversionGate.addRetireStep('drain', () => this.writeGate.drain())\n\t\t}\n\t\tthis.configNodeId = config.nodeId\n\t\tthis.databaseOwner =\n\t\t\ttypeof config.databaseOwner === 'string' && config.databaseOwner.length > 0\n\t\t\t\t? config.databaseOwner\n\t\t\t\t: null\n\t\tthis.dbName = config.dbName ?? 'kora-db'\n\t\tthis.isolation = config.isolation ?? 'shared'\n\t\tthis.emitter = config.emitter ?? null\n\t\tthis.localMutationHandler = config.localMutationHandler ?? null\n\t\tthis.secretKeyProvider = config.secretKeyProvider\n\t\tconst instantUpdates = config.instantUpdates\n\t\tthis.overlayController =\n\t\t\tinstantUpdates === undefined || instantUpdates === false\n\t\t\t\t? null\n\t\t\t\t: new OverlayController({\n\t\t\t\t\t\toptions: instantUpdates === true ? {} : instantUpdates,\n\t\t\t\t\t\tadapter: config.adapter,\n\t\t\t\t\t\temit: (event) => this.emitter?.emit(event),\n\t\t\t\t\t\twritesRefused: () => config.adapter.refusesWrites?.() ?? false,\n\t\t\t\t\t\t// A decided unknown outcome has no commit to announce it: re-run the queries.\n\t\t\t\t\t\trefresh: (collection) => this.subscriptionManager.invalidateFromPeer(collection),\n\t\t\t\t\t\t...(config.instantUpdatesInternals\n\t\t\t\t\t\t\t? { internals: config.instantUpdatesInternals }\n\t\t\t\t\t\t\t: {}),\n\t\t\t\t\t})\n\t\tthis.subscriptionManager = new SubscriptionManager({\n\t\t\tonQuerySubscribed: config.onQuerySubscribed,\n\t\t\t// Instant-UI overlay: null (every overlay path inert) unless the store has one.\n\t\t\tpendingWrites: () => this.overlayController?.registry ?? null,\n\t\t\t// A successful SQL read proves the adapter answers: decide writes whose commit\n\t\t\t// answer was lost (M2).\n\t\t\t...(this.overlayController\n\t\t\t\t? {\n\t\t\t\t\t\tonRead: (collection: string) => {\n\t\t\t\t\t\t\tif (this.overlayController?.registry.unknownEntries(collection).length) {\n\t\t\t\t\t\t\t\tvoid this.overlayController.resolveUnknown(collection)\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t},\n\t\t\t\t\t\tonPatched: (info: {\n\t\t\t\t\t\t\tqueryId: string\n\t\t\t\t\t\t\tcollection: string\n\t\t\t\t\t\t\tresultCount: number\n\t\t\t\t\t\t\tdurationMs: number\n\t\t\t\t\t\t}) => this.emitter?.emit({ type: 'query:patched', ...info }),\n\t\t\t\t\t}\n\t\t\t\t: {}),\n\t\t\tgetDefinition: (collection) => this.schema.collections[collection],\n\t\t\t// STORE-12: every subscription failure is observable (DevTools, app listeners).\n\t\t\tonQueryError: (failure) => {\n\t\t\t\tconst code =\n\t\t\t\t\tfailure.error instanceof KoraError ? failure.error.code : failure.error.name || 'Error'\n\t\t\t\tthis.emitter?.emit({\n\t\t\t\t\ttype: 'query:error',\n\t\t\t\t\tqueryId: failure.queryId,\n\t\t\t\t\tcollection: failure.collection,\n\t\t\t\t\tphase: failure.phase,\n\t\t\t\t\tcode,\n\t\t\t\t\tmessage: failure.error.message,\n\t\t\t\t})\n\t\t\t},\n\t\t})\n\t}\n\n\t/**\n\t * Open the store: initialize the database, load or generate a node ID,\n\t * restore the sequence number and version vector, and create Collection instances.\n\t */\n\tasync open(): Promise<void> {\n\t\tthis.keptOutsideNarrowing = null\n\t\ttry {\n\t\t\tawait this.adapter.open(this.schema)\n\t\t} catch (error) {\n\t\t\tconst formatAhead =\n\t\t\t\terror instanceof StorageFormatAheadError\n\t\t\t\t\t? { stored: error.storedFormat, code: error.codeFormat }\n\t\t\t\t\t: parseFormatAhead(error)\n\t\t\tif (formatAhead !== null) throw this.formatAhead(formatAhead.stored)\n\t\t\tconst ahead =\n\t\t\t\terror instanceof SchemaVersionAheadError\n\t\t\t\t\t? { stored: error.storedVersion, code: error.codeVersion }\n\t\t\t\t\t: parseSchemaAhead(error)\n\t\t\tif (ahead !== null) throw this.schemaAhead(ahead.stored)\n\t\t\tthrow error\n\t\t}\n\t\ttry {\n\t\t\tawait this.openOverAdapter()\n\t\t} catch (error) {\n\t\t\t// The adapter is open (and in a browser holds the leader and version gate locks):\n\t\t\t// a store that failed to open releases it, so no tab waits on a tab that never\n\t\t\t// became usable.\n\t\t\tawait this.adapter.close().catch(() => undefined)\n\t\t\tthrow error\n\t\t}\n\t\tthis.opened = true\n\t\ttry {\n\t\t\t// A replace restore that stopped between its transaction and re-applying this\n\t\t\t// device's unsynced writes journaled them: apply them now.\n\t\t\tconst journal = await this.adapter.query<{ name: string }>(\n\t\t\t\t\"SELECT name FROM sqlite_master WHERE type = 'table' AND name = '_kora_restore_pending'\",\n\t\t\t)\n\t\t\tif (journal.length > 0) {\n\t\t\t\tconst { replayInterruptedRestore } = await import('../backup/restore')\n\t\t\t\tawait replayInterruptedRestore(this.adapter, (operation) =>\n\t\t\t\t\tthis.applyRemoteOperation(operation),\n\t\t\t\t)\n\t\t\t}\n\t\t} catch (error) {\n\t\t\tthis.opened = false\n\t\t\tawait this.adapter.close().catch(() => undefined)\n\t\t\tthrow error\n\t\t}\n\t}\n\n\t/** The part of {@link open} that runs once the adapter is open. */\n\tprivate async openOverAdapter(): Promise<void> {\n\t\t// A database with neither a node id nor an epoch was created by THIS open: checked\n\t\t// before anything below writes either (storage-loss detection, offline-readiness\n\t\t// design 6.1). Only adapters that keep evidence outside the database are asked.\n\t\tconst evidence = this.adapter.getStorageEvidence?.() ?? null\n\t\tconst createdByThisOpen = evidence !== null && (await this.isDatabaseNew())\n\t\t// A database a build with a newer storage format opened is refused the same way,\n\t\t// before anything here writes to it (version gate, section 3).\n\t\tconst storedFormat = storedSchemaVersion(\n\t\t\tawait this.adapter.query<{ value: unknown }>(STORED_FORMAT_SQL),\n\t\t)\n\t\tif (storedFormat > KORA_STORAGE_FORMAT) {\n\t\t\tawait this.adapter.close().catch(() => undefined)\n\t\t\tthrow this.formatAhead(storedFormat)\n\t\t}\n\t\t// A database a newer build already migrated is refused before anything here writes\n\t\t// to it (RT-109). The DDL executors refuse it before their DDL; this also covers\n\t\t// adapters that restore their data after it (the IndexedDB fallback).\n\t\tconst stored = storedSchemaVersion(\n\t\t\tawait this.adapter.query<{ value: unknown }>(STORED_SCHEMA_VERSION_SQL),\n\t\t)\n\t\tif (stored > this.schema.version) {\n\t\t\tawait this.adapter.close().catch(() => undefined)\n\t\t\tthrow this.schemaAhead(stored)\n\t\t}\n\t\tif (stored > 0 && stored < this.schema.version) {\n\t\t\t// A migration will run (it can rebuild tables, dropping their indexes): clear the DDL\n\t\t\t// fingerprint first, so the next open re-applies the full DDL even if this one stops\n\t\t\t// part way (see applyDdlUnlessUnchanged in the SQLite WASM worker).\n\t\t\tawait this.adapter.execute(DDL_STATE_TABLE_SQL)\n\t\t\tawait this.adapter.execute('DELETE FROM _kora_ddl_state')\n\t\t\t// A migration can bring back a table an older release wrote (a collection re-added):\n\t\t\t// check every table again.\n\t\t\tawait this.adapter.execute('DELETE FROM _kora_meta WHERE key = ?', [\n\t\t\t\tVALUE_DOMAIN_RELAXED_META_KEY,\n\t\t\t])\n\t\t}\n\t\tif (storedFormat < KORA_STORAGE_FORMAT) {\n\t\t\t// Written once per format change, by the first build that uses it; never lowered.\n\t\t\tawait this.adapter.execute('INSERT OR REPLACE INTO _kora_meta (key, value) VALUES (?, ?)', [\n\t\t\t\tSTORAGE_FORMAT_META_KEY,\n\t\t\t\tString(KORA_STORAGE_FORMAT),\n\t\t\t])\n\t\t}\n\t\tawait this.adapter.execute(\n\t\t\t'CREATE TABLE IF NOT EXISTS _kora_scope_retractions (collection TEXT NOT NULL, record_id TEXT NOT NULL, position REAL, PRIMARY KEY (collection, record_id))',\n\t\t)\n\t\t// The delivery position the record was hidden at (null: unknown, a marker from an\n\t\t// older client or a retraction without one). It decides which operations show the\n\t\t// record again (see scopeVisibilityAfter).\n\t\tconst retractionColumns = await this.adapter.query<{ name: string }>(\n\t\t\t'PRAGMA table_info(_kora_scope_retractions)',\n\t\t)\n\t\tif (!retractionColumns.some((column) => column.name === 'position')) {\n\t\t\tawait this.adapter.execute('ALTER TABLE _kora_scope_retractions ADD COLUMN position REAL')\n\t\t}\n\t\tfor (const ddl of FOLD_TABLES_DDL) await this.adapter.execute(ddl)\n\t\tawait this.adapter.execute(SEED_TABLE_DDL)\n\t\tawait this.refreshSeedCount()\n\t\t// Local-only tables of `app.offline.keep()` (pins and component holds).\n\t\tawait ensureOfflinePinTables(this.adapter)\n\t\t// Which journaled writes (writes made before the store opened) already reached this\n\t\t// store. Local only, never synced; written in the same transaction as the write.\n\t\tawait this.adapter.execute(\n\t\t\t'CREATE TABLE IF NOT EXISTS _kora_journal_applied (op_key TEXT PRIMARY KEY, applied_at INTEGER NOT NULL)',\n\t\t)\n\t\tthis.foldActive = false\n\n\t\t// Tables created before beta.13 restate enum membership and requiredness as CHECK /\n\t\t// NOT NULL constraints that cannot evolve with the schema: rebuild them once without\n\t\t// (RT-101). Validation is the single authority for the value domain.\n\t\t// Once every table is relaxed it stays relaxed (this release creates no such\n\t\t// constraints), so later opens skip reading every table's catalog. A database an earlier\n\t\t// release wrote has no mark and is checked.\n\t\tif ((await this.readMeta(VALUE_DOMAIN_RELAXED_META_KEY)) !== '1') {\n\t\t\tawait relaxValueDomainConstraints(this.adapter, this.schema)\n\t\t\tawait this.adapter.execute('INSERT OR REPLACE INTO _kora_meta (key, value) VALUES (?, ?)', [\n\t\t\t\tVALUE_DOMAIN_RELAXED_META_KEY,\n\t\t\t\t'1',\n\t\t\t])\n\t\t}\n\t\t// Indexes named under the old, colliding scheme are replaced (STORE-15).\n\t\tawait dropLegacyIndexes(this.adapter, this.schema)\n\n\t\t// Load or generate node ID\n\t\tconst persistedNodeId = await this.readPersistedNodeId()\n\t\tthis.nodeId = await this.loadOrGenerateNodeId()\n\t\t// Every node id this database authors under is registered (RT-38, RT-40).\n\t\tawait registerLocalNode(this.adapter, this.nodeId)\n\t\t// A queue entry an earlier release left under an id a rotation already re-authored\n\t\t// (a crash between its two steps) is dropped: the queue holds the new copy.\n\t\tawait dropRewrittenQueueEntries(this.adapter)\n\t\tawait this.registerUnregisteredAuthors(persistedNodeId)\n\t\tconst ownNodeIds = await this.retireMovedPinnedNode(persistedNodeId)\n\n\t\t// Log integrity first (W8 step 0): repair rows an earlier release damaged and\n\t\t// quarantine the unrecoverable ones, before anything reads or folds the log.\n\t\tawait this.scanLog('quick')\n\n\t\t// (node_id, sequence_number) is unique in the operation log: repair any\n\t\t// duplicates an earlier version wrote, then enforce it with an index (W6).\n\t\tawait repairSequenceUniqueness(this.adapter, this.schema, ownNodeIds)\n\t\t// The terminal rejections an earlier release kept only in the app's list become\n\t\t// durable markers (RT-36).\n\t\tawait seedTerminalRejectionsOnce(this.adapter)\n\t\t// Raw-string columns use the lossless stored-text codec (RT-65); rows written\n\t\t// before it get their U+FFFF re-encoded once, before anything reads them.\n\t\tawait ensureStoredTextCodec(this.adapter, this.schema)\n\t\tif (this.isolation === 'per-tab' && !this.configNodeId) {\n\t\t\t// A live tab holds its node's lock, so a later tab adopts the node's unsynced\n\t\t\t// writes only after this tab is gone (RT-40).\n\t\t\tthis.releaseNodeLock = acquireNodeLock(nodeLockName(this.dbName, this.nodeId))\n\t\t} else if (this.configNodeId !== undefined) {\n\t\t\t// A pinned node (an auth device id) is shared by this database's tabs: each holds\n\t\t\t// it shared, so a repair of the node after the database moved off it (a shared\n\t\t\t// browser's next account) never runs while a tab still writes under it.\n\t\t\t// The grant is awaited: a request queued behind a repair's exclusive lock is not a hold,\n\t\t\t// and a tab that wrote meanwhile would upload the operations the repair is re-authoring.\n\t\t\tconst granted = await acquireNodeLockGranted(\n\t\t\t\tnodeLockName(this.dbName, this.nodeId),\n\t\t\t\t'shared',\n\t\t\t\tPINNED_NODE_LOCK_WAIT_MS,\n\t\t\t)\n\t\t\tif (!granted) {\n\t\t\t\tthrow new KoraError(\n\t\t\t\t\t`Another tab is repairing the local node \"${this.nodeId}\" and did not finish within ${PINNED_NODE_LOCK_WAIT_MS / 1000} seconds. Nothing was written. Close the other tab or reload this one to try again.`,\n\t\t\t\t\t'NODE_REPAIR_IN_PROGRESS',\n\t\t\t\t\t{ nodeId: this.nodeId, waitedMs: PINNED_NODE_LOCK_WAIT_MS },\n\t\t\t\t)\n\t\t\t}\n\t\t\tthis.releaseNodeLock = granted\n\t\t}\n\t\tthis.clock = new HybridLogicalClock(this.nodeId)\n\t\tthis.causalTracker = new CausalTracker()\n\n\t\t// The fold is active for writes as soon as the database's rows are known to be\n\t\t// fold materializations (W7); a pre-W7 database is re-materialized after its\n\t\t// schema migrations, whose backfills then write the legacy way.\n\t\tif (this.folder) {\n\t\t\tthis.folder.setAuthoritativeNodeIds((await loadAuthoritativeNodeIds(this.adapter)) ?? [])\n\t\t\tthis.foldActive =\n\t\t\t\t(await this.readMeta(FOLD_MATERIALIZATION_META_KEY)) === FOLD_MATERIALIZATION_CURRENT\n\t\t}\n\n\t\t// Run schema migrations if needed. Backfills write operations through the local\n\t\t// write path, so the node id and clock must exist first (STORE-13).\n\t\ttry {\n\t\t\t// Transforms that cannot read the stored log would fold those operations as\n\t\t\t// absent and erase them from their records: refuse to open instead (RT-103).\n\t\t\tawait this.assertTransformCoverage()\n\t\t\tawait this.runMigrationsIfNeeded()\n\t\t\tawait this.ensureLegacyBodiesCanonical()\n\t\t\tawait this.ensureMaterialization()\n\t\t} catch (error) {\n\t\t\tthis.releaseNodeLock?.()\n\t\t\tthis.releaseNodeLock = null\n\t\t\tthrow error\n\t\t}\n\n\t\t// Initialize sequence manager\n\t\tthis.sequenceManager = new SequenceManager(this.adapter, this.nodeId)\n\n\t\t// Load sequence number and version vector\n\t\tthis.sequenceNumber = await this.loadSequenceNumber()\n\t\tthis.versionVector = await this.loadVersionVector()\n\n\t\t// Create RelationEnforcer if the schema has relations.\n\t\t// The enforcer is shared across all Collection instances so that\n\t\t// cascading deletes can cross collection boundaries.\n\t\tconst hasRelations = Object.keys(this.schema.relations).length > 0\n\t\tthis.relationEnforcer = hasRelations ? new RelationEnforcer({ schema: this.schema }) : null\n\n\t\t// Create collection instances\n\t\tfor (const [name, definition] of Object.entries(this.schema.collections)) {\n\t\t\tconst col = new Collection(\n\t\t\t\tname,\n\t\t\t\tdefinition,\n\t\t\t\tthis.schema,\n\t\t\t\tthis.adapter,\n\t\t\t\tthis.clock,\n\t\t\t\tthis.nodeId,\n\t\t\t\t(collectionName, operation) => this.publishLocalOperation(collectionName, operation),\n\t\t\t\tthis.relationEnforcer,\n\t\t\t\tthis.localMutationHandler,\n\t\t\t\tthis.causalTracker,\n\t\t\t\tthis.secretKeyProvider,\n\t\t\t\t(error) => this.reportStorageError(error),\n\t\t\t\t(error, operationIds) => this.reportWriteDurabilityError(error, operationIds),\n\t\t\t\t() => this.reportWriteDurabilityRestored(),\n\t\t\t\t() => this.activeFold(),\n\t\t\t\tthis.maxOperationBytes,\n\t\t\t\t() => this.assertLocalWriteAllowed(),\n\t\t\t\t() => this.stampingUser,\n\t\t\t\tthis.overlayController?.overlay,\n\t\t\t)\n\t\t\tthis.collections.set(name, col)\n\t\t}\n\t\tawait this.finishStorageEvidence(evidence, createdByThisOpen)\n\t}\n\n\t/** True when `_kora_meta` holds neither a node id nor an epoch: the database is new. */\n\tprivate async isDatabaseNew(): Promise<boolean> {\n\t\ttry {\n\t\t\tconst rows = await this.adapter.query<{ key: string }>(\n\t\t\t\t'SELECT key FROM _kora_meta WHERE key IN (?, ?)',\n\t\t\t\t['node_id', DB_EPOCH_META_KEY],\n\t\t\t)\n\t\t\treturn rows.length === 0\n\t\t} catch {\n\t\t\t// Unreadable: never claim a database is new (that would report a loss).\n\t\t\treturn false\n\t\t}\n\t}\n\n\t/**\n\t * After the first durable open: report a vanished database, give this one an epoch, and\n\t * refresh the evidence kept outside it. Never fails the open: evidence is advisory.\n\t */\n\tprivate async finishStorageEvidence(\n\t\tevidence: import('../adapters/storage-evidence').StorageEvidence | null,\n\t\tcreatedByThisOpen: boolean,\n\t): Promise<void> {\n\t\tthis.storageEvidence = evidence\n\t\tif (evidence === null) return\n\t\ttry {\n\t\t\tconst eviction = createdByThisOpen ? evidence.detectEviction() : null\n\t\t\tif (eviction !== null) {\n\t\t\t\tthis.storageEviction = eviction\n\t\t\t\t// Durable until acknowledged: a reload before the app told the user keeps it.\n\t\t\t\tawait this.writeMeta(STORAGE_EVICTED_META_KEY, JSON.stringify(eviction))\n\t\t\t} else {\n\t\t\t\tthis.storageEviction = parseStoredEviction(await this.readMeta(STORAGE_EVICTED_META_KEY))\n\t\t\t}\n\t\t\tlet epoch = await this.readMeta(DB_EPOCH_META_KEY)\n\t\t\tif (epoch === null) {\n\t\t\t\tepoch = generateUUIDv7()\n\t\t\t\tawait this.writeMeta(DB_EPOCH_META_KEY, epoch)\n\t\t\t}\n\t\t\tawait evidence.recordEpoch(epoch, createdByThisOpen)\n\t\t\tif (eviction !== null) {\n\t\t\t\tthis.emitter?.emit({\n\t\t\t\t\ttype: 'store:storage-evicted',\n\t\t\t\t\tdbName: this.dbName,\n\t\t\t\t\tdetectedAt: eviction.detectedAt,\n\t\t\t\t\tlastOpenedAt: eviction.lastOpenedAt,\n\t\t\t\t\tevidence: eviction.evidence,\n\t\t\t\t\tlostWrites: eviction.lostWrites,\n\t\t\t\t\tmessage: `The local database \"${this.dbName}\" existed on this device and its storage was deleted${\n\t\t\t\t\t\teviction.lostWrites.count > 0\n\t\t\t\t\t\t\t? `; ${eviction.lostWrites.certain ? '' : 'at least '}${eviction.lostWrites.count} write(s) that only it held are lost`\n\t\t\t\t\t\t\t: ''\n\t\t\t\t\t}. It was reopened empty and will sync again.`,\n\t\t\t\t})\n\t\t\t}\n\t\t} catch (error) {\n\t\t\tconsole.warn(`[kora] Could not update the storage evidence of \"${this.dbName}\":`, error)\n\t\t}\n\t}\n\n\t/**\n\t * A detected loss of this database's storage (`store:storage-evicted`) the app has not\n\t * acknowledged yet, or null.\n\t */\n\tgetStorageEviction(): import('../adapters/storage-evidence').StorageEviction | null {\n\t\treturn this.storageEviction\n\t}\n\n\t/** The app told the user about the storage loss: forget it, durably. */\n\tasync acknowledgeStorageEviction(): Promise<void> {\n\t\tthis.ensureOpen()\n\t\tif (this.storageEviction === null) return\n\t\tthis.storageEviction = null\n\t\tawait this.adapter.execute('DELETE FROM _kora_meta WHERE key = ?', [STORAGE_EVICTED_META_KEY])\n\t}\n\n\t/** Whether the adapter keeps storage-loss evidence for this database (browser, durable). */\n\thasStorageEvidence(): boolean {\n\t\treturn this.storageEvidence !== null\n\t}\n\n\t/**\n\t * Record how many writes only this device holds, next to the database (storage\n\t * manifest), so a vanished database can say what it lost. `exact` is true when no write\n\t * follows this recording. A no-op on adapters that keep no evidence.\n\t */\n\tasync recordUnsyncedWrites(count: number, exact: boolean): Promise<void> {\n\t\tawait this.storageEvidence?.recordUnsynced(count, exact)\n\t}\n\n\t/**\n\t * Before a close, while this tab retires for a newer build (version gate, section 5 step\n\t * 4): wait for every admitted write, then make them durable or throw `PersistenceError`\n\t * (`context.code: 'UNSAVED_WRITES'`) with everything still open. A no-op otherwise.\n\t * `app.close()` calls it before it tears anything down.\n\t */\n\tasync prepareClose(): Promise<void> {\n\t\tconst gate = this.versionGate\n\t\tif (!gate?.isSuperseded() || gate.getState() !== 'retiring') return\n\t\tawait this.writeGate.drain()\n\t\tawait gate.assertClosable()\n\t}\n\n\t/**\n\t * Close the store: clear subscriptions and close the adapter.\n\t */\n\tasync close(): Promise<void> {\n\t\tawait this.prepareClose()\n\t\tthis.overlayController?.dispose()\n\t\tthis.subscriptionManager.clear()\n\t\tthis.collections.clear()\n\t\tthis.opened = false\n\t\ttry {\n\t\t\tawait this.adapter.close()\n\t\t} finally {\n\t\t\tconst release = this.releaseNodeLock\n\t\t\tthis.releaseNodeLock = null\n\t\t\tawait release?.()\n\t\t}\n\t}\n\n\t/**\n\t * Check the operation log (W8 step 0): every row must round-trip through the\n\t * canonical operation serializer. Rows an earlier release damaged in a recoverable\n\t * way (a JSON-encoded timestamp written by a beta.12 backup restore) are repaired;\n\t * unrecoverable rows move to the quarantine table, where no fold reads them. Also\n\t * reports sequence gaps in this database's own nodes (compaction, a lost tail).\n\t *\n\t * The store runs a quick variant (SQL prefilter) on every open. Rebuilding state from\n\t * the log must only run on a `clean` report.\n\t *\n\t * @param options - `repair: false` only reports; `mode: 'quick'` checks only the rows\n\t *   a SQL prefilter flags (default `'full'`: every row)\n\t * @returns The integrity report; emits `store:log-integrity` when rows changed\n\t */\n\tasync verifyLogIntegrity(options?: {\n\t\trepair?: boolean\n\t\tmode?: 'full' | 'quick'\n\t}): Promise<LogIntegrityReport> {\n\t\tthis.ensureOpen()\n\t\treturn this.scanLog(options?.mode ?? 'full', options?.repair ?? true)\n\t}\n\n\tprivate async scanLog(mode: 'full' | 'quick', repair = true): Promise<LogIntegrityReport> {\n\t\tconst localNodeIds = (await listLocalNodes(this.adapter)).map((node) => node.nodeId)\n\t\tconst report = await scanLogIntegrity(this.adapter, this.schema, {\n\t\t\tmode,\n\t\t\trepair,\n\t\t\tlocalNodeIds,\n\t\t})\n\t\tif (repair && (report.repaired.length > 0 || report.newlyQuarantined.length > 0)) {\n\t\t\tthis.emitter?.emit({\n\t\t\t\ttype: 'store:log-integrity',\n\t\t\t\tdbName: this.dbName,\n\t\t\t\trepaired: report.repaired.length,\n\t\t\t\tquarantined: report.newlyQuarantined.length,\n\t\t\t\tgaps: report.gaps.length,\n\t\t\t\tclean: report.clean,\n\t\t\t\tmessage: `Operation log of \"${this.dbName}\": ${report.repaired.length} row(s) repaired, ${report.newlyQuarantined.length} row(s) quarantined (${LOG_QUARANTINE_TABLE}).`,\n\t\t\t})\n\t\t}\n\t\treturn report\n\t}\n\n\t/**\n\t * Get a Collection instance for CRUD operations.\n\t * @throws {StoreNotOpenError} If the store is not open\n\t * @throws {KoraError} `UNKNOWN_COLLECTION` if the collection name is not in the schema\n\t */\n\tcollection(name: string): CollectionAccessor {\n\t\tthis.ensureOpen()\n\t\tconst col = this.collections.get(name)\n\t\tif (!col) {\n\t\t\tthrow new KoraError(\n\t\t\t\t`Unknown collection \"${name}\". Available: ${[...this.collections.keys()].join(', ')}`,\n\t\t\t\t'UNKNOWN_COLLECTION',\n\t\t\t\t{ collection: name },\n\t\t\t)\n\t\t}\n\n\t\tconst definition = this.schema.collections[name]\n\t\tif (!definition) {\n\t\t\tthrow new KoraError(`Collection definition not found for \"${name}\"`, 'UNKNOWN_COLLECTION', {\n\t\t\t\tcollection: name,\n\t\t\t})\n\t\t}\n\n\t\tconst gate = this.writeGate\n\t\treturn {\n\t\t\tinsert: (data: Record<string, unknown>, options?: WriteOptions) =>\n\t\t\t\tgate.run({ collection: name, operation: 'insert' }, () => col.insert(data, options)),\n\t\t\tinsertMany: (rows: readonly Record<string, unknown>[], options?: WriteOptions) =>\n\t\t\t\tgate.run({ collection: name, operation: 'insertMany' }, () =>\n\t\t\t\t\tcol.insertMany(rows, options),\n\t\t\t\t),\n\t\t\tfindById: (id: string) => col.findById(id),\n\t\t\tupdate: (id: string, data: Record<string, unknown>, options?: WriteOptions) =>\n\t\t\t\tgate.run({ collection: name, operation: 'update' }, () => col.update(id, data, options)),\n\t\t\tdelete: (id: string, options?: WriteOptions) =>\n\t\t\t\tgate.run({ collection: name, operation: 'delete' }, () => col.delete(id, options)),\n\t\t\twhere: (conditions) =>\n\t\t\t\tnew QueryBuilder(\n\t\t\t\t\tname,\n\t\t\t\t\tdefinition,\n\t\t\t\t\tthis.adapter,\n\t\t\t\t\tthis.subscriptionManager,\n\t\t\t\t\tconditions,\n\t\t\t\t\tthis.schema,\n\t\t\t\t),\n\t\t}\n\t}\n\n\t/**\n\t * Get the current version vector.\n\t */\n\tgetVersionVector(): VersionVector {\n\t\tthis.ensureOpen()\n\t\treturn new Map(this.versionVector)\n\t}\n\n\t/**\n\t * Get the node ID for this store instance.\n\t */\n\t/**\n\t * Records the offset between server time and this device's clock\n\t * (serverTime - localTime), learned at sync handshake. Lets the store's HLC\n\t * validate remote timestamps correctly even when the local clock is wrong.\n\t */\n\tsetClockReferenceOffset(offsetMs: number): void {\n\t\tthis.clock?.setReferenceOffset(offsetMs)\n\t}\n\n\tgetNodeId(): string {\n\t\tthis.ensureOpen()\n\t\treturn this.nodeId\n\t}\n\n\t/**\n\t * Whether the journaled write with this key already reached the store. Answered from the\n\t * table the write's own transaction filled, so it is exact after a crash at any point.\n\t */\n\tasync hasJournalApplied(opKey: string): Promise<boolean> {\n\t\tthis.ensureOpen()\n\t\tconst rows = await this.adapter.query<{ op_key: string }>(\n\t\t\t'SELECT op_key FROM _kora_journal_applied WHERE op_key = ?',\n\t\t\t[opKey],\n\t\t)\n\t\treturn rows.length > 0\n\t}\n\n\t/**\n\t * Forget journaled-write keys whose journal entries are gone (`opKeys`), and any key older\n\t * than `olderThanMs` (an entry that old was pruned long ago).\n\t */\n\tasync forgetJournalApplied(opKeys: readonly string[], olderThanMs?: number): Promise<void> {\n\t\tthis.ensureOpen()\n\t\tfor (const key of opKeys) {\n\t\t\tawait this.adapter.execute('DELETE FROM _kora_journal_applied WHERE op_key = ?', [key])\n\t\t}\n\t\tif (olderThanMs !== undefined) {\n\t\t\tawait this.adapter.execute('DELETE FROM _kora_journal_applied WHERE applied_at < ?', [\n\t\t\t\tDate.now() - olderThanMs,\n\t\t\t])\n\t\t}\n\t}\n\n\t/** The schema transforms the fold applies (transforms at fold time, RT-84). */\n\tgetOperationTransforms(): readonly OperationTransform[] {\n\t\treturn this.operationTransforms\n\t}\n\n\t/**\n\t * Apply a remote operation received from sync.\n\t * Checks for duplicates, applies to the data table, persists the operation,\n\t * and updates the version vector.\n\t */\n\tapplyRemoteOperation(stored: Operation, options?: ApplyRemoteOptions): Promise<ApplyResult> {\n\t\t// A refused operation is not applied and advances nothing: the newer build receives\n\t\t// it again from the delivery watermark (version gate, section 5 step 2).\n\t\tconst foreign = this.overlayController?.registry.beginForeign(stored.collection)\n\t\tconst applied = this.writeGate.run(\n\t\t\t{ collection: stored.collection, operation: 'apply-remote' },\n\t\t\t() => this.applyRemoteOperationNow(stored, options),\n\t\t)\n\t\treturn foreign ? applied.finally(foreign.end) : applied\n\t}\n\n\tprivate async applyRemoteOperationNow(\n\t\tstored: Operation,\n\t\toptions?: ApplyRemoteOptions,\n\t): Promise<ApplyResult> {\n\t\tconst result = await this.applyRemoteOperationUnmarked(stored, options)\n\t\t// The server sent this record: it is readable again, so a narrowing that kept it\n\t\t// only for its unsent writes no longer applies to it. A quarantine replay does not\n\t\t// say that: the operation was delivered at an earlier point of the stream.\n\t\tif (result !== 'skipped' && this.deliveryPositions.get(stored.id)?.replay !== true)\n\t\t\tawait this.forgetKeptOutsideNarrowing(stored.collection, stored.recordId)\n\t\treturn result\n\t}\n\n\tprivate async applyRemoteOperationUnmarked(\n\t\tstored: Operation,\n\t\toptions?: ApplyRemoteOptions,\n\t): Promise<ApplyResult> {\n\t\tthis.ensureOpen()\n\n\t\tconst collection = stored.collection\n\t\tconst definition = this.schema.collections[collection]\n\t\tif (!definition) {\n\t\t\treturn 'skipped'\n\t\t}\n\t\tconst fold = this.activeFold()\n\t\tif (fold) {\n\t\t\t// The fold reads the operation through the schema transforms itself (RT-84).\n\t\t\treturn this.applyRemoteFolded(stored, fold, options)\n\t\t}\n\t\t// Legacy materialization writes rows directly: it materializes the operation as\n\t\t// this schema reads it, and logs the operation exactly as written (RT-84).\n\t\tconst view = operationSchemaView(stored, this.schema.version, this.operationTransforms)\n\t\tif (view === null) return 'skipped'\n\t\tconst op = view\n\n\t\t// Materialization may use overridden data/timestamp (authoritative merge\n\t\t// results), but the LOG below always stores the canonical operation:\n\t\t// operations are immutable and content-addressed, so merged values must\n\t\t// never be persisted under the original operation's id.\n\t\tconst materializeTimestamp = options?.materializeTimestamp ?? op.timestamp\n\t\tconst remoteVersion = serializeRowVersion(materializeTimestamp)\n\t\tconst wallTime = materializeTimestamp.wallTime\n\t\tconst materializeSource = options?.materializeData ?? op.data\n\t\tconst deliveryPosition = this.deliveryPositionOf(stored, options)\n\t\t// Duration is reported to DevTools only; it never orders anything.\n\t\tconst startedAt = Date.now()\n\t\tconst outcome = { duplicate: false, revived: false }\n\n\t\t// Apply the operation to the data table (LWW-guarded; op log always appended below)\n\t\ttry {\n\t\t\tawait this.adapter.transaction(async (tx) => {\n\t\t\t\tthis.assertDeliveryStillCurrent(stored.id)\n\t\t\t\t// Content-addressed dedup INSIDE the write transaction: two concurrent\n\t\t\t\t// deliveries of one operation serialize here, and the second sees the\n\t\t\t\t// first's row instead of failing on the primary key (STORE-15).\n\t\t\t\tif (await isOperationLogged(tx, collection, op.id)) {\n\t\t\t\t\toutcome.duplicate = true\n\t\t\t\t\t// A re-delivery shows a retracted record again only when it was delivered\n\t\t\t\t\t// after the retraction (scopeVisibilityAfter).\n\t\t\t\t\tif (\n\t\t\t\t\t\t(await scopeVisibilityAfter(tx, op, deliveryPosition, true)) === 'shown' &&\n\t\t\t\t\t\t!(await endsInDomainDelete(tx, collection, op.recordId, op))\n\t\t\t\t\t) {\n\t\t\t\t\t\tawait tx.execute(`UPDATE ${quoteIdent(collection)} SET _deleted = 0 WHERE id = ?`, [\n\t\t\t\t\t\t\top.recordId,\n\t\t\t\t\t\t])\n\t\t\t\t\t\toutcome.revived = true\n\t\t\t\t\t}\n\t\t\t\t\treturn\n\t\t\t\t}\n\t\t\t\t// Whether this operation shows the record if a retraction hides it (and\n\t\t\t\t// clears the marker then), decided once, before anything is written.\n\t\t\t\tconst visibility = await scopeVisibilityAfter(tx, op, deliveryPosition, false)\n\t\t\t\t// A record a retraction keeps hidden is never revived by a tombstone merge.\n\t\t\t\tconst reactivate = options?.reactivateIfDeleted === true && visibility !== 'hidden'\n\n\t\t\t\t// Advance the local HLC; severe clock drift throws ClockDriftError (surfaced as sync:apply-failed).\n\t\t\t\tif (this.clock) {\n\t\t\t\t\t// A scope entry's newest field version can be later than its timestamp (the\n\t\t\t\t\t// record's creation, RT-27): the clock must move past every version it carries.\n\t\t\t\t\tthis.clock.receive(op.fieldVersions ? newestFieldVersion(op) : op.timestamp)\n\t\t\t\t}\n\n\t\t\t\t// Optimistic-concurrency guard: if the caller computed its data from a\n\t\t\t\t// snapshot, verify the row hasn't changed since. Throwing rolls the\n\t\t\t\t// whole transaction back (nothing written, op NOT logged) so the caller\n\t\t\t\t// can recompute against fresh state and retry.\n\t\t\t\tconst checkGuard = (row: RawCollectionRow | undefined): void => {\n\t\t\t\t\tconst guard = options?.guardRowState\n\t\t\t\t\tif (!guard) {\n\t\t\t\t\t\treturn\n\t\t\t\t\t}\n\t\t\t\t\tconst version = typeof row?._version === 'string' ? row._version : null\n\t\t\t\t\tconst fieldVersions =\n\t\t\t\t\t\ttypeof row?._field_versions === 'string' ? row._field_versions : null\n\t\t\t\t\tif (version !== guard.version || fieldVersions !== guard.fieldVersions) {\n\t\t\t\t\t\tthrow new OptimisticLockError(collection, op.recordId)\n\t\t\t\t\t}\n\t\t\t\t}\n\n\t\t\t\tif (options?.logOnly) {\n\t\t\t\t\t// Append-only: the caller (after folding the record's log) determined\n\t\t\t\t\t// this op does not change the authoritative row. Persist it for future\n\t\t\t\t\t// folds but leave the row untouched. Fall through to op-log insert + VV.\n\t\t\t\t} else if (\n\t\t\t\t\top.type === 'insert' &&\n\t\t\t\t\top.data &&\n\t\t\t\t\top.fieldVersions &&\n\t\t\t\t\t!options?.materializeData &&\n\t\t\t\t\t!options?.forceMaterialize &&\n\t\t\t\t\t!options?.materializeTimestamp\n\t\t\t\t) {\n\t\t\t\t\t// Server scope-entry insert (RT-27): every field carries its own version.\n\t\t\t\t\tawait this.applyFieldVersionedInsert(tx, op, definition, op.data, checkGuard, visibility)\n\t\t\t\t} else if (op.type === 'insert' && materializeSource) {\n\t\t\t\t\tconst serializedData = serializeRecord(materializeSource, definition.fields)\n\t\t\t\t\tconst existing = await tx.query<RawCollectionRow>(\n\t\t\t\t\t\t`SELECT _updated_at, _version, _field_versions, _deleted FROM ${collection} WHERE id = ?`,\n\t\t\t\t\t\t[op.recordId],\n\t\t\t\t\t)\n\t\t\t\t\tconst row = existing[0]\n\t\t\t\t\tcheckGuard(row)\n\n\t\t\t\t\tif (!row) {\n\t\t\t\t\t\tconst record: Record<string, unknown> = {\n\t\t\t\t\t\t\tid: op.recordId,\n\t\t\t\t\t\t\t...serializedData,\n\t\t\t\t\t\t\t_created_at: wallTime,\n\t\t\t\t\t\t\t_updated_at: wallTime,\n\t\t\t\t\t\t\t_version: remoteVersion,\n\t\t\t\t\t\t\t// Stamp every inserted field so per-field LWW has a real baseline.\n\t\t\t\t\t\t\t_field_versions: serializeFieldVersions(\n\t\t\t\t\t\t\t\tfieldVersionsForFields(Object.keys(serializedData), remoteVersion),\n\t\t\t\t\t\t\t),\n\t\t\t\t\t\t\t// A record retracted before its insert applied (a quarantined insert\n\t\t\t\t\t\t\t// replayed after the retraction that followed it) is written hidden.\n\t\t\t\t\t\t\t...(visibility === 'hidden' ? { _deleted: 1 } : {}),\n\t\t\t\t\t\t}\n\t\t\t\t\t\tconst insertQuery = buildInsertQuery(collection, record)\n\t\t\t\t\t\tawait tx.execute(insertQuery.sql, insertQuery.params)\n\n\t\t\t\t\t\t// Catch up on operations delivered BEFORE this insert (transports may\n\t\t\t\t\t\t// reorder): any update/delete already logged for this record was\n\t\t\t\t\t\t// applied while no row existed, so it never materialized. The row is\n\t\t\t\t\t\t// a fold of the log — fold the orphans now, in timestamp order,\n\t\t\t\t\t\t// inside this same transaction. Per-field LWW makes the result\n\t\t\t\t\t\t// identical to what an in-order device computed.\n\t\t\t\t\t\tawait this.foldOrphanedOperations(tx, collection, definition, op.recordId, op)\n\t\t\t\t\t} else if (row._deleted === 1 && visibility === 'hidden') {\n\t\t\t\t\t\t// Hidden by a scope retraction this operation does not undo: it is\n\t\t\t\t\t\t// logged below, the row stays hidden.\n\t\t\t\t\t} else if (\n\t\t\t\t\t\trow._deleted === 1 &&\n\t\t\t\t\t\tvisibility === 'shown' &&\n\t\t\t\t\t\t!(await endsInDomainDelete(tx, collection, op.recordId, op))\n\t\t\t\t\t) {\n\t\t\t\t\t\t// The row is hidden by a scope retraction (a view change, not a domain\n\t\t\t\t\t\t// delete) and the record is in the scope again (RT-19). Show it again\n\t\t\t\t\t\t// and merge per field,\n\t\t\t\t\t\t// exactly like an insert collision on a live row: fields this device\n\t\t\t\t\t\t// holds newer versions of are kept.\n\t\t\t\t\t\tconst { winners, merged } = resolvePerFieldLww(\n\t\t\t\t\t\t\tparseFieldVersions(row._field_versions),\n\t\t\t\t\t\t\tObject.keys(serializedData),\n\t\t\t\t\t\t\tremoteVersion,\n\t\t\t\t\t\t\ttypeof row._version === 'string' ? row._version : undefined,\n\t\t\t\t\t\t)\n\t\t\t\t\t\tconst fieldChanges: Record<string, unknown> = {\n\t\t\t\t\t\t\t_deleted: 0,\n\t\t\t\t\t\t\t_field_versions: serializeFieldVersions(merged),\n\t\t\t\t\t\t}\n\t\t\t\t\t\tfor (const field of winners) {\n\t\t\t\t\t\t\tfieldChanges[field] = serializedData[field]\n\t\t\t\t\t\t}\n\t\t\t\t\t\t// `_created_at` is left alone: the record was created long before it\n\t\t\t\t\t\t// re-entered this device's view.\n\t\t\t\t\t\tconst reactivateQuery = buildFieldFastForwardUpdateQuery(\n\t\t\t\t\t\t\tcollection,\n\t\t\t\t\t\t\top.recordId,\n\t\t\t\t\t\t\tfieldChanges,\n\t\t\t\t\t\t\tremoteVersion,\n\t\t\t\t\t\t\twallTime,\n\t\t\t\t\t\t)\n\t\t\t\t\t\tawait tx.execute(reactivateQuery.sql, reactivateQuery.params)\n\t\t\t\t\t} else if (row._deleted === 1) {\n\t\t\t\t\t\t// Insert vs tombstone: a strictly newer insert resurrects the record\n\t\t\t\t\t\t// with its full field set; an older one is stale (delete wins).\n\t\t\t\t\t\tif (isIncomingNewerThanRow(materializeTimestamp, row)) {\n\t\t\t\t\t\t\tconst fieldChanges: Record<string, unknown> = {\n\t\t\t\t\t\t\t\t...serializedData,\n\t\t\t\t\t\t\t\t_deleted: 0,\n\t\t\t\t\t\t\t\t_field_versions: serializeFieldVersions(\n\t\t\t\t\t\t\t\t\tfieldVersionsForFields(Object.keys(serializedData), remoteVersion),\n\t\t\t\t\t\t\t\t),\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\tconst upsert = buildFieldFastForwardUpdateQuery(\n\t\t\t\t\t\t\t\tcollection,\n\t\t\t\t\t\t\t\top.recordId,\n\t\t\t\t\t\t\t\tfieldChanges,\n\t\t\t\t\t\t\t\tremoteVersion,\n\t\t\t\t\t\t\t\twallTime,\n\t\t\t\t\t\t\t\t{ maxCreatedAt: wallTime },\n\t\t\t\t\t\t\t)\n\t\t\t\t\t\t\tawait tx.execute(upsert.sql, upsert.params)\n\t\t\t\t\t\t}\n\t\t\t\t\t} else {\n\t\t\t\t\t\t// Insert collision on a LIVE row (relayed insert racing a local one,\n\t\t\t\t\t\t// or an insert-vs-insert merge). A plain INSERT would violate the\n\t\t\t\t\t\t// primary key; resolve per-field instead, exactly like an update, so\n\t\t\t\t\t\t// every node converges no matter which insert (or interleaved\n\t\t\t\t\t\t// update) it saw first. `_created_at` converges to the max insert\n\t\t\t\t\t\t// wall time seen, applied even when every field loses.\n\t\t\t\t\t\tconst currentVersions = parseFieldVersions(row._field_versions)\n\t\t\t\t\t\tconst rowVersion = typeof row._version === 'string' ? row._version : undefined\n\t\t\t\t\t\tconst fieldChanges: Record<string, unknown> = {}\n\t\t\t\t\t\tlet fieldVersionsJson: string\n\t\t\t\t\t\tif (options?.forceMaterialize) {\n\t\t\t\t\t\t\t// Authoritative merged insert: every field is written.\n\t\t\t\t\t\t\tconst merged = { ...currentVersions }\n\t\t\t\t\t\t\tfor (const field of Object.keys(serializedData)) {\n\t\t\t\t\t\t\t\tfieldChanges[field] = serializedData[field]\n\t\t\t\t\t\t\t\tmerged[field] = remoteVersion\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\tfieldVersionsJson = serializeFieldVersions(merged)\n\t\t\t\t\t\t} else {\n\t\t\t\t\t\t\tconst { winners, merged } = resolvePerFieldLww(\n\t\t\t\t\t\t\t\tcurrentVersions,\n\t\t\t\t\t\t\t\tObject.keys(serializedData),\n\t\t\t\t\t\t\t\tremoteVersion,\n\t\t\t\t\t\t\t\trowVersion,\n\t\t\t\t\t\t\t)\n\t\t\t\t\t\t\tfor (const field of winners) {\n\t\t\t\t\t\t\t\tfieldChanges[field] = serializedData[field]\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\tfieldVersionsJson = serializeFieldVersions(merged)\n\t\t\t\t\t\t}\n\t\t\t\t\t\tconst upsert = buildFieldFastForwardUpdateQuery(\n\t\t\t\t\t\t\tcollection,\n\t\t\t\t\t\t\top.recordId,\n\t\t\t\t\t\t\t{ ...fieldChanges, _field_versions: fieldVersionsJson },\n\t\t\t\t\t\t\tremoteVersion,\n\t\t\t\t\t\t\twallTime,\n\t\t\t\t\t\t\t{ maxCreatedAt: wallTime },\n\t\t\t\t\t\t)\n\t\t\t\t\t\tawait tx.execute(upsert.sql, upsert.params)\n\t\t\t\t\t}\n\t\t\t\t} else if (op.type === 'update' && materializeSource) {\n\t\t\t\t\tconst serializedChanges = serializeRecord(materializeSource, definition.fields)\n\t\t\t\t\tconst changedFields = Object.keys(serializedChanges)\n\n\t\t\t\t\t// Read the current per-field versions INSIDE the transaction so the\n\t\t\t\t\t// resolve-then-write is atomic with respect to any concurrent local\n\t\t\t\t\t// mutation — this is what prevents a relayed remote op from clobbering\n\t\t\t\t\t// a newer local edit that lands between the read and the write.\n\t\t\t\t\tconst currentRows = await tx.query<RawCollectionRow>(\n\t\t\t\t\t\t`SELECT _version, _field_versions FROM ${quoteIdent(collection)} WHERE id = ?`,\n\t\t\t\t\t\t[op.recordId],\n\t\t\t\t\t)\n\t\t\t\t\tconst currentRow = currentRows[0]\n\t\t\t\t\tcheckGuard(currentRow)\n\n\t\t\t\t\tif (currentRow) {\n\t\t\t\t\t\tconst currentVersions = parseFieldVersions(currentRow._field_versions)\n\t\t\t\t\t\tconst rowVersion =\n\t\t\t\t\t\t\ttypeof currentRow._version === 'string' ? currentRow._version : undefined\n\n\t\t\t\t\t\tif (options?.forceMaterialize) {\n\t\t\t\t\t\t\t// Authoritative merged result (richtext / add-wins-set / constraint\n\t\t\t\t\t\t\t// resolution computed by the merge engine): write every changed\n\t\t\t\t\t\t\t// field and stamp its per-field version to this op's version, while\n\t\t\t\t\t\t\t// advancing the row watermark monotonically.\n\t\t\t\t\t\t\tconst merged = { ...currentVersions }\n\t\t\t\t\t\t\tfor (const field of changedFields) {\n\t\t\t\t\t\t\t\tmerged[field] = remoteVersion\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\tconst fieldChanges: Record<string, unknown> = {\n\t\t\t\t\t\t\t\t...serializedChanges,\n\t\t\t\t\t\t\t\t_field_versions: serializeFieldVersions(merged),\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\tif (reactivate) {\n\t\t\t\t\t\t\t\tfieldChanges._deleted = 0\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\tconst forceQuery = buildFieldFastForwardUpdateQuery(\n\t\t\t\t\t\t\t\tcollection,\n\t\t\t\t\t\t\t\top.recordId,\n\t\t\t\t\t\t\t\tfieldChanges,\n\t\t\t\t\t\t\t\tremoteVersion,\n\t\t\t\t\t\t\t\twallTime,\n\t\t\t\t\t\t\t)\n\t\t\t\t\t\t\tawait tx.execute(forceQuery.sql, forceQuery.params)\n\t\t\t\t\t\t} else {\n\t\t\t\t\t\t\t// Deterministic field-level LWW: write only the fields this op\n\t\t\t\t\t\t\t// wins (strictly newer than the field's stored version). Same\n\t\t\t\t\t\t\t// result on every node regardless of arrival order.\n\t\t\t\t\t\t\tconst { winners, merged } = resolvePerFieldLww(\n\t\t\t\t\t\t\t\tcurrentVersions,\n\t\t\t\t\t\t\t\tchangedFields,\n\t\t\t\t\t\t\t\tremoteVersion,\n\t\t\t\t\t\t\t\trowVersion,\n\t\t\t\t\t\t\t)\n\t\t\t\t\t\t\tif (winners.length > 0 || reactivate) {\n\t\t\t\t\t\t\t\tconst winningChanges: Record<string, unknown> = {\n\t\t\t\t\t\t\t\t\t_field_versions: serializeFieldVersions(merged),\n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\tfor (const field of winners) {\n\t\t\t\t\t\t\t\t\twinningChanges[field] = serializedChanges[field]\n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\tif (reactivate) {\n\t\t\t\t\t\t\t\t\twinningChanges._deleted = 0\n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\tconst forceQuery = buildFieldFastForwardUpdateQuery(\n\t\t\t\t\t\t\t\t\tcollection,\n\t\t\t\t\t\t\t\t\top.recordId,\n\t\t\t\t\t\t\t\t\twinningChanges,\n\t\t\t\t\t\t\t\t\tremoteVersion,\n\t\t\t\t\t\t\t\t\twallTime,\n\t\t\t\t\t\t\t\t)\n\t\t\t\t\t\t\t\tawait tx.execute(forceQuery.sql, forceQuery.params)\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\t// currentRow absent: nothing materialized to update (insert not yet\n\t\t\t\t\t// applied, or hard-absent). The op is still appended to the log below;\n\t\t\t\t\t// the pipeline handles tombstone reactivation separately.\n\t\t\t\t} else if (op.type === 'delete') {\n\t\t\t\t\tconst deleteQuery = buildLwwSoftDeleteQuery(\n\t\t\t\t\t\tcollection,\n\t\t\t\t\t\top.recordId,\n\t\t\t\t\t\twallTime,\n\t\t\t\t\t\tremoteVersion,\n\t\t\t\t\t)\n\t\t\t\t\tawait tx.execute(deleteQuery.sql, deleteQuery.params)\n\t\t\t\t}\n\t\t\t\tif (\n\t\t\t\t\tvisibility === 'shown' &&\n\t\t\t\t\top.type === 'update' &&\n\t\t\t\t\t!(await endsInDomainDelete(tx, collection, op.recordId, op))\n\t\t\t\t) {\n\t\t\t\t\t// Delivered after the retraction: the server holds the record in this view\n\t\t\t\t\t// again (the insert branches above show it themselves). Only the retraction's\n\t\t\t\t\t// hide is lifted: a domain delete newer than every write (this device's own\n\t\t\t\t\t// delete, under the marker) still holds, as it would without the marker.\n\t\t\t\t\tawait tx.execute(`UPDATE ${quoteIdent(collection)} SET _deleted = 0 WHERE id = ?`, [\n\t\t\t\t\t\top.recordId,\n\t\t\t\t\t])\n\t\t\t\t}\n\n\t\t\t\t// Persist the operation\n\t\t\t\tawait this.appendRemoteOperationRow(tx, stored)\n\n\t\t\t\t// Version vector: MAX with the stored value, never a value computed outside\n\t\t\t\t// this transaction (another tab may have advanced it). The in-memory\n\t\t\t\t// vector is updated only after commit.\n\t\t\t\tawait tx.execute(\n\t\t\t\t\t`INSERT INTO _kora_version_vector (node_id, sequence_number) VALUES (?, ?)\n     ON CONFLICT(node_id) DO UPDATE SET sequence_number = MAX(sequence_number, excluded.sequence_number)`,\n\t\t\t\t\t[op.nodeId, op.sequenceNumber],\n\t\t\t\t)\n\t\t\t\t// The position can move while the statements above ran; checked again\n\t\t\t\t// before the commit so a stale delivery's write rolls back.\n\t\t\t\tthis.assertDeliveryStillCurrent(stored.id)\n\t\t\t})\n\t\t} catch (error) {\n\t\t\tthis.reportStorageError(error)\n\t\t\tthrow error\n\t\t}\n\n\t\t// Committed. A duplicate still advances this runtime's vector and refreshes\n\t\t// its queries: another tab sharing the database may have applied the\n\t\t// operation first, and this tab must not stay blind to it (STORE-10).\n\t\tthis.recordOperationSequence(op)\n\t\tif (outcome.duplicate) {\n\t\t\tif (outcome.revived) {\n\t\t\t\tthis.subscriptionManager.invalidate(collection)\n\t\t\t} else {\n\t\t\t\tthis.subscriptionManager.notify(collection, op)\n\t\t\t}\n\t\t\treturn 'duplicate'\n\t\t}\n\n\t\tthis.subscriptionManager.notify(collection, op)\n\t\tthis.emitter?.emit({\n\t\t\ttype: 'operation:applied',\n\t\t\toperation: op,\n\t\t\tduration: Date.now() - startedAt,\n\t\t})\n\n\t\treturn 'applied'\n\t}\n\n\t/**\n\t * W7 remote apply: append the operation, then merge it into its record's fold\n\t * state, which re-materializes the row, all in one write transaction. There is no\n\t * read-decide-write race to guard: the state is read and written inside the\n\t * transaction, and the merge does not depend on the order operations arrive in.\n\t */\n\tprivate async applyRemoteFolded(\n\t\top: Operation,\n\t\tfold: RecordFolder,\n\t\toptions: ApplyRemoteOptions | undefined,\n\t): Promise<ApplyResult> {\n\t\tconst deliveryPosition = this.deliveryPositionOf(op, options)\n\t\tconst startedAt = Date.now()\n\t\tlet outcome: FoldedApplyOutcome = { duplicate: false, revived: false, traces: [] }\n\t\tlet completed = false\n\t\ttry {\n\t\t\tawait this.adapter.transaction(async (tx) => {\n\t\t\t\tthis.assertDeliveryStillCurrent(op.id)\n\t\t\t\toutcome = await this.applyRemoteFoldedInTx(tx, op, fold, deliveryPosition)\n\t\t\t\t// Checked again before the commit: the position can move while the fold ran.\n\t\t\t\tthis.assertDeliveryStillCurrent(op.id)\n\t\t\t\tcompleted = true\n\t\t\t})\n\t\t} catch (error) {\n\t\t\tthis.reportStorageError(error)\n\t\t\t// The commit's outcome may be unknown (it rejected after the transaction body\n\t\t\t// finished): if the operation is in the log, it landed and is published below,\n\t\t\t// not left for a retry to find as a duplicate that emits nothing (M2).\n\t\t\tif (!(completed && !outcome.duplicate && (await this.commitLanded(op)))) throw error\n\t\t}\n\t\treturn this.publishRemoteApply(op, outcome, options, Date.now() - startedAt)\n\t}\n\n\t/**\n\t * The transactional part of a W7 remote apply: dedup, retraction visibility, append,\n\t * fold and version vector, all through `tx`. Nothing in memory is published here\n\t * (see {@link publishRemoteApply}), so a caller that rolls `tx` back leaves no trace\n\t * except the HLC having seen the timestamp (monotonic, harmless).\n\t */\n\tprivate async applyRemoteFoldedInTx(\n\t\ttx: Transaction,\n\t\top: Operation,\n\t\tfold: RecordFolder,\n\t\tdeliveryPosition: number | undefined,\n\t): Promise<FoldedApplyOutcome> {\n\t\tconst collection = op.collection\n\t\tconst outcome: FoldedApplyOutcome = { duplicate: false, revived: false, traces: [] }\n\t\tif ((await isOperationLogged(tx, collection, op.id)) || (await isCompacted(tx, op))) {\n\t\t\toutcome.duplicate = true\n\t\t\t// A re-delivery shows a retracted record again only when it was delivered\n\t\t\t// after the retraction (scopeVisibilityAfter): then with every field of its\n\t\t\t// state (writes merged while it was hidden included).\n\t\t\tif ((await scopeVisibilityAfter(tx, op, deliveryPosition, true)) === 'shown') {\n\t\t\t\tconst state = await fold.loadState(tx, collection, op.recordId)\n\t\t\t\tif (state) {\n\t\t\t\t\tawait fold.materializeRow(tx, state, 'all', { clearRetraction: true })\n\t\t\t\t}\n\t\t\t\toutcome.revived = true\n\t\t\t}\n\t\t\treturn outcome\n\t\t}\n\t\tconst visibility = await scopeVisibilityAfter(tx, op, deliveryPosition, false)\n\t\tif (this.clock) {\n\t\t\t// A scope entry's newest field version can be later than its timestamp (the\n\t\t\t// record's creation, RT-27): the clock must move past every version it carries.\n\t\t\tthis.clock.receive(op.fieldVersions ? newestFieldVersion(op) : op.timestamp)\n\t\t}\n\t\tconst releasedSeed = await this.releaseSeedFor(tx, op)\n\t\tawait this.appendRemoteOperationRow(tx, op)\n\t\tconst applied = await fold.applyInTx(tx, op, 'remote', {\n\t\t\treveal: visibility === 'shown',\n\t\t})\n\t\t// A seeded record the user had written to kept its snapshot; with the insert now in the\n\t\t// log the snapshot is replaced by the exact fold (RT-68).\n\t\tif (releasedSeed && op.type === 'insert') {\n\t\t\tawait fold.settleSnapshotInTx(tx, collection, op.recordId)\n\t\t}\n\t\toutcome.traces = applied.traces\n\t\tawait tx.execute(\n\t\t\t`INSERT INTO _kora_version_vector (node_id, sequence_number) VALUES (?, ?)\n     ON CONFLICT(node_id) DO UPDATE SET sequence_number = MAX(sequence_number, excluded.sequence_number)`,\n\t\t\t[op.nodeId, op.sequenceNumber],\n\t\t)\n\t\treturn outcome\n\t}\n\n\t/**\n\t * {@link applyRemoteFoldedInTx} answered from what a delivery batch read up front (C3b,\n\t * `RemoteBatchPrefetch`): the same writes in the same order, without the reads. Returns\n\t * null, having done nothing, when this operation or its record is not one the cache can\n\t * answer for (a retracted record, a base, a snapshot, a shared node id, a taken sequence\n\t * number, a record the batch changed by another route); the caller then applies it the\n\t * per-operation way.\n\t */\n\tprivate async applyRemoteFoldedPrefetched(\n\t\ttx: Transaction,\n\t\top: Operation,\n\t\tfold: RecordFolder,\n\t\tprefetch: RemoteBatchPrefetch,\n\t\tdeferred: DeferredPrior[],\n\t): Promise<FoldedApplyOutcome | null> {\n\t\tif (!prefetch.covers(op)) return null\n\t\tconst record = prefetch.eligible(op.collection, op.recordId)\n\t\tif (record === null) return null\n\t\tconst outcome: FoldedApplyOutcome = { duplicate: false, revived: false, traces: [] }\n\t\tif (prefetch.isDuplicate(op)) {\n\t\t\t// No retraction marker (eligible): a re-delivery shows nothing again.\n\t\t\toutcome.duplicate = true\n\t\t\treturn outcome\n\t\t}\n\t\tif (prefetch.needsCarefulAppend(op)) return null\n\t\tif (this.clock) {\n\t\t\tthis.clock.receive(op.fieldVersions ? newestFieldVersion(op) : op.timestamp)\n\t\t}\n\t\tawait this.appendRemoteOperationRow(tx, op, true)\n\t\tconst applied = await fold.applyKnownInTx(\n\t\t\ttx,\n\t\t\top,\n\t\t\t{ state: record.state, row: record.row },\n\t\t\tdeferred,\n\t\t)\n\t\toutcome.traces = applied.traces\n\t\tawait tx.execute(\n\t\t\t`INSERT INTO _kora_version_vector (node_id, sequence_number) VALUES (?, ?)\n     ON CONFLICT(node_id) DO UPDATE SET sequence_number = MAX(sequence_number, excluded.sequence_number)`,\n\t\t\t[op.nodeId, op.sequenceNumber],\n\t\t)\n\t\tprefetch.noteApplied(op, record, applied)\n\t\treturn outcome\n\t}\n\n\t/** After commit: the in-memory effects of a committed remote apply. */\n\tprivate publishRemoteApply(\n\t\top: Operation,\n\t\toutcome: FoldedApplyOutcome,\n\t\toptions: ApplyRemoteOptions | undefined,\n\t\tduration: number,\n\t): ApplyResult {\n\t\tconst collection = op.collection\n\t\tthis.recordOperationSequence(op)\n\t\tif (outcome.duplicate) {\n\t\t\tif (outcome.revived) {\n\t\t\t\tthis.subscriptionManager.invalidate(collection)\n\t\t\t} else {\n\t\t\t\tthis.subscriptionManager.notify(collection, op)\n\t\t\t}\n\t\t\treturn 'duplicate'\n\t\t}\n\t\tthis.subscriptionManager.notify(collection, op)\n\t\tthis.emitMergeTraces(op, outcome.traces)\n\t\toptions?.onMergeTraces?.(outcome.traces)\n\t\tthis.emitter?.emit({ type: 'operation:applied', operation: op, duration })\n\t\treturn 'applied'\n\t}\n\n\t/**\n\t * Apply a delivery batch of remote operations in ONE storage transaction (C3,\n\t * docs/design/fast-first-sync.md). `fn` receives a {@link RemoteApplyBatch} whose\n\t * writes all go through that transaction; each operation (and retraction) runs in its\n\t * own savepoint, so a failing one is rolled back alone and the caller decides what\n\t * to do (quarantine it, or abort the batch).\n\t *\n\t * Everything this runtime publishes (version vector, subscription notifications,\n\t * `operation:applied`, merge traces, effects the caller registered with\n\t * {@link RemoteApplyBatch.afterCommit}) is held until the transaction commits and\n\t * runs in registration order after it; a rolled-back batch publishes nothing.\n\t *\n\t * @returns `fn`'s result, or `null` when this store cannot batch (legacy\n\t *   materialization, or records an access narrowing kept for unsent writes: those\n\t *   paths keep their per-operation bookkeeping) and the caller must apply one by one\n\t * @throws Whatever `fn` throws (the transaction is rolled back), or a storage error\n\t */\n\tapplyRemoteBatch<T>(fn: (batch: RemoteApplyBatch) => Promise<T>): Promise<{ value: T } | null> {\n\t\t// A retired tab applies no inbound batch: the refusal advances no watermark, and the\n\t\t// newer build receives the batch again from its own delivery watermark (version gate,\n\t\t// section 5 step 2). The drain waits for a batch already admitted.\n\t\tconst foreign = this.overlayController?.registry.beginForeign()\n\t\tconst applied = this.writeGate.run({ operation: 'apply-remote-batch' }, () =>\n\t\t\tthis.applyRemoteBatchNow(fn, foreign),\n\t\t)\n\t\treturn foreign ? applied.finally(foreign.end) : applied\n\t}\n\n\tprivate async applyRemoteBatchNow<T>(\n\t\tfn: (batch: RemoteApplyBatch) => Promise<T>,\n\t\tforeign?: ForeignApply,\n\t): Promise<{ value: T } | null> {\n\t\tthis.ensureOpen()\n\t\tconst fold = this.activeFold()\n\t\tif (!fold) return null\n\t\t// A record a narrowing kept is forgotten by the next operation that reaches it,\n\t\t// through a cache outside the transaction: that bookkeeping stays per operation.\n\t\tif ((await this.loadKeptOutsideNarrowing()).size > 0) return null\n\t\t// DDL cannot run inside the batch's transaction on every adapter: create first.\n\t\tawait ensureUnappliedTable(this.adapter)\n\t\tconst effects: Array<() => void> = []\n\t\tlet value: T | undefined\n\t\t// Set once `fn` returned inside the transaction: a later rejection is then a commit\n\t\t// whose outcome is unknown, not a failure of the batch's own work.\n\t\tlet completed = false\n\t\t// The newest operation this attempt added to the log (not a duplicate): all or none\n\t\t// of the transaction landed, so finding it proves the whole batch did.\n\t\tlet probe: Operation | null = null\n\t\ttry {\n\t\t\tawait this.adapter.transaction(async (tx) => {\n\t\t\t\tlet savepoints = 0\n\t\t\t\t// One write-behind buffer for the whole delivery batch: a step that reads nothing\n\t\t\t\t// adds its statements and sends nothing, so consecutive steps travel in one worker\n\t\t\t\t// request (up to the buffer's bound) instead of one round trip per operation (K1:\n\t\t\t\t// 20k operations were 20k requests with both threads idle). Reads, and every use\n\t\t\t\t// of the raw transaction below, send the buffer first, so order is kept.\n\t\t\t\tconst group = new WriteBehindTransaction(tx)\n\t\t\t\tconst prefetch = new RemoteBatchPrefetch(this.schema)\n\t\t\t\t// Prior operations of merge traces, read together before the commit (C3b).\n\t\t\t\tconst deferred: DeferredPrior[] = []\n\t\t\t\t// A statement that failed in the buffer surfaces at a LATER step's read, write or\n\t\t\t\t// the final flush, so the step that sees it is not the one that caused it. Such a\n\t\t\t\t// failure is not a verdict on that step: it ends the whole batch, which is rolled\n\t\t\t\t// back and applied operation by operation (the caller's fallback), where every\n\t\t\t\t// failure is attributed to its own operation as before.\n\t\t\t\tconst groupFailure = (error: unknown): KoraError =>\n\t\t\t\t\tnew KoraError(\n\t\t\t\t\t\t`A write of a delivery batch failed in the shared write buffer: ${\n\t\t\t\t\t\t\terror instanceof Error ? error.message : String(error)\n\t\t\t\t\t\t}`,\n\t\t\t\t\t\t'DELIVERY_BATCH_WRITE_FAILED',\n\t\t\t\t\t\t{ cause: error instanceof Error ? error.message : String(error) },\n\t\t\t\t\t)\n\t\t\t\t// The raw transaction for everything outside a step (prefetch, reads, the quarantine\n\t\t\t\t// and watermark rows): the buffer is sent first, and a failure of it ends the batch.\n\t\t\t\tconst flushGroup = async (): Promise<void> => {\n\t\t\t\t\ttry {\n\t\t\t\t\t\tawait group.flush()\n\t\t\t\t\t} catch (error) {\n\t\t\t\t\t\tawait group.settled()\n\t\t\t\t\t\tthrow groupFailure(error)\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\tconst direct: Transaction = {\n\t\t\t\t\texecute: async (sql, params) => {\n\t\t\t\t\t\tawait flushGroup()\n\t\t\t\t\t\tawait tx.execute(sql, params)\n\t\t\t\t\t},\n\t\t\t\t\tquery: async (sql, params) => {\n\t\t\t\t\t\tawait flushGroup()\n\t\t\t\t\t\treturn tx.query(sql, params)\n\t\t\t\t\t},\n\t\t\t\t}\n\t\t\t\t// A step whose write cannot fail on a constraint joins the batch's buffer (below); one\n\t\t\t\t// that can (a record pointing at a parent the database does not hold yet, a\n\t\t\t\t// retraction) is flushed on its own, so its failure is its own: `strictStep`.\n\t\t\t\t//\n\t\t\t\t// A pipelined step runs in a savepoint whose statements join the batch's buffer.\n\t\t\t\t// One that throws before its savepoint was sent is simply cut out of the buffer; one\n\t\t\t\t// whose savepoint was already sent (a read of the step flushed it) is undone with\n\t\t\t\t// ROLLBACK TO after every sent statement settled, so nothing of it lands later.\n\t\t\t\tconst pipelinedStep = async <R>(work: (step: Transaction) => Promise<R>): Promise<R> => {\n\t\t\t\t\tconst name = `kora_batch_${++savepoints}`\n\t\t\t\t\tconst mark = effects.length\n\t\t\t\t\tconst deferredMark = deferred.length\n\t\t\t\t\tconst issuedMark = group.issued\n\t\t\t\t\ttry {\n\t\t\t\t\t\tawait group.execute(`SAVEPOINT ${name}`)\n\t\t\t\t\t\tconst result = await work(group)\n\t\t\t\t\t\tawait group.execute(`RELEASE ${name}`)\n\t\t\t\t\t\treturn result\n\t\t\t\t\t} catch (error) {\n\t\t\t\t\t\t// Only this step is undone; the effects it registered go with it.\n\t\t\t\t\t\teffects.length = mark\n\t\t\t\t\t\tdeferred.length = deferredMark\n\t\t\t\t\t\tawait group.settled()\n\t\t\t\t\t\tif (group.failed) throw groupFailure(error)\n\t\t\t\t\t\tif (!group.truncateTo(issuedMark)) {\n\t\t\t\t\t\t\t// The step's savepoint was sent: undo it in the database.\n\t\t\t\t\t\t\tgroup.discardUnsent()\n\t\t\t\t\t\t\tawait tx.execute(`ROLLBACK TO ${name}`)\n\t\t\t\t\t\t\tawait tx.execute(`RELEASE ${name}`)\n\t\t\t\t\t\t}\n\t\t\t\t\t\tthrow error\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\t// The step alone in its own buffer, flushed when it ends: a failing statement\n\t\t\t\t// rejects that step's own await, and on a failure every statement already sent\n\t\t\t\t// settles before the ROLLBACK TO, so nothing of the step lands after it is undone.\n\t\t\t\tconst strictStep = async <R>(work: (step: Transaction) => Promise<R>): Promise<R> => {\n\t\t\t\t\tawait flushGroup()\n\t\t\t\t\tconst name = `kora_batch_${++savepoints}`\n\t\t\t\t\tconst mark = effects.length\n\t\t\t\t\tconst deferredMark = deferred.length\n\t\t\t\t\tconst step = new WriteBehindTransaction(tx)\n\t\t\t\t\ttry {\n\t\t\t\t\t\tawait step.execute(`SAVEPOINT ${name}`)\n\t\t\t\t\t\tconst result = await work(step)\n\t\t\t\t\t\tawait step.execute(`RELEASE ${name}`)\n\t\t\t\t\t\tawait step.flush()\n\t\t\t\t\t\treturn result\n\t\t\t\t\t} catch (error) {\n\t\t\t\t\t\teffects.length = mark\n\t\t\t\t\t\tdeferred.length = deferredMark\n\t\t\t\t\t\tawait step.settled()\n\t\t\t\t\t\t// A step that failed before anything was sent never opened its savepoint.\n\t\t\t\t\t\tif (step.discardUnsent()) {\n\t\t\t\t\t\t\tawait tx.execute(`ROLLBACK TO ${name}`)\n\t\t\t\t\t\t\tawait tx.execute(`RELEASE ${name}`)\n\t\t\t\t\t\t}\n\t\t\t\t\t\tthrow error\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\tconst inSavepoint = <R>(\n\t\t\t\t\twork: (step: Transaction) => Promise<R>,\n\t\t\t\t\tpipelined = false,\n\t\t\t\t): Promise<R> => (pipelined ? pipelinedStep(work) : strictStep(work))\n\t\t\t\t// Parents the database (or an earlier step of this batch) holds, per collection:\n\t\t\t\t// a child whose parents are all known cannot fail its foreign key, so it may be\n\t\t\t\t// pipelined. Only a prediction: a wrong \"known\" fails the buffer, which rolls the\n\t\t\t\t// batch back for the per-operation path; a wrong \"unknown\" only costs speed.\n\t\t\t\tconst parents = new Map<string, Set<string>>()\n\t\t\t\tconst foreignKeys = this.foreignKeysByCollection()\n\t\t\t\tconst parentIdsOf = (op: Operation): Array<{ to: string; id: string } | null> =>\n\t\t\t\t\t(foreignKeys.get(op.collection) ?? []).map(({ field, to }) => {\n\t\t\t\t\t\tconst id = op.data?.[field]\n\t\t\t\t\t\treturn typeof id === 'string' ? { to, id } : null\n\t\t\t\t\t})\n\t\t\t\tconst canPipeline = (op: Operation): boolean => {\n\t\t\t\t\tconst keys = foreignKeys.get(op.collection)\n\t\t\t\t\tif (keys === undefined || op.data === null) return true\n\t\t\t\t\tfor (const [index, { field }] of keys.entries()) {\n\t\t\t\t\t\tconst value = op.data[field]\n\t\t\t\t\t\tif (value === undefined || value === null) continue\n\t\t\t\t\t\tconst parent = parentIdsOf(op)[index]\n\t\t\t\t\t\tif (!parent || !parents.get(parent.to)?.has(parent.id)) return false\n\t\t\t\t\t}\n\t\t\t\t\treturn true\n\t\t\t\t}\n\t\t\t\tconst loadParents = async (operations: readonly Operation[]): Promise<void> => {\n\t\t\t\t\tconst wanted = new Map<string, Set<string>>()\n\t\t\t\t\tfor (const op of operations) {\n\t\t\t\t\t\tfor (const parent of parentIdsOf(op)) {\n\t\t\t\t\t\t\tif (!parent || parents.get(parent.to)?.has(parent.id)) continue\n\t\t\t\t\t\t\tconst ids = wanted.get(parent.to) ?? new Set<string>()\n\t\t\t\t\t\t\tids.add(parent.id)\n\t\t\t\t\t\t\twanted.set(parent.to, ids)\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t\tfor (const [collection, ids] of wanted) {\n\t\t\t\t\t\tconst list = [...ids]\n\t\t\t\t\t\tfor (let start = 0; start < list.length; start += PARENT_LOOKUP_CHUNK) {\n\t\t\t\t\t\t\tconst part = list.slice(start, start + PARENT_LOOKUP_CHUNK)\n\t\t\t\t\t\t\tconst rows = await direct.query<{ id: string }>(\n\t\t\t\t\t\t\t\t`SELECT id FROM ${quoteIdent(collection)} WHERE id IN (${part.map(() => '?').join(', ')})`,\n\t\t\t\t\t\t\t\tpart,\n\t\t\t\t\t\t\t)\n\t\t\t\t\t\t\tconst known = parents.get(collection) ?? new Set<string>()\n\t\t\t\t\t\t\tfor (const row of rows) known.add(row.id)\n\t\t\t\t\t\t\tparents.set(collection, known)\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\tconst applyStep = (\n\t\t\t\t\top: Operation,\n\t\t\t\t\toptions: Parameters<RemoteApplyBatch['applyRemoteOperation']>[1],\n\t\t\t\t): Promise<ApplyResult> =>\n\t\t\t\t\tinSavepoint(async (step) => {\n\t\t\t\t\t\tif (!this.schema.collections[op.collection]) return 'skipped'\n\t\t\t\t\t\t// From here the collection's rows may change before the batch publishes.\n\t\t\t\t\t\tforeign?.touch(op.collection)\n\t\t\t\t\t\tconst startedAt = Date.now()\n\t\t\t\t\t\tconst position = options?.deliveryPosition\n\t\t\t\t\t\tlet outcome = await this.applyRemoteFoldedPrefetched(step, op, fold, prefetch, deferred)\n\t\t\t\t\t\tif (outcome === null) {\n\t\t\t\t\t\t\toutcome = await this.applyRemoteFoldedInTx(step, op, fold, position)\n\t\t\t\t\t\t\t// Whatever that route wrote, the cache does not know: the record is read\n\t\t\t\t\t\t\t// from the transaction from now on, and the operation's sequence number\n\t\t\t\t\t\t\t// is taken (a later operation of the same node and number is a conflict).\n\t\t\t\t\t\t\tprefetch.markDirty(op.collection, op.recordId)\n\t\t\t\t\t\t\tprefetch.noteAppended(op)\n\t\t\t\t\t\t}\n\t\t\t\t\t\tconst applied = outcome\n\t\t\t\t\t\tconst duration = Date.now() - startedAt\n\t\t\t\t\t\tconst result: ApplyResult = applied.duplicate ? 'duplicate' : 'applied'\n\t\t\t\t\t\tif (!applied.duplicate) {\n\t\t\t\t\t\t\tprobe = op\n\t\t\t\t\t\t\tif (op.type === 'insert') {\n\t\t\t\t\t\t\t\tconst known = parents.get(op.collection) ?? new Set<string>()\n\t\t\t\t\t\t\t\tknown.add(op.recordId)\n\t\t\t\t\t\t\t\tparents.set(op.collection, known)\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t}\n\t\t\t\t\t\teffects.push(() => {\n\t\t\t\t\t\t\tthis.publishRemoteApply(op, applied, options, duration)\n\t\t\t\t\t\t})\n\t\t\t\t\t\treturn result\n\t\t\t\t\t}, canPipeline(op))\n\t\t\t\tconst batch: RemoteApplyBatch = {\n\t\t\t\t\ttx,\n\t\t\t\t\tflush: flushGroup,\n\t\t\t\t\tprefetch: async (operations) => {\n\t\t\t\t\t\tawait prefetch.load(direct, operations)\n\t\t\t\t\t\tawait loadParents(operations)\n\t\t\t\t\t},\n\t\t\t\t\tapplyRemoteOperation: async (op, options) => {\n\t\t\t\t\t\tconst probeBefore = probe\n\t\t\t\t\t\ttry {\n\t\t\t\t\t\t\treturn await applyStep(op, options)\n\t\t\t\t\t\t} catch (error) {\n\t\t\t\t\t\t\t// The step is undone, so what the cache learned from it is wrong: the\n\t\t\t\t\t\t\t// record is read from the transaction from now on.\n\t\t\t\t\t\t\tprefetch.markDirty(op.collection, op.recordId)\n\t\t\t\t\t\t\tprefetch.noteAppended(op)\n\t\t\t\t\t\t\t// Nor may it prove the commit landed: a strict step sets the probe before\n\t\t\t\t\t\t\t// its flush, which can still fail and roll the step back.\n\t\t\t\t\t\t\tprobe = probeBefore\n\t\t\t\t\t\t\tthrow error\n\t\t\t\t\t\t}\n\t\t\t\t\t},\n\t\t\t\t\tapplyScopeRetraction: (collection, recordId, position) =>\n\t\t\t\t\t\tinSavepoint(async (step) => {\n\t\t\t\t\t\t\tif (!this.schema.collections[collection]) return\n\t\t\t\t\t\t\tprefetch.markDirty(collection, recordId)\n\t\t\t\t\t\t\tawait this.applyScopeRetractionInTx(step, collection, recordId, position)\n\t\t\t\t\t\t\teffects.push(() => this.subscriptionManager.invalidate(collection, [recordId]))\n\t\t\t\t\t\t}),\n\t\t\t\t\tapplyProvisionalSideEffects: async (parent, sideEffects) => {\n\t\t\t\t\t\tconst built = await this.buildProvisionalSideEffects(parent, sideEffects)\n\t\t\t\t\t\tif (built.length === 0) return 0\n\t\t\t\t\t\treturn inSavepoint(async (step) => {\n\t\t\t\t\t\t\tfor (const op of built) {\n\t\t\t\t\t\t\t\tprefetch.markDirty(op.collection, op.recordId)\n\t\t\t\t\t\t\t\tawait fold.applyProvisionalInTx(step, op, parent.id)\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\tconst touched = new Set(built.map((op) => op.collection))\n\t\t\t\t\t\t\teffects.push(() => {\n\t\t\t\t\t\t\t\tfor (const collection of touched) this.subscriptionManager.invalidate(collection)\n\t\t\t\t\t\t\t})\n\t\t\t\t\t\t\treturn built.length\n\t\t\t\t\t\t})\n\t\t\t\t\t},\n\t\t\t\t\tfindMaterializedRow: (collection, recordId) =>\n\t\t\t\t\t\tthis.findMaterializedRowIn(direct, collection, recordId),\n\t\t\t\t\tread: (collection) => this.readInTransaction(direct, collection),\n\t\t\t\t\tsaveInboundQuarantine: (entries, watermark) =>\n\t\t\t\t\t\tsaveUnappliedOperationsInTx(direct, entries, watermark),\n\t\t\t\t\tsaveDeliveryWatermark: (signature, watermark, completion) =>\n\t\t\t\t\t\tsaveDeliveryWatermarkInTx(direct, signature, watermark, completion),\n\t\t\t\t\tafterCommit: (effect) => {\n\t\t\t\t\t\teffects.push(effect)\n\t\t\t\t\t},\n\t\t\t\t}\n\t\t\t\tvalue = await fn(batch)\n\t\t\t\tawait flushGroup()\n\t\t\t\tif (deferred.length > 0) await fold.resolveDeferredPriors(tx, deferred)\n\t\t\t\tcompleted = true\n\t\t\t})\n\t\t} catch (error) {\n\t\t\tthis.reportStorageError(error)\n\t\t\t// The commit's outcome may be unknown (it rejected after `fn` finished, for example\n\t\t\t// a leader change cut the COMMIT's answer). When the batch's newest operation is in\n\t\t\t// the log the whole transaction landed (it is atomic): publish its effects and\n\t\t\t// return as committed, instead of letting the caller re-apply the batch operation\n\t\t\t// by operation as duplicates, which emit no `operation:applied` or merge trace\n\t\t\t// (M2). Otherwise it rolled back, or nothing of it can be proven: rethrow.\n\t\t\tconst newest: Operation | null = probe\n\t\t\tif (!(completed && newest !== null && (await this.commitLanded(newest)))) throw error\n\t\t}\n\t\tfor (const effect of effects) {\n\t\t\ttry {\n\t\t\t\teffect()\n\t\t\t} catch (error) {\n\t\t\t\t// The batch is committed: one failing listener must not keep the others (or\n\t\t\t\t// the caller's acknowledgement) from running.\n\t\t\t\tconsole.error('[kora] post-commit effect of a remote batch failed', error)\n\t\t\t}\n\t\t}\n\t\treturn { value: value as T }\n\t}\n\n\t/**\n\t * After a transaction that rejected although its body finished: whether `op`, which that\n\t * transaction added to the log, is in the log now (so the commit landed). A lookup that\n\t * itself fails proves nothing, so it answers false and the caller reports the original error.\n\t */\n\tprivate async commitLanded(op: Operation): Promise<boolean> {\n\t\ttry {\n\t\t\treturn await isOperationLogged(this.adapter, op.collection, op.id)\n\t\t} catch {\n\t\t\treturn false\n\t\t}\n\t}\n\n\t/** DevTools: every fold decision that was a conflict, plus one completion per merge. */\n\tprivate emitMergeTraces(op: Operation, traces: MergeTrace[]): void {\n\t\tif (!this.emitter || traces.length === 0) return\n\t\tconst first = traces[0] as MergeTrace\n\t\tthis.emitter.emit({ type: 'merge:started', operationA: first.operationA, operationB: op })\n\t\tfor (const trace of traces) this.emitter.emit({ type: 'merge:conflict', trace })\n\t\tthis.emitter.emit({ type: 'merge:completed', trace: first })\n\t}\n\n\t/**\n\t * A remote operation applied for a delivery whose position moved while it waited for the\n\t * database writes nothing: asked first thing inside the write transaction (the wait for\n\t * the adapter's mutex is unbounded), the transaction rolls back.\n\t */\n\tprivate assertDeliveryStillCurrent(operationId: string): void {\n\t\tconst isCurrent = this.deliveryPositions.get(operationId)?.isCurrent\n\t\tif (isCurrent !== undefined && !isCurrent()) throw new StaleStoreWrite()\n\t}\n\n\t/** The delivery position of a remote operation being applied, if known. */\n\tprivate deliveryPositionOf(\n\t\top: Operation,\n\t\toptions: ApplyRemoteOptions | undefined,\n\t): number | undefined {\n\t\treturn options?.deliveryPosition ?? this.deliveryPositions.get(op.id)?.position\n\t}\n\n\t/**\n\t * The columns of each collection that reference another collection's rows, as the\n\t * schema's tables declare them (`REFERENCES`): a write of one can fail on a missing parent.\n\t */\n\tprivate foreignKeysByCollection(): Map<string, Array<{ field: string; to: string }>> {\n\t\tif (this.foreignKeyIndex) return this.foreignKeyIndex\n\t\tconst index = new Map<string, Array<{ field: string; to: string }>>()\n\t\tfor (const relation of Object.values(this.schema.relations ?? {})) {\n\t\t\tconst list = index.get(relation.from) ?? []\n\t\t\tlist.push({ field: relation.field, to: relation.to })\n\t\t\tindex.set(relation.from, list)\n\t\t}\n\t\tthis.foreignKeyIndex = index\n\t\treturn index\n\t}\n\n\t/** The record fold, once the database's rows are fold materializations. */\n\tprivate activeFold(): RecordFolder | undefined {\n\t\treturn this.foldActive && this.folder ? this.folder : undefined\n\t}\n\n\t/**\n\t * The record's W7 fold state (null under legacy materialization or when the\n\t * record has none). For DevTools, tests and the server-comparison harness.\n\t */\n\tasync getFoldState(collection: string, recordId: string): Promise<FoldState | null> {\n\t\tthis.ensureOpen()\n\t\tconst fold = this.activeFold()\n\t\tif (!fold) return null\n\t\tlet state: FoldState | null = null\n\t\tawait this.adapter.transaction(async (tx) => {\n\t\t\tstate = await fold.loadState(tx, collection, recordId)\n\t\t})\n\t\treturn state\n\t}\n\n\t/** Whether rows are materialized by the W7 fold (false under `materialization: 'legacy'`). */\n\tisFoldMaterialized(): boolean {\n\t\treturn this.activeFold() !== undefined\n\t}\n\n\tprivate async readMeta(key: string): Promise<string | null> {\n\t\tconst rows = await this.adapter.query<MetaRow>('SELECT value FROM _kora_meta WHERE key = ?', [\n\t\t\tkey,\n\t\t])\n\t\treturn rows[0]?.value ?? null\n\t}\n\n\tprivate async writeMeta(key: string, value: string): Promise<void> {\n\t\tawait this.adapter.execute('INSERT OR REPLACE INTO _kora_meta (key, value) VALUES (?, ?)', [\n\t\t\tkey,\n\t\t\tvalue,\n\t\t])\n\t}\n\n\t/**\n\t * Write every genuine beta.12 clear of the op log into its logged body, once per\n\t * database (RT-83, RT-85): the fold folds bodies as written, so the clear must be in\n\t * the body. Records already materialized by the fold are re-folded.\n\t */\n\tprivate async ensureLegacyBodiesCanonical(): Promise<void> {\n\t\tconst folder = this.folder\n\t\tif (!folder) return\n\t\tif ((await this.readMeta(LEGACY_BODIES_META_KEY)) !== null) return\n\t\tconst rewritten = await canonicalizeLegacyLogBodies(this.adapter, this.schema, this.nodeId)\n\t\tif (rewritten.length > 0 && this.foldActive) {\n\t\t\tconst seen = new Set<string>()\n\t\t\tawait this.adapter.transaction(async (tx) => {\n\t\t\t\tfor (const { collection, recordId } of rewritten) {\n\t\t\t\t\tconst key = `${collection}\\u0000${recordId}`\n\t\t\t\t\tif (seen.has(key)) continue\n\t\t\t\t\tseen.add(key)\n\t\t\t\t\tawait folder.refoldInTx(tx, collection, recordId)\n\t\t\t\t}\n\t\t\t})\n\t\t}\n\t\tawait this.writeMeta(LEGACY_BODIES_META_KEY, String(rewritten.length))\n\t}\n\n\t/**\n\t * Make every row a materialization of its record's fold state (W7), once per\n\t * database and fold-state version. Runs after the W8 log-integrity scan: a\n\t * clean log is rebuilt with the fold; an incomplete (compacted) log rebuilds on\n\t * top of the rows as base snapshots; a log with quarantined rows is never\n\t * rebuilt from (rows are kept and become base snapshots), and\n\t * `store:rematerialized` reports which happened.\n\t */\n\tprivate async ensureMaterialization(forceSnapshot = false): Promise<void> {\n\t\tconst current = await this.readMeta(FOLD_MATERIALIZATION_META_KEY)\n\t\tif (!this.folder) {\n\t\t\tif (current !== FOLD_MATERIALIZATION_LEGACY) {\n\t\t\t\tawait this.writeMeta(FOLD_MATERIALIZATION_META_KEY, FOLD_MATERIALIZATION_LEGACY)\n\t\t\t}\n\t\t\treturn\n\t\t}\n\t\tif (current === FOLD_MATERIALIZATION_CURRENT) {\n\t\t\tthis.foldActive = true\n\t\t\tawait this.ensureFoldPlan()\n\t\t\treturn\n\t\t}\n\t\tconst report = await this.scanLog('full')\n\t\t// Only the records that own a quarantined row are kept as they are (RT-68); the\n\t\t// rest are rebuilt from a log that is complete for them unless it was compacted\n\t\t// or has holes.\n\t\tconst kept = await loadQuarantinedRecords(this.adapter)\n\t\t// A hole in an own node's sequence that a quarantined row explains belongs to\n\t\t// that row's record (kept above), not to the whole log.\n\t\tconst quarantinedSeqs = new Set(\n\t\t\treport.quarantined.map((row) => `${row.nodeId ?? ''}\\u0000${row.sequenceNumber ?? ''}`),\n\t\t)\n\t\tconst unexplainedGaps = report.gaps.filter((gap) => {\n\t\t\tfor (let s = gap.from; s <= gap.to; s++) {\n\t\t\t\tif (!quarantinedSeqs.has(`${gap.nodeId}\\u0000${s}`)) return true\n\t\t\t}\n\t\t\treturn false\n\t\t})\n\t\tconst mode: Exclude<RematerializationMode, 'kept'> =\n\t\t\t!forceSnapshot && unexplainedGaps.length === 0 && report.compactedAt === null\n\t\t\t\t? 'log'\n\t\t\t\t: 'snapshot+log'\n\t\tconst result = await rematerializeDatabase(this.adapter, this.schema, this.folder, mode, kept)\n\t\tawait this.writeMeta(FOLD_MATERIALIZATION_META_KEY, FOLD_MATERIALIZATION_CURRENT)\n\t\tawait this.writeMeta(\n\t\t\tFOLD_PLAN_META_KEY,\n\t\t\tJSON.stringify(foldPlanFingerprints(this.schema, this.operationTransforms)),\n\t\t)\n\t\tthis.foldActive = true\n\t\tif (result.snapshots > 0) await this.requestSnapshotResync()\n\t\tif (result.changedRows > 0) {\n\t\t\t// Other tabs on this database hear about it once the bus is wired (RT-98).\n\t\t\tfor (const collection of Object.keys(this.schema.collections)) {\n\t\t\t\tthis.subscriptionManager.invalidate(collection)\n\t\t\t}\n\t\t}\n\t\tif (result.records > 0) {\n\t\t\tthis.emitter?.emit({\n\t\t\t\ttype: 'store:rematerialized',\n\t\t\t\tdbName: this.dbName,\n\t\t\t\tmode: result.mode,\n\t\t\t\trecords: result.records,\n\t\t\t\tchangedRows: result.changedRows,\n\t\t\t\tmessage:\n\t\t\t\t\tresult.mode === 'kept'\n\t\t\t\t\t\t? `Operation log of \"${this.dbName}\" has quarantined rows: the records that own them were kept as they were (row snapshots); ${result.records} record(s) re-materialized, ${result.changedRows} row(s) changed.`\n\t\t\t\t\t\t: `Re-materialized ${result.records} record(s) of \"${this.dbName}\" with the per-field fold (${result.mode}); ${result.changedRows} row(s) changed.`,\n\t\t\t})\n\t\t}\n\t}\n\n\t/**\n\t * Refuse to open when a schema version in the local operation log has no transform\n\t * path to the current schema (RT-103). Operations of a NEWER schema (authored by an\n\t * upgraded peer) are not checked: they are kept aside until this device upgrades.\n\t */\n\tprivate async assertTransformCoverage(): Promise<void> {\n\t\tconst transforms = this.operationTransforms\n\t\tif (transforms === undefined || transforms.length === 0) return\n\t\tconst versions = new Set<number>()\n\t\tfor (const collection of Object.keys(this.schema.collections)) {\n\t\t\tconst rows = await this.adapter.query<{ v: number }>(\n\t\t\t\t`SELECT DISTINCT schema_version AS v FROM ${quoteIdent(`_kora_ops_${collection}`)}`,\n\t\t\t)\n\t\t\tfor (const row of rows) {\n\t\t\t\tconst version = Number(row.v)\n\t\t\t\tif (version < this.schema.version) versions.add(version)\n\t\t\t}\n\t\t}\n\t\tassertOperationTransformCoverage(\n\t\t\tversions,\n\t\t\tthis.schema.version,\n\t\t\ttransforms,\n\t\t\t`local database \"${this.dbName}\"`,\n\t\t)\n\t}\n\n\t/**\n\t * Re-fold the records of every collection whose fold plan changed since the rows\n\t * were materialized (RT-63): a field that became `merge('counter')`, an array that\n\t * became append-only, a new or edited resolver. Their stored states hold fields of\n\t * the old kind, which the fold refuses (`FoldStateError`). Each record is rebuilt\n\t * from its log with the new plan; compacted bases and row snapshots are adapted\n\t * (a re-planned field restarts from its materialized value at its version). The\n\t * client's equivalent of the server stores' `fold_plan_fingerprint`.\n\t */\n\tprivate async ensureFoldPlan(): Promise<void> {\n\t\tconst folder = this.folder\n\t\tif (!folder) return\n\t\tconst current = foldPlanFingerprints(this.schema, this.operationTransforms)\n\t\tconst storedRaw = await this.readMeta(FOLD_PLAN_META_KEY)\n\t\tlet changed: string[]\n\t\tif (storedRaw === null) {\n\t\t\t// Materialized before the fingerprint was recorded: re-fold the collections\n\t\t\t// whose stored states actually hold a field of another kind.\n\t\t\tchanged = await collectionsWithMismatchedStates(this.adapter, this.schema)\n\t\t} else {\n\t\t\tlet stored: Record<string, unknown> = {}\n\t\t\ttry {\n\t\t\t\tstored = JSON.parse(storedRaw) as Record<string, unknown>\n\t\t\t} catch {\n\t\t\t\tstored = {}\n\t\t\t}\n\t\t\tchanged = Object.keys(current).filter((name) => stored[name] !== current[name])\n\t\t}\n\t\tif (changed.length > 0) {\n\t\t\tconst result = await rematerializeDatabase(\n\t\t\t\tthis.adapter,\n\t\t\t\tthis.schema,\n\t\t\t\tfolder,\n\t\t\t\t'log',\n\t\t\t\tundefined,\n\t\t\t\tchanged,\n\t\t\t)\n\t\t\tif (result.snapshots > 0) await this.requestSnapshotResync()\n\t\t\tfor (const collection of changed) this.subscriptionManager.invalidate(collection)\n\t\t\tthis.emitter?.emit({\n\t\t\t\ttype: 'store:rematerialized',\n\t\t\t\tdbName: this.dbName,\n\t\t\t\tmode: result.mode,\n\t\t\t\trecords: result.records,\n\t\t\t\tchangedRows: result.changedRows,\n\t\t\t\tmessage: `The fold plan of ${changed.map((name) => `\"${name}\"`).join(', ')} changed (schema): re-folded ${result.records} record(s) of \"${this.dbName}\"; ${result.changedRows} row(s) changed.`,\n\t\t\t})\n\t\t}\n\t\tawait this.writeMeta(FOLD_PLAN_META_KEY, JSON.stringify(current))\n\t}\n\n\t/**\n\t * Row snapshots were created (RT-68): ask the sync server for a full resync (the\n\t * delivery watermarks restart at 0, as after a restore), so each such record gets\n\t * its complete history back; {@link settleSnapshotRecords} then drops the\n\t * snapshots once the resync has caught up.\n\t */\n\tprivate async requestSnapshotResync(): Promise<void> {\n\t\t// Every watermark restarts at 0 and the stream replays: a full resync (I12).\n\t\tthis.overlayController?.clear()\n\t\tawait this.clearSeedsAtClearPoint('a full resync')\n\t\tawait this.adapter.transaction(async (tx) => {\n\t\t\tawait tx.execute('UPDATE _kora_meta SET value = ? WHERE key = ? OR key LIKE ?', [\n\t\t\t\t'0',\n\t\t\t\tDELIVERY_WATERMARK_META_KEY,\n\t\t\t\t`${DELIVERY_WATERMARK_META_KEY}:%`,\n\t\t\t])\n\t\t\tawait tx.execute('DELETE FROM _kora_meta WHERE key = ?', [DELTA_CURSOR_META_KEY])\n\t\t\tawait tx.execute('INSERT OR REPLACE INTO _kora_meta (key, value) VALUES (?, ?)', [\n\t\t\t\tSNAPSHOT_RESYNC_META_KEY,\n\t\t\t\t'pending',\n\t\t\t])\n\t\t})\n\t}\n\n\t/**\n\t * Records whose state still folds against a row snapshot (approximate: a late\n\t * concurrent write older than a field's version is not folded, RT-68).\n\t */\n\tasync getSnapshotRecords(): Promise<Array<{ collection: string; recordId: string }>> {\n\t\tthis.ensureOpen()\n\t\tconst folder = this.folder\n\t\tif (!folder) return []\n\t\tlet out: Array<{ collection: string; recordId: string }> = []\n\t\tawait this.adapter.transaction(async (tx) => {\n\t\t\tout = await folder.listSnapshotRecords(tx)\n\t\t})\n\t\treturn out\n\t}\n\n\t/**\n\t * Called by sync when a delivery stream has caught up (its final batch fully\n\t * applied). After the full resync {@link requestSnapshotResync} asked for, every\n\t * row-snapshot record whose insert is back in the log is re-folded from its\n\t * complete history and stops being approximate (RT-68). Also retires the\n\t * provisional cascades of remote deletes (RT-69): the server's own copies were\n\t * delivered by now, and any it did not derive must not stay applied locally.\n\t *\n\t * With `provisionalOnly` only the provisional cascades are retired (RT-93: a stream\n\t * batch from a server that derives no cascades, which is not the end of a resync).\n\t *\n\t * @param options - `provisionalOnly`: leave row snapshots for the next catch-up\n\t * @returns How many snapshots were dropped\n\t */\n\tasync settleAfterCatchUp(options: { provisionalOnly?: boolean } = {}): Promise<number> {\n\t\tthis.ensureOpen()\n\t\tconst folder = this.activeFold()\n\t\tif (!folder) return 0\n\t\tconst pending =\n\t\t\toptions.provisionalOnly !== true &&\n\t\t\t(await this.readMeta(SNAPSHOT_RESYNC_META_KEY)) === 'pending'\n\t\tlet settled = 0\n\t\tconst touched = new Set<string>()\n\t\tawait this.adapter.transaction(async (tx) => {\n\t\t\tfor (const { collection, recordId } of await folder.listProvisionalRecords(tx)) {\n\t\t\t\tawait folder.deleteProvisional(tx, collection, recordId, null)\n\t\t\t\tawait folder.refoldInTx(tx, collection, recordId)\n\t\t\t\ttouched.add(collection)\n\t\t\t}\n\t\t\tif (pending) {\n\t\t\t\tfor (const { collection, recordId } of await folder.listSnapshotRecords(tx)) {\n\t\t\t\t\tif (await folder.settleSnapshotInTx(tx, collection, recordId)) {\n\t\t\t\t\t\tsettled += 1\n\t\t\t\t\t\ttouched.add(collection)\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\tawait tx.execute('DELETE FROM _kora_meta WHERE key = ?', [SNAPSHOT_RESYNC_META_KEY])\n\t\t\t}\n\t\t})\n\t\tfor (const collection of touched) this.subscriptionManager.invalidate(collection)\n\t\treturn settled\n\t}\n\n\t/**\n\t * Apply the cascades / set-nulls of a REMOTE delete as local-only provisional\n\t * effects (RT-69): folded into the children like operations, but never logged,\n\t * sequenced or queued for upload. The server derives and relays its own copy;\n\t * when it arrives (same parent, same record) the provisional effect is retired.\n\t *\n\t * @param parent - The remote delete\n\t * @param effects - Its side effects, as the referential check derived them\n\t */\n\tasync applyProvisionalSideEffects(\n\t\tparent: Operation,\n\t\teffects: ReadonlyArray<ProvisionalSideEffect>,\n\t): Promise<number> {\n\t\tthis.ensureOpen()\n\t\tconst folder = this.activeFold()\n\t\tif (!folder || effects.length === 0) return 0\n\t\tconst touched = new Set<string>()\n\t\tlet applied = 0\n\t\tconst built = await this.buildProvisionalSideEffects(parent, effects)\n\t\tawait this.adapter.transaction(async (tx) => {\n\t\t\tfor (const op of built) {\n\t\t\t\tawait folder.applyProvisionalInTx(tx, op, parent.id)\n\t\t\t\ttouched.add(op.collection)\n\t\t\t\tapplied += 1\n\t\t\t}\n\t\t})\n\t\tfor (const collection of touched) this.subscriptionManager.invalidate(collection)\n\t\treturn applied\n\t}\n\n\t/** The provisional operations of a remote delete's side effects (RT-69). */\n\tprivate async buildProvisionalSideEffects(\n\t\tparent: Operation,\n\t\teffects: ReadonlyArray<ProvisionalSideEffect>,\n\t): Promise<Operation[]> {\n\t\t// Stamped right after the parent (its HLC, next logical ticks), exactly like the\n\t\t// server's copy, so a write to the child later than the delete still wins.\n\t\tconst clock = new HybridLogicalClock(PROVISIONAL_NODE_ID, {\n\t\t\tnow: () => parent.timestamp.wallTime,\n\t\t})\n\t\tclock.advanceTo(parent.timestamp)\n\t\tconst built: Operation[] = []\n\t\tfor (const effect of effects) {\n\t\t\tif (!this.schema.collections[effect.collection]) continue\n\t\t\tconst op: Operation = {\n\t\t\t\tid: await deriveSideEffectOpId(parent.id, `provisional/${effect.ruleId}`, effect.recordId),\n\t\t\t\tnodeId: PROVISIONAL_NODE_ID,\n\t\t\t\ttype: effect.type,\n\t\t\t\tcollection: effect.collection,\n\t\t\t\trecordId: effect.recordId,\n\t\t\t\tdata: effect.type === 'delete' ? null : effect.data,\n\t\t\t\tpreviousData: effect.type === 'delete' ? null : effect.previousData,\n\t\t\t\ttimestamp: clock.now(),\n\t\t\t\tsequenceNumber: 0,\n\t\t\t\tcausalDeps: [parent.id],\n\t\t\t\tschemaVersion: this.schema.version,\n\t\t\t}\n\t\t\tbuilt.push(op)\n\t\t}\n\t\treturn built\n\t}\n\n\t/**\n\t * Node ids whose writes win `merge('server-authoritative')` fields (the server's,\n\t * from the sync handshake). Every `kora:server:` id is authoritative by prefix, so\n\t * only explicit ids (legacy server node ids, configured extras) are kept: the device\n\t * persists the UNION of every explicit id it has learned and never drops one (RT-75).\n\t * Handshakes differ per server instance (each lists what it knows), so a list that\n\t * omits an id is not a revocation.\n\t *\n\t * Revocation is explicit (RT-81): ids a handshake lists in `revokedAuthoritativeNodeIds`\n\t * are removed from the union, persisted as revoked, and never learned again. Records\n\t * of collections with such fields are re-folded only when the explicit set changes\n\t * (grows, or loses a revoked id).\n\t *\n\t * @param nodeIds - The server's authoritative node ids (one handshake's list)\n\t * @param revokedNodeIds - Explicit ids the server revoked (one handshake's list)\n\t */\n\tasync setAuthoritativeNodeIds(\n\t\tnodeIds: readonly string[],\n\t\trevokedNodeIds: readonly string[] = [],\n\t): Promise<void> {\n\t\tthis.ensureOpen()\n\t\tconst folder = this.folder\n\t\tconst persisted = await loadAuthoritativeNodeIds(this.adapter)\n\t\tconst persistedRevoked = await loadRevokedAuthoritativeNodeIds(this.adapter)\n\t\tconst revoked = new Set(\n\t\t\t[...persistedRevoked, ...revokedNodeIds].filter((id) => !isServerNodeId(id)),\n\t\t)\n\t\tif (revoked.size > persistedRevoked.length) {\n\t\t\tawait saveRevokedAuthoritativeNodeIds(this.adapter, [...revoked].sort())\n\t\t}\n\t\tconst previous = new Set(\n\t\t\t[...(persisted ?? []), ...(folder ? folder.getAuthoritativeNodeIds() : [])].filter(\n\t\t\t\t(id) => !isServerNodeId(id),\n\t\t\t),\n\t\t)\n\t\tconst known = new Set([...previous].filter((id) => !revoked.has(id)))\n\t\tconst dropped = previous.size - known.size\n\t\tconst learned = [...new Set(nodeIds)].filter(\n\t\t\t(id) => !isServerNodeId(id) && !known.has(id) && !revoked.has(id),\n\t\t)\n\t\tconst next = [...known, ...learned].sort()\n\t\tconst stored = persisted === null ? null : [...persisted].sort()\n\t\tif (stored === null || JSON.stringify(stored) !== JSON.stringify(next)) {\n\t\t\t// One persisted list (`sync_authoritative_node_ids`) serves the fold and the\n\t\t\t// sync engine's verification exemptions, so they can never disagree.\n\t\t\tawait saveAuthoritativeNodeIds(this.adapter, next)\n\t\t}\n\t\tif (!folder) return\n\t\tfolder.setAuthoritativeNodeIds(next)\n\t\tif (learned.length === 0 && dropped === 0) return\n\t\tconst fold = this.activeFold()\n\t\tif (!fold) return\n\t\tfor (const collection of Object.keys(this.schema.collections)) {\n\t\t\tif (!fold.hasAuthoritativeFields(collection)) continue\n\t\t\tconst ids = await this.adapter.query<{ record_id: string }>(\n\t\t\t\t`SELECT record_id FROM ${FOLD_STATE_TABLE} WHERE collection = ?`,\n\t\t\t\t[collection],\n\t\t\t)\n\t\t\tawait this.adapter.transaction(async (tx) => {\n\t\t\t\tfor (const { record_id } of ids) await fold.refoldInTx(tx, collection, record_id)\n\t\t\t})\n\t\t\tthis.subscriptionManager.invalidate(collection)\n\t\t}\n\t}\n\n\t/**\n\t * A log rewrite's in-transaction step (rebase, rotation, re-author): re-fold the records\n\t * of the rewritten operations in the transaction that rewrites them, so a crash can never\n\t * leave a fold state with the old stamps or ids. `more` runs first in the same\n\t * transaction. `touched` collects the records, for invalidating views after the commit.\n\t */\n\tprivate refoldInRewrite(\n\t\ttouched: Map<string, Set<string>>,\n\t\tmore?: (tx: Transaction) => Promise<void>,\n\t): (tx: Transaction, operations: readonly Operation[]) => Promise<void> {\n\t\treturn async (tx, operations) => {\n\t\t\tawait more?.(tx)\n\t\t\tconst fold = this.activeFold()\n\t\t\tif (!fold) return\n\t\t\tfor (const operation of operations) {\n\t\t\t\tconst records = touched.get(operation.collection) ?? new Set<string>()\n\t\t\t\trecords.add(operation.recordId)\n\t\t\t\ttouched.set(operation.collection, records)\n\t\t\t}\n\t\t\tfor (const [collection, records] of touched) {\n\t\t\t\tfor (const recordId of records) await fold.refoldInTx(tx, collection, recordId)\n\t\t\t}\n\t\t}\n\t}\n\n\t/** Views over records a rewrite re-folded in its transaction read them again. */\n\tprivate invalidateRefolded(touched: Map<string, Set<string>>): void {\n\t\tfor (const [collection, records] of touched) {\n\t\t\tthis.subscriptionManager.invalidate(collection, [...records])\n\t\t}\n\t}\n\n\t/**\n\t * Re-fold the records of these operations from base + log (W7 exclusion: an\n\t * operation with a terminal-rejection marker is left out).\n\t */\n\tprivate async refoldRecordsOf(operationIds: readonly string[]): Promise<void> {\n\t\tconst fold = this.activeFold()\n\t\tif (!fold || operationIds.length === 0) return\n\t\tconst touched = new Map<string, Set<string>>()\n\t\tfor (const collection of Object.keys(this.schema.collections)) {\n\t\t\tconst table = quoteIdent(`_kora_ops_${collection}`)\n\t\t\tfor (let i = 0; i < operationIds.length; i += 500) {\n\t\t\t\tconst chunk = operationIds.slice(i, i + 500)\n\t\t\t\tconst rows = await this.adapter.query<{ record_id: string }>(\n\t\t\t\t\t`SELECT DISTINCT record_id FROM ${table} WHERE id IN (${chunk.map(() => '?').join(', ')})`,\n\t\t\t\t\tchunk,\n\t\t\t\t)\n\t\t\t\tfor (const row of rows) {\n\t\t\t\t\tconst set = touched.get(collection) ?? new Set<string>()\n\t\t\t\t\tset.add(row.record_id)\n\t\t\t\t\ttouched.set(collection, set)\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\tif (touched.size === 0) return\n\t\tawait this.adapter.transaction(async (tx) => {\n\t\t\tfor (const [collection, records] of touched) {\n\t\t\t\tfor (const recordId of records) await fold.refoldInTx(tx, collection, recordId)\n\t\t\t}\n\t\t})\n\t\tfor (const [collection, records] of touched) {\n\t\t\tthis.subscriptionManager.invalidate(collection, [...records])\n\t\t}\n\t}\n\n\t/**\n\t * Append a remote operation to the log. If another operation of the same node\n\t * already holds its sequence number (a beta.12 device could produce such\n\t * pairs), the log keeps the existing row and this one is recorded in the\n\t * sequence-conflicts table, where dedup and record folds still see it.\n\t */\n\tprivate async appendRemoteOperationRow(\n\t\ttx: Transaction,\n\t\top: Operation,\n\t\t/**\n\t\t * The caller read (C3b) that no node of this database authored `op` and that no\n\t\t * operation of its node holds its sequence number: both checks are skipped.\n\t\t */\n\t\tknownFresh = false,\n\t): Promise<void> {\n\t\t// Received under one of this database's own node ids (a beta.12 shared browser gave\n\t\t// several users' databases one node): another database's write, never re-authored here.\n\t\tif (!knownFresh) await noteReceivedUnderLocalNode(tx, op.nodeId, op.id)\n\t\tconst table = quoteIdent(`_kora_ops_${op.collection}`)\n\t\tconst holder = knownFresh\n\t\t\t? []\n\t\t\t: await tx.query<{ id: string }>(\n\t\t\t\t\t`SELECT id FROM ${table} WHERE node_id = ? AND sequence_number = ?`,\n\t\t\t\t\t[op.nodeId, op.sequenceNumber],\n\t\t\t\t)\n\t\tconst opRow = serializeOperation(op)\n\t\tif (holder.length > 0) {\n\t\t\tawait insertConflictRow(\n\t\t\t\ttx,\n\t\t\t\top.collection,\n\t\t\t\topRow,\n\t\t\t\t'remote-sequence-conflict',\n\t\t\t\tnull,\n\t\t\t\tnull,\n\t\t\t\tDate.now(),\n\t\t\t)\n\t\t\treturn\n\t\t}\n\t\tconst opInsert = buildInsertQuery(\n\t\t\t`_kora_ops_${op.collection}`,\n\t\t\topRow as unknown as Record<string, unknown>,\n\t\t)\n\t\tawait tx.execute(opInsert.sql, opInsert.params)\n\t}\n\n\t/**\n\t * Record where in the delivery stream an operation the sync engine is about to apply\n\t * was delivered (`replay`: it is a quarantine replay), or clear it (`null`). The\n\t * remote apply of that operation decides a retracted record's visibility by it\n\t * (scopeVisibilityAfter). Keyed by operation id, so side effects the apply derives\n\t * for other records never inherit it.\n\t */\n\tnoteDeliveryPosition(\n\t\toperationId: string,\n\t\tposition: { position?: number; replay: boolean; isCurrent?: () => boolean } | null,\n\t): void {\n\t\tif (position === null) this.deliveryPositions.delete(operationId)\n\t\telse this.deliveryPositions.set(operationId, position)\n\t}\n\n\t/**\n\t * A delivery run starts at `watermark` (every handshake). Everything a run up to the\n\t * watermark positioned is at most `watermark + 0.5` (a scope entry at the watermark's\n\t * own sequence). Anything above was positioned by a run that went further: the stream\n\t * restarted lower (another view, a server rollback, a forced full resync). Retraction\n\t * markers above move to `watermark + 0.25` and quarantined operations above to\n\t * `watermark`, so they come before everything the new run delivers: an operation it\n\t * delivers shows a record again, and a quarantined one stays behind the retraction it\n\t * came before. A resumed stream moves nothing.\n\t */\n\tasync rebaseDeliveryRun(watermark: number): Promise<void> {\n\t\tthis.ensureOpen()\n\t\tconst ceiling = watermark + 0.5\n\t\tawait this.adapter.execute(\n\t\t\t'UPDATE _kora_scope_retractions SET position = ? WHERE position IS NOT NULL AND position > ?',\n\t\t\t[watermark + 0.25, ceiling],\n\t\t)\n\t\tawait rebaseUnappliedOperations(this.adapter, watermark, ceiling)\n\t}\n\n\t/**\n\t * Hide a record from this client's authorized materialized view. This writes no\n\t * replicated operation and therefore cannot be mistaken for a domain deletion.\n\t * The marker records `position`, where in delivery order the record was hidden: only\n\t * an operation delivered after it shows the record again (unknown: see\n\t * scopeVisibilityAfter).\n\t */\n\tasync applyScopeRetraction(\n\t\tcollection: string,\n\t\trecordId: string,\n\t\tposition?: number,\n\t\toptions: { isCurrent?: () => boolean } = {},\n\t): Promise<boolean> {\n\t\tthis.ensureOpen()\n\t\tif (!this.schema.collections[collection]) return true\n\t\tlet applied = true\n\t\ttry {\n\t\t\tawait this.adapter.transaction(async (tx) => {\n\t\t\t\t// The transaction waits for the adapter's mutex, an unbounded wait: whether the delivery\n\t\t\t\t// the hide is for still stands is asked inside it, before the first write. (The check\n\t\t\t\t// before the commit rolls back everything stale on its own; this one saves the writes.)\n\t\t\t\tif (options.isCurrent && !options.isCurrent()) {\n\t\t\t\t\tapplied = false\n\t\t\t\t\treturn\n\t\t\t\t}\n\t\t\t\tawait this.applyScopeRetractionInTx(tx, collection, recordId, position)\n\t\t\t\t// And again before the commit: the position can move while the writes ran, and the\n\t\t\t\t// hide then rolls back (a hide of the previous view must not outlive it).\n\t\t\t\tif (options.isCurrent && !options.isCurrent()) throw new StaleStoreWrite()\n\t\t\t})\n\t\t} catch (error) {\n\t\t\tif (!(error instanceof StaleStoreWrite)) throw error\n\t\t\tapplied = false\n\t\t}\n\t\tif (applied) this.subscriptionManager.invalidate(collection, [recordId])\n\t\treturn applied\n\t}\n\n\t/** The writes of {@link applyScopeRetraction}, through `tx`. */\n\tprivate async applyScopeRetractionInTx(\n\t\ttx: Transaction,\n\t\tcollection: string,\n\t\trecordId: string,\n\t\tposition: number | undefined,\n\t): Promise<void> {\n\t\tawait tx.execute(`UPDATE ${quoteIdent(collection)} SET _deleted = 1 WHERE id = ?`, [recordId])\n\t\t// The later of two known positions holds (a re-sent earlier retraction never moves\n\t\t// it back); an unknown one makes the order unknown.\n\t\tawait tx.execute(\n\t\t\t`INSERT INTO _kora_scope_retractions (collection, record_id, position) VALUES (?, ?, ?)\n\t\t\t\tON CONFLICT (collection, record_id) DO UPDATE SET position = CASE\n\t\t\t\t\tWHEN excluded.position IS NULL OR _kora_scope_retractions.position IS NULL THEN excluded.position\n\t\t\t\t\tELSE MAX(_kora_scope_retractions.position, excluded.position) END`,\n\t\t\t[collection, recordId, position ?? null],\n\t\t)\n\t}\n\n\t/**\n\t * Hide every live row of `collection` outside `scope` (null: the whole collection),\n\t * except the records in `keep` (records with unsent local operations). Judged on\n\t * local values. Returns the ids hidden.\n\t *\n\t * A kept record outside the scope is remembered (in `_kora_meta`, so a restart keeps\n\t * it): {@link recheckAccessNarrowing} hides it once its operations are refused.\n\t */\n\tasync applyCollectionNarrowing(\n\t\tcollection: string,\n\t\tscope: Record<string, unknown> | null,\n\t\tkeep: ReadonlySet<string>,\n\t\tposition?: number,\n\t\toptions: { isCurrent?: () => boolean; view?: string } = {},\n\t): Promise<string[]> {\n\t\tthis.ensureOpen()\n\t\tconst definition = this.schema.collections[collection]\n\t\tif (!definition) return []\n\t\t// Every await below is a place the delivery position can move. The whole narrowing (every\n\t\t// hide and the record of what it kept) is one transaction that asks first thing inside it,\n\t\t// and once more before it commits, whether the position it is for still stands: a narrowing\n\t\t// for a position that moved changes nothing, and none of it is left half applied.\n\t\tconst current = (): boolean => options.isCurrent?.() !== false\n\t\tconst rows = await this.adapter.query<RawCollectionRow>(\n\t\t\t`SELECT * FROM ${quoteIdent(collection)} WHERE _deleted = 0`,\n\t\t)\n\t\tif (!current()) return []\n\t\tconst retracted: string[] = []\n\t\tconst kept: string[] = []\n\t\tfor (const row of rows) {\n\t\t\tconst record = deserializeRecord(row, definition.fields)\n\t\t\tconst recordId = String(record.id)\n\t\t\tif (scope !== null && recordMatchesCollectionScope(record, scope)) continue\n\t\t\tif (keep.has(recordId)) {\n\t\t\t\tkept.push(recordId)\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\tretracted.push(recordId)\n\t\t}\n\t\tconst cache = await this.loadKeptOutsideNarrowing()\n\t\tlet nextState: KeptOutsideNarrowing | null = null\n\t\ttry {\n\t\t\tawait this.adapter.transaction(async (tx) => {\n\t\t\t\tif (!current()) throw new StaleStoreWrite()\n\t\t\t\tfor (const recordId of retracted) {\n\t\t\t\t\tawait this.applyScopeRetractionInTx(tx, collection, recordId, position)\n\t\t\t\t}\n\t\t\t\t// Read in the same turn as the write that stores it: a deferral recorded while the\n\t\t\t\t// hides ran is part of what is kept.\n\t\t\t\tconst deferred = cache.get(collection)?.retracted ?? []\n\t\t\t\tnextState =\n\t\t\t\t\tkept.length > 0 || deferred.length > 0\n\t\t\t\t\t\t? {\n\t\t\t\t\t\t\t\tscope,\n\t\t\t\t\t\t\t\tkept,\n\t\t\t\t\t\t\t\tretracted: deferred,\n\t\t\t\t\t\t\t\t...(options.view !== undefined ? { view: options.view } : {}),\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t: null\n\t\t\t\tawait this.writeKeptOutsideNarrowingInTx(tx, collection, nextState)\n\t\t\t\tif (!current()) throw new StaleStoreWrite()\n\t\t\t})\n\t\t} catch (error) {\n\t\t\tif (error instanceof StaleStoreWrite) return []\n\t\t\tthrow error\n\t\t}\n\t\tif (nextState === null) cache.delete(collection)\n\t\telse cache.set(collection, nextState)\n\t\tif (retracted.length > 0) this.subscriptionManager.invalidate(collection, retracted)\n\t\treturn retracted\n\t}\n\n\t/**\n\t * Defer a scope retraction of a record of an access collection while the record has\n\t * unsent writes: they upload and the server judges them, and the record is hidden\n\t * once none is pending ({@link recheckAccessNarrowing}). Returns false (retract now)\n\t * for any other collection. With `isCurrent`, nothing is recorded for a delivery whose\n\t * position moved (asked inside the transaction that writes it).\n\t */\n\tasync deferScopeRetraction(\n\t\tcollection: string,\n\t\trecordId: string,\n\t\toptions: { isCurrent?: () => boolean } = {},\n\t): Promise<boolean> {\n\t\tthis.ensureOpen()\n\t\tif (!this.schema.access?.collections[collection]) return false\n\t\tconst cache = await this.loadKeptOutsideNarrowing()\n\t\tconst current = (): boolean => options.isCurrent?.() !== false\n\t\tlet recorded: KeptOutsideNarrowing | null = null\n\t\ttry {\n\t\t\tawait this.adapter.transaction(async (tx) => {\n\t\t\t\tif (!current()) throw new StaleStoreWrite()\n\t\t\t\tconst state = cache.get(collection) ?? { scope: null, kept: [], retracted: [] }\n\t\t\t\tconst retracted = state.retracted ?? []\n\t\t\t\tif (retracted.includes(recordId)) return\n\t\t\t\trecorded = { ...state, retracted: [...retracted, recordId] }\n\t\t\t\tawait this.writeKeptOutsideNarrowingInTx(tx, collection, recorded)\n\t\t\t\tif (!current()) throw new StaleStoreWrite()\n\t\t\t})\n\t\t} catch (error) {\n\t\t\t// The caller must not hide the record either: report it as deferred.\n\t\t\tif (error instanceof StaleStoreWrite) return true\n\t\t\tthrow error\n\t\t}\n\t\tif (recorded !== null) cache.set(collection, recorded)\n\t\treturn true\n\t}\n\n\t/**\n\t * Hide the records an access narrowing kept for their unsent operations once none of\n\t * their operations is pending any more (refused, or quarantined) and they are still\n\t * outside the narrowed scope. Returns the records hidden.\n\t *\n\t * @param pending - The record ids of a collection that still have unsent operations\n\t */\n\tasync recheckAccessNarrowing(\n\t\tpending: (collection: string) => ReadonlySet<string>,\n\t\toptions: { retractedOnly?: boolean; position?: number; view?: string } = {},\n\t): Promise<Array<{ collection: string; recordId: string }>> {\n\t\tthis.ensureOpen()\n\t\tconst hidden: Array<{ collection: string; recordId: string }> = []\n\t\tfor (const [collection, state] of await this.loadKeptOutsideNarrowing()) {\n\t\t\tconst definition = this.schema.collections[collection]\n\t\t\tconst stillPending = pending(collection)\n\t\t\tconst live = async (recordId: string): Promise<Record<string, unknown> | null> => {\n\t\t\t\tif (!definition) return null\n\t\t\t\tconst rows = await this.adapter.query<RawCollectionRow>(\n\t\t\t\t\t`SELECT * FROM ${quoteIdent(collection)} WHERE id = ? AND _deleted = 0`,\n\t\t\t\t\t[recordId],\n\t\t\t\t)\n\t\t\t\tconst row = rows[0]\n\t\t\t\treturn row ? deserializeRecord(row, definition.fields) : null\n\t\t\t}\n\t\t\t// Records the server retracted: hidden once nothing of theirs is pending, whatever\n\t\t\t// became of the writes (an accepted write does not make a record readable).\n\t\t\tconst retracted: string[] = []\n\t\t\tfor (const recordId of state.retracted ?? []) {\n\t\t\t\tif (stillPending.has(recordId)) {\n\t\t\t\t\tretracted.push(recordId)\n\t\t\t\t\tcontinue\n\t\t\t\t}\n\t\t\t\tif (await live(recordId)) {\n\t\t\t\t\tawait this.applyScopeRetraction(collection, recordId, options.position)\n\t\t\t\t\thidden.push({ collection, recordId })\n\t\t\t\t}\n\t\t\t}\n\t\t\t// Records a narrowing kept: judged against it once their writes were refused.\n\t\t\tconst kept: string[] = []\n\t\t\tfor (const recordId of state.kept) {\n\t\t\t\t// Under another view the narrowing's scope says nothing about the record (the view\n\t\t\t\t// that is current may include it): it stays, judged when its own view is back.\n\t\t\t\tconst otherView =\n\t\t\t\t\tstate.view !== undefined && options.view !== undefined && state.view !== options.view\n\t\t\t\tif (options.retractedOnly || otherView || stillPending.has(recordId)) {\n\t\t\t\t\tkept.push(recordId)\n\t\t\t\t\tcontinue\n\t\t\t\t}\n\t\t\t\tconst record = await live(recordId)\n\t\t\t\tif (!record) continue\n\t\t\t\tif (state.scope !== null && recordMatchesCollectionScope(record, state.scope)) continue\n\t\t\t\tawait this.applyScopeRetraction(collection, recordId, options.position)\n\t\t\t\thidden.push({ collection, recordId })\n\t\t\t}\n\t\t\tif (\n\t\t\t\tkept.length !== state.kept.length ||\n\t\t\t\tretracted.length !== (state.retracted ?? []).length\n\t\t\t) {\n\t\t\t\tawait this.saveKeptOutsideNarrowing(\n\t\t\t\t\tcollection,\n\t\t\t\t\tkept.length > 0 || retracted.length > 0\n\t\t\t\t\t\t? { ...state, scope: state.scope, kept, retracted }\n\t\t\t\t\t\t: null,\n\t\t\t\t)\n\t\t\t}\n\t\t}\n\t\treturn hidden\n\t}\n\n\t/** Drop one record from the records an access narrowing kept (it was re-sent). */\n\tprivate async forgetKeptOutsideNarrowing(collection: string, recordId: string): Promise<void> {\n\t\tconst states = await this.loadKeptOutsideNarrowing()\n\t\tconst state = states.get(collection)\n\t\tif (!state) return\n\t\tif (!state.kept.includes(recordId) && !(state.retracted ?? []).includes(recordId)) return\n\t\tconst kept = state.kept.filter((id) => id !== recordId)\n\t\tconst retracted = (state.retracted ?? []).filter((id) => id !== recordId)\n\t\tawait this.saveKeptOutsideNarrowing(\n\t\t\tcollection,\n\t\t\tkept.length > 0 || retracted.length > 0 ? { ...state, kept, retracted } : null,\n\t\t)\n\t}\n\n\tprivate async loadKeptOutsideNarrowing(): Promise<Map<string, KeptOutsideNarrowing>> {\n\t\tif (this.keptOutsideNarrowing) return this.keptOutsideNarrowing\n\t\tconst rows = await this.adapter.query<{ key: string; value: string }>(\n\t\t\t'SELECT key, value FROM _kora_meta WHERE key LIKE ?',\n\t\t\t[`${ACCESS_NARROWING_META_PREFIX}%`],\n\t\t)\n\t\tconst out = new Map<string, KeptOutsideNarrowing>()\n\t\tfor (const row of rows) {\n\t\t\ttry {\n\t\t\t\tconst parsed = JSON.parse(row.value) as {\n\t\t\t\t\tscope?: Record<string, unknown> | null\n\t\t\t\t\tkept?: unknown\n\t\t\t\t\tretracted?: unknown\n\t\t\t\t\tview?: unknown\n\t\t\t\t}\n\t\t\t\tif (!Array.isArray(parsed.kept)) continue\n\t\t\t\tout.set(row.key.slice(ACCESS_NARROWING_META_PREFIX.length), {\n\t\t\t\t\tscope: parsed.scope ?? null,\n\t\t\t\t\tkept: parsed.kept.filter((id): id is string => typeof id === 'string'),\n\t\t\t\t\tretracted: Array.isArray(parsed.retracted)\n\t\t\t\t\t\t? parsed.retracted.filter((id): id is string => typeof id === 'string')\n\t\t\t\t\t\t: [],\n\t\t\t\t\t...(typeof parsed.view === 'string' ? { view: parsed.view } : {}),\n\t\t\t\t})\n\t\t\t} catch {\n\t\t\t\t// A malformed entry cannot name a scope: drop it rather than guess.\n\t\t\t\tawait this.adapter.execute('DELETE FROM _kora_meta WHERE key = ?', [row.key])\n\t\t\t}\n\t\t}\n\t\tthis.keptOutsideNarrowing = out\n\t\treturn out\n\t}\n\n\t/** The meta write of {@link saveKeptOutsideNarrowing} through `tx` (the cache is the caller's, after the commit). */\n\tprivate async writeKeptOutsideNarrowingInTx(\n\t\ttx: Transaction,\n\t\tcollection: string,\n\t\tstate: KeptOutsideNarrowing | null,\n\t): Promise<void> {\n\t\tconst key = `${ACCESS_NARROWING_META_PREFIX}${collection}`\n\t\tif (state === null) {\n\t\t\tawait tx.execute('DELETE FROM _kora_meta WHERE key = ?', [key])\n\t\t\treturn\n\t\t}\n\t\tawait tx.execute('INSERT OR REPLACE INTO _kora_meta (key, value) VALUES (?, ?)', [\n\t\t\tkey,\n\t\t\tJSON.stringify(state),\n\t\t])\n\t}\n\n\tprivate async saveKeptOutsideNarrowing(\n\t\tcollection: string,\n\t\tstate: KeptOutsideNarrowing | null,\n\t): Promise<void> {\n\t\tconst key = `${ACCESS_NARROWING_META_PREFIX}${collection}`\n\t\tconst cache = await this.loadKeptOutsideNarrowing()\n\t\t// Durable first: the cache only ever reflects what is stored, so a failed write is\n\t\t// retried (a re-sent batch) instead of being taken as done.\n\t\tif (state === null) {\n\t\t\tawait this.adapter.execute('DELETE FROM _kora_meta WHERE key = ?', [key])\n\t\t\tcache.delete(collection)\n\t\t\treturn\n\t\t}\n\t\tawait this.adapter.execute('INSERT OR REPLACE INTO _kora_meta (key, value) VALUES (?, ?)', [\n\t\t\tkey,\n\t\t\tJSON.stringify(state),\n\t\t])\n\t\tcache.set(collection, state)\n\t}\n\n\t/**\n\t * Hide all live rows that no longer match a newly accepted server scope. With\n\t * `shouldContinue`, stops before the next retraction once it returns false (the\n\t * sync session that accepted the scope ended) and returns the rows already hidden.\n\t */\n\tasync applyScopeNarrowing(\n\t\tscopes: Record<string, Record<string, unknown>>,\n\t\toptions: { shouldContinue?: () => boolean; position?: number } = {},\n\t): Promise<Array<{ collection: string; recordId: string }>> {\n\t\tthis.ensureOpen()\n\t\tconst shouldContinue = options.shouldContinue ?? (() => true)\n\t\tconst retractions: Array<{ collection: string; recordId: string }> = []\n\t\tfor (const [collection, definition] of Object.entries(this.schema.collections)) {\n\t\t\tif (!shouldContinue()) return retractions\n\t\t\tconst rows = await this.adapter.query<RawCollectionRow>(\n\t\t\t\t`SELECT * FROM ${quoteIdent(collection)} WHERE _deleted = 0`,\n\t\t\t)\n\t\t\tconst predicate = scopes[collection]\n\t\t\tfor (const row of rows) {\n\t\t\t\tconst record = deserializeRecord(row, definition.fields)\n\t\t\t\t// The one shared matcher (conjunction or `$or`, fails closed), so the device\n\t\t\t\t// hides exactly what the server stopped delivering.\n\t\t\t\tconst matches = predicate !== undefined && recordMatchesCollectionScope(record, predicate)\n\t\t\t\tif (!matches) {\n\t\t\t\t\tif (!shouldContinue()) return retractions\n\t\t\t\t\tawait this.applyScopeRetraction(collection, String(record.id), options.position)\n\t\t\t\t\tretractions.push({ collection, recordId: String(record.id) })\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\treturn retractions\n\t}\n\n\t/**\n\t * Materialize a server scope-entry insert (RT-19) whose fields each carry their\n\t * own version (RT-27). The entry restates the record's current server values; a\n\t * single whole-row stamp would let a field the server last wrote long ago\n\t * overwrite this device's newer unsynced edit of it, after which the device's own\n\t * operation uploads and wins on the server (divergence). So every field is resolved\n\t * on its own, by last-write-wins against this row's `_field_versions`:\n\t *\n\t * - no row: inserted with each field stamped at its own version, `_created_at`\n\t *   at the record's creation (the entry's `timestamp`), then any orphaned\n\t *   updates/deletes are folded in as for any insert;\n\t * - live row, or a row hidden by a scope retraction: per-field LWW (a retracted\n\t *   row is shown again; `_created_at` is kept);\n\t * - domain tombstone: revived only when the entry's newest field version is\n\t *   newer than the tombstone, then per-field LWW.\n\t *\n\t * Deterministic and idempotent: the outcome depends only on the stored and\n\t * incoming per-field versions, and a re-applied entry wins no field.\n\t */\n\tprivate async applyFieldVersionedInsert(\n\t\ttx: Transaction,\n\t\top: Operation,\n\t\tdefinition: NonNullable<SchemaDefinition['collections'][string]>,\n\t\tdata: Record<string, unknown>,\n\t\tcheckGuard: (row: RawCollectionRow | undefined) => void,\n\t\tvisibility: ScopeVisibility,\n\t): Promise<void> {\n\t\tconst collection = op.collection\n\t\tconst serialized = serializeRecord(data, definition.fields)\n\t\tconst versions = op.fieldVersions ?? {}\n\t\tconst latest = newestFieldVersion(op)\n\t\tconst latestVersion = serializeRowVersion(latest)\n\t\tconst incoming: FieldVersions = {}\n\t\tfor (const field of Object.keys(serialized)) {\n\t\t\t// A field without its own version (renamed by a schema transform) falls back\n\t\t\t// to the entry's newest version: the single-stamp rule of RT-19.\n\t\t\tconst version = versions[field]\n\t\t\tincoming[field] = version ? serializeRowVersion(version) : latestVersion\n\t\t}\n\n\t\tconst rows = await tx.query<RawCollectionRow>(\n\t\t\t`SELECT _updated_at, _version, _field_versions, _deleted FROM ${quoteIdent(collection)} WHERE id = ?`,\n\t\t\t[op.recordId],\n\t\t)\n\t\tconst row = rows[0]\n\t\tcheckGuard(row)\n\n\t\tif (!row) {\n\t\t\tconst record: Record<string, unknown> = {\n\t\t\t\tid: op.recordId,\n\t\t\t\t...serialized,\n\t\t\t\t_created_at: op.timestamp.wallTime,\n\t\t\t\t_updated_at: latest.wallTime,\n\t\t\t\t_version: latestVersion,\n\t\t\t\t_field_versions: serializeFieldVersions(incoming),\n\t\t\t\t...(visibility === 'hidden' ? { _deleted: 1 } : {}),\n\t\t\t}\n\t\t\tconst insertQuery = buildInsertQuery(collection, record)\n\t\t\tawait tx.execute(insertQuery.sql, insertQuery.params)\n\t\t\tawait this.foldOrphanedOperations(tx, collection, definition, op.recordId, op)\n\t\t\treturn\n\t\t}\n\n\t\tif (row._deleted === 1) {\n\t\t\t// Hidden by a retraction this entry does not undo: nothing changes.\n\t\t\tif (visibility === 'hidden') return\n\t\t\t// A domain delete newer than everything the entry carries still wins, also under\n\t\t\t// a retraction marker the entry lifts (this device's own delete).\n\t\t\tconst retractedOnly =\n\t\t\t\tvisibility === 'shown' && !(await endsInDomainDelete(tx, collection, op.recordId, op))\n\t\t\tif (!retractedOnly && !isIncomingNewerThanRow(latest, row)) return\n\t\t}\n\n\t\tconst current = parseFieldVersions(row._field_versions)\n\t\tconst rowVersion = typeof row._version === 'string' ? row._version : undefined\n\t\tconst merged: FieldVersions = { ...current }\n\t\tconst changes: Record<string, unknown> = {}\n\t\tfor (const [field, version] of Object.entries(incoming)) {\n\t\t\tif (version > effectiveFieldVersion(current, field, rowVersion)) {\n\t\t\t\tchanges[field] = serialized[field]\n\t\t\t\tmerged[field] = version\n\t\t\t}\n\t\t}\n\t\tif (row._deleted === 1) {\n\t\t\tchanges._deleted = 0\n\t\t}\n\t\tchanges._field_versions = serializeFieldVersions(merged)\n\t\tconst update = buildFieldFastForwardUpdateQuery(\n\t\t\tcollection,\n\t\t\top.recordId,\n\t\t\tchanges,\n\t\t\tlatestVersion,\n\t\t\tlatest.wallTime,\n\t\t)\n\t\tawait tx.execute(update.sql, update.params)\n\t}\n\n\t/**\n\t * Materialize update/delete operations that were logged for a record BEFORE\n\t * its insert arrived (reordered delivery). Runs inside the insert's write\n\t * transaction, folding each orphan in timestamp order through the exact\n\t * per-field LWW / LWW-delete rules the normal apply paths use, so the final\n\t * row state equals what a device that received the operations in causal\n\t * order computed. Called only when the insert created a previously-absent\n\t * row — in that case every logged update/delete for the record is\n\t * necessarily an orphan (rows are soft-deleted, never removed, so a row\n\t * that is absent now was never materialized).\n\t */\n\tprivate async foldOrphanedOperations(\n\t\ttx: Transaction,\n\t\tcollection: string,\n\t\tdefinition: NonNullable<SchemaDefinition['collections'][string]>,\n\t\trecordId: string,\n\t\tinsertOp: Operation,\n\t): Promise<void> {\n\t\tconst orphanRows = [\n\t\t\t...(await tx.query<OperationRow>(\n\t\t\t\t`SELECT * FROM ${quoteIdent(`_kora_ops_${collection}`)} WHERE record_id = ? AND type IN ('update', 'delete')`,\n\t\t\t\t[recordId],\n\t\t\t)),\n\t\t\t...(await loadRetainedConflictRows(\n\t\t\t\t(sql, params) => tx.query(sql, params),\n\t\t\t\tcollection,\n\t\t\t\trecordId,\n\t\t\t\t['update', 'delete'],\n\t\t\t)),\n\t\t]\n\t\tif (orphanRows.length === 0) {\n\t\t\treturn\n\t\t}\n\n\t\tconst orphans = orphanRows\n\t\t\t.map((r) => deserializeOperationWithCollection(r, collection))\n\t\t\t.sort((a, b) => HybridLogicalClock.compare(a.timestamp, b.timestamp))\n\n\t\tfor (const orphan of orphans) {\n\t\t\tconst orphanVersion = serializeRowVersion(orphan.timestamp)\n\t\t\tconst orphanWall = orphan.timestamp.wallTime\n\n\t\t\tif (orphan.type === 'update' && orphan.data) {\n\t\t\t\tconst orphanChanges = serializeRecord(orphan.data, definition.fields)\n\t\t\t\tconst rows = await tx.query<RawCollectionRow>(\n\t\t\t\t\t`SELECT _version, _field_versions FROM ${quoteIdent(collection)} WHERE id = ?`,\n\t\t\t\t\t[recordId],\n\t\t\t\t)\n\t\t\t\tconst current = rows[0]\n\t\t\t\tif (!current) {\n\t\t\t\t\tcontinue\n\t\t\t\t}\n\t\t\t\tconst { winners, merged } = resolvePerFieldLww(\n\t\t\t\t\tparseFieldVersions(current._field_versions),\n\t\t\t\t\tObject.keys(orphanChanges),\n\t\t\t\t\torphanVersion,\n\t\t\t\t\ttypeof current._version === 'string' ? current._version : undefined,\n\t\t\t\t)\n\t\t\t\tif (winners.length > 0) {\n\t\t\t\t\tconst winningChanges: Record<string, unknown> = {\n\t\t\t\t\t\t_field_versions: serializeFieldVersions(merged),\n\t\t\t\t\t}\n\t\t\t\t\tfor (const field of winners) {\n\t\t\t\t\t\twinningChanges[field] = orphanChanges[field]\n\t\t\t\t\t}\n\t\t\t\t\tconst query = buildFieldFastForwardUpdateQuery(\n\t\t\t\t\t\tcollection,\n\t\t\t\t\t\trecordId,\n\t\t\t\t\t\twinningChanges,\n\t\t\t\t\t\torphanVersion,\n\t\t\t\t\t\torphanWall,\n\t\t\t\t\t)\n\t\t\t\t\tawait tx.execute(query.sql, query.params)\n\t\t\t\t}\n\t\t\t} else if (orphan.type === 'delete') {\n\t\t\t\tconst query = buildLwwSoftDeleteQuery(collection, recordId, orphanWall, orphanVersion)\n\t\t\t\tawait tx.execute(query.sql, query.params)\n\t\t\t}\n\t\t}\n\n\t\t// Atomic-op fields need composition, not last-write-wins: the per-field LWW\n\t\t// loop above would keep only one concurrent increment's resolved value and drop\n\t\t// the rest. Re-materialize just the atomic fields by folding [insert, ...orphans]\n\t\t// in HLC order through the shared atomic-aware replay — the same fold the server\n\t\t// and the live apply path use — so an atomic op that arrived before its insert\n\t\t// (reordered delivery) composes correctly instead of losing deltas. Only the\n\t\t// field VALUES are overwritten; their per-field versions were already stamped to\n\t\t// the latest writer by the loop above, so future LWW stays correct.\n\t\tconst atomicFields = new Set<string>()\n\t\tfor (const orphan of orphans) {\n\t\t\tif (orphan.type === 'update' && orphan.atomicOps) {\n\t\t\t\tfor (const field of Object.keys(orphan.atomicOps)) {\n\t\t\t\t\tatomicFields.add(field)\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\tif (atomicFields.size > 0) {\n\t\t\t// A scope-entry insert expands into its per-field writes (RT-27).\n\t\t\tconst ordered = expandFieldVersionedOperations([insertOp, ...orphans])\n\t\t\tconst folded = replayOperationsForRecord(ordered)\n\t\t\tif (folded) {\n\t\t\t\tconst composed: Record<string, unknown> = {}\n\t\t\t\tfor (const field of atomicFields) {\n\t\t\t\t\tif (field in folded) {\n\t\t\t\t\t\tcomposed[field] = folded[field]\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\tconst serialized = serializeRecord(composed, definition.fields)\n\t\t\t\tconst cols = Object.keys(serialized)\n\t\t\t\tif (cols.length > 0) {\n\t\t\t\t\tconst setClause = cols.map((c) => `${quoteIdent(c)} = ?`).join(', ')\n\t\t\t\t\tawait tx.execute(`UPDATE ${quoteIdent(collection)} SET ${setClause} WHERE id = ?`, [\n\t\t\t\t\t\t...cols.map((c) => serialized[c]),\n\t\t\t\t\t\trecordId,\n\t\t\t\t\t])\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\n\t/**\n\t * Get operations from a node within a sequence number range.\n\t * Implements the OperationLog interface for computeDelta.\n\t */\n\tasync getRange(nodeId: string, fromSeq: number, toSeq: number): Promise<Operation[]> {\n\t\treturn this.getOperationRange(nodeId, fromSeq, toSeq)\n\t}\n\n\t/**\n\t * Get operations from a node within a sequence number range.\n\t */\n\tasync getOperationRange(nodeId: string, fromSeq: number, toSeq: number): Promise<Operation[]> {\n\t\tthis.ensureOpen()\n\t\tconst allOps: Operation[] = []\n\n\t\tfor (const collectionName of Object.keys(this.schema.collections)) {\n\t\t\tconst rows = await this.adapter.query<OperationRow>(\n\t\t\t\t`SELECT * FROM ${quoteIdent(`_kora_ops_${collectionName}`)} WHERE node_id = ? AND sequence_number >= ? AND sequence_number <= ? ORDER BY sequence_number ASC`,\n\t\t\t\t[nodeId, fromSeq, toSeq],\n\t\t\t)\n\t\t\tfor (const row of rows) {\n\t\t\t\tallOps.push(deserializeOperationWithCollection(row, collectionName))\n\t\t\t}\n\t\t}\n\n\t\t// Sort by sequence number across collections\n\t\tallOps.sort((a, b) => a.sequenceNumber - b.sequenceNumber)\n\t\treturn allOps\n\t}\n\n\t/**\n\t * Load every operation from the local append-only log across all collections.\n\t * Used by sync delta computation, backup export, and time-travel replay.\n\t */\n\tasync getAllOperations(): Promise<Operation[]> {\n\t\tthis.ensureOpen()\n\t\tconst allOps: Operation[] = []\n\n\t\tfor (const collectionName of Object.keys(this.schema.collections)) {\n\t\t\tconst rows = await this.adapter.query<OperationRow>(\n\t\t\t\t`SELECT * FROM ${quoteIdent(`_kora_ops_${collectionName}`)} ORDER BY sequence_number ASC`,\n\t\t\t)\n\t\t\tfor (const row of rows) {\n\t\t\t\tallOps.push(deserializeOperationWithCollection(row, collectionName))\n\t\t\t}\n\t\t}\n\n\t\treturn allOps\n\t}\n\n\t/**\n\t * Rebuild an in-memory snapshot of materialized state at a causal cut in the op log.\n\t * Does not mutate the live store — intended for DevTools time-travel inspection.\n\t *\n\t * @param operationId - Content-addressed id of the operation to replay through (inclusive)\n\t * @throws {OperationError} When the operation id is not present in the local log\n\t */\n\tasync replayTo(operationId: string): Promise<ReplaySnapshot> {\n\t\tthis.ensureOpen()\n\t\tconst start = Date.now()\n\t\tconst allOps = await this.getAllOperations()\n\t\tconst aliasRows = await this.adapter.query<{ id: string; reemitted_as: string }>(\n\t\t\t`SELECT id, reemitted_as FROM ${SEQ_CONFLICTS_TABLE} WHERE reemitted_as IS NOT NULL AND reemitted_as <> id`,\n\t\t)\n\t\tconst aliases = new Map(aliasRows.map((row) => [row.id, row.reemitted_as]))\n\t\tconst snapshot = buildReplaySnapshot(\n\t\t\tthis.schema,\n\t\t\tallOps,\n\t\t\toperationId,\n\t\t\taliases,\n\t\t\tthis.operationTransforms,\n\t\t)\n\n\t\tif (this.emitter) {\n\t\t\tthis.emitter.emit({\n\t\t\t\ttype: 'replay:completed',\n\t\t\t\ttargetOperationId: operationId,\n\t\t\t\toperationsApplied: snapshot.operationsApplied.length,\n\t\t\t\tduration: Date.now() - start,\n\t\t\t})\n\t\t}\n\n\t\treturn snapshot\n\t}\n\n\t/**\n\t * Persist a merge trace to the durable audit log.\n\t */\n\tasync appendAuditTrace(trace: import('../audit/types').PersistedAuditTrace): Promise<void> {\n\t\t// An async function: a closed store rejects the promise (callers such as the audit\n\t\t// bridge rely on `.catch`) instead of throwing inside an event listener.\n\t\tthis.ensureOpen()\n\t\t// Traces appended in the same turn (a delivery batch publishes all of its merge\n\t\t// traces together after its commit) are written in one transaction, in order, instead\n\t\t// of one autocommit write each (C3b). The returned promise settles with its trace.\n\t\treturn new Promise<void>((resolve, reject) => {\n\t\t\tthis.auditQueue.push({ trace, resolve, reject })\n\t\t\tif (!this.auditFlushScheduled) {\n\t\t\t\tthis.auditFlushScheduled = true\n\t\t\t\tqueueMicrotask(() => {\n\t\t\t\t\tvoid this.flushAuditQueue()\n\t\t\t\t})\n\t\t\t}\n\t\t})\n\t}\n\n\tprivate readonly auditQueue: Array<{\n\t\ttrace: import('../audit/types').PersistedAuditTrace\n\t\tresolve: () => void\n\t\treject: (error: unknown) => void\n\t}> = []\n\tprivate auditFlushScheduled = false\n\n\tprivate async flushAuditQueue(): Promise<void> {\n\t\tconst group = this.auditQueue.splice(0)\n\t\tthis.auditFlushScheduled = false\n\t\tif (group.length === 0) return\n\t\ttry {\n\t\t\tconst { appendAuditTrace: append, appendAuditTraces: appendAll } = await import(\n\t\t\t\t'../audit/audit-trace-store'\n\t\t\t)\n\t\t\tif (group.length > 1) {\n\t\t\t\ttry {\n\t\t\t\t\tawait appendAll(\n\t\t\t\t\t\tthis.adapter,\n\t\t\t\t\t\tgroup.map((entry) => entry.trace),\n\t\t\t\t\t)\n\t\t\t\t\tfor (const entry of group) entry.resolve()\n\t\t\t\t\treturn\n\t\t\t\t} catch {\n\t\t\t\t\t// Not written as a group: each trace is written (and fails) on its own.\n\t\t\t\t}\n\t\t\t}\n\t\t\tfor (const entry of group) {\n\t\t\t\ttry {\n\t\t\t\t\tawait append(this.adapter, entry.trace)\n\t\t\t\t\tentry.resolve()\n\t\t\t\t} catch (error) {\n\t\t\t\t\tentry.reject(error)\n\t\t\t\t}\n\t\t\t}\n\t\t} catch (error) {\n\t\t\tfor (const entry of group) entry.reject(error)\n\t\t}\n\t}\n\n\t/**\n\t * Read persisted audit traces with optional filters.\n\t */\n\tasync getAuditTraces(\n\t\tquery?: import('../audit/types').AuditTraceQuery,\n\t): Promise<import('../audit/types').PersistedAuditTrace[]> {\n\t\tthis.ensureOpen()\n\t\tconst { readAuditTraces } = await import('../audit/audit-trace-store')\n\t\treturn readAuditTraces(this.adapter, query)\n\t}\n\n\t/**\n\t * Export operations and merge traces as a portable audit bundle.\n\t */\n\tasync exportAudit(options?: import('../audit/types').AuditExportOptions): Promise<Uint8Array> {\n\t\tthis.ensureOpen()\n\t\tconst { exportAudit: doExport } = await import('../audit/export-audit')\n\t\treturn doExport(this.adapter, this.schema, this.nodeId, this.schema.version, options)\n\t}\n\n\t/**\n\t * Get the schema definition.\n\t */\n\tgetSchema(): SchemaDefinition {\n\t\treturn this.schema\n\t}\n\n\t/**\n\t * The instant-updates overlay of this store, or null when it was not built with\n\t * `instantUpdates`. Internal: `createApp` reads it for `app.storage.writes`, tests for\n\t * the registry.\n\t *\n\t * @internal\n\t */\n\tgetOverlayController(): OverlayController | null {\n\t\treturn this.overlayController\n\t}\n\n\t/**\n\t * Route local CRUD through the unified apply pipeline (korajs ApplyPipeline).\n\t */\n\tsetLocalMutationHandler(handler: LocalMutationHandler | null): void {\n\t\tthis.localMutationHandler = handler\n\t\tfor (const col of this.collections.values()) {\n\t\t\tcol.setMutationHandler(handler)\n\t\t}\n\t}\n\n\t/**\n\t * Notify this store that another same-origin runtime committed an operation to\n\t * the shared local database. The operation has already been persisted and\n\t * materialized by the database owner; this method only advances in-memory causal\n\t * watermarks and invalidates local reactive queries so already-open tabs stay\n\t * live without reapplying or rewriting the operation.\n\t */\n\tnotifyExternalOperation(operation: Operation): void {\n\t\tthis.ensureOpen()\n\t\tconst definition = this.schema.collections[operation.collection]\n\t\tif (!definition) {\n\t\t\treturn\n\t\t}\n\t\tthis.recordOperationSequence(operation)\n\t\tthis.subscriptionManager.invalidateFromPeer(operation.collection)\n\t}\n\n\t/**\n\t * Notify this store that another same-origin runtime changed rows of a collection\n\t * in the shared local database without an operation this tab can see (a re-fold,\n\t * a scope retraction, a restore; RT-98). Only re-runs the affected live queries.\n\t *\n\t * @param collection - The collection whose rows changed\n\t */\n\tnotifyExternalChange(collection: string): void {\n\t\tthis.ensureOpen()\n\t\tif (!this.schema.collections[collection]) return\n\t\tthis.subscriptionManager.invalidateFromPeer(collection)\n\t}\n\n\t/**\n\t * Listen to every committed change this store makes to collection rows: local\n\t * writes, remote applies, and changes without a new operation (re-folds, scope\n\t * retraction, cascade settling, rematerialization, restore). The cross-tab bus\n\t * relays these to other tabs on the same database (RT-98).\n\t *\n\t * @returns An unsubscribe function\n\t */\n\tonRecordsChanged(listener: RecordsChangeListener): () => void {\n\t\treturn this.subscriptionManager.onRecordsChanged(listener)\n\t}\n\n\t/**\n\t * Build the local write context for a collection: everything the single local\n\t * write path needs (used by Collection writes and by ApplyPipeline).\n\t */\n\tcreateMutationContext(\n\t\tcollection: string,\n\t\toptions?: {\n\t\t\textraCausalDeps?: string[]\n\t\t\t/**\n\t\t\t * Stamp the writes with this clock instead of the store's (it must be this\n\t\t\t * node's). Used for the side effects of a remote delete, stamped right after\n\t\t\t * the delete like the server's copy (seam 5), never with the device's \"now\".\n\t\t\t */\n\t\t\tclock?: HybridLogicalClock\n\t\t},\n\t): LocalMutationContext {\n\t\tthis.ensureOpen()\n\t\tconst definition = this.schema.collections[collection]\n\t\tif (!definition || !this.clock) {\n\t\t\tthrow new StoreNotOpenError()\n\t\t}\n\t\tconst beforeLocalDelete = this.localMutationHandler?.beforeLocalDelete\n\t\tconst fold = this.activeFold()\n\t\t// Writes with a custom clock or extra causal parents are system writes (the side\n\t\t// effects of a remote delete): never shown early, they are not the user's edits.\n\t\tconst overlay =\n\t\t\toptions?.clock === undefined && options?.extraCausalDeps === undefined\n\t\t\t\t? this.overlayController?.overlay\n\t\t\t\t: undefined\n\t\treturn {\n\t\t\t...(fold ? { fold } : {}),\n\t\t\t...(overlay ? { overlay } : {}),\n\t\t\tcollection,\n\t\t\tdefinition,\n\t\t\tschema: this.schema,\n\t\t\tadapter: this.adapter,\n\t\t\tclock: options?.clock ?? this.clock,\n\t\t\tnodeId: this.nodeId,\n\t\t\tonMutation: (collectionName, operation) =>\n\t\t\t\tthis.publishLocalOperation(collectionName, operation),\n\t\t\trelationEnforcer: this.relationEnforcer,\n\t\t\tcausalTracker: this.causalTracker,\n\t\t\t...(options?.extraCausalDeps ? { extraCausalDeps: options.extraCausalDeps } : {}),\n\t\t\t...(this.secretKeyProvider ? { secretKeyProvider: this.secretKeyProvider } : {}),\n\t\t\t...(this.maxOperationBytes !== undefined\n\t\t\t\t? { maxOperationBytes: this.maxOperationBytes }\n\t\t\t\t: {}),\n\t\t\tassertLocalWriteAllowed: () => this.assertLocalWriteAllowed(),\n\t\t\tsignedInUser: () => this.stampingUser,\n\t\t\t...(beforeLocalDelete\n\t\t\t\t? { beforeLocalDelete: beforeLocalDelete.bind(this.localMutationHandler) }\n\t\t\t\t: {}),\n\t\t\tonStorageError: (error) => this.reportStorageError(error),\n\t\t\tonWriteDurabilityError: (error, operationIds) =>\n\t\t\t\tthis.reportWriteDurabilityError(error, operationIds),\n\t\t\tonWriteDurable: () => this.reportWriteDurabilityRestored(),\n\t\t}\n\t}\n\n\t/**\n\t * Load a materialized row by ID, including soft-deleted tombstones.\n\t */\n\tasync findMaterializedRow(\n\t\tcollection: string,\n\t\trecordId: string,\n\t): Promise<MaterializedRowSnapshot | null> {\n\t\tthis.ensureOpen()\n\t\treturn this.findMaterializedRowIn(this.adapter, collection, recordId)\n\t}\n\n\t/**\n\t * A collection's reads through `tx`, with the same SQL and deserialization as\n\t * `store.collection(name)` (the same {@link QueryBuilder}, on a read-only view of `tx`).\n\t */\n\tprivate readInTransaction(tx: Transaction, collection: string): RemoteBatchCollectionReader {\n\t\tconst definition = this.schema.collections[collection]\n\t\tif (!definition) {\n\t\t\tthrow new KoraError(`Unknown collection \"${collection}\"`, 'UNKNOWN_COLLECTION', {\n\t\t\t\tcollection,\n\t\t\t})\n\t\t}\n\t\tconst readOnly = (method: string): never => {\n\t\t\tthrow new KoraError(\n\t\t\t\t`A remote batch's read view cannot ${method}: write through the batch.`,\n\t\t\t\t'REMOTE_BATCH_READ_ONLY',\n\t\t\t\t{ collection, method },\n\t\t\t)\n\t\t}\n\t\tconst view: StorageAdapter = {\n\t\t\topen: async () => readOnly('open'),\n\t\t\tclose: async () => readOnly('close'),\n\t\t\texecute: async () => readOnly('execute'),\n\t\t\tquery: <T>(sql: string, params?: unknown[]) => tx.query<T>(sql, params),\n\t\t\ttransaction: async () => readOnly('transaction'),\n\t\t\tmigrate: async () => readOnly('migrate'),\n\t\t}\n\t\treturn {\n\t\t\tfindById: async (id) => {\n\t\t\t\tconst rows = await tx.query<RawCollectionRow>(\n\t\t\t\t\t`SELECT * FROM ${quoteIdent(collection)} WHERE id = ? AND _deleted = 0`,\n\t\t\t\t\t[id],\n\t\t\t\t)\n\t\t\t\tconst row = rows[0]\n\t\t\t\treturn row ? deserializeRecord(row, definition.fields) : null\n\t\t\t},\n\t\t\twhere: (conditions) =>\n\t\t\t\tnew QueryBuilder(\n\t\t\t\t\tcollection,\n\t\t\t\t\tdefinition,\n\t\t\t\t\tview,\n\t\t\t\t\tthis.subscriptionManager,\n\t\t\t\t\tconditions,\n\t\t\t\t\tthis.schema,\n\t\t\t\t),\n\t\t}\n\t}\n\n\t/** {@link findMaterializedRow} through a given handle (a transaction, or the adapter). */\n\tprivate async findMaterializedRowIn(\n\t\treader: Pick<Transaction, 'query'>,\n\t\tcollection: string,\n\t\trecordId: string,\n\t): Promise<MaterializedRowSnapshot | null> {\n\t\tconst definition = this.schema.collections[collection]\n\t\tif (!definition) {\n\t\t\treturn null\n\t\t}\n\n\t\tconst rows = await reader.query<RawCollectionRow>(\n\t\t\t`SELECT * FROM ${quoteIdent(collection)} WHERE id = ?`,\n\t\t\t[recordId],\n\t\t)\n\t\tconst row = rows[0]\n\t\tif (!row) {\n\t\t\treturn null\n\t\t}\n\n\t\treturn {\n\t\t\trecord: deserializeRecord(row, definition.fields),\n\t\t\tdeleted: row._deleted === 1,\n\t\t}\n\t}\n\n\t/**\n\t * Raw version state of a materialized row, for optimistic-concurrency guarded\n\t * applies: capture this snapshot before computing a merge, pass it as\n\t * `guardRowState`, and the apply refuses to write if the row changed since.\n\t * Returns null when no row exists (which is itself a valid guard state — the\n\t * apply then requires the row to still be absent).\n\t */\n\tasync getRowVersionState(collection: string, recordId: string): Promise<RowVersionState | null> {\n\t\tthis.ensureOpen()\n\t\tif (!this.schema.collections[collection]) {\n\t\t\treturn null\n\t\t}\n\t\tconst rows = await this.adapter.query<RawCollectionRow>(\n\t\t\t`SELECT _version, _field_versions FROM ${quoteIdent(collection)} WHERE id = ?`,\n\t\t\t[recordId],\n\t\t)\n\t\tconst row = rows[0]\n\t\tif (!row) {\n\t\t\treturn null\n\t\t}\n\t\treturn {\n\t\t\tversion: typeof row._version === 'string' ? row._version : null,\n\t\t\tfieldVersions: typeof row._field_versions === 'string' ? row._field_versions : null,\n\t\t}\n\t}\n\n\t/**\n\t * Latest operation from this device for a record (used for delete-vs-update merge on sync).\n\t */\n\t/**\n\t * Load the last server version vector acknowledged by this client (persisted in `_kora_meta`).\n\t */\n\tasync loadLastAckedServerVector(): Promise<VersionVector> {\n\t\tthis.ensureOpen()\n\t\treturn loadLastAckedServerVector(this.adapter)\n\t}\n\n\t/**\n\t * Persist the last server version vector this client believes the server has applied.\n\t */\n\tasync saveLastAckedServerVector(vector: VersionVector): Promise<void> {\n\t\tthis.ensureOpen()\n\t\tawait saveLastAckedServerVector(this.adapter, vector)\n\t}\n\n\t/**\n\t * Load the per-device node token the sync server issued for this node id (RT-12).\n\t */\n\tasync loadNodeToken(nodeId?: string): Promise<string | null> {\n\t\tthis.ensureOpen()\n\t\treturn loadNodeToken(this.adapter, nodeId ?? this.nodeId)\n\t}\n\n\t/**\n\t * Persist the per-device node token under its node id (the current one by default).\n\t */\n\tasync saveNodeToken(token: string, nodeId?: string): Promise<void> {\n\t\tthis.ensureOpen()\n\t\tawait saveNodeToken(this.adapter, token, nodeId ?? this.nodeId)\n\t}\n\n\t/**\n\t * Load the node ids the sync server named authoritative (protocol v2), or null when\n\t * no protocol-2 server ever answered.\n\t */\n\tasync loadAuthoritativeNodeIds(): Promise<string[] | null> {\n\t\tthis.ensureOpen()\n\t\treturn loadAuthoritativeNodeIds(this.adapter)\n\t}\n\n\t/**\n\t * Persist the node ids the sync server named authoritative (protocol v2). Same as\n\t * {@link setAuthoritativeNodeIds}: merged into the union of learned explicit ids,\n\t * and the fold re-folds affected records only when that set grows.\n\t */\n\tasync saveAuthoritativeNodeIds(nodeIds: string[]): Promise<void> {\n\t\tawait this.setAuthoritativeNodeIds(nodeIds)\n\t}\n\n\t/**\n\t * Load persisted delta cursor for resuming paginated initial sync.\n\t */\n\tasync loadDeltaCursor(): Promise<string | null> {\n\t\tthis.ensureOpen()\n\t\treturn loadDeltaCursor(this.adapter)\n\t}\n\n\t/**\n\t * Persist or clear the delta cursor for paginated initial sync resume.\n\t */\n\tasync saveDeltaCursor(cursor: string | null): Promise<void> {\n\t\tthis.ensureOpen()\n\t\tawait saveDeltaCursor(this.adapter, cursor)\n\t}\n\n\t/**\n\t * Load the persisted delivery watermark for a view signature (0 when none recorded).\n\t * Defaults to the unfiltered view so existing single-watermark reads keep working.\n\t */\n\tasync loadDeliveryWatermark(signature = ''): Promise<number> {\n\t\tthis.ensureOpen()\n\t\treturn loadDeliveryWatermark(this.adapter, signature)\n\t}\n\n\t/**\n\t * Persist the delivery watermark for a view signature so it survives a client restart.\n\t */\n\tasync saveDeliveryWatermark(\n\t\tsignature: string,\n\t\twatermark: number,\n\t\tcompletion?: OfflineCompletion,\n\t): Promise<void> {\n\t\tthis.ensureOpen()\n\t\tawait this.clearOverlayOnWatermarkReset(signature, watermark)\n\t\tawait saveDeliveryWatermark(this.adapter, signature, watermark, completion)\n\t}\n\n\t/**\n\t * A view's delivery watermark going back to 0 is a full resync (a forced resync, a\n\t * snapshot resync, a sequence-conflict recovery): the stream replays the view, so\n\t * nothing pending is kept over it (I12). Only reads when something is pending.\n\t */\n\tprivate async clearOverlayOnWatermarkReset(signature: string, watermark: number): Promise<void> {\n\t\tconst controller = this.overlayController\n\t\tif (!controller || watermark !== 0 || controller.registry.list().length === 0) return\n\t\tif ((await loadDeliveryWatermark(this.adapter, signature)) > 0) controller.clear()\n\t}\n\n\t/** Record that a delivery unit is about to apply operations (offline-readiness 4.1). */\n\tasync openOfflineUnit(unit: OfflineUnitKey): Promise<void> {\n\t\tthis.ensureOpen()\n\t\tawait openOfflineUnit(this.adapter, unit)\n\t}\n\n\t/** Delete every completion mark (clear-before-apply, watermark resets). */\n\tasync clearOfflineMarks(): Promise<void> {\n\t\tthis.ensureOpen()\n\t\tawait clearOfflineMarks(this.adapter)\n\t}\n\n\t/** Every completion mark and open unit key. */\n\tasync loadOfflineMarks(): Promise<OfflineMarksSnapshot> {\n\t\tthis.ensureOpen()\n\t\treturn loadOfflineMarks(this.adapter)\n\t}\n\n\t/** Every pin of `app.offline.keep()`, oldest first. */\n\tasync loadOfflinePins(): Promise<StoredOfflinePin[]> {\n\t\tthis.ensureOpen()\n\t\treturn loadOfflinePins(this.adapter)\n\t}\n\n\t/** Every component hold on a pin, across all tabs. */\n\tasync loadOfflinePinHolds(): Promise<StoredOfflinePinHold[]> {\n\t\tthis.ensureOpen()\n\t\treturn loadOfflinePinHolds(this.adapter)\n\t}\n\n\t/**\n\t * `keep()`: record a pin (idempotent) and mark it explicit. Refused past the pin limit\n\t * (`OFFLINE_PIN_LIMIT`). Durable when the promise resolves, on the IndexedDB fallback too.\n\t */\n\tasync keepOfflinePin(pin: NewOfflinePin): Promise<OfflinePinWriteResult> {\n\t\tthis.ensureOpen()\n\t\treturn this.writeOfflinePins(() => keepOfflinePin(this.adapter, pin, Date.now()))\n\t}\n\n\t/** `release()`: clear the explicit flag; the pin goes when no component holds it. */\n\tasync releaseOfflinePin(\n\t\tid: string,\n\t\toptions: { stillHeld?: boolean } = {},\n\t): Promise<OfflinePinWriteResult> {\n\t\tthis.ensureOpen()\n\t\treturn this.writeOfflinePins(() => releaseOfflinePin(this.adapter, id, options))\n\t}\n\n\t/** Create a pin without marking it kept by the app (explicit-mode holds). */\n\tasync ensureOfflinePin(pin: NewOfflinePin): Promise<OfflinePinWriteResult> {\n\t\tthis.ensureOpen()\n\t\treturn this.writeOfflinePins(() => ensureOfflinePin(this.adapter, pin, Date.now()))\n\t}\n\n\t/** A component starts holding a pin, creating it when absent. */\n\tasync addOfflinePinHold(\n\t\tpin: NewOfflinePin,\n\t\thold: Omit<StoredOfflinePinHold, 'pinId'>,\n\t): Promise<OfflinePinWriteResult> {\n\t\tthis.ensureOpen()\n\t\treturn this.writeOfflinePins(() => addOfflinePinHold(this.adapter, pin, hold, Date.now()))\n\t}\n\n\t/** A component stops holding a pin; the pin goes with its last holder unless explicit. */\n\tasync removeOfflinePinHold(pinId: string, holder: string): Promise<OfflinePinWriteResult> {\n\t\tthis.ensureOpen()\n\t\treturn this.writeOfflinePins(() => removeOfflinePinHold(this.adapter, pinId, holder))\n\t}\n\n\t/** Delete the holds of tabs for which `isStale(tabId)` is true, and pins only they kept. */\n\tasync pruneOfflinePinHolds(\n\t\tisStale: (tabId: string) => boolean,\n\t): Promise<{ holdsRemoved: number; pinsRemoved: number }> {\n\t\tthis.ensureOpen()\n\t\treturn this.writeOfflinePins(() => pruneOfflinePinHolds(this.adapter, isStale))\n\t}\n\n\t/** Record when a pin was last seen complete (display only). */\n\tasync markOfflinePinCompleted(id: string, at: number | null): Promise<void> {\n\t\tthis.ensureOpen()\n\t\t// Display only: no durability barrier (a lost value is re-derived).\n\t\tawait this.trackWrite({ operation: 'offline-pin-completed' }, () =>\n\t\t\tmarkOfflinePinCompleted(this.adapter, id, at),\n\t\t)\n\t}\n\n\tprivate writeOfflinePins<T>(write: () => Promise<T>): Promise<T> {\n\t\t// Through the write gate (a superseded tab writes nothing), and durable before it\n\t\t// resolves: on the IndexedDB fallback that means a stored snapshot.\n\t\treturn this.trackWrite({ operation: 'offline-pin' }, async () => {\n\t\t\tconst result = await write()\n\t\t\tawait this.adapter.ensureDurable?.()\n\t\t\treturn result\n\t\t})\n\t}\n\n\t/**\n\t * Resolves once everything committed so far is in a persisted snapshot, without forcing\n\t * one. Null on adapters whose commits are durable.\n\t */\n\twhenPersisted(): Promise<void> | null {\n\t\tthis.ensureOpen()\n\t\treturn this.adapter.whenPersisted ? this.adapter.whenPersisted() : null\n\t}\n\n\t/**\n\t * Load every persisted view watermark, keyed by signature.\n\t */\n\tasync loadAllDeliveryWatermarks(): Promise<Record<string, number>> {\n\t\tthis.ensureOpen()\n\t\treturn loadAllDeliveryWatermarks(this.adapter)\n\t}\n\n\t/**\n\t * Delete a persisted view watermark (safe: the view back-fills from 0 when next visited).\n\t */\n\tasync deleteDeliveryWatermark(signature: string): Promise<void> {\n\t\tthis.ensureOpen()\n\t\tawait this.clearOverlayOnWatermarkReset(signature, 0)\n\t\tawait deleteDeliveryWatermark(this.adapter, signature)\n\t\tawait deleteOfflineViewMarks(this.adapter, signature)\n\t\tawait this.adapter.execute('DELETE FROM _kora_meta WHERE key = ?', [\n\t\t\t`${DELIVERY_ANCHOR_META_PREFIX}${signature}`,\n\t\t])\n\t}\n\n\t/**\n\t * Record delivered operations the sync engine deliberately did not apply (inbound\n\t * quarantine, W4) and, when given, advance a view's delivery watermark in the same\n\t * transaction, so the watermark never passes an operation that is neither applied nor\n\t * recorded.\n\t */\n\tasync saveInboundQuarantine(\n\t\tentries: UnappliedOperation[],\n\t\twatermark?: { signature: string; watermark: number; completion?: OfflineCompletion },\n\t): Promise<void> {\n\t\tthis.ensureOpen()\n\t\tawait saveUnappliedOperations(this.adapter, entries, watermark)\n\t}\n\n\t/** Every quarantined inbound operation, oldest delivery first. */\n\tasync loadInboundQuarantine(): Promise<UnappliedOperation[]> {\n\t\tthis.ensureOpen()\n\t\treturn loadUnappliedOperations(this.adapter)\n\t}\n\n\t/** Remove quarantined inbound operations (applied on replay, or reconciled). */\n\tasync removeInboundQuarantine(operationIds: string[]): Promise<void> {\n\t\tthis.ensureOpen()\n\t\tawait removeUnappliedOperations(this.adapter, operationIds)\n\t}\n\n\t/**\n\t * The contiguous acknowledged prefix of this device's own operations for a node id,\n\t * or null when none was recorded under that contract (W3).\n\t */\n\tasync loadOwnAckedThrough(nodeId: string): Promise<number | null> {\n\t\tthis.ensureOpen()\n\t\treturn loadOwnAckedThrough(this.adapter, nodeId)\n\t}\n\n\t/** Persist the contiguous acknowledged own-operation prefix for a node id. */\n\tasync saveOwnAckedThrough(nodeId: string, sequence: number): Promise<void> {\n\t\tthis.ensureOpen()\n\t\tawait saveOwnAckedThrough(this.adapter, nodeId, sequence)\n\t}\n\n\t/** The downlink scope the sync server last accepted (null when none). */\n\tasync loadAcceptedDownlinkScope(): Promise<Record<string, Record<string, unknown>> | null> {\n\t\tthis.ensureOpen()\n\t\treturn loadAcceptedDownlinkScope(this.adapter)\n\t}\n\n\t/** Persist (or clear) the downlink scope the sync server last accepted. */\n\t/**\n\t * Delivery anchors by view signature, each with the watermark it belongs to. The sync\n\t * engine reports a view's anchor at handshake only while it still matches the view's\n\t * watermark, which is how a server whose log was rewound by a restore recognizes it.\n\t */\n\tasync loadDeliveryAnchors(): Promise<Record<string, { watermark: number; anchor: string }>> {\n\t\tthis.ensureOpen()\n\t\tconst rows = await this.adapter.query<{ key: string; value: string }>(\n\t\t\t'SELECT key, value FROM _kora_meta WHERE substr(key, 1, ?) = ?',\n\t\t\t[DELIVERY_ANCHOR_META_PREFIX.length, DELIVERY_ANCHOR_META_PREFIX],\n\t\t)\n\t\tconst anchors: Record<string, { watermark: number; anchor: string }> = {}\n\t\tfor (const row of rows) {\n\t\t\ttry {\n\t\t\t\tconst parsed = JSON.parse(row.value) as { watermark?: unknown; anchor?: unknown }\n\t\t\t\tif (typeof parsed.watermark === 'number' && typeof parsed.anchor === 'string') {\n\t\t\t\t\tanchors[row.key.slice(DELIVERY_ANCHOR_META_PREFIX.length)] = {\n\t\t\t\t\t\twatermark: parsed.watermark,\n\t\t\t\t\t\tanchor: parsed.anchor,\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t} catch {\n\t\t\t\t// An unreadable anchor is no anchor: the handshake omits it.\n\t\t\t}\n\t\t}\n\t\treturn anchors\n\t}\n\n\t/** Persist a view's delivery anchor, replacing the previous one. */\n\tasync saveDeliveryAnchor(\n\t\tsignature: string,\n\t\trecord: { watermark: number; anchor: string },\n\t): Promise<void> {\n\t\tthis.ensureOpen()\n\t\tawait this.adapter.execute('INSERT OR REPLACE INTO _kora_meta (key, value) VALUES (?, ?)', [\n\t\t\t`${DELIVERY_ANCHOR_META_PREFIX}${signature}`,\n\t\t\tJSON.stringify({ watermark: record.watermark, anchor: record.anchor }),\n\t\t])\n\t}\n\n\t/** The access read rules' key this device was last fully re-scoped under (null: none). */\n\tasync loadAccessRulesKey(): Promise<string | null> {\n\t\tthis.ensureOpen()\n\t\tconst rows = await this.adapter.query<{ value: string }>(\n\t\t\t'SELECT value FROM _kora_meta WHERE key = ?',\n\t\t\t[ACCESS_RULES_KEY_META_KEY],\n\t\t)\n\t\treturn rows[0]?.value ?? null\n\t}\n\n\t/** Persist the access read rules' key this device was fully re-scoped under. */\n\tasync saveAccessRulesKey(key: string): Promise<void> {\n\t\tthis.ensureOpen()\n\t\tawait this.adapter.execute('INSERT OR REPLACE INTO _kora_meta (key, value) VALUES (?, ?)', [\n\t\t\tACCESS_RULES_KEY_META_KEY,\n\t\t\tkey,\n\t\t])\n\t}\n\n\tasync saveAcceptedDownlinkScope(\n\t\tscope: Record<string, Record<string, unknown>> | null,\n\t): Promise<void> {\n\t\tthis.ensureOpen()\n\t\tawait saveAcceptedDownlinkScope(this.adapter, scope)\n\t}\n\n\t/**\n\t * Local operations not yet reflected on the server version vector.\n\t */\n\tasync getUnsyncedOperations(serverVector: VersionVector): Promise<Operation[]> {\n\t\tthis.ensureOpen()\n\t\treturn collectOperationsAheadOfServer(\n\t\t\tthis.getVersionVector(),\n\t\t\tserverVector,\n\t\t\t(nodeId, fromSeq, toSeq) => this.getOperationRange(nodeId, fromSeq, toSeq),\n\t\t)\n\t}\n\n\t/**\n\t * Move this device to a fresh node id, re-authoring its never-acknowledged\n\t * operations under it (RT-21). Used when the sync server refuses the current node\n\t * id (`NODE_ID_CLAIMED`): the device keeps every local write and uploads it under\n\t * the new id. Acknowledged history stays under the old id. Persisted atomically;\n\t * later writes use the new id.\n\t *\n\t * @param unsyncedOpIds - Ids of this node's operations the server never acknowledged\n\t * @returns The new node id and the rewritten operations (for the outbound queue)\n\t * @throws {KoraError} When the node id is pinned (`StoreConfig.nodeId`, or per-tab isolation)\n\t */\n\tasync rotateNodeId(unsyncedOpIds: string[]): Promise<NodeRotationResult> {\n\t\tthis.ensureOpen()\n\t\tif (this.configNodeId || this.isolation === 'per-tab') {\n\t\t\tthrow new KoraError(\n\t\t\t\t'This store uses a pinned node id, so it cannot move to a fresh one after the sync server refused it.',\n\t\t\t\t'NODE_ID_PINNED',\n\t\t\t\t{\n\t\t\t\t\tnodeId: this.nodeId,\n\t\t\t\t\tfix: 'Remove StoreConfig.nodeId, or give the device a node id no other device uses.',\n\t\t\t\t},\n\t\t\t)\n\t\t}\n\t\tconst oldNodeId = this.nodeId\n\t\tconst oldClock = this.clock\n\t\tconst oldBinding = (await listLocalNodes(this.adapter)).find(\n\t\t\t(node) => node.nodeId === oldNodeId,\n\t\t)\n\t\tconst freshNodeId = generateUUIDv7()\n\t\tconst touched = new Map<string, Set<string>>()\n\t\tawait ensureLocalSyncRecordTables(this.adapter)\n\t\tconst result = await rotateUnsyncedOperationsInLog(\n\t\t\tthis.adapter,\n\t\t\tthis.schema,\n\t\t\tunsyncedOpIds,\n\t\t\toldNodeId,\n\t\t\tfreshNodeId,\n\t\t\t{\n\t\t\t\t// Registered, bound and re-folded in the rewrite's transaction: the re-authored\n\t\t\t\t// operations have new ids that their records' fold states must name, and keep\n\t\t\t\t// their author (RT-50), so they are never held as unassigned.\n\t\t\t\tinTransaction: this.refoldInRewrite(touched, async (tx) => {\n\t\t\t\t\tawait registerLocalNode(tx, freshNodeId)\n\t\t\t\t\tif (oldBinding?.principal) {\n\t\t\t\t\t\tawait setLocalNodePrincipal(\n\t\t\t\t\t\t\ttx,\n\t\t\t\t\t\t\tfreshNodeId,\n\t\t\t\t\t\t\toldBinding.principal,\n\t\t\t\t\t\t\toldBinding.binding ?? 'app',\n\t\t\t\t\t\t)\n\t\t\t\t\t}\n\t\t\t\t}),\n\t\t\t},\n\t\t)\n\t\tthis.nodeId = result.nodeId\n\t\tconst clock = new HybridLogicalClock(this.nodeId)\n\t\tif (oldClock) {\n\t\t\tconst last = oldClock.now()\n\t\t\tclock.advanceTo({ ...last, nodeId: this.nodeId })\n\t\t\tconst offset = oldClock.getReferenceOffset()\n\t\t\tif (offset !== null) clock.setReferenceOffset(offset)\n\t\t}\n\t\tthis.clock = clock\n\t\tthis.causalTracker = new CausalTracker()\n\t\tthis.sequenceManager = new SequenceManager(this.adapter, this.nodeId)\n\t\tthis.versionVector = await this.loadVersionVector()\n\t\t// The persisted counter (MAX with the stored value, W6), not a local count.\n\t\tthis.sequenceNumber = this.versionVector.get(this.nodeId) ?? result.operations.length\n\t\tfor (const collection of this.collections.values()) {\n\t\t\tcollection.rebindNode(clock, this.nodeId, this.relationEnforcer, this.causalTracker)\n\t\t}\n\t\tthis.invalidateRefolded(touched)\n\t\treturn result\n\t}\n\n\t/**\n\t * Re-author another local node's never-acknowledged operations under a fresh node id\n\t * bound to `principal` (the user they belong to). Used when the sync server refuses an\n\t * adopted node whose writes belong to the signed-in user (the app assigned them, or\n\t * the node was created for them) but which no claims-aware server ever accepted: a\n\t * beta.12 database's node with history the server recorded no owner for. The store's\n\t * own node id, clock and counters are untouched; the fresh node is registered, so the\n\t * sync engine adopts it like any other local node.\n\t *\n\t * @param fromNodeId - The refused local node (never the store's own)\n\t * @param unsyncedOpIds - Ids of its operations the server never acknowledged\n\t * @param principal - The user the writes belong to (the fresh node's binding)\n\t * @returns The fresh node id and the rewritten operations (for the outbound queue)\n\t * @throws {KoraError} `NODE_ID_UNKNOWN` when `fromNodeId` is the store's own node or\n\t *   not a local node\n\t */\n\tasync reauthorLocalNode(\n\t\tfromNodeId: string,\n\t\tunsyncedOpIds: string[],\n\t\tprincipal: string,\n\t): Promise<NodeRotationResult> {\n\t\tthis.ensureOpen()\n\t\tconst from = (await listLocalNodes(this.adapter)).find((node) => node.nodeId === fromNodeId)\n\t\tif (fromNodeId === this.nodeId || !from) {\n\t\t\tthrow new KoraError(\n\t\t\t\t`Node id \"${fromNodeId}\" is not another local node of this database, so its writes cannot be re-authored.`,\n\t\t\t\t'NODE_ID_UNKNOWN',\n\t\t\t\t{ nodeId: fromNodeId, storeNodeId: this.nodeId },\n\t\t\t)\n\t\t}\n\t\tconst freshNodeId = generateUUIDv7()\n\t\tconst touched = new Map<string, Set<string>>()\n\t\tawait ensureLocalSyncRecordTables(this.adapter)\n\t\tconst result = await rotateUnsyncedOperationsInLog(\n\t\t\tthis.adapter,\n\t\t\tthis.schema,\n\t\t\tunsyncedOpIds,\n\t\t\tfromNodeId,\n\t\t\tfreshNodeId,\n\t\t\t{\n\t\t\t\tmoveDatabaseNode: false,\n\t\t\t\tinTransaction: this.refoldInRewrite(touched, async (tx) => {\n\t\t\t\t\tawait registerLocalNode(tx, freshNodeId)\n\t\t\t\t\tawait setLocalNodePrincipal(tx, freshNodeId, principal, 'fresh')\n\t\t\t\t}),\n\t\t\t},\n\t\t)\n\t\tthis.versionVector = await this.loadVersionVector()\n\t\tthis.invalidateRefolded(touched)\n\t\treturn result\n\t}\n\n\t/**\n\t * Re-author a retired local node's operations under this store's own node (a browser\n\t * shared between accounts: see `LocalNodeRecord.retired`). The caller passes the ones\n\t * the sync server does NOT hold (it asked by id) and that it never refused for good;\n\t * the server's version-vector entry for a shared node says nothing about this\n\t * database's writes, so it is never used here. Each keeps its type, record, data and\n\t * HLC wall time and counter, and takes the own node id (in `nodeId` and\n\t * `timestamp.nodeId`), the own node's next sequence numbers (allocated in the same\n\t * transaction as every local write's), and a recomputed content id; causal deps among\n\t * them are rewritten and materialized versions re-stamped (the node-rotation path).\n\t *\n\t * When a rewritten timestamp would equal one the own node already used (a device clock\n\t * that went back), the operations go to a fresh node bound to the same user instead,\n\t * which uploads like any adopted node.\n\t *\n\t * @param fromNodeId - The retired node (never the store's own)\n\t * @param operationIds - Its operations to re-author\n\t * @returns The node they now belong to, the rewritten operations and the id mapping\n\t * @throws {KoraError} `NODE_ID_UNKNOWN` when `fromNodeId` is the store's own node or not\n\t *   a retired local node\n\t */\n\tasync reauthorIntoOwnNode(\n\t\tfromNodeId: string,\n\t\toperationIds: string[],\n\t): Promise<NodeRotationResult> {\n\t\tthis.ensureOpen()\n\t\tconst nodes = await listLocalNodes(this.adapter)\n\t\tconst from = nodes.find((node) => node.nodeId === fromNodeId)\n\t\tif (fromNodeId === this.nodeId || !from?.retired) {\n\t\t\tthrow new KoraError(\n\t\t\t\t`Node id \"${fromNodeId}\" is not a retired local node of this database, so its writes cannot be re-authored under it.`,\n\t\t\t\t'NODE_ID_UNKNOWN',\n\t\t\t\t{ nodeId: fromNodeId, storeNodeId: this.nodeId },\n\t\t\t)\n\t\t}\n\t\tconst ownPrincipal = nodes.find((node) => node.nodeId === this.nodeId)?.principal ?? null\n\t\tconst principal = from.principal ?? null\n\t\tlet result: NodeRotationResult\n\t\tconst touched = new Map<string, Set<string>>()\n\t\tif (principal !== null && principal === ownPrincipal) {\n\t\t\ttry {\n\t\t\t\tresult = await rotateUnsyncedOperationsInLog(\n\t\t\t\t\tthis.adapter,\n\t\t\t\t\tthis.schema,\n\t\t\t\t\toperationIds,\n\t\t\t\t\tfromNodeId,\n\t\t\t\t\tthis.nodeId,\n\t\t\t\t\t{ moveDatabaseNode: false, append: true, inTransaction: this.refoldInRewrite(touched) },\n\t\t\t\t)\n\t\t\t} catch (error) {\n\t\t\t\tif (!(error instanceof KoraError) || error.code !== 'TIMESTAMP_TAKEN') throw error\n\t\t\t\ttouched.clear()\n\t\t\t\tresult = await this.reauthorUnderFreshNode(fromNodeId, operationIds, principal, touched)\n\t\t\t}\n\t\t} else if (principal !== null) {\n\t\t\tresult = await this.reauthorUnderFreshNode(fromNodeId, operationIds, principal, touched)\n\t\t} else {\n\t\t\tthrow new KoraError(\n\t\t\t\t`Node id \"${fromNodeId}\" has no recorded user, so its writes cannot be re-authored for anyone.`,\n\t\t\t\t'NODE_ID_UNKNOWN',\n\t\t\t\t{ nodeId: fromNodeId, storeNodeId: this.nodeId },\n\t\t\t)\n\t\t}\n\t\tthis.versionVector = await this.loadVersionVector()\n\t\tthis.sequenceNumber = this.versionVector.get(this.nodeId) ?? this.sequenceNumber\n\t\tthis.invalidateRefolded(touched)\n\t\treturn result\n\t}\n\n\tprivate async reauthorUnderFreshNode(\n\t\tfromNodeId: string,\n\t\toperationIds: string[],\n\t\tprincipal: string,\n\t\ttouched: Map<string, Set<string>>,\n\t): Promise<NodeRotationResult> {\n\t\tconst freshNodeId = generateUUIDv7()\n\t\tawait ensureLocalSyncRecordTables(this.adapter)\n\t\treturn rotateUnsyncedOperationsInLog(\n\t\t\tthis.adapter,\n\t\t\tthis.schema,\n\t\t\toperationIds,\n\t\t\tfromNodeId,\n\t\t\tfreshNodeId,\n\t\t\t{\n\t\t\t\tmoveDatabaseNode: false,\n\t\t\t\tinTransaction: this.refoldInRewrite(touched, async (tx) => {\n\t\t\t\t\tawait registerLocalNode(tx, freshNodeId)\n\t\t\t\t\tawait setLocalNodePrincipal(tx, freshNodeId, principal, 'fresh')\n\t\t\t\t}),\n\t\t\t},\n\t\t)\n\t}\n\n\t/**\n\t * Move this database back to a node id it authored under before (RT-38): after the\n\t * sync server refused the current node, the device tries a node a returning user\n\t * owns. Nothing is rewritten; later writes use `nodeId`.\n\t *\n\t * @throws {KoraError} When the node id is pinned, or `nodeId` is not a local node\n\t */\n\tasync switchNodeId(nodeId: string): Promise<void> {\n\t\tthis.ensureOpen()\n\t\tif (this.configNodeId || this.isolation === 'per-tab') {\n\t\t\tthrow new KoraError(\n\t\t\t\t'This store uses a pinned node id, so it cannot switch to another one.',\n\t\t\t\t'NODE_ID_PINNED',\n\t\t\t\t{ nodeId: this.nodeId },\n\t\t\t)\n\t\t}\n\t\tif (nodeId === this.nodeId) return\n\t\tif (isReservedNodeId(nodeId)) throw new ReservedNodeIdError(nodeId, 'switchNodeId')\n\t\tconst known = (await listLocalNodes(this.adapter)).some((node) => node.nodeId === nodeId)\n\t\tif (!known) {\n\t\t\tthrow new KoraError(\n\t\t\t\t`Node id \"${nodeId}\" was never used by this database, so the store cannot switch to it.`,\n\t\t\t\t'NODE_ID_UNKNOWN',\n\t\t\t\t{ nodeId },\n\t\t\t)\n\t\t}\n\t\tawait this.adapter.transaction((tx) => moveDatabaseNodeId(tx, nodeId))\n\t\tawait this.rebindToNode(nodeId)\n\t}\n\n\t/** Point the clock, sequence counter and collections at `nodeId` (already persisted). */\n\tprivate async rebindToNode(nodeId: string): Promise<void> {\n\t\t// Another node, user or database state: nothing pending describes it (I12).\n\t\tthis.overlayController?.clear()\n\t\tconst oldClock = this.clock\n\t\tthis.nodeId = nodeId\n\t\tconst clock = new HybridLogicalClock(this.nodeId)\n\t\tif (oldClock) {\n\t\t\tconst last = oldClock.now()\n\t\t\tclock.advanceTo({ ...last, nodeId: this.nodeId })\n\t\t\tconst offset = oldClock.getReferenceOffset()\n\t\t\tif (offset !== null) clock.setReferenceOffset(offset)\n\t\t}\n\t\tthis.clock = clock\n\t\tthis.causalTracker = new CausalTracker()\n\t\tthis.sequenceManager = new SequenceManager(this.adapter, this.nodeId)\n\t\tthis.versionVector = await this.loadVersionVector()\n\t\tthis.sequenceNumber = this.versionVector.get(this.nodeId) ?? 0\n\t\tfor (const collection of this.collections.values()) {\n\t\t\tcollection.rebindNode(clock, this.nodeId, this.relationEnforcer, this.causalTracker)\n\t\t}\n\t}\n\n\t/**\n\t * Bind this database's writes to the signed-in user (RT-42). Call it whenever the\n\t * signed-in user is known or changes, BEFORE the next local write (`createApp` does\n\t * so at start and on every auth change of `sync.authClient`).\n\t *\n\t * - The current node belongs to `principal`: nothing changes.\n\t * - The current node is unbound and has no history (no write, never synced): it is\n\t *   bound to `principal` (every write under it from now on is theirs).\n\t * - The current node is unbound but has history (a database from before RT-42, or\n\t *   writes made while nobody was signed in): its owner is NOT guessed (RT-50). The\n\t *   store moves to `principal`'s own node, and the old node's owner is learned from\n\t *   the sync server (the first accepted handshake as it binds it; a refusal rules\n\t *   that user out). A node that never synced cannot be attributed by anyone: its\n\t *   unsynced writes are held for the app to assign or discard (`app.sync.assignHeld`,\n\t *   `app.sync.discardHeld`).\n\t * - It belongs to another user: the store moves to `principal`'s own local node (the\n\t *   most recent one, not held), or to a fresh node bound to `principal`. Nothing is\n\t *   rewritten: the other user's unsynced writes stay under their node, and sync never\n\t *   uploads them on this user's session (they count as `heldOperations`).\n\t *\n\t * A pinned node id (`StoreConfig.nodeId`, such as an auth device id) cannot move:\n\t * `conflict` is then true when it belongs to another user, and sync refuses to\n\t * upload it under `principal`; an unbound pinned node with history stays unbound\n\t * until the server accepts it for a user. Under `per-tab` isolation the tab moves to\n\t * a fresh per-tab node.\n\t *\n\t * @param principal - The signed-in user id\n\t * @returns The node now in use and whether it changed\n\t */\n\tasync bindPrincipal(principal: string): Promise<PrincipalBinding> {\n\t\t// A different user than the last one: their view starts without the previous\n\t\t// user's pending writes (I12).\n\t\tconst changingUser = this.signedInPrincipal !== null && principal !== this.signedInPrincipal\n\t\tif (changingUser) this.overlayController?.clear()\n\t\t// Another user is signing in: until their node is bound, no insert is stamped with\n\t\t// either user (it would be written on the previous user's node, as them). Set before\n\t\t// anything is awaited, so no insert can slip in between.\n\t\tif (principal !== this.stampingUser) this.stampingUser = null\n\t\t// What was read for the previous user must not be readable by this one (I5).\n\t\tif (changingUser) await this.clearSeedsAtClearPoint('a change of user')\n\t\tconst binding = await this.bindPrincipalToNode(principal)\n\t\t// The server's word was about the previous user; another user may own the node.\n\t\tif (principal !== this.signedInPrincipal) this.pinnedNodeRefusedByServer = false\n\t\t// While the pinned node belongs to another user, local writes are refused (F9):\n\t\t// they could only be written under that user's node and would upload as theirs.\n\t\tthis.pinnedNodeOwnedBy = binding.conflict\n\t\t\t? ((await listLocalNodes(this.adapter)).find((node) => node.nodeId === this.nodeId)\n\t\t\t\t\t?.principal ?? null)\n\t\t\t: null\n\t\tthis.signedInPrincipal = principal\n\t\tthis.stampingUser = principal\n\t\treturn binding\n\t}\n\n\t/**\n\t * The user signed out: inserts stop stamping `stamp('userId')` fields with the previous\n\t * user. The node binding is left as it is (the next sign-in decides it).\n\t */\n\tclearSignedInUser(): void {\n\t\t// Sign-out: what this tab was showing as pending was the signed-out user's (I12).\n\t\tthis.overlayController?.clear()\n\t\tthis.stampingUser = null\n\t\t// The purge is asynchronous; a failure is reported (SEED_PURGE_FAILED), not lost.\n\t\tvoid this.clearSeedsAtClearPoint('sign-out').catch(() => undefined)\n\t}\n\n\t/**\n\t * The sync server refused this store's pinned node id because another user owns it\n\t * (`owned: true`), or later accepted it (`false`). A pinned node cannot move to a fresh\n\t * id, so writes made under it could only ever upload as its owner: while the server\n\t * says so, local writes are refused (F9). A no-op for a store whose node is not pinned\n\t * (it moves to a fresh node instead).\n\t *\n\t * @param owned - Whether the server reported the node owned by another user\n\t */\n\tsetPinnedNodeOwnedElsewhere(owned: boolean): void {\n\t\tif (!this.configNodeId) return\n\t\tthis.pinnedNodeRefusedByServer = owned\n\t}\n\n\t/**\n\t * Make this store read-only (a reason) or writable again (null). While read-only, every local\n\t * write (insert, update, delete, transaction) throws {@link StoreReadOnlyError} before anything\n\t * is recorded; reads, subscriptions and incoming sync carry on. It applies to this app instance\n\t * only and is not persisted.\n\t *\n\t * @param reason - Why, in words a person reads (\"previewing as Ama\"); null to allow writes again\n\t */\n\tsetReadOnly(reason: string | null): void {\n\t\tthis.readOnlyReason = reason && reason.trim() !== '' ? reason : null\n\t}\n\n\t/** The reason this store is read-only, or null when it is writable. */\n\tgetReadOnlyReason(): string | null {\n\t\treturn this.readOnlyReason\n\t}\n\n\t/** Throws when a local write is not allowed now (read-only, or the node is another user's). */\n\tassertWritable(): void {\n\t\tthis.assertLocalWriteAllowed()\n\t}\n\n\t/** Refuse a local write while read-only, or while the pinned node belongs to another user (F9). */\n\tprivate assertLocalWriteAllowed(): void {\n\t\tif (this.readOnlyReason !== null) throw new StoreReadOnlyError(this.readOnlyReason)\n\t\tif (this.pinnedNodeOwnedBy === null && !this.pinnedNodeRefusedByServer) return\n\t\tthrow new NodeOwnedByAnotherUserError(this.nodeId, this.signedInPrincipal)\n\t}\n\n\tprivate async bindPrincipalToNode(principal: string): Promise<PrincipalBinding> {\n\t\tthis.ensureOpen()\n\t\tconst previousNodeId = this.nodeId\n\t\tconst nodes = await listLocalNodes(this.adapter)\n\t\tconst current = nodes.find((node) => node.nodeId === this.nodeId)\n\t\tconst owner = current?.principal ?? null\n\t\tif (owner === principal) {\n\t\t\treturn { nodeId: this.nodeId, previousNodeId, switched: false, conflict: false }\n\t\t}\n\t\tif (owner === null) {\n\t\t\tconst written = (await this.loadVersionVector()).get(this.nodeId) ?? 0\n\t\t\tif (written === 0 && !(current?.accepted ?? false)) {\n\t\t\t\tawait setLocalNodePrincipal(this.adapter, this.nodeId, principal, 'fresh')\n\t\t\t\treturn { nodeId: this.nodeId, previousNodeId, switched: false, conflict: false }\n\t\t\t}\n\t\t\tif (this.configNodeId) {\n\t\t\t\t// Cannot move: the server decides whose it is at the first handshake.\n\t\t\t\treturn { nodeId: this.nodeId, previousNodeId, switched: false, conflict: false }\n\t\t\t}\n\t\t} else if (this.configNodeId) {\n\t\t\treturn { nodeId: this.nodeId, previousNodeId, switched: false, conflict: true }\n\t\t}\n\t\tif (this.isolation === 'per-tab') {\n\t\t\t// A per-tab node belongs to its tab; another user in this tab gets a fresh one.\n\t\t\tconst fresh = generateUUIDv7()\n\t\t\tawait registerLocalNode(this.adapter, fresh)\n\t\t\tawait setLocalNodePrincipal(this.adapter, fresh, principal, 'fresh')\n\t\t\tsavePerTabNodeId(this.dbName, fresh)\n\t\t\tthis.releaseNodeLock?.()\n\t\t\tthis.releaseNodeLock = acquireNodeLock(nodeLockName(this.dbName, fresh))\n\t\t\tawait this.rebindToNode(fresh)\n\t\t\treturn { nodeId: fresh, previousNodeId, switched: true, conflict: false }\n\t\t}\n\t\tconst own = nodes\n\t\t\t.filter((node) => node.principal === principal && !node.held)\n\t\t\t.sort((a, b) => b.createdAt - a.createdAt)[0]\n\t\tif (own) {\n\t\t\tawait this.switchNodeId(own.nodeId)\n\t\t\treturn { nodeId: own.nodeId, previousNodeId, switched: true, conflict: false }\n\t\t}\n\t\tconst fresh = generateUUIDv7()\n\t\tawait this.adapter.transaction((tx) => moveDatabaseNodeId(tx, fresh))\n\t\tawait registerLocalNode(this.adapter, fresh)\n\t\tawait setLocalNodePrincipal(this.adapter, fresh, principal, 'fresh')\n\t\tawait this.rebindToNode(fresh)\n\t\treturn { nodeId: fresh, previousNodeId, switched: true, conflict: false }\n\t}\n\n\t/**\n\t * A sync handshake as `nodeId` was accepted for `principal` (RT-50): bind an unbound\n\t * node (or replace a guessed binding) from the server's answer.\n\t */\n\tasync confirmNodePrincipal(nodeId: string, principal: string): Promise<void> {\n\t\tthis.ensureOpen()\n\t\tawait confirmLocalNodePrincipal(this.adapter, nodeId, principal)\n\t}\n\n\t/**\n\t * The sync server refused `nodeId` for `principal` (RT-50): clear a guessed binding,\n\t * and remember that an unbound node is not theirs.\n\t */\n\tasync recordNodeRefusedFor(nodeId: string, principal: string): Promise<void> {\n\t\tthis.ensureOpen()\n\t\tawait recordLocalNodeRefusedFor(this.adapter, nodeId, principal)\n\t}\n\n\t/**\n\t * Assign a held, unbound local node's writes to `principal` (RT-50): an explicit app\n\t * decision for writes nobody can attribute (a database that never synced).\n\t *\n\t * @returns false when the node is unknown, the store's own, already bound, or was\n\t *   refused for `principal` by the server\n\t */\n\tasync assignNodePrincipal(nodeId: string, principal: string): Promise<boolean> {\n\t\tthis.ensureOpen()\n\t\tif (nodeId === this.nodeId) return false\n\t\treturn assignLocalNodePrincipal(this.adapter, nodeId, principal)\n\t}\n\n\t/**\n\t * Forget a local node other than the store's own whatever it still holds (RT-50: the\n\t * app discarded its held writes, which were marked never to upload first).\n\t */\n\tasync dropLocalNode(nodeId: string): Promise<void> {\n\t\tthis.ensureOpen()\n\t\tif (nodeId === this.nodeId) return\n\t\tawait dropLocalNode(this.adapter, nodeId)\n\t}\n\n\t/** The adoption schedule of this database's local nodes (RT-46). */\n\tasync loadAdoptionSchedule(): Promise<AdoptionSchedule> {\n\t\tthis.ensureOpen()\n\t\treturn loadAdoptionSchedule(this.adapter)\n\t}\n\n\t/** Persist the adoption schedule (RT-46). */\n\tasync saveAdoptionSchedule(schedule: AdoptionSchedule): Promise<void> {\n\t\tthis.ensureOpen()\n\t\tawait saveAdoptionSchedule(this.adapter, schedule)\n\t}\n\n\t/**\n\t * Raise a local node's sequence counter to at least `floor`, in a transaction (the\n\t * same MAX every reservation uses, W6), so the next write never reuses a number the\n\t * server already holds (RT-35: the device lost the tail of its log, for example on a\n\t * reload inside the IndexedDB snapshot window or after restoring an older copy).\n\t *\n\t * @returns Whether the counter moved\n\t */\n\tasync raiseSequenceFloor(nodeId: string, floor: number): Promise<boolean> {\n\t\tthis.ensureOpen()\n\t\tlet raised = false\n\t\tawait this.adapter.transaction(async (tx) => {\n\t\t\tconst rows = await tx.query<VersionVectorRow>(\n\t\t\t\t'SELECT sequence_number FROM _kora_version_vector WHERE node_id = ?',\n\t\t\t\t[nodeId],\n\t\t\t)\n\t\t\tconst current = rows[0]?.sequence_number ?? 0\n\t\t\tif (floor <= current) return\n\t\t\tawait tx.execute(\n\t\t\t\t`INSERT INTO _kora_version_vector (node_id, sequence_number) VALUES (?, ?)\n     ON CONFLICT(node_id) DO UPDATE SET sequence_number = MAX(sequence_number, excluded.sequence_number)`,\n\t\t\t\t[nodeId, floor],\n\t\t\t)\n\t\t\traised = true\n\t\t})\n\t\tif (raised) {\n\t\t\tconst previous = this.versionVector.get(nodeId) ?? 0\n\t\t\tthis.versionVector.set(nodeId, Math.max(previous, floor))\n\t\t\tif (nodeId === this.nodeId) this.sequenceNumber = Math.max(this.sequenceNumber, floor)\n\t\t}\n\t\treturn raised\n\t}\n\n\t/**\n\t * Give one of a local node's operations a fresh sequence number above `floor`\n\t * (RT-35): the server refused it with `SEQUENCE_CONFLICT` because it holds another\n\t * operation of this node under that number (one this device lost). A version-1\n\t * operation keeps its id (its hash does not cover the sequence number), exactly like\n\t * the W6 sequence repair; a version-2 operation (protocol v2) is re-hashed under the\n\t * new number, so it carries a new id. The old identity is recorded in\n\t * `_kora_seq_conflicts` (`reemitted_as`).\n\t *\n\t * A new id would leave later operations naming the old one in `causalDeps`: those in\n\t * `rewritableDependents` (operations the server never stored: never sent) are\n\t * rewritten to name the new id, and re-hashed, transitively, in the same\n\t * transaction. Dependents already sent keep their ids (the server may hold them);\n\t * their dep resolves through the `_kora_seq_conflicts` record. Every touched record\n\t * is re-folded (fold stamps carry operation ids).\n\t *\n\t * @param rewritableDependents - Ids of this node's operations that were never sent\n\t * @returns The renumbered operation and the rewritten dependents, or null when the\n\t *   operation is not in the log\n\t */\n\tasync resequenceOperation(\n\t\toperationId: string,\n\t\tnodeId: string,\n\t\tfloor: number,\n\t\trewritableDependents: readonly string[] = [],\n\t): Promise<ResequenceResult | null> {\n\t\tthis.ensureOpen()\n\t\tconst found: { result: ResequenceResult | null } = { result: null }\n\t\tconst collections = Object.keys(this.schema.collections)\n\t\tawait this.adapter.transaction(async (tx) => {\n\t\t\tfor (const collection of collections) {\n\t\t\t\tconst table = quoteIdent(`_kora_ops_${collection}`)\n\t\t\t\tconst rows = await tx.query<OperationRow>(\n\t\t\t\t\t`SELECT * FROM ${table} WHERE id = ? AND node_id = ?`,\n\t\t\t\t\t[operationId, nodeId],\n\t\t\t\t)\n\t\t\t\tconst row = rows[0]\n\t\t\t\tif (!row) continue\n\t\t\t\tawait tx.execute(\n\t\t\t\t\t`INSERT INTO _kora_version_vector (node_id, sequence_number) VALUES (?, ?)\n     ON CONFLICT(node_id) DO UPDATE SET sequence_number = MAX(sequence_number, excluded.sequence_number)`,\n\t\t\t\t\t[nodeId, floor],\n\t\t\t\t)\n\t\t\t\tconst sequence = await allocateNextSequenceInTransaction(tx, nodeId)\n\t\t\t\t// A version-2 id covers the sequence number (CORE-1): such an operation is\n\t\t\t\t// re-hashed under the new number (the server never stored it).\n\t\t\t\tconst moved = await renumberOperationRow(tx, collection, row, sequence)\n\t\t\t\tawait insertConflictRow(\n\t\t\t\t\ttx,\n\t\t\t\t\tcollection,\n\t\t\t\t\trow,\n\t\t\t\t\t'server-sequence-conflict',\n\t\t\t\t\tmoved.id,\n\t\t\t\t\tsequence,\n\t\t\t\t\tDate.now(),\n\t\t\t\t)\n\t\t\t\tconst idMapping: Record<string, string> = moved.id !== row.id ? { [row.id]: moved.id } : {}\n\t\t\t\tconst rewritable = new Set(rewritableDependents)\n\t\t\t\trewritable.delete(row.id)\n\t\t\t\tconst dependents =\n\t\t\t\t\tmoved.id !== row.id\n\t\t\t\t\t\t? await rewriteDependentsInTx(tx, collections, nodeId, idMapping, rewritable)\n\t\t\t\t\t\t: []\n\t\t\t\tfound.result = { operation: moved, dependents, idMapping }\n\t\t\t\treturn\n\t\t\t}\n\t\t})\n\t\tconst result = found.result\n\t\tif (!result) return null\n\t\tthis.recordOperationSequence(result.operation)\n\t\tif (Object.keys(result.idMapping).length > 0) {\n\t\t\tawait this.refoldRecordsOf([result.operation.id, ...result.dependents.map((op) => op.id)])\n\t\t}\n\t\treturn result\n\t}\n\n\t/**\n\t * Durability barrier (RT-35): resolves once every write committed so far is durable\n\t * on this device. Sync awaits it before an operation leaves the device.\n\t */\n\tasync ensureDurable(): Promise<void> {\n\t\tthis.ensureOpen()\n\t\tawait this.adapter.ensureDurable?.()\n\t}\n\n\t/** Record operations the server refused for good (RT-36). Never cleared. */\n\tasync recordTerminalRejections(entries: TerminalRejection[]): Promise<void> {\n\t\tthis.ensureOpen()\n\t\tawait recordTerminalRejections(this.adapter, entries)\n\t\t// The server never stored these operations: re-fold their records without them,\n\t\t// so this device converges to the server's state (W7 step 2).\n\t\tawait this.refoldRecordsOf(entries.map((entry) => entry.operationId))\n\t}\n\n\t/** Which of these operation ids the server refused for good (RT-36). */\n\tasync findTerminalRejections(operationIds: string[]): Promise<Set<string>> {\n\t\tthis.ensureOpen()\n\t\treturn findTerminalRejections(this.adapter, operationIds)\n\t}\n\n\t/** Every node id this database authored operations under (RT-38, RT-40). */\n\tasync listLocalNodes(): Promise<LocalNodeRecord[]> {\n\t\tthis.ensureOpen()\n\t\treturn listLocalNodes(this.adapter)\n\t}\n\n\t/** Forget a drained local node other than this store's own (RT-40). */\n\tasync forgetLocalNode(nodeId: string): Promise<void> {\n\t\tthis.ensureOpen()\n\t\tif (nodeId === this.nodeId) return\n\t\tawait forgetLocalNode(this.adapter, nodeId)\n\t}\n\n\t/** The current refusal cycle: the count of accepted sync handshakes (RT-38). */\n\tasync loadAcceptedCycle(): Promise<number> {\n\t\tthis.ensureOpen()\n\t\treturn loadAcceptedCycle(this.adapter)\n\t}\n\n\t/** Record an accepted sync handshake as `nodeId` (RT-38). */\n\tasync markLocalNodeAccepted(nodeId: string): Promise<void> {\n\t\tthis.ensureOpen()\n\t\tawait markLocalNodeAccepted(this.adapter, nodeId)\n\t}\n\n\t/** Record that the sync server refused `nodeId`; `held` holds its writes (RT-38). */\n\tasync markLocalNodeRefused(nodeId: string, held: boolean): Promise<void> {\n\t\tthis.ensureOpen()\n\t\tawait markLocalNodeRefused(this.adapter, nodeId, held)\n\t}\n\n\t/**\n\t * Retire another local node whose writes belong to `principal` (bound as `binding`):\n\t * it is never used for a session again, and its writes the server does not hold are\n\t * re-authored under this store's node ({@link reauthorIntoOwnNode}).\n\t */\n\tasync retireLocalNode(\n\t\tnodeId: string,\n\t\tprincipal: string,\n\t\tbinding: 'app' | 'fresh' | 'database',\n\t): Promise<void> {\n\t\tthis.ensureOpen()\n\t\tif (nodeId === this.nodeId) return\n\t\tawait retireLocalNode(this.adapter, nodeId, principal, binding)\n\t}\n\n\t/**\n\t * Which of `operations` (all of local node `nodeId`) this database authored itself\n\t * rather than received under that node (see `findAuthoredHere` in local-sync-records).\n\t */\n\tasync findAuthoredHere(\n\t\tnodeId: string,\n\t\toperations: ReadonlyArray<{ id: string; sequenceNumber: number }>,\n\t): Promise<Set<string>> {\n\t\tthis.ensureOpen()\n\t\treturn findAuthoredHere(this.adapter, nodeId, operations)\n\t}\n\n\t/**\n\t * Take over another local node's unsynced writes (RT-40): resolves to a release\n\t * function when no live tab uses `nodeId` (its lock is free), or null when one does.\n\t * Without Web Locks (Node, old browsers) the node is assumed free.\n\t */\n\tasync claimLocalNode(nodeId: string): Promise<(() => void) | null> {\n\t\tthis.ensureOpen()\n\t\tif (nodeId === this.nodeId) return null\n\t\treturn tryAcquireNodeLock(nodeLockName(this.dbName, nodeId))\n\t}\n\n\t/** Whether a live tab holds `nodeId` (per-tab isolation, RT-40). */\n\tasync isLocalNodeLive(nodeId: string): Promise<boolean> {\n\t\tthis.ensureOpen()\n\t\tif (nodeId === this.nodeId) return true\n\t\treturn isNodeLockHeld(nodeLockName(this.dbName, nodeId))\n\t}\n\n\t/**\n\t * Re-stamp never-acknowledged local operations after a fast device clock was\n\t * corrected, so sync can resume immediately. Safe because unacknowledged\n\t * operations are private to this device (like unpushed git commits);\n\t * acknowledged/shared operations are immutable and never touched.\n\t *\n\t * After the rewrite the store's HLC is advanced past the highest new\n\t * timestamp so subsequent local writes keep sorting after the rebased ops.\n\t * No data-change notifications are emitted: materialized values are\n\t * unchanged, only version stamps move.\n\t */\n\tasync rebaseUnsyncedOperations(\n\t\tunsyncedOpIds: string[],\n\t\tcorrectedNowMs: number,\n\t): Promise<ClockRebaseResult> {\n\t\tthis.ensureOpen()\n\t\t// Under the write gate, so a tab whose build was superseded cannot rewrite the log. The\n\t\t// read phase and the rewrite share one transaction (rebaseUnsyncedOperationsInLog), so no\n\t\t// local write lands between them.\n\t\treturn this.writeGate.run({ operation: 'rebase' }, async () => {\n\t\t\t// Local writes that start from now on wait until the outcome is settled (the remap\n\t\t\t// committed, or undone): the adapter's lock wakes a queued write before this code\n\t\t\t// learns whether the rewrite committed. Taken before any await.\n\t\t\tconst releaseWrites = this.causalTracker?.hold()\n\t\t\t// Re-stamped operations order differently: their records are re-folded in the\n\t\t\t// rewrite's transaction, so a crash never leaves the old stamps in a fold state.\n\t\t\tconst touched = new Map<string, Set<string>>()\n\t\t\tconst refold = this.refoldInRewrite(touched)\n\t\t\t// Undoes the head remap when the rewrite does not commit.\n\t\t\tlet undoRemap: (() => void) | undefined\n\t\t\tlet result: ClockRebaseResult\n\t\t\ttry {\n\t\t\t\tresult = await rebaseUnsyncedOperationsInLog(\n\t\t\t\t\tthis.adapter,\n\t\t\t\t\tthis.schema,\n\t\t\t\t\tunsyncedOpIds,\n\t\t\t\t\tcorrectedNowMs,\n\t\t\t\t\t{\n\t\t\t\t\t\tinTransaction: async (tx, operations, rewrite) => {\n\t\t\t\t\t\t\tawait refold(tx, operations)\n\t\t\t\t\t\t\t// Last in the rewrite's transaction, before it commits: a local write queued\n\t\t\t\t\t\t\t// behind it (writes build their causalDeps inside their own transaction)\n\t\t\t\t\t\t\t// already sees the new ids and a clock past every rewritten stamp. The\n\t\t\t\t\t\t\t// store's code after the transaction would run too late.\n\t\t\t\t\t\t\tundoRemap = this.causalTracker?.remapIds(rewrite.idMapping)\n\t\t\t\t\t\t\tif (rewrite.newMaxTimestamp && this.clock) {\n\t\t\t\t\t\t\t\t// Only forward; harmless if the rewrite then rolls back.\n\t\t\t\t\t\t\t\tthis.clock.advanceTo(rewrite.newMaxTimestamp)\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} catch (error) {\n\t\t\t\tundoRemap?.()\n\t\t\t\tthrow error\n\t\t\t} finally {\n\t\t\t\treleaseWrites?.()\n\t\t\t}\n\t\t\tthis.invalidateRefolded(touched)\n\t\t\treturn result\n\t\t})\n\t}\n\n\t/**\n\t * Count of local operations ahead of the server version vector.\n\t */\n\tasync countUnsyncedOperations(serverVector: VersionVector): Promise<number> {\n\t\tconst ops = await this.getUnsyncedOperations(serverVector)\n\t\treturn ops.length\n\t}\n\n\t/**\n\t * Compact the local operation log. Only removes ops the server has acknowledged\n\t * (per {@link CompactionStrategy}). With the W7 fold (STORE-14), the effect of the\n\t * removed operations is first joined into each record's base fold state, so a\n\t * re-fold (rejection exclusion, a later re-materialization) and the merge of a\n\t * late operation stay exact; delete, atomic and custom-resolver operations are\n\t * kept, and a re-delivered compacted id is a duplicate by its node's compacted\n\t * prefix.\n\t */\n\tcompact(strategy: CompactionStrategy): Promise<CompactionResult> {\n\t\treturn this.writeGate.run({ operation: 'compact' }, () => this.compactNow(strategy))\n\t}\n\n\tprivate async compactNow(strategy: CompactionStrategy): Promise<CompactionResult> {\n\t\tthis.ensureOpen()\n\t\tconst fold = this.activeFold()\n\t\tif (strategy.mode === 'never') {\n\t\t\treturn compactOperationLog(this.adapter, this.schema, strategy, createVersionVector())\n\t\t}\n\n\t\tconst serverVector = strategy.serverVector ?? (await loadLastAckedServerVector(this.adapter))\n\t\tif (fold) {\n\t\t\treturn compactFoldedLog(this.adapter, this.schema, fold, strategy, serverVector)\n\t\t}\n\t\treturn compactOperationLog(this.adapter, this.schema, strategy, serverVector)\n\t}\n\n\t/**\n\t * Merge session remote vector with persisted last-acked vector (max per node).\n\t */\n\tmergeServerVectors(sessionVector: VersionVector, persistedVector: VersionVector): VersionVector {\n\t\treturn mergeVersionVectors(persistedVector, sessionVector)\n\t}\n\n\tasync getLatestLocalOperationForRecord(\n\t\tcollection: string,\n\t\trecordId: string,\n\t): Promise<Operation | null> {\n\t\tthis.ensureOpen()\n\t\tconst rows = await this.adapter.query<OperationRow>(\n\t\t\t`SELECT * FROM ${quoteIdent(`_kora_ops_${collection}`)} WHERE node_id = ? AND record_id = ? ORDER BY sequence_number DESC LIMIT 1`,\n\t\t\t[this.nodeId, recordId],\n\t\t)\n\t\tconst row = rows[0]\n\t\tif (!row) {\n\t\t\treturn null\n\t\t}\n\t\treturn deserializeOperationWithCollection(row, collection)\n\t}\n\n\t/**\n\t * Latest operation for a record from any node (for 3-way merge when local op log is empty).\n\t */\n\tasync getLatestOperationForRecord(\n\t\tcollection: string,\n\t\trecordId: string,\n\t): Promise<Operation | null> {\n\t\tthis.ensureOpen()\n\t\tconst rows = await this.adapter.query<OperationRow>(\n\t\t\t`SELECT * FROM ${quoteIdent(`_kora_ops_${collection}`)} WHERE record_id = ?`,\n\t\t\t[recordId],\n\t\t)\n\n\t\tlet latest: Operation | null = null\n\t\tfor (const row of rows) {\n\t\t\tconst op = deserializeOperationWithCollection(row, collection)\n\t\t\tif (!latest || HybridLogicalClock.compare(op.timestamp, latest.timestamp) > 0) {\n\t\t\t\tlatest = op\n\t\t\t}\n\t\t}\n\t\treturn latest\n\t}\n\n\t/**\n\t * All operations for a record, sorted in HLC total order (wallTime, logical,\n\t * nodeId). Used by the apply pipeline to materialize atomic-op fields by folding\n\t * the record's log, matching the server's materialization exactly.\n\t */\n\tasync getOperationsForRecord(collection: string, recordId: string): Promise<Operation[]> {\n\t\tthis.ensureOpen()\n\t\tconst rows = [\n\t\t\t...(await this.adapter.query<OperationRow>(\n\t\t\t\t`SELECT * FROM ${quoteIdent(`_kora_ops_${collection}`)} WHERE record_id = ?`,\n\t\t\t\t[recordId],\n\t\t\t)),\n\t\t\t// Other nodes' operations kept only in the sequence-conflicts table still\n\t\t\t// belong to the record's history.\n\t\t\t...(await loadRetainedConflictRows(\n\t\t\t\t(sql, params) => this.adapter.query(sql, params),\n\t\t\t\tcollection,\n\t\t\t\trecordId,\n\t\t\t)),\n\t\t]\n\t\tconst ops = rows.map((row) => deserializeOperationWithCollection(row, collection))\n\t\tops.sort((a, b) => HybridLogicalClock.compare(a.timestamp, b.timestamp))\n\t\treturn ops\n\t}\n\n\t/** Expose the subscription manager for direct access (e.g., by QueryBuilder) */\n\tgetSubscriptionManager(): SubscriptionManager {\n\t\treturn this.subscriptionManager\n\t}\n\n\t/**\n\t * Get the sequence manager for offline-safe sequence generation.\n\t * @throws {StoreNotOpenError} If the store is not open\n\t */\n\tgetSequenceManager(): SequenceManager {\n\t\tthis.ensureOpen()\n\t\tif (!this.sequenceManager) {\n\t\t\tthrow new StoreNotOpenError()\n\t\t}\n\t\treturn this.sequenceManager\n\t}\n\n\t/**\n\t * Create a TransactionContext for atomic multi-collection operations.\n\t * The returned context buffers all mutations and commits them atomically.\n\t *\n\t * After commit, the caller is responsible for notifying subscriptions\n\t * and emitting events for each operation.\n\t */\n\tcreateTransaction(): TransactionContext {\n\t\tthis.ensureOpen()\n\t\tif (!this.clock) {\n\t\t\tthrow new StoreNotOpenError()\n\t\t}\n\t\tconst beforeLocalDelete = this.localMutationHandler?.beforeLocalDelete\n\t\tconst fold = this.activeFold()\n\t\treturn new TransactionContext({\n\t\t\t...(this.maxOperationBytes !== undefined\n\t\t\t\t? { maxOperationBytes: this.maxOperationBytes }\n\t\t\t\t: {}),\n\t\t\tassertLocalWriteAllowed: () => this.assertLocalWriteAllowed(),\n\t\t\t// Instant updates (S6a): rows the callback reads can serve as the group's bases.\n\t\t\t...(this.overlayController\n\t\t\t\t? {\n\t\t\t\t\t\treadToken: (collection: string) =>\n\t\t\t\t\t\t\tthis.overlayController?.registry.seedStamp(collection) ?? -1,\n\t\t\t\t\t}\n\t\t\t\t: {}),\n\t\t\t// Captured with the node id below: a transaction's inserts are stamped as the user\n\t\t\t// whose node authors them, even if another user signs in before it commits.\n\t\t\tsignedInUser: (\n\t\t\t\t(user) => () =>\n\t\t\t\t\tuser\n\t\t\t)(this.stampingUser),\n\t\t\t...(fold ? { fold } : {}),\n\t\t\tschema: this.schema,\n\t\t\tadapter: this.adapter,\n\t\t\tclock: this.clock,\n\t\t\tnodeId: this.nodeId,\n\t\t\trelationEnforcer: this.relationEnforcer,\n\t\t\tcausalTracker: this.causalTracker,\n\t\t\t...(this.secretKeyProvider ? { secretKeyProvider: this.secretKeyProvider } : {}),\n\t\t\t...(beforeLocalDelete\n\t\t\t\t? { beforeLocalDelete: beforeLocalDelete.bind(this.localMutationHandler) }\n\t\t\t\t: {}),\n\t\t\tonStorageError: (error) => this.reportStorageError(error),\n\t\t})\n\t}\n\n\t/**\n\t * Execute a function within a transaction. All mutations performed on the\n\t * TransactionContext are committed atomically. Subscription notifications\n\t * are batched and fired after the commit.\n\t *\n\t * If the function throws, the transaction is rolled back and the error is re-thrown.\n\t *\n\t * @param fn - Function receiving a TransactionContext for buffered operations\n\t * @returns The operations that were committed\n\t */\n\ttransaction(fn: (tx: TransactionContext) => Promise<void>): Promise<Operation[]> {\n\t\treturn this.writeGate.run({ operation: 'transaction' }, () => this.transactionNow(fn))\n\t}\n\n\tprivate async transactionNow(\n\t\tfn: (tx: TransactionContext) => Promise<void>,\n\t): Promise<Operation[]> {\n\t\t// The transaction commits after the callback's awaits: the observer of the code\n\t\t// that started it is captured now, while it is current.\n\t\tconst observer = currentWriteObserver()\n\t\tconst tx = this.createTransaction()\n\t\ttry {\n\t\t\tawait fn(tx)\n\t\t} catch (error) {\n\t\t\ttx.rollback()\n\t\t\tthrow error\n\t\t}\n\t\tconst { operations } = await tx.commit(this.transactionOverlayOptions())\n\t\tnotifyWriteObserver(observer, operations)\n\n\t\t// Notify subscriptions and emit events after commit\n\t\tfor (const op of operations) {\n\t\t\tthis.publishLocalOperation(op.collection, op)\n\t\t}\n\n\t\tif (this.adapter.ensureDurable) {\n\t\t\ttry {\n\t\t\t\tawait this.adapter.ensureDurable()\n\t\t\t\tthis.reportWriteDurabilityRestored()\n\t\t\t} catch (error) {\n\t\t\t\tthis.reportStorageError(error)\n\t\t\t\tthrow this.reportWriteDurabilityError(\n\t\t\t\t\terror,\n\t\t\t\t\toperations.map((operation) => operation.id),\n\t\t\t\t)\n\t\t\t}\n\t\t}\n\n\t\treturn operations\n\t}\n\n\t/**\n\t * Instant updates for a transaction (S6a): predict its sealed buffer as one entry group.\n\t * Undefined (the commit runs exactly as without the overlay) unless the store has one.\n\t */\n\tprivate transactionOverlayOptions(): TransactionCommitOptions | undefined {\n\t\tconst overlay = this.overlayController?.overlay\n\t\tif (!overlay) return undefined\n\t\tconst fold = this.activeFold()\n\t\tconst env = {\n\t\t\tschema: this.schema,\n\t\t\tnodeId: this.nodeId,\n\t\t\tadapter: this.adapter,\n\t\t\tassertLocalWriteAllowed: () => this.assertLocalWriteAllowed(),\n\t\t\t...(fold ? { fold } : {}),\n\t\t}\n\t\treturn {\n\t\t\tprepare: (writes, observed) => {\n\t\t\t\t// Writes called while this group reads wait for it, and it for earlier readers.\n\t\t\t\tconst order = groupOrderKeys(writes)\n\t\t\t\tconst turn = overlay.registry.order.enter(order.keys, { all: order.all })\n\t\t\t\tconst start = (): TransactionRegistrar | Promise<TransactionRegistrar> => {\n\t\t\t\t\ttry {\n\t\t\t\t\t\tconst reads = readGroupBasesIfNeeded(env, overlay, writes, observed)\n\t\t\t\t\t\tif (reads instanceof Promise) turn.hold()\n\t\t\t\t\t\tconst registrar = (resolved: Awaited<typeof reads>): TransactionRegistrar => {\n\t\t\t\t\t\t\treturn () => {\n\t\t\t\t\t\t\t\ttry {\n\t\t\t\t\t\t\t\t\treturn trackGroup(env, overlay, writes, resolved, observed)\n\t\t\t\t\t\t\t\t} finally {\n\t\t\t\t\t\t\t\t\t// Registered in the step that starts the storage transaction.\n\t\t\t\t\t\t\t\t\tturn.release()\n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t}\n\t\t\t\t\t\treturn reads instanceof Promise\n\t\t\t\t\t\t\t? reads.then(registrar, (error) => {\n\t\t\t\t\t\t\t\t\tturn.release()\n\t\t\t\t\t\t\t\t\tthrow error\n\t\t\t\t\t\t\t\t})\n\t\t\t\t\t\t\t: registrar(reads)\n\t\t\t\t\t} catch (error) {\n\t\t\t\t\t\tturn.release()\n\t\t\t\t\t\tthrow error\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\treturn turn.wait ? turn.wait.then(start) : start()\n\t\t\t},\n\t\t}\n\t}\n\n\t/**\n\t * Export all data as a portable backup binary.\n\t * Includes operations, version vector, metadata, and optionally materialized records.\n\t *\n\t * @param options - Backup options (includeRecords, collections, onProgress)\n\t * @returns Backup as a Uint8Array\n\t */\n\tasync exportBackup(options?: BackupOptions): Promise<Uint8Array> {\n\t\tthis.ensureOpen()\n\t\tconst { exportBackup: doExport } = await import('../backup/backup')\n\t\treturn doExport(this.adapter, this.schema, this.nodeId, this.schema.version, options)\n\t}\n\n\t/**\n\t * Restore data from a backup binary (format version 2, STORE-5).\n\t *\n\t * - `merge: true`: every backup operation is applied through the remote-apply path\n\t *   (deduplicated by id, merged per field), the version vector advances by MAX, and\n\t *   nothing of the exporting device's identity or sync state is imported.\n\t * - Replace (default): the data is replaced by the backup's while this device keeps\n\t *   its node id, local nodes and principal bindings, its own sequence counters never\n\t *   move backwards, and unsynced own writes are kept (see\n\t *   `RestoreOptions.keepUnsyncedWrites`). Then {@link reloadFromDisk} runs.\n\t *\n\t * A version-1 file (Kora 1.0.0-beta.12 and earlier) is converted first, exactly as\n\t * `convertBackupV1` does (`result.convertedFromVersion: 1`); one holding an operation\n\t * whose timestamp cannot be recovered is refused (`BACKUP_OPERATION_INVALID`).\n\t *\n\t * @param data - The backup data\n\t * @param options - Restore options (merge, collections, keepUnsyncedWrites, onProgress)\n\t * @param internal - `applyOperation`: the app's remote-apply path (defaults to\n\t *   {@link applyRemoteOperation}); `createApp` passes the merge-aware pipeline sync uses\n\t * @returns Result of the restore operation\n\t */\n\timportBackup(\n\t\tdata: Uint8Array,\n\t\toptions?: RestoreOptions,\n\t\tinternal?: { applyOperation?: (operation: Operation) => Promise<ApplyResult> },\n\t): Promise<RestoreResult> {\n\t\treturn this.writeGate.run({ operation: 'import-backup' }, () =>\n\t\t\tthis.importBackupNow(data, options, internal),\n\t\t)\n\t}\n\n\tprivate async importBackupNow(\n\t\tdata: Uint8Array,\n\t\toptions?: RestoreOptions,\n\t\tinternal?: { applyOperation?: (operation: Operation) => Promise<ApplyResult> },\n\t): Promise<RestoreResult> {\n\t\tthis.ensureOpen()\n\t\t// The restore rewrites rows underneath any pending write (I12).\n\t\tthis.overlayController?.clear()\n\t\tawait this.clearSeedsAtClearPoint('a restore')\n\t\tconst started = Date.now()\n\t\tconst onProgress = options?.onProgress ?? (() => {})\n\t\tconst { BackupFormatError, convertBackupV1, parseBackup, readBackupManifest } = await import(\n\t\t\t'../backup/backup'\n\t\t)\n\t\tconst { restoreMerge, restoreReplace } = await import('../backup/restore')\n\t\tonProgress({ phase: 'verifying', progress: 0, message: 'Verifying backup' })\n\t\tlet parsed: Awaited<ReturnType<typeof parseBackup>>\n\t\tlet convertedFromVersion: 1 | undefined\n\t\ttry {\n\t\t\t// A version-1 file (beta.12 and earlier) is converted here, with the same\n\t\t\t// deterministic rules as convertBackupV1 (F3): the exporting device's identity is\n\t\t\t// dropped and damaged timestamps are recovered. An operation that cannot be\n\t\t\t// recovered still refuses the file; dropping it stays an explicit choice.\n\t\t\tlet bytes = data\n\t\t\tif (readBackupManifest(data).version === 1) {\n\t\t\t\tbytes = await convertBackupV1(data)\n\t\t\t\tconvertedFromVersion = 1\n\t\t\t}\n\t\t\tparsed = await parseBackup(\n\t\t\t\tbytes,\n\t\t\t\toptions?.collections ? { collections: options.collections } : undefined,\n\t\t\t)\n\t\t} catch (error) {\n\t\t\tif (!(error instanceof BackupFormatError)) throw error\n\t\t\treturn {\n\t\t\t\toperationsRestored: 0,\n\t\t\t\trecordsRestored: 0,\n\t\t\t\tsuccess: false,\n\t\t\t\terror: error.message,\n\t\t\t\terrorCode: error.code,\n\t\t\t\tduration: Date.now() - started,\n\t\t\t}\n\t\t}\n\t\tif (parsed.manifest.schemaVersion > this.schema.version) {\n\t\t\treturn {\n\t\t\t\toperationsRestored: 0,\n\t\t\t\trecordsRestored: 0,\n\t\t\t\tsuccess: false,\n\t\t\t\terror: `The backup was written by schema version ${parsed.manifest.schemaVersion}; this app runs version ${this.schema.version}. Update the app before restoring it.`,\n\t\t\t\terrorCode: 'BACKUP_SCHEMA_NEWER',\n\t\t\t\tduration: Date.now() - started,\n\t\t\t}\n\t\t}\n\t\tonProgress({ phase: 'restoring', progress: 0.3, message: 'Restoring' })\n\t\tconst explicitAuthorities = new Set((await loadAuthoritativeNodeIds(this.adapter)) ?? [])\n\t\tconst host = {\n\t\t\tadapter: this.adapter,\n\t\t\tschema: this.schema,\n\t\t\tapplyOperation:\n\t\t\t\tinternal?.applyOperation ?? ((op: Operation) => this.applyRemoteOperation(op)),\n\t\t\tlistLocalNodes: () => listLocalNodes(this.adapter),\n\t\t\tisServerAuthority: (nodeId: string) =>\n\t\t\t\tisReservedNodeId(nodeId) || explicitAuthorities.has(nodeId),\n\t\t}\n\t\tif (options?.merge) await this.mergeBackupFoldState(parsed, options.collections !== undefined)\n\t\tconst counts = options?.merge\n\t\t\t? await restoreMerge(host, parsed, options.collections !== undefined)\n\t\t\t: await restoreReplace(host, parsed, {\n\t\t\t\t\tcollections: options?.collections ?? null,\n\t\t\t\t\tkeepUnsyncedWrites: options?.keepUnsyncedWrites ?? true,\n\t\t\t\t})\n\t\tif (!options?.merge && this.folder) {\n\t\t\t// Restored rows and log replace what the fold states described: rebuild them,\n\t\t\t// from the backup's base states and log (RT-66). A file from an earlier\n\t\t\t// release carries no base states, and its log may have been compacted: its\n\t\t\t// records are rebuilt on top of its rows instead (row snapshots).\n\t\t\tawait this.adapter.execute('DELETE FROM _kora_meta WHERE key = ?', [\n\t\t\t\tFOLD_MATERIALIZATION_META_KEY,\n\t\t\t])\n\t\t\tthis.foldActive = false\n\t\t\tawait this.ensureMaterialization(parsed.manifest.includesFoldState !== true)\n\t\t}\n\t\tawait this.reloadFromDisk()\n\t\tonProgress({ phase: 'restoring', progress: 1, message: 'Done' })\n\t\treturn {\n\t\t\toperationsRestored: counts.operationsRestored,\n\t\t\trecordsRestored: counts.recordsRestored,\n\t\t\t...(options?.merge ? {} : { unsyncedWritesKept: counts.unsyncedWritesKept }),\n\t\t\t...(counts.serverOperationsSkipped\n\t\t\t\t? { serverOperationsSkipped: counts.serverOperationsSkipped }\n\t\t\t\t: {}),\n\t\t\t...(convertedFromVersion ? { convertedFromVersion } : {}),\n\t\t\tsuccess: true,\n\t\t\tduration: Date.now() - started,\n\t\t}\n\t}\n\n\t/**\n\t * Merge mode (RT-66): join the backup's compacted base states and row snapshots\n\t * into this database's, and re-fold those records, before the backup's operations\n\t * are applied. The join is the fold's state-based merge, so the result equals\n\t * folding both devices' histories together. Compacted prefixes advance by MAX\n\t * (unfiltered restores only: the prefix is per node, across collections).\n\t */\n\tprivate async mergeBackupFoldState(\n\t\tparsed: import('../backup/backup').ParsedBackup,\n\t\tfiltered: boolean,\n\t): Promise<void> {\n\t\tconst folder = this.activeFold()\n\t\tif (!folder) return\n\t\tconst touched = new Map<string, Set<string>>()\n\t\tawait this.adapter.transaction(async (tx) => {\n\t\t\tfor (const [rows, kind] of [\n\t\t\t\t[parsed.foldBases, 'base'],\n\t\t\t\t[parsed.foldSnapshots, 'snapshot'],\n\t\t\t] as const) {\n\t\t\t\tfor (const row of rows) {\n\t\t\t\t\tif (!this.schema.collections[row.collection]) continue\n\t\t\t\t\tlet state: FoldState\n\t\t\t\t\ttry {\n\t\t\t\t\t\tstate = deserializeFoldState(row.state)\n\t\t\t\t\t} catch {\n\t\t\t\t\t\tcontinue\n\t\t\t\t\t}\n\t\t\t\t\tif (state.c !== row.collection || state.r !== row.recordId) continue\n\t\t\t\t\tif (kind === 'base') await folder.joinIntoBase(tx, state)\n\t\t\t\t\telse await folder.saveSnapshot(tx, state)\n\t\t\t\t\tconst ids = touched.get(row.collection) ?? new Set<string>()\n\t\t\t\t\tids.add(row.recordId)\n\t\t\t\t\ttouched.set(row.collection, ids)\n\t\t\t\t}\n\t\t\t}\n\t\t\tif (!filtered) {\n\t\t\t\tfor (const [nodeId, sequence] of parsed.compactedThrough) {\n\t\t\t\t\tawait tx.execute(\n\t\t\t\t\t\t`INSERT INTO ${COMPACTED_THROUGH_TABLE} (node_id, sequence_number) VALUES (?, ?)\n     ON CONFLICT(node_id) DO UPDATE SET sequence_number = MAX(sequence_number, excluded.sequence_number)`,\n\t\t\t\t\t\t[nodeId, sequence],\n\t\t\t\t\t)\n\t\t\t\t}\n\t\t\t}\n\t\t\tfor (const [collection, ids] of touched) {\n\t\t\t\tfor (const recordId of ids) await folder.refoldInTx(tx, collection, recordId)\n\t\t\t}\n\t\t})\n\t\tfor (const [collection, ids] of touched)\n\t\t\tthis.subscriptionManager.invalidate(collection, [...ids])\n\t}\n\n\t/**\n\t * Re-read this store's state from the database after it changed underneath it (a\n\t * backup restore): the node id, version vector and own sequence counter, the clock\n\t * (advanced past every timestamp in the log), and a fresh causal tracker. Every live\n\t * query re-runs. The local node registry and terminal rejections are always read\n\t * from the database, so they need no reload.\n\t */\n\tasync reloadFromDisk(): Promise<void> {\n\t\tthis.ensureOpen()\n\t\t// Before the node is rebound and the queries re-run (I12).\n\t\tthis.overlayController?.clear()\n\t\tawait this.clearSeedsAtClearPoint('a reload from disk')\n\t\tlet nodeId = this.nodeId\n\t\tif (!this.configNodeId && this.isolation !== 'per-tab') {\n\t\t\tconst rows = await this.adapter.query<MetaRow>(\n\t\t\t\t\"SELECT value FROM _kora_meta WHERE key = 'node_id'\",\n\t\t\t)\n\t\t\tnodeId = rows[0]?.value ?? this.nodeId\n\t\t}\n\t\tawait this.rebindToNode(nodeId)\n\t\tconst newest = await this.loadNewestLogTimestamp()\n\t\tif (newest && this.clock) {\n\t\t\tthis.clock.advanceTo({ ...newest, nodeId: this.nodeId })\n\t\t}\n\t\tfor (const collection of Object.keys(this.schema.collections)) {\n\t\t\tthis.subscriptionManager.invalidate(collection)\n\t\t}\n\t}\n\n\t/** The greatest HLC timestamp in the operation log (canonical strings sort by HLC). */\n\tprivate async loadNewestLogTimestamp(): Promise<HLCTimestamp | null> {\n\t\tlet newest: string | null = null\n\t\tfor (const collection of Object.keys(this.schema.collections)) {\n\t\t\tconst rows = await this.adapter.query<{ t: string | null }>(\n\t\t\t\t`SELECT MAX(timestamp) AS t FROM ${quoteIdent(`_kora_ops_${collection}`)}`,\n\t\t\t)\n\t\t\tconst value = rows[0]?.t ?? null\n\t\t\tif (value !== null && (newest === null || value > newest)) newest = value\n\t\t}\n\t\treturn newest === null ? null : HybridLogicalClock.deserialize(newest)\n\t}\n\n\t/**\n\t * Read backup manifest without loading the entire backup.\n\t *\n\t * @param data - The raw backup data\n\t * @returns The backup manifest\n\t */\n\tstatic readBackupManifest(data: Uint8Array): BackupManifest {\n\t\treturn readManifest(data)\n\t}\n\n\tprivate recordOperationSequence(operation: Operation): void {\n\t\tconst prev = this.versionVector.get(operation.nodeId) ?? 0\n\t\tif (operation.sequenceNumber > prev) {\n\t\t\tthis.versionVector.set(operation.nodeId, operation.sequenceNumber)\n\t\t}\n\t\tif (operation.nodeId === this.nodeId) {\n\t\t\tthis.sequenceNumber = Math.max(this.sequenceNumber, operation.sequenceNumber)\n\t\t}\n\t}\n\n\t/** Post-commit publication of a committed local operation. */\n\tprivate publishLocalOperation(collection: string, operation: Operation): void {\n\t\tthis.recordOperationSequence(operation)\n\t\tthis.subscriptionManager.notify(collection, operation)\n\t\tthis.emitter?.emit({ type: 'operation:created', operation })\n\t}\n\n\t/**\n\t * Map an out-of-space storage failure to `store:quota-exceeded` (STORE-15).\n\t * The error itself still propagates to the caller; this only makes the\n\t * condition observable on every adapter, not just IndexedDB.\n\t */\n\tprivate reportStorageError(error: unknown): void {\n\t\tif (!isStorageFullError(error)) return\n\t\tthis.emitter?.emit({\n\t\t\ttype: 'store:quota-exceeded',\n\t\t\tdbName: this.dbName,\n\t\t\tmessage: error instanceof Error ? error.message : String(error),\n\t\t})\n\t}\n\n\t/**\n\t * Whether resolved local writes are durable (`app.storage.writes`). `failing` after a\n\t * committed write could not be confirmed on durable storage; `permanent` when its\n\t * snapshot lineage was superseded, which holds until the page is reloaded.\n\t */\n\tgetWriteDurability(): WriteDurabilityState {\n\t\tif (!this.writeDurabilityFailing) return { state: 'durable' }\n\t\treturn {\n\t\t\tstate: 'failing',\n\t\t\tpermanent: this.writeDurabilityPermanentlyFailed,\n\t\t\tsince: this.writeDurabilitySince,\n\t\t\tmessage: this.writeDurabilityMessage,\n\t\t}\n\t}\n\n\tprivate reportWriteDurabilityError(\n\t\terror: unknown,\n\t\toperationIds: readonly string[],\n\t): WriteNotDurableError {\n\t\tconst wrapped = new WriteNotDurableError(operationIds, error)\n\t\tif (!this.writeDurabilityFailing) this.writeDurabilitySince = Date.now()\n\t\tthis.writeDurabilityFailing = true\n\t\tthis.writeDurabilityMessage = wrapped.message\n\t\tif (isSnapshotSuperseded(error)) this.writeDurabilityPermanentlyFailed = true\n\t\tthis.emitter?.emit({\n\t\t\ttype: 'store:write-durability',\n\t\t\tdbName: this.dbName,\n\t\t\tstate: 'failing',\n\t\t\tmessage: wrapped.message,\n\t\t\toperationIds: [...operationIds],\n\t\t})\n\t\treturn wrapped\n\t}\n\n\tprivate reportWriteDurabilityRestored(): void {\n\t\t// Once IndexedDB refuses this tab's lineage, no later barrier from the same\n\t\t// live store can prove its committed writes durable. Only a fresh store after\n\t\t// reload may report recovery.\n\t\tif (!this.writeDurabilityFailing || this.writeDurabilityPermanentlyFailed) return\n\t\tthis.writeDurabilityFailing = false\n\t\tthis.emitter?.emit({\n\t\t\ttype: 'store:write-durability',\n\t\t\tdbName: this.dbName,\n\t\t\tstate: 'restored',\n\t\t\tmessage: 'Local writes are durable again.',\n\t\t\toperationIds: [],\n\t\t})\n\t}\n\n\t/** Report a database a newer storage format opened (`store:format-ahead`), build the error. */\n\tprivate formatAhead(storedFormat: number): StorageFormatAheadError {\n\t\tconst error = new StorageFormatAheadError(this.dbName, storedFormat, KORA_STORAGE_FORMAT)\n\t\tthis.emitter?.emit({\n\t\t\ttype: 'store:format-ahead',\n\t\t\tdbName: this.dbName,\n\t\t\tstoredFormat,\n\t\t\tcodeFormat: KORA_STORAGE_FORMAT,\n\t\t\tmessage: error.message,\n\t\t})\n\t\treturn error\n\t}\n\n\t/**\n\t * Run `fn` as one write of this store: refused with `BuildSupersededError` (nothing\n\t * started) once the tab is superseded by a newer build, and waited for by retirement\n\t * otherwise. The app routes its own write entry points (blobs) through it.\n\t */\n\t/** Evidence kept outside the database (null: the adapter keeps none). */\n\tprivate storageEvidence: import('../adapters/storage-evidence').StorageEvidence | null = null\n\t/** A detected storage loss the app has not acknowledged yet. */\n\tprivate storageEviction: import('../adapters/storage-evidence').StorageEviction | null = null\n\n\ttrackWrite<T>(scope: WriteScope, fn: () => Promise<T>): Promise<T> {\n\t\treturn this.writeGate.run(scope, fn)\n\t}\n\n\t/**\n\t * Writes this store admitted that have not settled yet: local writes, transactions and\n\t * applied sync batches. A reload while this is above zero can lose a write the user\n\t * already saw (instant updates), so updates and unload guards wait for zero.\n\t */\n\tpendingWriteCount(): number {\n\t\treturn this.writeGate.pendingCount()\n\t}\n\n\t/** Resolves once every write admitted so far, and any admitted meanwhile, has settled. Never rejects. */\n\twhenWritesSettled(): Promise<void> {\n\t\treturn this.writeGate.drain()\n\t}\n\n\t/** Whether this store refuses writes because a newer build superseded its tab. */\n\tisWriteRefused(): boolean {\n\t\treturn this.writeGate.isClosed()\n\t}\n\n\t/** Report a database a newer build migrated (`store:schema-ahead`) and build the error. */\n\tprivate schemaAhead(storedVersion: number): SchemaVersionAheadError {\n\t\tconst error = new SchemaVersionAheadError(this.dbName, storedVersion, this.schema.version)\n\t\tthis.emitter?.emit({\n\t\t\ttype: 'store:schema-ahead',\n\t\t\tdbName: this.dbName,\n\t\t\tstoredVersion,\n\t\t\tcodeVersion: this.schema.version,\n\t\t\tmessage: error.message,\n\t\t})\n\t\treturn error\n\t}\n\n\t/**\n\t * Run pending schema migrations (STORE-13, NEW-STORE-1): one transaction per version\n\t * (DDL, backfills, `schema_version`); backfills write operations through the local\n\t * write path so they sync, unless declared `localOnly`.\n\t */\n\tprivate async runMigrationsIfNeeded(): Promise<void> {\n\t\tconst clock = this.clock\n\t\tif (!clock) throw new StoreNotOpenError()\n\t\tconst fold = this.activeFold()\n\t\tawait runSchemaMigrations({\n\t\t\tadapter: this.adapter,\n\t\t\tschema: this.schema,\n\t\t\tenv: {\n\t\t\t\t...(fold ? { fold } : {}),\n\t\t\t\tschema: this.schema,\n\t\t\t\tclock,\n\t\t\t\tnodeId: this.nodeId,\n\t\t\t\trelationEnforcer: null,\n\t\t\t\t...(this.secretKeyProvider ? { secretKeyProvider: this.secretKeyProvider } : {}),\n\t\t\t},\n\t\t\tcausalTracker: this.causalTracker,\n\t\t\tonOperation: (operation) => this.publishLocalOperation(operation.collection, operation),\n\t\t})\n\t}\n\n\t/**\n\t * The pinned node of a database that belongs to one user moved (the user's auth device\n\t * id changed: on a browser shared between accounts each account gets its own, and a\n\t * beta.12 browser gave every account the same one). The previous node may be shared\n\t * with another user's database, so it is retired: never used for a session, adopted or\n\t * handed over again. Its writes are this user's (the database is opened only for them);\n\t * those the server does not hold are re-authored under this user's node once the server\n\t * says which it holds (`reauthorIntoOwnNode`). A retired node that is pinned again is\n\t * revived.\n\t *\n\t * @returns The node ids this database authored its own operations under, for the\n\t *   sequence-uniqueness repair\n\t */\n\tprivate async retireMovedPinnedNode(persistedNodeId: string | null): Promise<string[]> {\n\t\tconst own = [this.nodeId]\n\t\tconst nodes = await listLocalNodes(this.adapter)\n\t\tif (nodes.find((node) => node.nodeId === this.nodeId)?.retired) {\n\t\t\tawait reviveLocalNode(this.adapter, this.nodeId)\n\t\t}\n\t\tif (\n\t\t\tthis.configNodeId !== undefined &&\n\t\t\tthis.isolation !== 'per-tab' &&\n\t\t\tthis.databaseOwner !== null &&\n\t\t\tpersistedNodeId !== null &&\n\t\t\tpersistedNodeId !== this.nodeId &&\n\t\t\t!isReservedNodeId(persistedNodeId)\n\t\t) {\n\t\t\tawait retireLocalNode(this.adapter, persistedNodeId, this.databaseOwner)\n\t\t}\n\t\tfor (const node of await listLocalNodes(this.adapter)) {\n\t\t\tif (node.retired && node.principal === this.databaseOwner && node.nodeId !== this.nodeId) {\n\t\t\t\town.push(node.nodeId)\n\t\t\t}\n\t\t}\n\t\treturn own\n\t}\n\n\t/** The node id the database persisted before this open, if any. */\n\tprivate async readPersistedNodeId(): Promise<string | null> {\n\t\tconst rows = await this.adapter.query<MetaRow>(\n\t\t\t\"SELECT value FROM _kora_meta WHERE key = 'node_id'\",\n\t\t)\n\t\treturn rows[0]?.value ?? null\n\t}\n\n\t/**\n\t * Register node ids this database authored under that the registry does not know\n\t * yet: the node id a pinned `nodeId` (the auth device id) just replaced, and the\n\t * authors of queued operations. A beta.12 database had no registry, and a template\n\t * app created before its user signed in authored under a random node; once the\n\t * store is pinned to the device id, that node's queued writes would otherwise sit in\n\t * the queue forever, neither uploaded nor reported. Registered, they are adopted or\n\t * held (`status.heldNodes`) like any other local node's writes. Only the outbound\n\t * queue is read: received operations never enter it.\n\t */\n\tprivate async registerUnregisteredAuthors(persistedNodeId: string | null): Promise<void> {\n\t\tconst authors = new Set<string>()\n\t\tif (\n\t\t\tpersistedNodeId !== null &&\n\t\t\tpersistedNodeId !== this.nodeId &&\n\t\t\t!isReservedNodeId(persistedNodeId)\n\t\t) {\n\t\t\t// The database's own previous node: never \"from the queue\".\n\t\t\tawait registerLocalNode(this.adapter, persistedNodeId)\n\t\t}\n\t\tconst queued = await this.adapter.query<{ payload: string }>(\n\t\t\t'SELECT payload FROM _kora_sync_queue',\n\t\t)\n\t\tfor (const row of queued) {\n\t\t\ttry {\n\t\t\t\tconst nodeId = (JSON.parse(row.payload) as { node_id?: unknown }).node_id\n\t\t\t\tif (typeof nodeId === 'string' && nodeId.length > 0) authors.add(nodeId)\n\t\t\t} catch {\n\t\t\t\t// An unreadable queue row is surfaced by the queue's own load.\n\t\t\t}\n\t\t}\n\t\tauthors.delete(this.nodeId)\n\t\tif (persistedNodeId !== null) authors.delete(persistedNodeId)\n\t\tfor (const nodeId of authors) {\n\t\t\tif (isReservedNodeId(nodeId)) continue\n\t\t\tawait registerLocalNode(this.adapter, nodeId, { fromQueue: true })\n\t\t}\n\t}\n\n\tprivate async loadOrGenerateNodeId(): Promise<string> {\n\t\t// The `kora:` namespace is Kora's own (server nodes `kora:server:<id>` are\n\t\t// authoritative by prefix, RT-61): a device never authors under such an id.\n\t\tif (this.configNodeId && isReservedNodeId(this.configNodeId)) {\n\t\t\tthrow new ReservedNodeIdError(this.configNodeId, 'StoreConfig.nodeId')\n\t\t}\n\t\tif (this.configNodeId) {\n\t\t\tif (this.isolation !== 'per-tab') {\n\t\t\t\tawait this.adapter.execute(\n\t\t\t\t\t\"INSERT OR REPLACE INTO _kora_meta (key, value) VALUES ('node_id', ?)\",\n\t\t\t\t\t[this.configNodeId],\n\t\t\t\t)\n\t\t\t}\n\t\t\treturn this.configNodeId\n\t\t}\n\n\t\tif (this.isolation === 'per-tab') {\n\t\t\treturn resolvePerTabNodeId(this.dbName)\n\t\t}\n\n\t\t// Try to load existing node ID\n\t\tconst rows = await this.adapter.query<MetaRow>(\n\t\t\t\"SELECT value FROM _kora_meta WHERE key = 'node_id'\",\n\t\t)\n\t\tif (rows[0] && !isReservedNodeId(rows[0].value)) {\n\t\t\treturn rows[0].value\n\t\t}\n\n\t\t// Generate a new node id (a UUIDv7, never in the reserved `kora:` namespace). A\n\t\t// persisted reserved id (written by something other than this client) is never\n\t\t// adopted: the database gets a fresh identity instead.\n\t\tconst newNodeId = generateUUIDv7()\n\t\tawait this.adapter.execute(\n\t\t\t\"INSERT OR REPLACE INTO _kora_meta (key, value) VALUES ('node_id', ?)\",\n\t\t\t[newNodeId],\n\t\t)\n\t\treturn newNodeId\n\t}\n\n\tprivate async loadSequenceNumber(): Promise<number> {\n\t\tconst rows = await this.adapter.query<VersionVectorRow>(\n\t\t\t'SELECT sequence_number FROM _kora_version_vector WHERE node_id = ?',\n\t\t\t[this.nodeId],\n\t\t)\n\t\treturn rows[0]?.sequence_number ?? 0\n\t}\n\n\tprivate async loadVersionVector(): Promise<VersionVector> {\n\t\tconst rows = await this.adapter.query<VersionVectorRow>(\n\t\t\t'SELECT node_id, sequence_number FROM _kora_version_vector',\n\t\t)\n\t\tconst vector = createVersionVector()\n\t\tfor (const row of rows) {\n\t\t\tvector.set(row.node_id, row.sequence_number)\n\t\t}\n\t\treturn vector\n\t}\n\n\t/**\n\t * Open a staging replica: a scratch in-memory store of the same schema that a large\n\t * first sync is applied into, then merged here in one controlled pass (see\n\t * {@link StagingReplica}). Null when this store cannot stage: the adapter has no scratch\n\t * database, rows are not fold materializations, an access narrowing kept records for\n\t * unsent writes, the log holds quarantined rows, or the schema has a `restrict`\n\t * relation (a remote delete is judged against the live children, which staging does not\n\t * hold). The caller then replicates straight into this store, as before.\n\t */\n\tasync beginStaging(\n\t\toptions: { explicit?: boolean; cancelWaitMs?: number } = {},\n\t): Promise<StagingReplica | null> {\n\t\tthis.ensureOpen()\n\t\tif (this.adapter.prefersStaging === false && options.explicit !== true) return null\n\t\tif (!this.isFoldMaterialized() || !this.adapter.createStagingAdapter) return null\n\t\tif (Object.values(this.schema.relations).some((relation) => relation.onDelete === 'restrict')) {\n\t\t\treturn null\n\t\t}\n\t\tif ((await this.loadKeptOutsideNarrowing()).size > 0) return null\n\t\tif ((await loadQuarantinedRecords(this.adapter)).records.size > 0) return null\n\t\tconst adapter = await this.adapter.createStagingAdapter()\n\t\tif (!adapter) return null\n\t\t// Secondary indexes are built once, by the merge's inserts into the live tables: the\n\t\t// staging tables keep only the indexes the apply path reads.\n\t\tconst stagingSchema: SchemaDefinition = {\n\t\t\t...this.schema,\n\t\t\tcollections: Object.fromEntries(\n\t\t\t\tObject.entries(this.schema.collections).map(([name, definition]) => [\n\t\t\t\t\tname,\n\t\t\t\t\t{ ...definition, indexes: [] },\n\t\t\t\t]),\n\t\t\t),\n\t\t}\n\t\tconst events = new ReplicaEventBuffer(this.emitter)\n\t\tconst staging = new Store({\n\t\t\tschema: stagingSchema,\n\t\t\tadapter,\n\t\t\tdbName: `${this.dbName}__staging`,\n\t\t\tmaterialization: 'fold',\n\t\t\toperationTransforms: this.operationTransforms,\n\t\t\t...(this.maxOperationBytes !== undefined\n\t\t\t\t? { maxOperationBytes: this.maxOperationBytes }\n\t\t\t\t: {}),\n\t\t\t// Buffered: an operation in the replica is not in this database yet, so nothing\n\t\t\t// announced about it may reach this database's listeners until the merge committed.\n\t\t\temitter: events,\n\t\t})\n\t\ttry {\n\t\t\tawait staging.open()\n\t\t\t// The replica validates remote timestamps exactly as this store's clock does: with\n\t\t\t// the same server reference offset (a device whose clock is minutes slow would\n\t\t\t// otherwise quarantine the stream as drift) and, when no offset is known, with the\n\t\t\t// same cold or warm start (a warm clock refuses a far-future stamp, a cold one\n\t\t\t// cannot tell, and the replica must not be the more trusting of the two).\n\t\t\tconst offset = this.clock?.getReferenceOffset() ?? null\n\t\t\tif (offset !== null) staging.setClockReferenceOffset(offset)\n\t\t\telse if (this.clock?.hasObservedTime()) staging.setClockReferenceOffset(0)\n\t\t\tif (!staging.isFoldMaterialized())\n\t\t\t\tthrow new Error('the staging store is not fold-materialized')\n\t\t\t// The fold of server-authoritative fields depends on the server's node ids.\n\t\t\tawait staging.setAuthoritativeNodeIds((await this.loadAuthoritativeNodeIds()) ?? [])\n\t\t} catch (error) {\n\t\t\tawait staging.close().catch(() => undefined)\n\t\t\tthis.emitter?.emit({\n\t\t\t\ttype: 'store:persistence-error',\n\t\t\t\tdbName: `${this.dbName}__staging`,\n\t\t\t\tmessage: `The staging database could not be opened; replicating into the live database instead: ${\n\t\t\t\t\terror instanceof Error ? error.message : String(error)\n\t\t\t\t}`,\n\t\t\t\tcode: 'STAGING_UNAVAILABLE',\n\t\t\t})\n\t\t\treturn null\n\t\t}\n\t\tconst authorities = (store: Store): string =>\n\t\t\tJSON.stringify([...(store.folder?.getAuthoritativeNodeIds() ?? [])].sort())\n\t\tconst stagedAuthorities = authorities(this)\n\t\tlet replica: StagingReplica | null = null\n\t\tconst host: StagingMergeHost = {\n\t\t\tschema: this.schema,\n\t\t\ttransaction: (fn) =>\n\t\t\t\tthis.writeGate.run({ operation: 'staging-merge' }, () => this.adapter.transaction(fn)),\n\t\t\tlocalNodeIds: async () => {\n\t\t\t\tconst nodes = await listLocalNodes(this.adapter)\n\t\t\t\treturn new Set([this.nodeId, ...nodes.map((node) => node.nodeId)])\n\t\t\t},\n\t\t\ttouchCollection: (collection) => {\n\t\t\t\tforeign?.touch(collection)\n\t\t\t},\n\t\t\tnoteVersionVector: (entries) => {\n\t\t\t\tfor (const [nodeId, sequenceNumber] of entries) {\n\t\t\t\t\tif (sequenceNumber > (this.versionVector.get(nodeId) ?? 0)) {\n\t\t\t\t\t\tthis.versionVector.set(nodeId, sequenceNumber)\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t},\n\t\t\treceiveTimestamp: (timestamp) => {\n\t\t\t\ttry {\n\t\t\t\t\tthis.clock?.receive(timestamp)\n\t\t\t\t} catch (error) {\n\t\t\t\t\t// The same operations were validated against this clock while they were staged;\n\t\t\t\t\t// a timestamp it refuses now is reported, never fatal (clock drift never blocks).\n\t\t\t\t\tthis.emitter?.emit({\n\t\t\t\t\t\ttype: 'store:persistence-error',\n\t\t\t\t\t\tdbName: this.dbName,\n\t\t\t\t\t\tmessage: `The newest staged timestamp was not adopted by the clock: ${\n\t\t\t\t\t\t\terror instanceof Error ? error.message : String(error)\n\t\t\t\t\t\t}`,\n\t\t\t\t\t\tcode: 'STAGING_CLOCK_NOT_ADOPTED',\n\t\t\t\t\t})\n\t\t\t\t}\n\t\t\t},\n\t\t\tinvalidate: (collection) => this.subscriptionManager.invalidate(collection),\n\t\t\tpurgeSeeds: async (tx, collection, ids) => {\n\t\t\t\tconst folder = this.activeFold()\n\t\t\t\tif (!folder) return\n\t\t\t\tconst only =\n\t\t\t\t\tcollection !== null && ids !== null\n\t\t\t\t\t\t? ids.map((recordId) => ({ collection, recordId }))\n\t\t\t\t\t\t: undefined\n\t\t\t\tawait purgeSeedsInTx(tx, only)\n\t\t\t},\n\t\t\tsettleSnapshots: (collection, ids) => this.settleSnapshots(collection, ids),\n\t\t\treplay: async (operation) => {\n\t\t\t\tawait this.applyRemoteOperation(operation)\n\t\t\t},\n\t\t\tassertWritable: () => {\n\t\t\t\tthis.ensureOpen()\n\t\t\t},\n\t\t\tshouldContinue: () => this.opened && !(replica?.isClosed() ?? false),\n\t\t}\n\t\t// Instant-update verification must not trust rows the merge is about to write.\n\t\tconst foreign = this.overlayController?.registry.beginForeign()\n\t\treplica = new StagingReplica(\n\t\t\tstaging,\n\t\t\tadapter,\n\t\t\thost,\n\t\t\t() => authorities(this) === authorities(staging) && authorities(this) === stagedAuthorities,\n\t\t\t() => foreign?.end(),\n\t\t\tevents,\n\t\t\toptions.cancelWaitMs,\n\t\t)\n\t\tconst created = replica\n\t\treturn created\n\t}\n\n\t/**\n\t * Keep the records a read-through answer showed, so this device can answer the same queries\n\t * from its own database before replication delivers them (first-visit parity S4b, 5.6).\n\t * Seeds are no operations: nothing is logged, sequenced or uploaded. A record the database\n\t * already holds history for is not touched, and every skip is reported.\n\t *\n\t * @param inputs - Records of an answer, in the delivery wire form\n\t * @param meta - The frontier and grant key the answer was read at\n\t * @returns Which records were seeded and which were skipped, with the reason\n\t */\n\tasync seedRecords(inputs: readonly SeedInput[], meta: SeedMeta): Promise<SeedOutcome> {\n\t\tthis.ensureOpen()\n\t\tconst folder = this.activeFold()\n\t\tif (!folder) {\n\t\t\treturn {\n\t\t\t\tseeded: [],\n\t\t\t\tskipped: inputs.map((input) => ({\n\t\t\t\t\tcollection: input.collection,\n\t\t\t\t\tid: input.id,\n\t\t\t\t\treason: 'fold-inactive' as const,\n\t\t\t\t})),\n\t\t\t}\n\t\t}\n\t\tconst collections = [...new Set(inputs.map((input) => input.collection))]\n\t\tconst foreign = this.overlayController?.registry.beginForeign()\n\t\tlet outcome: SeedOutcome = { seeded: [], skipped: [] }\n\t\t// An upper bound before the seeds exist, never below the truth (see releaseSeedFor).\n\t\tthis.seedCount += inputs.length\n\t\ttry {\n\t\t\tawait this.writeGate.run({ operation: 'seed' }, () =>\n\t\t\t\tthis.adapter.transaction(async (tx) => {\n\t\t\t\t\toutcome = await seedRecordsInTx(tx, folder, this.schema, inputs, meta, (timestamp) =>\n\t\t\t\t\t\tthis.adoptSeedTimestamp(timestamp),\n\t\t\t\t\t)\n\t\t\t\t}),\n\t\t\t)\n\t\t} finally {\n\t\t\tforeign?.end()\n\t\t\tawait this.refreshSeedCount()\n\t\t}\n\t\tfor (const collection of collections) {\n\t\t\tconst ids = outcome.seeded.filter((s) => s.collection === collection).map((s) => s.id)\n\t\t\tif (ids.length > 0) this.subscriptionManager.invalidate(collection, ids)\n\t\t}\n\t\treturn outcome\n\t}\n\n\t/**\n\t * Delete seeds: all of them, or those of `only`. A seeded record this device never wrote to\n\t * is removed as if it had never been read; one it wrote to keeps its snapshot (the marker\n\t * goes) so the user's edit stays visible, and is returned as `retained`. Used by the merge,\n\t * by a change of grant and by the clear points (sign-out, user switch, resync, restore).\n\t */\n\tasync purgeSeeds(\n\t\tonly?: ReadonlyArray<{ collection: string; recordId: string }>,\n\t): Promise<PurgeOutcome> {\n\t\tthis.ensureOpen()\n\t\treturn this.purgeSeedsNow(only)\n\t}\n\n\t/** {@link purgeSeeds} without the open check: a resync can be requested while the store opens. */\n\tprivate async purgeSeedsNow(\n\t\tonly?: ReadonlyArray<{ collection: string; recordId: string }>,\n\t): Promise<PurgeOutcome> {\n\t\tconst folder = this.activeFold()\n\t\tconst outcome: PurgeOutcome = { removed: [], retained: [] }\n\t\tif (!folder) return outcome\n\t\tconst foreign = this.overlayController?.registry.beginForeign()\n\t\ttry {\n\t\t\tawait this.writeGate.run({ operation: 'seed-purge' }, () =>\n\t\t\t\tthis.adapter.transaction(async (tx) => {\n\t\t\t\t\tconst result = await purgeSeedsInTx(tx, only)\n\t\t\t\t\toutcome.removed = result.removed\n\t\t\t\t\toutcome.retained = result.retained\n\t\t\t\t}),\n\t\t\t)\n\t\t} finally {\n\t\t\tforeign?.end()\n\t\t\tawait this.refreshSeedCount()\n\t\t}\n\t\tconst touched = [...outcome.removed, ...outcome.retained]\n\t\tfor (const collection of new Set(touched.map((seed) => seed.collection))) {\n\t\t\tthis.subscriptionManager.invalidate(\n\t\t\t\tcollection,\n\t\t\t\ttouched.filter((seed) => seed.collection === collection).map((seed) => seed.recordId),\n\t\t\t)\n\t\t}\n\t\treturn outcome\n\t}\n\n\t/**\n\t * Drop the row snapshots (RT-68) of records whose real history is now in the log, and\n\t * re-fold them exactly. Called after a merge replayed the operations of seeded records.\n\t *\n\t * @returns The records that still have only a snapshot as history (orphaned), reported\n\t *   as a `SEED_ORPHANED` persistence notice; they keep the snapshot so edits stay visible\n\t */\n\tasync settleSnapshots(collection: string, ids: readonly string[]): Promise<readonly string[]> {\n\t\tthis.ensureOpen()\n\t\tawait this.refreshSeedCount()\n\t\tconst folder = this.activeFold()\n\t\tif (!folder || ids.length === 0) return []\n\t\tconst orphaned: string[] = []\n\t\tawait this.writeGate.run({ operation: 'seed-settle' }, () =>\n\t\t\tthis.adapter.transaction(async (tx) => {\n\t\t\t\torphaned.length = 0\n\t\t\t\tfor (const id of ids) {\n\t\t\t\t\tconst held = await tx.query<{ n: number }>(\n\t\t\t\t\t\t'SELECT COUNT(*) AS n FROM _kora_fold_snapshot WHERE collection = ? AND record_id = ?',\n\t\t\t\t\t\t[collection, id],\n\t\t\t\t\t)\n\t\t\t\t\tif ((held[0]?.n ?? 0) === 0) continue\n\t\t\t\t\tif (!(await folder.settleSnapshotInTx(tx, collection, id))) orphaned.push(id)\n\t\t\t\t}\n\t\t\t}),\n\t\t)\n\t\tif (orphaned.length > 0) {\n\t\t\tthis.emitter?.emit({\n\t\t\t\ttype: 'store:persistence-error',\n\t\t\t\tdbName: this.dbName,\n\t\t\t\tmessage: `${orphaned.length} seeded record(s) of \"${collection}\" have no history from the server and keep the snapshot they were read as, so the edits made on them stay visible.`,\n\t\t\t\tcode: 'SEED_ORPHANED',\n\t\t\t})\n\t\t}\n\t\tfor (const id of ids) this.subscriptionManager.invalidate(collection, [id])\n\t\treturn orphaned\n\t}\n\n\t/**\n\t * Delete the seeds read under a grant other than `grantKey` (a revoked membership must not\n\t * leave seeded rows behind, 5.6.4). A seed the device has written to is left as it is: the\n\t * user's own edit is theirs, and the server judges the upload.\n\t *\n\t * @returns The seeds that were deleted\n\t */\n\tasync purgeSeedsExceptGrant(grantKey: string): Promise<SeedRow[]> {\n\t\tthis.ensureOpen()\n\t\tconst folder = this.activeFold()\n\t\tif (!folder) return []\n\t\tconst removed: SeedRow[] = []\n\t\tawait this.writeGate.run({ operation: 'seed-purge' }, () =>\n\t\t\tthis.adapter.transaction(async (tx) => {\n\t\t\t\tconst stale = (await listSeedsInTx(tx)).filter((seed) => seed.grantKey !== grantKey)\n\t\t\t\tif (stale.length === 0) return\n\t\t\t\tconst result = await purgeSeedsInTx(tx, stale, { writtenSeeds: 'leave' })\n\t\t\t\tremoved.push(...result.removed)\n\t\t\t}),\n\t\t)\n\t\tawait this.refreshSeedCount()\n\t\tfor (const collection of new Set(removed.map((seed) => seed.collection))) {\n\t\t\tthis.subscriptionManager.invalidate(\n\t\t\t\tcollection,\n\t\t\t\tremoved.filter((seed) => seed.collection === collection).map((seed) => seed.recordId),\n\t\t\t)\n\t\t}\n\t\treturn removed\n\t}\n\n\t/**\n\t * A clear point (sign-out, user switch, full resync, restore, reload): what was read under\n\t * the previous state must not outlive it, whatever the reason, so a failure is never\n\t * swallowed.\n\t */\n\tprivate async clearSeedsAtClearPoint(point: string): Promise<void> {\n\t\ttry {\n\t\t\tawait this.purgeSeedsNow()\n\t\t} catch (error) {\n\t\t\tthis.emitter?.emit({\n\t\t\t\ttype: 'store:persistence-error',\n\t\t\t\tdbName: this.dbName,\n\t\t\t\tmessage: `Seeded records could not be cleared at ${point}: ${\n\t\t\t\t\terror instanceof Error ? error.message : String(error)\n\t\t\t\t}`,\n\t\t\t\tcode: 'SEED_PURGE_FAILED',\n\t\t\t})\n\t\t\tthrow error\n\t\t}\n\t}\n\n\t/**\n\t * Seeds exist only while replication goes to the staging replica (I3): the first remote\n\t * operation that reaches the main database for a seeded record releases that record's seed,\n\t * so the operation folds exactly as it would have without one. A record the device wrote to\n\t * keeps its snapshot until its insert arrives.\n\t *\n\t * @returns Whether a seed was released\n\t */\n\tprivate async releaseSeedFor(tx: Transaction, op: Operation): Promise<boolean> {\n\t\tif (this.seedCount === 0) return false\n\t\tconst held = await tx.query<{ n: number }>(\n\t\t\t'SELECT COUNT(*) AS n FROM _kora_seed WHERE collection = ? AND record_id = ?',\n\t\t\t[op.collection, op.recordId],\n\t\t)\n\t\tif ((held[0]?.n ?? 0) === 0) return false\n\t\tawait purgeSeedsInTx(tx, [{ collection: op.collection, recordId: op.recordId }])\n\t\t// Not decremented: the transaction may still roll back, and a count that is too low would\n\t\t// let a later operation skip a seed it must release. It is recomputed after a commit.\n\t\treturn true\n\t}\n\n\tprivate async refreshSeedCount(): Promise<void> {\n\t\tconst rows = await this.adapter.query<{ n: number }>('SELECT COUNT(*) AS n FROM _kora_seed')\n\t\tthis.seedCount = rows[0]?.n ?? 0\n\t}\n\n\t/** The seed markers the database holds. */\n\tasync listSeeds(): Promise<SeedRow[]> {\n\t\tthis.ensureOpen()\n\t\tlet rows: SeedRow[] = []\n\t\tawait this.adapter.transaction(async (tx) => {\n\t\t\trows = await listSeedsInTx(tx)\n\t\t})\n\t\treturn rows\n\t}\n\n\t/** Advance the clock past a seeded record's newest write; false when the clock refuses it. */\n\tprivate adoptSeedTimestamp(timestamp: HLCTimestamp): boolean {\n\t\ttry {\n\t\t\tthis.clock?.receive(timestamp)\n\t\t\treturn true\n\t\t} catch {\n\t\t\treturn false\n\t\t}\n\t}\n\n\tprivate ensureOpen(): void {\n\t\tif (!this.opened) {\n\t\t\tthrow new StoreNotOpenError()\n\t\t}\n\t}\n}\n\n/**\n * Public-facing collection accessor. Provides CRUD + where.\n */\nexport interface CollectionAccessor {\n\tinsert(\n\t\tdata: Record<string, unknown>,\n\t\toptions?: import('../types').WriteOptions,\n\t): Promise<import('../types').CollectionRecord>\n\t/**\n\t * Insert several records in ONE storage transaction: all of them or none. Every\n\t * row is validated before anything is written; each becomes its own insert\n\t * operation, in input order, sharing one `transactionId`. Live queries are\n\t * notified once, after the commit. Much faster than an `insert` loop for bulk\n\t * writes (one transaction and one commit instead of one per record).\n\t *\n\t * @returns The inserted records, in input order\n\t */\n\tinsertMany(\n\t\trows: readonly Record<string, unknown>[],\n\t\toptions?: import('../types').WriteOptions,\n\t): Promise<import('../types').CollectionRecord[]>\n\tfindById(id: string): Promise<import('../types').CollectionRecord | null>\n\tupdate(\n\t\tid: string,\n\t\tdata: Record<string, unknown>,\n\t\toptions?: import('../types').WriteOptions,\n\t): Promise<import('../types').CollectionRecord>\n\tdelete(id: string, options?: import('../types').WriteOptions): Promise<void>\n\twhere(conditions: Record<string, unknown>): QueryBuilder\n}\n\n/**\n * The newest HLC an operation carries: its timestamp, or for a scope-entry insert\n * (RT-27) the greatest of its timestamp and every per-field version.\n */\nfunction newestFieldVersion(op: Operation): HLCTimestamp {\n\tlet newest = op.timestamp\n\tfor (const version of Object.values(op.fieldVersions ?? {})) {\n\t\tif (HybridLogicalClock.compare(version, newest) > 0) newest = version\n\t}\n\treturn newest\n}\n\n/**\n * Whether a record's operations end in a domain delete: its newest delete (log and\n * retained conflicts) is newer than its newest insert or update, `incoming` included\n * on its own side (a delete is a delete, an insert or update a write; it may be a\n * duplicate of a logged operation). The rule a fold applies (\"the later of the newest delete and the\n * newest write decides\"), used by legacy materialization, which shares `_deleted` between\n * a domain tombstone and a scope retraction's hide, before it lifts that hide.\n */\nasync function endsInDomainDelete(\n\ttx: Transaction,\n\tcollection: string,\n\trecordId: string,\n\tincoming: Operation | null,\n): Promise<boolean> {\n\tconst rows = [\n\t\t...(await tx.query<OperationRow>(\n\t\t\t`SELECT * FROM ${quoteIdent(`_kora_ops_${collection}`)} WHERE record_id = ?`,\n\t\t\t[recordId],\n\t\t)),\n\t\t...(await loadRetainedConflictRows(\n\t\t\t(sql, params) => tx.query(sql, params),\n\t\t\tcollection,\n\t\t\trecordId,\n\t\t)),\n\t]\n\t// The incoming operation counts on its own side: a delete (a duplicate re-delivery of\n\t// one, possibly) is a delete, never a write that would tie with its logged copy.\n\tlet newestDelete: HLCTimestamp | null = incoming?.type === 'delete' ? incoming.timestamp : null\n\tlet newestWrite: HLCTimestamp | null =\n\t\tincoming && incoming.type !== 'delete' ? newestFieldVersion(incoming) : null\n\tfor (const row of rows) {\n\t\tconst op = deserializeOperationWithCollection(row, collection)\n\t\tif (op.type === 'delete') {\n\t\t\tif (newestDelete === null || HybridLogicalClock.compare(op.timestamp, newestDelete) > 0) {\n\t\t\t\tnewestDelete = op.timestamp\n\t\t\t}\n\t\t\tcontinue\n\t\t}\n\t\tconst written = newestFieldVersion(op)\n\t\tif (newestWrite === null || HybridLogicalClock.compare(written, newestWrite) > 0) {\n\t\t\tnewestWrite = written\n\t\t}\n\t}\n\tif (newestDelete === null) return false\n\treturn newestWrite === null || HybridLogicalClock.compare(newestDelete, newestWrite) > 0\n}\n\n/**\n * What a remote operation does to a record a scope retraction hid (RT-19):\n * - `'none'`: the record has no retraction marker.\n * - `'shown'`: the operation comes after the retraction in delivery order, so the server\n *   holds the record in this device's view again. The marker is cleared and the row shown.\n * - `'hidden'`: the operation comes before the retraction (a quarantined insert replayed\n *   later, a duplicate re-delivery). It is logged and folded; the row stays hidden.\n */\ntype ScopeVisibility = 'none' | 'shown' | 'hidden'\n\n/**\n * Decide {@link ScopeVisibility} for `op` at delivery position `position`, and clear the\n * marker when the record is shown again.\n *\n * The server delivers an operation only while its record is in the device's view at the\n * operation's delivery sequence, and retracts the record at the sequence where it leaves.\n * So whichever comes later in delivery order, the record's latest delivered operation or\n * its latest retraction, decides whether the device may show it: the operation shows it\n * when its position is after the marker's.\n *\n * Positions are global delivery sequences (one log per server): an operation and a\n * retraction sit at their own sequence, a scope entry at its trigger's sequence + 0.5\n * (after a retraction at that sequence). A narrowing hides as of base + 0.25 (at the\n * start of a batch with base b), or watermark + 0.25 (at the handshake, or once unsent\n * writes resolved). A stream that restarts lower moves the earlier run's positions\n * before itself (rebaseDeliveryRun), so the new run decides.\n *\n * When either position is unknown (a relay, the version-vector delta, an older server or\n * a marker written before positions existed) the order cannot be told. The rule of\n * earlier releases then holds: a server scope entry or a new insert shows the record\n * again; an update, a delete or a duplicate of an ordinary operation does not.\n */\nasync function scopeVisibilityAfter(\n\ttx: Transaction,\n\top: Operation,\n\tposition: number | undefined,\n\tduplicate: boolean,\n): Promise<ScopeVisibility> {\n\tconst rows = await tx.query<{ position: number | null }>(\n\t\t'SELECT position FROM _kora_scope_retractions WHERE collection = ? AND record_id = ?',\n\t\t[op.collection, op.recordId],\n\t)\n\tconst marker = rows[0]\n\tif (marker === undefined) return 'none'\n\tconst hiddenAt = marker.position === null ? null : Number(marker.position)\n\tconst shown =\n\t\tposition !== undefined && hiddenAt !== null\n\t\t\t? position > hiddenAt\n\t\t\t: isScopeEntryOperation(op) || (!duplicate && op.type === 'insert')\n\tif (!shown) return 'hidden'\n\tawait tx.execute('DELETE FROM _kora_scope_retractions WHERE collection = ? AND record_id = ?', [\n\t\top.collection,\n\t\top.recordId,\n\t])\n\treturn 'shown'\n}\n\n/** Node of server-synthesized scope-entry inserts (RT-19). */\nconst SCOPE_ENTRY_NODE_ID = 'kora:scope-entry'\n\n/** Whether `op` is a server scope entry: the insert that brings a record into view. */\nfunction isScopeEntryOperation(op: Operation): boolean {\n\treturn op.type === 'insert' && op.nodeId === SCOPE_ENTRY_NODE_ID\n}\n","import type {\n\tCausalTracker,\n\tCollectionDefinition,\n\tHybridLogicalClock,\n\tOperation,\n\tSchemaDefinition,\n\tSecretKeyProvider,\n} from '@korajs/core'\nimport { quoteIdent } from '@korajs/core'\nimport type { WriteNotDurableError } from '../errors'\nimport type { RecordFolder } from '../fold/record-folder'\nimport { executeDelete } from '../mutations/execute-delete'\nimport { executeInsert, executeInsertMany } from '../mutations/execute-insert'\nimport { executeUpdate } from '../mutations/execute-update'\nimport type { LocalMutationContext } from '../mutations/types'\nimport type { WriteOverlay } from '../overlay/write-overlay'\nimport type { RelationEnforcer } from '../relations/relation-enforcer'\nimport { deserializeRecord } from '../serialization/serializer'\nimport type {\n\tCollectionRecord,\n\tLocalMutationHandler,\n\tRawCollectionRow,\n\tStorageAdapter,\n\tWriteOptions,\n} from '../types'\n\n/**\n * Callback invoked after a mutation so the Store can notify subscriptions.\n */\nexport type MutationCallback = (collection: string, operation: Operation) => void\n\n/**\n * Collection provides CRUD operations on a single schema collection.\n * Delegates to {@link LocalMutationHandler} when configured (unified apply pipeline),\n * otherwise uses shared mutation executors directly.\n */\nexport class Collection {\n\tconstructor(\n\t\tprivate readonly name: string,\n\t\tprivate readonly definition: CollectionDefinition,\n\t\tprivate readonly schema: SchemaDefinition,\n\t\tprivate readonly adapter: StorageAdapter,\n\t\tprivate clock: HybridLogicalClock,\n\t\tprivate nodeId: string,\n\t\tprivate readonly onMutation: MutationCallback,\n\t\tprivate relationEnforcer: RelationEnforcer | null,\n\t\tprivate mutationHandler: LocalMutationHandler | null,\n\t\tprivate causalTracker: CausalTracker | null,\n\t\tprivate readonly secretKeyProvider?: SecretKeyProvider,\n\t\tprivate readonly onStorageError?: (error: unknown) => void,\n\t\tprivate readonly onWriteDurabilityError?: (\n\t\t\terror: unknown,\n\t\t\toperationIds: readonly string[],\n\t\t) => WriteNotDurableError,\n\t\tprivate readonly onWriteDurable?: () => void,\n\t\tprivate readonly fold?: () => RecordFolder | undefined,\n\t\tprivate readonly maxOperationBytes?: number,\n\t\tprivate readonly assertLocalWriteAllowed?: () => void,\n\t\tprivate readonly signedInUser?: () => string | null,\n\t\tprivate readonly overlay?: WriteOverlay,\n\t) {}\n\n\t/**\n\t * Point this collection at the store's new device identity after a node-id\n\t * rotation (RT-21). Internal: called by the owning Store only.\n\t *\n\t * @internal\n\t */\n\trebindNode(\n\t\tclock: HybridLogicalClock,\n\t\tnodeId: string,\n\t\trelationEnforcer: RelationEnforcer | null,\n\t\tcausalTracker: CausalTracker | null,\n\t): void {\n\t\tthis.clock = clock\n\t\tthis.nodeId = nodeId\n\t\tthis.relationEnforcer = relationEnforcer\n\t\tthis.causalTracker = causalTracker\n\t}\n\n\tprivate mutationContext(): LocalMutationContext {\n\t\tconst fold = this.fold?.()\n\t\treturn {\n\t\t\t...(fold ? { fold } : {}),\n\t\t\tcollection: this.name,\n\t\t\tdefinition: this.definition,\n\t\t\tschema: this.schema,\n\t\t\tadapter: this.adapter,\n\t\t\tclock: this.clock,\n\t\t\tnodeId: this.nodeId,\n\t\t\tonMutation: this.onMutation,\n\t\t\trelationEnforcer: this.relationEnforcer,\n\t\t\tcausalTracker: this.causalTracker,\n\t\t\t...(this.secretKeyProvider ? { secretKeyProvider: this.secretKeyProvider } : {}),\n\t\t\t...(this.onStorageError ? { onStorageError: this.onStorageError } : {}),\n\t\t\t...(this.onWriteDurabilityError\n\t\t\t\t? { onWriteDurabilityError: this.onWriteDurabilityError }\n\t\t\t\t: {}),\n\t\t\t...(this.onWriteDurable ? { onWriteDurable: this.onWriteDurable } : {}),\n\t\t\t...(this.maxOperationBytes !== undefined\n\t\t\t\t? { maxOperationBytes: this.maxOperationBytes }\n\t\t\t\t: {}),\n\t\t\t...(this.assertLocalWriteAllowed\n\t\t\t\t? { assertLocalWriteAllowed: this.assertLocalWriteAllowed }\n\t\t\t\t: {}),\n\t\t\t...(this.signedInUser ? { signedInUser: this.signedInUser } : {}),\n\t\t\t...(this.overlay ? { overlay: this.overlay } : {}),\n\t\t}\n\t}\n\n\tasync insert(data: Record<string, unknown>, options?: WriteOptions): Promise<CollectionRecord> {\n\t\t// Checked here too: a write relayed to another tab must still respect this tab's state.\n\t\tthis.assertLocalWriteAllowed?.()\n\t\tif (this.mutationHandler) {\n\t\t\treturn this.mutationHandler.insert(this.name, data, options)\n\t\t}\n\t\treturn executeInsert(this.mutationContext(), data, options)\n\t}\n\n\t/**\n\t * Insert several records in ONE storage transaction: all of them or none. Each\n\t * record still gets its own insert operation (see {@link executeInsertMany}).\n\t */\n\tasync insertMany(\n\t\trows: readonly Record<string, unknown>[],\n\t\toptions?: WriteOptions,\n\t): Promise<CollectionRecord[]> {\n\t\tthis.assertLocalWriteAllowed?.()\n\t\tif (this.mutationHandler?.insertMany) {\n\t\t\treturn this.mutationHandler.insertMany(this.name, rows, options)\n\t\t}\n\t\treturn executeInsertMany(this.mutationContext(), rows, options)\n\t}\n\n\tasync findById(id: string): Promise<CollectionRecord | null> {\n\t\tconst rows = await this.adapter.query<RawCollectionRow>(\n\t\t\t`SELECT * FROM ${quoteIdent(this.name)} WHERE id = ? AND _deleted = 0`,\n\t\t\t[id],\n\t\t)\n\t\tconst row = rows[0]\n\t\tif (!row) return null\n\t\treturn deserializeRecord(row, this.definition.fields)\n\t}\n\n\tasync update(\n\t\tid: string,\n\t\tdata: Record<string, unknown>,\n\t\toptions?: WriteOptions,\n\t): Promise<CollectionRecord> {\n\t\tthis.assertLocalWriteAllowed?.()\n\t\tif (this.mutationHandler) {\n\t\t\treturn this.mutationHandler.update(this.name, id, data, options)\n\t\t}\n\t\treturn executeUpdate(this.mutationContext(), id, data, options)\n\t}\n\n\tasync delete(id: string, options?: WriteOptions): Promise<void> {\n\t\tthis.assertLocalWriteAllowed?.()\n\t\tif (this.mutationHandler) {\n\t\t\tawait this.mutationHandler.delete(this.name, id, options)\n\t\t\treturn\n\t\t}\n\t\tawait executeDelete(this.mutationContext(), id, options)\n\t}\n\n\tgetName(): string {\n\t\treturn this.name\n\t}\n\n\tgetDefinition(): CollectionDefinition {\n\t\treturn this.definition\n\t}\n\n\t/** Replace the mutation handler (e.g. after ApplyPipeline is wired in createApp). */\n\tsetMutationHandler(handler: LocalMutationHandler | null): void {\n\t\tthis.mutationHandler = handler\n\t}\n}\n","import type { SchemaDefinition, VersionVector } from '@korajs/core'\nimport { HybridLogicalClock, createVersionVector, quoteIdent } from '@korajs/core'\nimport type { StorageAdapter, Transaction } from '../types'\nimport type { CompactionResult, CompactionStrategy } from './types'\nimport { COMPACTION_BASELINE_META_KEY } from './types'\n\n/**\n * Compute per-node sequence watermarks safe to compact (server has acknowledged these ops).\n */\nexport function computeAckCompactionWatermark(serverVector: VersionVector): VersionVector {\n\tconst watermark = createVersionVector()\n\tfor (const [nodeId, seq] of serverVector) {\n\t\tif (seq > 0) {\n\t\t\twatermark.set(nodeId, seq)\n\t\t}\n\t}\n\treturn watermark\n}\n\n/**\n * Remove acknowledged, materialized operation log entries from `_kora_ops_*` tables.\n * Does not modify collection rows — they are the compaction baseline snapshot.\n */\nexport async function compactOperationLog(\n\tadapter: StorageAdapter,\n\tschema: SchemaDefinition,\n\tstrategy: CompactionStrategy,\n\tserverVector: VersionVector,\n): Promise<CompactionResult> {\n\tif (strategy.mode === 'never') {\n\t\treturn { deletedCount: 0, watermark: createVersionVector() }\n\t}\n\n\tconst watermark = computeAckCompactionWatermark(serverVector)\n\tif (watermark.size === 0) {\n\t\treturn { deletedCount: 0, watermark }\n\t}\n\n\tconst ageCutoffWall =\n\t\tstrategy.mode === 'after-days' ? Date.now() - strategy.days * 24 * 60 * 60 * 1000 : null\n\tconst ageCutoffSerialized =\n\t\tageCutoffWall !== null\n\t\t\t? HybridLogicalClock.serialize({\n\t\t\t\t\twallTime: ageCutoffWall,\n\t\t\t\t\tlogical: 0,\n\t\t\t\t\tnodeId: '',\n\t\t\t\t}).slice(0, 15)\n\t\t\t: null\n\n\tlet deletedCount = 0\n\tconst collectionNames = Object.keys(schema.collections)\n\n\tawait adapter.transaction(async (tx: Transaction) => {\n\t\tfor (const collectionName of collectionNames) {\n\t\t\t// Already quoted here so the buildCountSql / buildDeleteSql helpers can\n\t\t\t// interpolate it verbatim (they do not route through sql-builder).\n\t\t\tconst table = quoteIdent(`_kora_ops_${collectionName}`)\n\t\t\tfor (const [nodeId, maxSeq] of watermark) {\n\t\t\t\tif (maxSeq <= 0) continue\n\n\t\t\t\tconst countSql = buildCountSql(table, ageCutoffSerialized !== null)\n\t\t\t\tconst countParams =\n\t\t\t\t\tageCutoffSerialized !== null ? [nodeId, maxSeq, ageCutoffSerialized] : [nodeId, maxSeq]\n\t\t\t\tconst countRows = await tx.query<{ count: number }>(countSql, countParams)\n\t\t\t\tdeletedCount += countRows[0]?.count ?? 0\n\n\t\t\t\tconst deleteSql = buildDeleteSql(table, ageCutoffSerialized !== null)\n\t\t\t\tawait tx.execute(deleteSql, countParams)\n\t\t\t}\n\t\t}\n\n\t\tawait tx.execute('INSERT OR REPLACE INTO _kora_meta (key, value) VALUES (?, ?)', [\n\t\t\tCOMPACTION_BASELINE_META_KEY,\n\t\t\tString(Date.now()),\n\t\t])\n\t})\n\n\treturn { deletedCount, watermark }\n}\n\nfunction buildCountSql(table: string, withAge: boolean): string {\n\tif (withAge) {\n\t\treturn `SELECT COUNT(*) as count FROM ${table} WHERE node_id = ? AND sequence_number <= ? AND SUBSTR(timestamp, 1, 15) < ?`\n\t}\n\treturn `SELECT COUNT(*) as count FROM ${table} WHERE node_id = ? AND sequence_number <= ?`\n}\n\nfunction buildDeleteSql(table: string, withAge: boolean): string {\n\tif (withAge) {\n\t\treturn `DELETE FROM ${table} WHERE node_id = ? AND sequence_number <= ? AND SUBSTR(timestamp, 1, 15) < ?`\n\t}\n\treturn `DELETE FROM ${table} WHERE node_id = ? AND sequence_number <= ?`\n}\n","import {\n\ttype FoldState,\n\tHybridLogicalClock,\n\ttype Operation,\n\ttype SchemaDefinition,\n\ttype VersionVector,\n\tcreateFoldState,\n\tcreateVersionVector,\n\tmergeOp,\n\tquoteIdent,\n} from '@korajs/core'\nimport { computeAckCompactionWatermark } from '../compaction/compact-operation-log'\nimport type { CompactionResult, CompactionStrategy } from '../compaction/types'\nimport { COMPACTION_BASELINE_META_KEY } from '../compaction/types'\nimport { deserializeOperationWithCollection } from '../serialization/serializer'\nimport { SEQ_CONFLICTS_TABLE } from '../store/sequence-repair'\nimport type { OperationRow, StorageAdapter, Transaction } from '../types'\nimport { COMPACTED_THROUGH_TABLE, type RecordFolder } from './record-folder'\n\n/**\n * Whether compaction must keep this operation in the log. The fold state alone is\n * enough to merge later operations, but the plan keeps the operations whose effect\n * cannot be rebuilt from a row snapshot should a future fold-state version need to\n * re-fold from the log: deletes (the tombstone register), atomic intents and writes\n * to custom-resolver fields.\n */\nfunction mustKeep(op: Operation, schema: SchemaDefinition): boolean {\n\tif (op.type === 'delete') return true\n\tif (op.atomicOps !== undefined && Object.keys(op.atomicOps).length > 0) return true\n\tconst resolvers = schema.collections[op.collection]?.resolvers ?? {}\n\treturn Object.keys(op.data ?? {}).some((field) => resolvers[field] !== undefined)\n}\n\n/**\n * Per node, the largest sequence k <= the server's acknowledged sequence such that\n * this database holds every operation 1..k (in some collection's log or the\n * retained sequence conflicts). Only such a prefix can be declared compacted:\n * an operation of that node at or below it is then known to be a duplicate.\n */\nasync function contiguousPrefixes(\n\ttx: Transaction,\n\tschema: SchemaDefinition,\n\tacked: VersionVector,\n): Promise<VersionVector> {\n\tconst out = createVersionVector()\n\tfor (const [nodeId, ackedSeq] of acked) {\n\t\tif (ackedSeq <= 0) continue\n\t\tconst seqs = new Set<number>()\n\t\tfor (const collection of Object.keys(schema.collections)) {\n\t\t\tconst rows = await tx.query<{ sequence_number: number }>(\n\t\t\t\t`SELECT sequence_number FROM ${quoteIdent(`_kora_ops_${collection}`)} WHERE node_id = ? AND sequence_number <= ?`,\n\t\t\t\t[nodeId, ackedSeq],\n\t\t\t)\n\t\t\tfor (const row of rows) seqs.add(row.sequence_number)\n\t\t}\n\t\tconst conflicts = await tx.query<{ sequence_number: number }>(\n\t\t\t`SELECT sequence_number FROM ${SEQ_CONFLICTS_TABLE} WHERE node_id = ? AND sequence_number <= ?`,\n\t\t\t[nodeId, ackedSeq],\n\t\t)\n\t\tfor (const row of conflicts) seqs.add(row.sequence_number)\n\t\tconst through = await tx.query<{ sequence_number: number }>(\n\t\t\t`SELECT sequence_number FROM ${COMPACTED_THROUGH_TABLE} WHERE node_id = ?`,\n\t\t\t[nodeId],\n\t\t)\n\t\tlet k = through[0]?.sequence_number ?? 0\n\t\twhile (k < ackedSeq && seqs.has(k + 1)) k += 1\n\t\tif (k > 0) out.set(nodeId, k)\n\t}\n\treturn out\n}\n\n/**\n * Compaction under the W7 fold (STORE-14). For every node, operations within the\n * contiguous prefix the server acknowledged (and older than the age cutoff, for\n * `after-days`) are folded per record into the record's base state, then removed\n * from the log. The record's live fold state is unchanged (it already holds them):\n * `state = join(base, fold(log))` holds before and after.\n *\n * Operations the server terminally rejected are never folded into a base.\n */\nexport async function compactFoldedLog(\n\tadapter: StorageAdapter,\n\tschema: SchemaDefinition,\n\tfolder: RecordFolder,\n\tstrategy: CompactionStrategy,\n\tserverVector: VersionVector,\n): Promise<CompactionResult> {\n\tconst acked = computeAckCompactionWatermark(serverVector)\n\tif (acked.size === 0) return { deletedCount: 0, watermark: acked }\n\tconst cutoff =\n\t\tstrategy.mode === 'after-days'\n\t\t\t? HybridLogicalClock.serialize({\n\t\t\t\t\twallTime: Date.now() - strategy.days * 24 * 60 * 60 * 1000,\n\t\t\t\t\tlogical: 0,\n\t\t\t\t\tnodeId: '',\n\t\t\t\t}).slice(0, 15)\n\t\t\t: null\n\n\tlet deletedCount = 0\n\tlet watermark = createVersionVector()\n\tawait adapter.transaction(async (tx) => {\n\t\twatermark = await contiguousPrefixes(tx, schema, acked)\n\t\tfor (const collection of Object.keys(schema.collections)) {\n\t\t\tconst table = quoteIdent(`_kora_ops_${collection}`)\n\t\t\tconst byRecord = new Map<string, Operation[]>()\n\t\t\tfor (const [nodeId, maxSeq] of watermark) {\n\t\t\t\tconst rows = await tx.query<OperationRow>(\n\t\t\t\t\t`SELECT * FROM ${table} WHERE node_id = ? AND sequence_number <= ?${cutoff !== null ? ' AND SUBSTR(timestamp, 1, 15) < ?' : ''}`,\n\t\t\t\t\tcutoff !== null ? [nodeId, maxSeq, cutoff] : [nodeId, maxSeq],\n\t\t\t\t)\n\t\t\t\tfor (const row of rows) {\n\t\t\t\t\tconst op = deserializeOperationWithCollection(row, collection)\n\t\t\t\t\tif (mustKeep(op, schema)) continue\n\t\t\t\t\tconst list = byRecord.get(op.recordId) ?? []\n\t\t\t\t\tlist.push(op)\n\t\t\t\t\tbyRecord.set(op.recordId, list)\n\t\t\t\t}\n\t\t\t}\n\t\t\tfor (const [recordId, ops] of byRecord) {\n\t\t\t\tconst rejected = await folder.loadTerminalRejections(\n\t\t\t\t\ttx,\n\t\t\t\t\tops.map((op) => op.id),\n\t\t\t\t)\n\t\t\t\tlet addition: FoldState = createFoldState(collection, recordId)\n\t\t\t\tlet any = false\n\t\t\t\tfor (const op of ops) {\n\t\t\t\t\tif (rejected.has(op.id)) continue\n\t\t\t\t\taddition = mergeOp(addition, op, schema, folder.options()).state\n\t\t\t\t\tany = true\n\t\t\t\t}\n\t\t\t\tif (any) await folder.joinIntoBase(tx, addition)\n\t\t\t\tfor (let i = 0; i < ops.length; i += 500) {\n\t\t\t\t\tconst chunk = ops.slice(i, i + 500)\n\t\t\t\t\tawait tx.execute(\n\t\t\t\t\t\t`DELETE FROM ${table} WHERE id IN (${chunk.map(() => '?').join(', ')})`,\n\t\t\t\t\t\tchunk.map((op) => op.id),\n\t\t\t\t\t)\n\t\t\t\t}\n\t\t\t\tdeletedCount += ops.length\n\t\t\t}\n\t\t}\n\t\tfor (const [nodeId, seq] of watermark) {\n\t\t\tawait tx.execute(\n\t\t\t\t`INSERT INTO ${COMPACTED_THROUGH_TABLE} (node_id, sequence_number) VALUES (?, ?)\n     ON CONFLICT(node_id) DO UPDATE SET sequence_number = MAX(sequence_number, excluded.sequence_number)`,\n\t\t\t\t[nodeId, seq],\n\t\t\t)\n\t\t}\n\t\tawait tx.execute('INSERT OR REPLACE INTO _kora_meta (key, value) VALUES (?, ?)', [\n\t\t\tCOMPACTION_BASELINE_META_KEY,\n\t\t\tString(Date.now()),\n\t\t])\n\t})\n\treturn { deletedCount, watermark }\n}\n","import {\n\tcanonicalizeLegacyOperation,\n\tcanonicalizeProvenLegacyClear,\n\tquoteIdent,\n} from '@korajs/core'\nimport type { Operation, SchemaDefinition } from '@korajs/core'\nimport { deserializeOperationWithCollection, serializeOperation } from '../serialization/serializer'\nimport type { OperationRow, StorageAdapter } from '../types'\n\n/** `_kora_meta` key: the op log's legacy bodies were made canonical (RT-83, RT-85). */\nexport const LEGACY_BODIES_META_KEY = 'legacy_bodies_canonical'\n\n/** A log row rewritten into its canonical legacy body. */\nexport interface CanonicalizedLegacyBody {\n\tcollection: string\n\trecordId: string\n}\n\n/**\n * Make every genuine beta.12 clear in the operation log explicit, once per database\n * (RT-83, RT-85).\n *\n * beta.12 applied `update(id, { field: undefined })` as a clear, hashed the member as\n * `null`, and logged JSON without it. Every later replica folds a stored body as\n * written (the fold has no legacy rule: a body a schema transform rewrote must never be\n * read as a clear), so the clear is written into the logged body here, where its\n * provenance is known:\n * - this device's own operations that declare no hash version were written by its\n *   beta.12 self (beta.13 always declares version 2): a `previousData` key absent from\n *   `data` is always such a clear;\n * - any other node's undeclared update is rewritten only when its id PROVES the clear\n *   (`canonicalizeProvenLegacyClear`), as on inbound delivery.\n * The restored body has the same id: version 1 hashes `undefined` and `null` alike.\n *\n * @param adapter - The storage adapter\n * @param schema - The schema (collections with a log)\n * @param ownNodeId - This device's node id\n * @returns The rewritten rows' records (to re-fold)\n */\nexport async function canonicalizeLegacyLogBodies(\n\tadapter: StorageAdapter,\n\tschema: SchemaDefinition,\n\townNodeId: string,\n): Promise<CanonicalizedLegacyBody[]> {\n\tconst rewritten: CanonicalizedLegacyBody[] = []\n\tfor (const collection of Object.keys(schema.collections)) {\n\t\tconst table = quoteIdent(`_kora_ops_${collection}`)\n\t\tconst rows = await adapter.query<OperationRow>(\n\t\t\t`SELECT * FROM ${table} WHERE type = 'update' AND previous_data IS NOT NULL`,\n\t\t)\n\t\tconst updates: Array<{ id: string; data: string | null }> = []\n\t\tfor (const row of rows) {\n\t\t\tlet op: Operation\n\t\t\ttry {\n\t\t\t\top = deserializeOperationWithCollection(row, collection)\n\t\t\t} catch {\n\t\t\t\t// An unreadable row is the log-integrity scan's business, not this one's.\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\tif (op.hashVersion === 2 || canonicalizeLegacyOperation(op) === op) continue\n\t\t\tconst canonical =\n\t\t\t\top.nodeId === ownNodeId\n\t\t\t\t\t? canonicalizeLegacyOperation(op)\n\t\t\t\t\t: await canonicalizeProvenLegacyClear(op)\n\t\t\tif (canonical === op) continue\n\t\t\tupdates.push({ id: op.id, data: serializeOperation(canonical).data })\n\t\t\trewritten.push({ collection, recordId: op.recordId })\n\t\t}\n\t\tif (updates.length === 0) continue\n\t\tawait adapter.transaction(async (tx) => {\n\t\t\tfor (const update of updates) {\n\t\t\t\tawait tx.execute(`UPDATE ${table} SET data = ? WHERE id = ?`, [update.data, update.id])\n\t\t\t}\n\t\t})\n\t}\n\treturn rewritten\n}\n","import {\n\ttype FoldState,\n\ttype HLCTimestamp,\n\tHybridLogicalClock,\n\ttype SchemaDefinition,\n\tcreateSnapshotState,\n\tjoinStates,\n\tquoteIdent,\n} from '@korajs/core'\nimport { deserializeRecord } from '../serialization/serializer'\nimport type { RawCollectionRow, StorageAdapter } from '../types'\nimport { FOLD_STATE_TABLE, type RecordFolder } from './record-folder'\n\n/**\n * How a database is re-materialized on its first open with the W7 fold:\n *\n * - `'log'`: the log is clean (W8 integrity scan): every record is rebuilt with the\n *   fold from its operations. This also repairs replicas that diverged under the\n *   pairwise merge of beta.12/13.\n * - `'snapshot+log'`: the log is not complete (it was compacted, or has sequence\n *   gaps): each existing row becomes the record's row snapshot (its values at\n *   their `_field_versions`, exact where a stored fold state still has them), and\n *   the remaining operations are folded on top.\n * - `'kept'`: the log has quarantined rows (W8). Only the records that own a\n *   quarantined row are kept exactly as they are (their row becomes their snapshot,\n *   nothing is rebuilt from their log); every other record is rebuilt as in `'log'`\n *   or `'snapshot+log'` (RT-68).\n *\n * Row snapshots are approximate (see `createSnapshotState`); records that fold\n * against one are listed in `_kora_fold_snapshot` until their history is complete\n * again (a scope entry with the server's fold state, or a full resync).\n */\nexport type RematerializationMode = 'log' | 'snapshot+log' | 'kept'\n\n/** Result of {@link rematerializeDatabase}. */\nexport interface RematerializationResult {\n\tmode: RematerializationMode\n\t/** Records whose state was rebuilt. */\n\trecords: number\n\t/** Rows whose visible values changed. */\n\tchangedRows: number\n\t/** Records that now fold against a row snapshot (approximate until settled). */\n\tsnapshots: number\n}\n\n/** Which records to keep as row snapshots (they own quarantined log rows). */\nexport interface KeptRecords {\n\t/** `collection` -> record ids. */\n\trecords: ReadonlyMap<string, ReadonlySet<string>>\n\t/** Collections with a quarantined row whose record id is unknown: kept whole. */\n\tcollections: ReadonlySet<string>\n}\n\nconst BATCH = 200\n\n/**\n * Rebuild every record's fold state and row. Runs once per database (the store\n * records completion in `_kora_meta`), after the W8 log-integrity scan and the\n * schema migrations. One write transaction per batch of records, so a crash\n * resumes from scratch safely (the rebuild is a pure function of the log and rows).\n *\n * @param mode - `'log'` or `'snapshot+log'` for the records that are not kept;\n *   `'kept'` is reported when `kept` names any record\n * @param kept - Records owning quarantined log rows (kept as they are)\n * @param collections - Only these collections (default: all)\n */\nexport async function rematerializeDatabase(\n\tadapter: StorageAdapter,\n\tschema: SchemaDefinition,\n\tfolder: RecordFolder,\n\tmode: Exclude<RematerializationMode, 'kept'>,\n\tkept: KeptRecords = { records: new Map(), collections: new Set() },\n\tcollections?: readonly string[],\n): Promise<RematerializationResult> {\n\tlet records = 0\n\tlet changedRows = 0\n\tlet snapshots = 0\n\tconst authoritative = folder.getAuthoritativeNodeIds()\n\tfor (const [collection, definition] of Object.entries(schema.collections)) {\n\t\tif (collections && !collections.includes(collection)) continue\n\t\tconst ids = new Set<string>()\n\t\tfor (const row of await adapter.query<{ id: string }>(\n\t\t\t`SELECT id FROM ${quoteIdent(collection)}`,\n\t\t)) {\n\t\t\tids.add(row.id)\n\t\t}\n\t\tfor (const row of await adapter.query<{ record_id: string }>(\n\t\t\t`SELECT DISTINCT record_id FROM ${quoteIdent(`_kora_ops_${collection}`)}`,\n\t\t)) {\n\t\t\tids.add(row.record_id)\n\t\t}\n\t\tconst keptIds = kept.records.get(collection)\n\t\tconst keepAll = kept.collections.has(collection)\n\t\tconst all = [...ids].sort()\n\t\tfor (let i = 0; i < all.length; i += BATCH) {\n\t\t\tconst batch = all.slice(i, i + BATCH)\n\t\t\tawait adapter.transaction(async (tx) => {\n\t\t\t\tfor (const recordId of batch) {\n\t\t\t\t\trecords += 1\n\t\t\t\t\tconst rows = await tx.query<RawCollectionRow>(\n\t\t\t\t\t\t`SELECT * FROM ${quoteIdent(collection)} WHERE id = ?`,\n\t\t\t\t\t\t[recordId],\n\t\t\t\t\t)\n\t\t\t\t\tconst row = rows[0]\n\t\t\t\t\tconst before = row ? JSON.stringify(deserializeRecord(row, definition.fields)) : null\n\t\t\t\t\tconst seed = await folder.loadStoredState(tx, collection, recordId)\n\t\t\t\t\tawait tx.execute(\n\t\t\t\t\t\t`DELETE FROM ${FOLD_STATE_TABLE} WHERE collection = ? AND record_id = ?`,\n\t\t\t\t\t\t[collection, recordId],\n\t\t\t\t\t)\n\t\t\t\t\tconst snapshotOf = (from: RawCollectionRow): FoldState =>\n\t\t\t\t\t\tsnapshotFromRow(from, collection, schema, { seed, authoritative })\n\t\t\t\t\tif (keepAll || keptIds?.has(recordId)) {\n\t\t\t\t\t\tif (row) {\n\t\t\t\t\t\t\t// Owns a quarantined row: never rebuilt from its log; the row stays as\n\t\t\t\t\t\t\t// it is and later operations merge onto it.\n\t\t\t\t\t\t\tconst snapshot = snapshotOf(row)\n\t\t\t\t\t\t\tawait folder.saveSnapshot(tx, snapshot)\n\t\t\t\t\t\t\tsnapshots += 1\n\t\t\t\t\t\t\tconst base = await folder.loadBase(tx, collection, recordId)\n\t\t\t\t\t\t\tawait folder.saveState(tx, base ? joinStates(base, snapshot, schema) : snapshot)\n\t\t\t\t\t\t}\n\t\t\t\t\t\tcontinue\n\t\t\t\t\t}\n\t\t\t\t\tif (mode === 'snapshot+log' && row) {\n\t\t\t\t\t\tawait folder.saveSnapshot(tx, snapshotOf(row))\n\t\t\t\t\t\tsnapshots += 1\n\t\t\t\t\t}\n\t\t\t\t\tconst state = await folder.foldFromLog(tx, collection, recordId)\n\t\t\t\t\tif (state === null) {\n\t\t\t\t\t\t// No operation and no base: a row the log never had (cannot happen on a\n\t\t\t\t\t\t// clean log; kept as a snapshot rather than dropped).\n\t\t\t\t\t\tif (row) {\n\t\t\t\t\t\t\tconst snapshot = snapshotOf(row)\n\t\t\t\t\t\t\tawait folder.saveSnapshot(tx, snapshot)\n\t\t\t\t\t\t\tawait folder.saveState(tx, snapshot)\n\t\t\t\t\t\t\tsnapshots += 1\n\t\t\t\t\t\t}\n\t\t\t\t\t\tcontinue\n\t\t\t\t\t}\n\t\t\t\t\tawait folder.saveState(tx, state)\n\t\t\t\t\tawait folder.materializeRow(tx, state, 'all', { clearRetraction: false })\n\t\t\t\t\tconst afterRows = await tx.query<RawCollectionRow>(\n\t\t\t\t\t\t`SELECT * FROM ${quoteIdent(collection)} WHERE id = ?`,\n\t\t\t\t\t\t[recordId],\n\t\t\t\t\t)\n\t\t\t\t\tconst after = afterRows[0]\n\t\t\t\t\t\t? JSON.stringify(deserializeRecord(afterRows[0], definition.fields))\n\t\t\t\t\t\t: null\n\t\t\t\t\tif (before !== after) changedRows += 1\n\t\t\t\t}\n\t\t\t})\n\t\t}\n\t}\n\tconst keptAny = kept.collections.size > 0 || [...kept.records.values()].some((s) => s.size > 0)\n\treturn { mode: keptAny ? 'kept' : mode, records, changedRows, snapshots }\n}\n\n/**\n * The base snapshot of a materialized row: its values at their `_field_versions`\n * (rows from before per-field versions fall back to `_version`, then `_updated_at`).\n * With a `seed` (the record's stored fold state), every field it still holds in\n * the current plan's kind is taken from it exactly (RT-68).\n */\nexport function snapshotFromRow(\n\trow: RawCollectionRow,\n\tcollection: string,\n\tschema: SchemaDefinition,\n\toptions: { seed?: FoldState | null; authoritative?: ReadonlySet<string> } = {},\n): FoldState {\n\tconst definition = schema.collections[collection]\n\tconst record = definition ? deserializeRecord(row, definition.fields) : { id: row.id }\n\tconst { id: _id, createdAt: _c, updatedAt: _u, ...values } = record as Record<string, unknown>\n\tconst latest = rowVersion(row)\n\tconst fieldVersions: Record<string, HLCTimestamp> = {}\n\tconst raw = typeof row._field_versions === 'string' ? row._field_versions : '{}'\n\ttry {\n\t\tfor (const [field, version] of Object.entries(JSON.parse(raw) as Record<string, unknown>)) {\n\t\t\tif (typeof version === 'string' && version.length > 0) {\n\t\t\t\tfieldVersions[field] = HybridLogicalClock.deserialize(version)\n\t\t\t}\n\t\t}\n\t} catch {\n\t\t// Malformed versions: every field falls back to the row version.\n\t}\n\tconst createdAt = typeof row._created_at === 'number' ? row._created_at : latest.wallTime\n\treturn createSnapshotState(\n\t\t{\n\t\t\tcollection,\n\t\t\trecordId: row.id,\n\t\t\tvalues,\n\t\t\tfieldVersions,\n\t\t\tcreated: { wallTime: createdAt, logical: 0, nodeId: '' },\n\t\t\tlatest,\n\t\t\tdeleted: row._deleted === 1,\n\t\t},\n\t\tschema,\n\t\t{\n\t\t\t...(options.seed ? { seed: options.seed } : {}),\n\t\t\t...(options.authoritative ? { authoritativeNodeIds: options.authoritative } : {}),\n\t\t},\n\t)\n}\n\nfunction rowVersion(row: RawCollectionRow): HLCTimestamp {\n\tif (typeof row._version === 'string' && row._version.length > 0) {\n\t\ttry {\n\t\t\treturn HybridLogicalClock.deserialize(row._version)\n\t\t} catch {\n\t\t\t// fall through\n\t\t}\n\t}\n\tconst wall = typeof row._updated_at === 'number' ? row._updated_at : 0\n\treturn { wallTime: wall, logical: 0, nodeId: '' }\n}\n","import {\n\ttype FoldState,\n\tFoldStateError,\n\ttype Operation,\n\ttype SchemaDefinition,\n\tdeserializeFoldState,\n\tmismatchedFoldFields,\n\tquoteIdent,\n} from '@korajs/core'\nimport { SEQ_CONFLICTS_TABLE } from '../store/sequence-repair'\nimport { LOCAL_NODES_TABLE } from '../sync/local-sync-records'\nimport type { Transaction } from '../types'\nimport { MAX_PARAMS, runTerms } from './query-terms'\nimport {\n\tCOMPACTED_THROUGH_TABLE,\n\tFOLD_BASE_TABLE,\n\tFOLD_SNAPSHOT_TABLE,\n\tFOLD_STATE_TABLE,\n\tPROVISIONAL_OPS_TABLE,\n} from './record-folder'\n\n/**\n * C3b (docs/design/fast-first-sync.md): what a delivery batch needs to know about the\n * database before it applies its operations, read in a handful of queries instead of\n * about thirteen per operation.\n *\n * A remote operation's apply asks the same questions of the database every time: is the\n * operation already in the log (or compacted away), who holds its sequence number, is the\n * record's fold state stored, does the record have a base, a snapshot, provisional effects\n * or a retraction marker, which row is materialized. Inside a write transaction nothing\n * but the batch itself changes those answers, so they are read once for every operation\n * of the batch (IN lists, under SQLite's variable limit) and then kept up to date in\n * memory by the batch's own writes, so an operation sees the results of the earlier\n * operations of its batch exactly as if it had read them back.\n *\n * Only the common case is answered from memory: a record with a readable fold state, or\n * one that is plainly new, and nothing unusual around it. Anything else (a record with a\n * base, snapshot, provisional effect, retraction marker, retained sequence conflict or\n * unreadable state, a node this database also writes under, a taken sequence number, a\n * record the batch touched by another route) is not eligible, and its operations take the\n * per-operation path, which reads through the transaction as before. The fast path is an\n * optimization of that path, never a different behavior: both produce the same log rows,\n * fold states and rows (tests/prefetch property test).\n */\n\n/** What the batch knows about one record. */\nexport interface PrefetchedRecord {\n\treadonly collection: string\n\treadonly recordId: string\n\t/** The stored fold state, when one is stored and readable. */\n\tstate: FoldState | null\n\t/** A state row exists that the current plan cannot read: the record is re-folded. */\n\tunreadable: boolean\n\t/** The record has operations in its log (this batch's included). */\n\thasLog: boolean\n\t/** The record has a compacted base state (only a record without a stored state cares). */\n\thasBase: boolean\n\t/** Row snapshot, provisional effect, retained conflict or retraction marker. */\n\tunusual: boolean\n\t/** The materialized row, or null when there is none. */\n\trow: { deleted: boolean } | null\n\t/** The batch changed the record by a route the cache does not follow. */\n\tdirty: boolean\n}\n\ninterface Term {\n\tsql: string\n\tparams: unknown[]\n}\n\ntype Row = {\n\tc: string | null\n\tk: string\n\ta: string | null\n\tb: string | null\n\tn: unknown\n\ts: unknown\n}\n\nexport class RemoteBatchPrefetch {\n\tprivate readonly records = new Map<string, PrefetchedRecord>()\n\t/** `collection \\0 id` of operations in a collection's log. */\n\tprivate readonly logged = new Set<string>()\n\t/** Ids of operations retained in the sequence-conflicts table (any collection). */\n\tprivate readonly conflictIds = new Set<string>()\n\t/** `collection \\0 node \\0 sequence` held in a collection's log. */\n\tprivate readonly holders = new Set<string>()\n\tprivate readonly compacted = new Map<string, number>()\n\tprivate readonly localNodes = new Set<string>()\n\tprivate readonly loadedIds = new Set<string>()\n\tprivate readonly loadedNodes = new Set<string>()\n\n\tconstructor(private readonly schema: SchemaDefinition) {}\n\n\t/**\n\t * Read everything `operations` need, in a few queries. Operations of collections the\n\t * schema does not have are left out (they are skipped or quarantined without a read).\n\t * Safe to call again with more operations: what was loaded is not read twice.\n\t */\n\tasync load(tx: Transaction, operations: readonly Operation[]): Promise<void> {\n\t\tconst fresh = operations.filter((op) => this.schema.collections[op.collection])\n\t\tconst newRecords = new Map<string, { collection: string; recordId: string }>()\n\t\tconst byCollection = new Map<\n\t\t\tstring,\n\t\t\t{\n\t\t\t\trecords: Set<string>\n\t\t\t\tids: Set<string>\n\t\t\t\tpairs: Map<string, { node: string; seq: number }>\n\t\t\t\trowIds: Set<string>\n\t\t\t}\n\t\t>()\n\t\tconst newIds = new Set<string>()\n\t\tconst newNodes = new Set<string>()\n\t\tfor (const op of fresh) {\n\t\t\tconst key = recordKey(op.collection, op.recordId)\n\t\t\tconst needRecord = !this.records.has(key)\n\t\t\tif (needRecord) newRecords.set(key, { collection: op.collection, recordId: op.recordId })\n\t\t\tconst idKey = `${op.collection}\\0${op.id}`\n\t\t\tconst needId = !this.loadedIds.has(idKey)\n\t\t\tif (!needRecord && !needId) continue\n\t\t\tlet group = byCollection.get(op.collection)\n\t\t\tif (!group) {\n\t\t\t\tgroup = { records: new Set(), ids: new Set(), pairs: new Map(), rowIds: new Set() }\n\t\t\t\tbyCollection.set(op.collection, group)\n\t\t\t}\n\t\t\tif (needRecord) {\n\t\t\t\tgroup.records.add(op.recordId)\n\t\t\t\tgroup.rowIds.add(op.recordId)\n\t\t\t}\n\t\t\tif (needId) {\n\t\t\t\tgroup.ids.add(op.id)\n\t\t\t\tgroup.pairs.set(`${op.nodeId}\\0${op.sequenceNumber}`, {\n\t\t\t\t\tnode: op.nodeId,\n\t\t\t\t\tseq: op.sequenceNumber,\n\t\t\t\t})\n\t\t\t\tnewIds.add(idKey)\n\t\t\t\tif (!this.loadedNodes.has(op.nodeId)) newNodes.add(op.nodeId)\n\t\t\t}\n\t\t}\n\t\tif (newRecords.size === 0 && newIds.size === 0) return\n\n\t\t// Per-record tables (the fold's, the retraction markers, retained conflicts).\n\t\tconst keys = [...newRecords.values()]\n\t\tfor (const key of keys) {\n\t\t\tthis.records.set(recordKey(key.collection, key.recordId), {\n\t\t\t\tcollection: key.collection,\n\t\t\t\trecordId: key.recordId,\n\t\t\t\tstate: null,\n\t\t\t\tunreadable: false,\n\t\t\t\thasLog: false,\n\t\t\t\thasBase: false,\n\t\t\t\tunusual: false,\n\t\t\t\trow: null,\n\t\t\t\tdirty: false,\n\t\t\t})\n\t\t}\n\t\tconst RECORD_CHUNK = Math.floor(MAX_PARAMS / 2)\n\t\tfor (let start = 0; start < keys.length; start += RECORD_CHUNK) {\n\t\t\tconst chunk = keys.slice(start, start + RECORD_CHUNK)\n\t\t\tconst values = chunk.map(() => '(?, ?)').join(', ')\n\t\t\tconst join = (table: string, alias: string, extra = ''): string =>\n\t\t\t\t`FROM ${table} ${alias} JOIN k ON ${alias}.collection = k.c AND ${alias}.record_id = k.r${extra}`\n\t\t\tconst rows = await tx.query<Row>(\n\t\t\t\t`WITH k(c, r) AS (VALUES ${values})\nSELECT f.collection AS c, 'state' AS k, f.state AS a, NULL AS b, NULL AS n, f.record_id AS s ${join(FOLD_STATE_TABLE, 'f')}\nUNION ALL SELECT x.collection, 'base', NULL, NULL, NULL, x.record_id ${join(FOLD_BASE_TABLE, 'x')}\nUNION ALL SELECT x.collection, 'snapshot', NULL, NULL, NULL, x.record_id ${join(FOLD_SNAPSHOT_TABLE, 'x')}\nUNION ALL SELECT x.collection, 'provisional', NULL, NULL, NULL, x.record_id ${join(PROVISIONAL_OPS_TABLE, 'x')}\nUNION ALL SELECT x.collection, 'marker', NULL, NULL, NULL, x.record_id ${join('_kora_scope_retractions', 'x')}\nUNION ALL SELECT x.collection, 'retained', x.id, NULL, NULL, x.record_id ${join(SEQ_CONFLICTS_TABLE, 'x', ' WHERE x.reemitted_as IS NULL')}`,\n\t\t\t\tchunk.flatMap((key) => [key.collection, key.recordId]),\n\t\t\t)\n\t\t\tfor (const row of rows) {\n\t\t\t\tconst record = this.records.get(recordKey(String(row.c), String(row.s)))\n\t\t\t\tif (!record) continue\n\t\t\t\tif (row.k === 'state') this.readState(record, String(row.a))\n\t\t\t\telse if (row.k === 'base') record.hasBase = true\n\t\t\t\telse record.unusual = true\n\t\t\t\tif (row.k === 'retained' && row.a !== null) this.conflictIds.add(row.a)\n\t\t\t}\n\t\t}\n\n\t\t// Per-collection tables: the log (by record, by id, by sequence) and the rows.\n\t\tconst terms: Term[] = []\n\t\tfor (const [collection, group] of byCollection) {\n\t\t\tconst log = quoteIdent(`_kora_ops_${collection}`)\n\t\t\tfor (const chunk of chunked([...group.records], MAX_PARAMS - 2)) {\n\t\t\t\tterms.push({\n\t\t\t\t\tsql: `SELECT ? AS c, 'r' AS k, NULL AS a, record_id AS b, NULL AS n, COUNT(*) AS s FROM ${log} WHERE record_id IN (${marks(chunk.length)}) GROUP BY record_id`,\n\t\t\t\t\tparams: [collection, ...chunk],\n\t\t\t\t})\n\t\t\t}\n\t\t\tfor (const chunk of chunked([...group.ids], MAX_PARAMS - 2)) {\n\t\t\t\tterms.push({\n\t\t\t\t\tsql: `SELECT ? AS c, 'i' AS k, id AS a, record_id AS b, node_id AS n, sequence_number AS s FROM ${log} WHERE id IN (${marks(chunk.length)})`,\n\t\t\t\t\tparams: [collection, ...chunk],\n\t\t\t\t})\n\t\t\t}\n\t\t\tfor (const chunk of chunked([...group.pairs.values()], Math.floor((MAX_PARAMS - 2) / 2))) {\n\t\t\t\tterms.push({\n\t\t\t\t\tsql: `SELECT ? AS c, 's' AS k, id AS a, record_id AS b, node_id AS n, sequence_number AS s FROM ${log} WHERE (node_id, sequence_number) IN (VALUES ${chunk\n\t\t\t\t\t\t.map(() => '(?, ?)')\n\t\t\t\t\t\t.join(', ')})`,\n\t\t\t\t\tparams: [collection, ...chunk.flatMap((pair) => [pair.node, pair.seq])],\n\t\t\t\t})\n\t\t\t}\n\t\t\tfor (const chunk of chunked([...group.rowIds], MAX_PARAMS - 2)) {\n\t\t\t\tterms.push({\n\t\t\t\t\tsql: `SELECT ? AS c, 'w' AS k, id AS a, NULL AS b, NULL AS n, _deleted AS s FROM ${quoteIdent(collection)} WHERE id IN (${marks(chunk.length)})`,\n\t\t\t\t\tparams: [collection, ...chunk],\n\t\t\t\t})\n\t\t\t}\n\t\t}\n\t\t// Node-level tables and retained conflicts by id.\n\t\tconst nodes = [...newNodes]\n\t\tfor (const chunk of chunked(nodes, Math.floor((MAX_PARAMS - 2) / 2))) {\n\t\t\tterms.push({\n\t\t\t\tsql: `SELECT NULL AS c, 'compacted' AS k, node_id AS a, NULL AS b, NULL AS n, sequence_number AS s FROM ${COMPACTED_THROUGH_TABLE} WHERE node_id IN (${marks(chunk.length)})`,\n\t\t\t\tparams: [...chunk],\n\t\t\t})\n\t\t\tterms.push({\n\t\t\t\tsql: `SELECT NULL AS c, 'local' AS k, node_id AS a, NULL AS b, NULL AS n, NULL AS s FROM ${LOCAL_NODES_TABLE} WHERE node_id IN (${marks(chunk.length)})`,\n\t\t\t\tparams: [...chunk],\n\t\t\t})\n\t\t}\n\t\tconst ids = [...new Set([...byCollection.values()].flatMap((group) => [...group.ids]))]\n\t\tfor (const chunk of chunked(ids, MAX_PARAMS - 2)) {\n\t\t\tterms.push({\n\t\t\t\tsql: `SELECT NULL AS c, 'conflictid' AS k, id AS a, NULL AS b, NULL AS n, NULL AS s FROM ${SEQ_CONFLICTS_TABLE} WHERE reemitted_as IS NULL AND id IN (${marks(chunk.length)})`,\n\t\t\t\tparams: [...chunk],\n\t\t\t})\n\t\t}\n\t\tfor (const rows of await runTerms(tx, terms)) {\n\t\t\tfor (const row of rows) this.absorb(row as Row)\n\t\t}\n\t\tfor (const idKey of newIds) this.loadedIds.add(idKey)\n\t\tfor (const node of newNodes) this.loadedNodes.add(node)\n\t}\n\n\t/**\n\t * Whether the batch read everything `op` needs (its id, its sequence number and its node).\n\t * An operation that was never announced cannot be answered from memory: it takes the\n\t * per-operation path, which reads the transaction.\n\t */\n\tcovers(op: Operation): boolean {\n\t\treturn this.loadedIds.has(`${op.collection}\\0${op.id}`) && this.loadedNodes.has(op.nodeId)\n\t}\n\n\t/**\n\t * An operation was appended to (or attempted against) the log by the per-operation path.\n\t * Its sequence number is taken from now on, so a later operation of the same node and\n\t * number is found a conflict instead of hitting the unique index. Over-approximating is\n\t * safe: a holder that is not one only sends a later operation down the careful path.\n\t */\n\tnoteAppended(op: Operation): void {\n\t\tthis.logged.add(`${op.collection}\\0${op.id}`)\n\t\tthis.holders.add(`${op.collection}\\0${op.nodeId}\\0${op.sequenceNumber}`)\n\t}\n\n\t/** The record's knowledge when its operations can be applied from memory, else null. */\n\teligible(collection: string, recordId: string): PrefetchedRecord | null {\n\t\tconst record = this.records.get(recordKey(collection, recordId))\n\t\tif (!record || record.dirty || record.unusual || record.unreadable) return null\n\t\t// No stored state: only a record with no history at all is plainly new.\n\t\tif (record.state === null && (record.hasLog || record.hasBase)) return null\n\t\treturn record\n\t}\n\n\t/** Whether `op` is already in the log, retained as a sequence conflict, or compacted away. */\n\tisDuplicate(op: Operation): boolean {\n\t\tif (this.logged.has(`${op.collection}\\0${op.id}`) || this.conflictIds.has(op.id)) return true\n\t\tconst through = this.compacted.get(op.nodeId)\n\t\treturn through !== undefined && op.sequenceNumber <= through\n\t}\n\n\t/**\n\t * Whether `op`'s append needs the careful path: its node is also one of this database's\n\t * (a beta.12 shared node: the append records it as received), or another operation of\n\t * its node holds its sequence number (the append keeps it in the conflicts table).\n\t */\n\tneedsCarefulAppend(op: Operation): boolean {\n\t\treturn (\n\t\t\tthis.localNodes.has(op.nodeId) ||\n\t\t\tthis.holders.has(`${op.collection}\\0${op.nodeId}\\0${op.sequenceNumber}`)\n\t\t)\n\t}\n\n\t/** Follow a committed-in-transaction fast apply: the operation is in the log now. */\n\tnoteApplied(\n\t\top: Operation,\n\t\trecord: PrefetchedRecord,\n\t\tresult: { saved: FoldState | null; row: { deleted: boolean } | null; refolded: boolean },\n\t): void {\n\t\tthis.logged.add(`${op.collection}\\0${op.id}`)\n\t\tthis.holders.add(`${op.collection}\\0${op.nodeId}\\0${op.sequenceNumber}`)\n\t\trecord.hasLog = true\n\t\tif (result.refolded) {\n\t\t\trecord.dirty = true\n\t\t\treturn\n\t\t}\n\t\tif (result.saved !== null) record.state = result.saved\n\t\trecord.row = result.row\n\t}\n\n\t/**\n\t * The record was (or may have been) changed by something the cache does not follow: a\n\t * per-operation apply, a retraction, a provisional side effect. Its operations read the\n\t * transaction from now on.\n\t */\n\tmarkDirty(collection: string, recordId: string): void {\n\t\tconst record = this.records.get(recordKey(collection, recordId))\n\t\tif (record) record.dirty = true\n\t}\n\n\tprivate readState(record: PrefetchedRecord, raw: string): void {\n\t\ttry {\n\t\t\tconst state = deserializeFoldState(raw)\n\t\t\t// A plan the schema has since changed re-folds the record (RT-63).\n\t\t\tif (mismatchedFoldFields(state, this.schema).length > 0) record.unreadable = true\n\t\t\telse record.state = state\n\t\t} catch (error) {\n\t\t\tif (!(error instanceof FoldStateError)) throw error\n\t\t\trecord.unreadable = true\n\t\t}\n\t}\n\n\tprivate absorb(row: Row): void {\n\t\tswitch (row.k) {\n\t\t\tcase 'r': {\n\t\t\t\t// Only whether the record has a history matters here; its operations' ids and\n\t\t\t\t// sequence numbers are asked for by the batch's own operations ('i', 's').\n\t\t\t\tconst record = this.records.get(recordKey(String(row.c), String(row.b)))\n\t\t\t\tif (record) record.hasLog = true\n\t\t\t\tbreak\n\t\t\t}\n\t\t\tcase 'i':\n\t\t\tcase 's':\n\t\t\t\tthis.logged.add(`${row.c}\\0${row.a}`)\n\t\t\t\tthis.holders.add(`${row.c}\\0${row.n}\\0${row.s}`)\n\t\t\t\tbreak\n\t\t\tcase 'w': {\n\t\t\t\tconst record = this.records.get(recordKey(String(row.c), String(row.a)))\n\t\t\t\tif (record) record.row = { deleted: Number(row.s) === 1 }\n\t\t\t\tbreak\n\t\t\t}\n\t\t\tcase 'compacted':\n\t\t\t\tthis.compacted.set(String(row.a), Number(row.s))\n\t\t\t\tbreak\n\t\t\tcase 'local':\n\t\t\t\tthis.localNodes.add(String(row.a))\n\t\t\t\tbreak\n\t\t\tcase 'conflictid':\n\t\t\t\tthis.conflictIds.add(String(row.a))\n\t\t\t\tbreak\n\t\t}\n\t}\n}\n\nfunction recordKey(collection: string, recordId: string): string {\n\treturn `${collection}\\0${recordId}`\n}\n\nfunction marks(count: number): string {\n\treturn new Array<string>(count).fill('?').join(', ')\n}\n\nfunction chunked<T>(items: readonly T[], size: number): T[][] {\n\tconst out: T[][] = []\n\tfor (let start = 0; start < items.length; start += size)\n\t\tout.push(items.slice(start, start + size))\n\treturn out\n}\n","import { KoraError, migrationStepsToSQL, quoteIdent, validateRecord } from '@korajs/core'\nimport type { CausalTracker, MigrationStep, Operation, SchemaDefinition } from '@korajs/core'\nimport {\n\tCausalScope,\n\ttype WriteEnv,\n\ttype WriteScope,\n\twithWriteScope,\n} from '../mutations/write-context'\nimport { writeUpdateInTx } from '../mutations/write-ops'\nimport { deserializeRecord, serializeRecord } from '../serialization/serializer'\nimport type { MetaRow, RawCollectionRow, StorageAdapter, Transaction } from '../types'\n\ntype BackfillStep = Extract<MigrationStep, { type: 'backfill' }>\n\n/** Keys every record carries besides its schema fields. */\nconst RECORD_KEYS: ReadonlySet<string> = new Set(['id', 'createdAt', 'updatedAt'])\n\n/** Everything the migration runner needs from the store. */\nexport interface MigrationRunContext {\n\treadonly adapter: StorageAdapter\n\treadonly schema: SchemaDefinition\n\t/** Write environment of the store's current node (clock, node id, secrets). */\n\treadonly env: Omit<WriteEnv, 'mutationName' | 'transactionId'>\n\treadonly causalTracker: CausalTracker | null\n\t/** Called after each version commits, once per operation its backfills wrote. */\n\treadonly onOperation: (operation: Operation) => void\n}\n\n/**\n * Bring the local database from its stored schema version to `schema.version`\n * (STORE-13, NEW-STORE-1).\n *\n * Each version runs in ONE transaction: its structural DDL, its backfills and the\n * `schema_version` write. A failure (a throwing transform, a crash) leaves no partial\n * effect, so a retry never applies a non-idempotent backfill twice.\n *\n * Backfill transforms receive the deserialized record (booleans, arrays, objects as the\n * app reads them). Every changed record is written through the single local write path\n * as an update operation with mutation name `migration:v<N>`, so the backfilled values\n * sync to the server and other devices; a step declared `localOnly` rewrites the rows\n * only. Fields the transform returns unchanged are not written.\n *\n * @returns The operations the backfills wrote, in commit order\n */\nexport async function runSchemaMigrations(ctx: MigrationRunContext): Promise<Operation[]> {\n\tconst stored = await readStoredSchemaVersion(ctx.adapter)\n\tconst target = ctx.schema.version\n\tif (stored >= target) {\n\t\tif (stored === 0) await writeSchemaVersion(ctx.adapter, target)\n\t\treturn []\n\t}\n\n\tconst written: Operation[] = []\n\tconst migrations = ctx.schema.migrations ?? {}\n\tfor (let version = stored + 1; version <= target; version++) {\n\t\tconst migration = migrations[version]\n\t\tconst steps = migration?.steps ?? []\n\t\tconst committed: Operation[] = []\n\t\tconst causal = new CausalScope(ctx.causalTracker, false)\n\t\tawait ctx.adapter.transaction(async (tx) => {\n\t\t\tfor (const step of steps) {\n\t\t\t\tif (step.type === 'renameField') {\n\t\t\t\t\tawait renameColumn(tx, step.collection, step.from, step.to)\n\t\t\t\t\tcontinue\n\t\t\t\t}\n\t\t\t\tfor (const sql of migrationStepsToSQL([step])) {\n\t\t\t\t\tawait executeStructural(tx, sql)\n\t\t\t\t}\n\t\t\t}\n\t\t\tconst backfills = steps.filter((step): step is BackfillStep => step.type === 'backfill')\n\t\t\tif (backfills.length > 0) {\n\t\t\t\tconst env: WriteEnv = { ...ctx.env, mutationName: `migration:v${version}` }\n\t\t\t\tawait withWriteScope(tx, ctx.env.nodeId, causal, async (scope) => {\n\t\t\t\t\tfor (const step of backfills) {\n\t\t\t\t\t\tcommitted.push(...(await runBackfill(ctx.schema, env, scope, version, step)))\n\t\t\t\t\t}\n\t\t\t\t})\n\t\t\t}\n\t\t\tawait tx.execute(\n\t\t\t\t\"INSERT OR REPLACE INTO _kora_meta (key, value) VALUES ('schema_version', ?)\",\n\t\t\t\t[String(version)],\n\t\t\t)\n\t\t})\n\t\tcausal.publish()\n\t\tfor (const operation of committed) ctx.onOperation(operation)\n\t\twritten.push(...committed)\n\t}\n\treturn written\n}\n\n/**\n * Structural DDL, tolerating \"duplicate column name\": the adapter's open already ran the\n * current schema's DDL, which adds the target schema's columns (`--kora:safe-alter`).\n * Inside a transaction a failed statement rolls back only itself.\n */\nasync function executeStructural(tx: Transaction, sql: string): Promise<void> {\n\ttry {\n\t\tawait tx.execute(sql)\n\t} catch (error) {\n\t\tconst message = error instanceof Error ? error.message : String(error)\n\t\tif (!message.includes('duplicate column name')) throw error\n\t}\n}\n\n/**\n * A `renameField` step. The adapter's open has already run the target schema's DDL, whose\n * `--kora:safe-alter` adds the renamed field's column (empty, or holding its default) and\n * creates the target schema's indexes on it; a plain `RENAME COLUMN` would then fail\n * \"duplicate column name\" and leave the values in the old column. The pre-added column is\n * dropped first (with the indexes on it, recreated afterwards), so the rename keeps the\n * values and the source column's constraints. Runs inside the version's transaction.\n */\nasync function renameColumn(\n\ttx: Transaction,\n\tcollection: string,\n\tfrom: string,\n\tto: string,\n): Promise<void> {\n\tconst table = quoteIdent(collection)\n\tconst columns = await tx.query<{ name: string }>(\n\t\t`SELECT name FROM pragma_table_info(${sqlText(collection)})`,\n\t)\n\tconst names = new Set(columns.map((column) => column.name))\n\t// A database created at (or past) this version: the open's DDL already made `to` and\n\t// there is no `from` to carry over (a fresh install of a schema whose history has\n\t// renames). Nothing to rename.\n\tif (!names.has(from) && names.has(to)) return\n\tif (names.has(from) && names.has(to)) {\n\t\tconst indexes = await tx.query<{ name: string; sql: string }>(\n\t\t\t`SELECT m.name AS name, m.sql AS sql FROM sqlite_master m WHERE m.type = 'index' AND m.tbl_name = ${sqlText(collection)} AND m.sql IS NOT NULL AND EXISTS (SELECT 1 FROM pragma_index_info(m.name) i WHERE i.name = ${sqlText(to)})`,\n\t\t)\n\t\tfor (const index of indexes) await tx.execute(`DROP INDEX ${quoteIdent(index.name)}`)\n\t\tawait tx.execute(`ALTER TABLE ${table} DROP COLUMN ${quoteIdent(to)}`)\n\t\tawait tx.execute(`ALTER TABLE ${table} RENAME COLUMN ${quoteIdent(from)} TO ${quoteIdent(to)}`)\n\t\tfor (const index of indexes) {\n\t\t\tawait tx.execute(index.sql.replace(/^CREATE INDEX /i, 'CREATE INDEX IF NOT EXISTS '))\n\t\t}\n\t\treturn\n\t}\n\tawait executeStructural(\n\t\ttx,\n\t\t`ALTER TABLE ${table} RENAME COLUMN ${quoteIdent(from)} TO ${quoteIdent(to)}`,\n\t)\n}\n\nfunction sqlText(value: string): string {\n\treturn `'${value.replaceAll(\"'\", \"''\")}'`\n}\n\nasync function runBackfill(\n\tschema: SchemaDefinition,\n\tenv: WriteEnv,\n\tscope: WriteScope,\n\tversion: number,\n\tstep: BackfillStep,\n): Promise<Operation[]> {\n\tconst definition = schema.collections[step.collection]\n\tif (!definition) {\n\t\tthrow new KoraError(\n\t\t\t`Migration v${version} backfills unknown collection \"${step.collection}\".`,\n\t\t\t'MIGRATION_UNKNOWN_COLLECTION',\n\t\t\t{ version, collection: step.collection },\n\t\t)\n\t}\n\tconst rows = await scope.tx.query<RawCollectionRow>(\n\t\t`SELECT * FROM ${quoteIdent(step.collection)} WHERE _deleted = 0 ORDER BY id`,\n\t)\n\tconst operations: Operation[] = []\n\tfor (const row of rows) {\n\t\tconst record = deserializeRecord(row, definition.fields)\n\t\tconst updates = step.transform({ ...record })\n\t\tif (updates === null || typeof updates !== 'object') continue\n\t\tconst changes: Record<string, unknown> = {}\n\t\tfor (const [field, value] of Object.entries(updates)) {\n\t\t\t// `{ ...record, x }` restates the record's own keys: unchanged ones are ignored.\n\t\t\tif (RECORD_KEYS.has(field) && sameValue(record[field], value)) continue\n\t\t\tif (!(field in definition.fields)) {\n\t\t\t\tthrow new KoraError(\n\t\t\t\t\t`Migration v${version} backfill of \"${step.collection}\" returned unknown field \"${field}\".`,\n\t\t\t\t\t'MIGRATION_UNKNOWN_FIELD',\n\t\t\t\t\t{ version, collection: step.collection, field, fix: 'Return only schema fields.' },\n\t\t\t\t)\n\t\t\t}\n\t\t\tif (!sameValue(record[field], value)) changes[field] = value\n\t\t}\n\t\tif (Object.keys(changes).length === 0) continue\n\n\t\tif (step.localOnly) {\n\t\t\tconst serialized = serializeRecord(changes, definition.fields)\n\t\t\tconst columns = Object.keys(serialized)\n\t\t\tawait scope.tx.execute(\n\t\t\t\t`UPDATE ${quoteIdent(step.collection)} SET ${columns.map((c) => `${quoteIdent(c)} = ?`).join(', ')} WHERE id = ?`,\n\t\t\t\t[...columns.map((c) => serialized[c]), row.id],\n\t\t\t)\n\t\t\tcontinue\n\t\t}\n\t\tconst validated = validateRecord(step.collection, definition, changes, 'update')\n\t\tconst result = await writeUpdateInTx(env, scope, step.collection, row.id, validated)\n\t\tif (result.operation) operations.push(result.operation)\n\t}\n\treturn operations\n}\n\n/** Structural equality for record values (JSON-shaped; bytes compared bytewise). */\nfunction sameValue(a: unknown, b: unknown): boolean {\n\tif (Object.is(a, b)) return true\n\tif (a instanceof Uint8Array || b instanceof Uint8Array) {\n\t\tif (!(a instanceof Uint8Array) || !(b instanceof Uint8Array) || a.length !== b.length) {\n\t\t\treturn false\n\t\t}\n\t\treturn a.every((byte, index) => byte === b[index])\n\t}\n\tif (a === null || b === null || typeof a !== 'object' || typeof b !== 'object') {\n\t\t// A missing value and null are the same stored value.\n\t\treturn (a ?? null) === (b ?? null)\n\t}\n\tif (Array.isArray(a) !== Array.isArray(b)) return false\n\tconst keysA = Object.keys(a)\n\tconst keysB = Object.keys(b)\n\tif (keysA.length !== keysB.length) return false\n\treturn keysA.every((key) =>\n\t\tsameValue((a as Record<string, unknown>)[key], (b as Record<string, unknown>)[key]),\n\t)\n}\n\nasync function readStoredSchemaVersion(adapter: StorageAdapter): Promise<number> {\n\tconst rows = await adapter.query<MetaRow>(\n\t\t\"SELECT value FROM _kora_meta WHERE key = 'schema_version'\",\n\t)\n\treturn rows[0] ? Number(rows[0].value) : 0\n}\n\nasync function writeSchemaVersion(adapter: StorageAdapter, version: number): Promise<void> {\n\tawait adapter.execute(\n\t\t\"INSERT OR REPLACE INTO _kora_meta (key, value) VALUES ('schema_version', ?)\",\n\t\t[String(version)],\n\t)\n}\n","/*\n * Keeps the start order of local updates, deletes and transactions that touch the SAME\n * record equal to their call order when one of them has to read before it can be predicted\n * (instant-UI stage S6b).\n *\n * A write registers its prediction and starts its storage transaction in ONE synchronous\n * step, so that overlapping writes register in transaction order (design 5.6) and the\n * operation log is the one written with the overlay off (I2). When a prediction first needs\n * a read (the record's row, or the fold state an array write builds on), that step is split\n * by an `await`: a write called later would start first, and `update(id); delete(id)`\n * issued without awaiting would run as delete, update and fail. A write that reads holds\n * the turn of its record; a write called while that turn is held waits for it. Writes of\n * other records never wait, so 500 updates of cold records read in parallel, and a write\n * that needs no read and touches no held record takes no turn (a map lookup). A delete also\n * waits for every held turn, because its cascades write other records, and while it is held\n * it is a barrier: every write called after it waits for it, whatever record it touches. Consequence, by\n * design: operations of independent records may be logged in a different order than with the\n * overlay off when one of them had to read (per-record order is always the call order).\n */\n\n/** One write's place in the order of the writes that read. */\nexport interface WriteTurn {\n\t/**\n\t * Resolves when every earlier write that was still reading has started its storage\n\t * transaction. Null when there is none: the write proceeds synchronously. Await it\n\t * before reading.\n\t */\n\treadonly wait: Promise<void> | null\n\t/**\n\t * The write is going to be asynchronous (it reads): writes called from now on wait for\n\t * it. Already held when `wait` is not null.\n\t */\n\thold(): void\n\t/** The write has started its storage transaction, or was given up. Idempotent. */\n\trelease(): void\n}\n\n/** Per-registry bookkeeping of the writes that are reading, by record key. */\nexport class WriteOrder {\n\tprivate readonly tails = new Map<string, Promise<void>>()\n\t/** The turn of a write that waits for everything (a delete): every later write waits for it. */\n\tprivate barrier: Promise<void> | null = null\n\n\t/**\n\t * Call synchronously when a local update, delete or transaction is called.\n\t *\n\t * @param keys - The records the write touches (`recordKey(collection, id)`)\n\t * @param options - `all`: also wait for every held turn (a delete, whose cascades reach\n\t *   other records)\n\t */\n\tenter(keys: readonly string[], options: { all?: boolean } = {}): WriteTurn {\n\t\tlet prior: Promise<void> | null = null\n\t\tconst priors: Array<Promise<void>> = []\n\t\tif (this.tails.size > 0 || this.barrier !== null) {\n\t\t\t// A held delete is a barrier: its cascades write other records, so no later write\n\t\t\t// may start before it, whatever record that write touches.\n\t\t\tif (this.barrier) priors.push(this.barrier)\n\t\t\tif (options.all) for (const tail of this.tails.values()) priors.push(tail)\n\t\t\telse\n\t\t\t\tfor (const key of keys) {\n\t\t\t\t\tconst tail = this.tails.get(key)\n\t\t\t\t\tif (tail) priors.push(tail)\n\t\t\t\t}\n\t\t\tif (priors.length > 0) prior = Promise.all(priors).then(() => {})\n\t\t}\n\t\tlet mine: Promise<void> | null = null\n\t\tlet open: () => void = () => {}\n\t\tconst hold = (): void => {\n\t\t\tif (mine) return\n\t\t\tconst ours = new Promise<void>((resolve) => {\n\t\t\t\topen = resolve\n\t\t\t})\n\t\t\tmine = ours\n\t\t\tfor (const key of keys) this.tails.set(key, ours)\n\t\t\tif (options.all) this.barrier = ours\n\t\t}\n\t\tif (prior !== null) hold()\n\t\treturn {\n\t\t\twait: prior,\n\t\t\thold,\n\t\t\trelease: () => {\n\t\t\t\tif (!mine) return\n\t\t\t\tconst ours = mine\n\t\t\t\tmine = null\n\t\t\t\tfor (const key of keys) if (this.tails.get(key) === ours) this.tails.delete(key)\n\t\t\t\tif (this.barrier === ours) this.barrier = null\n\t\t\t\topen()\n\t\t\t},\n\t\t}\n\t}\n\n\t/** Whether a write is reading right now (diagnostics and tests). */\n\tget busy(): boolean {\n\t\treturn this.tails.size > 0 || this.barrier !== null\n\t}\n}\n","import type { FoldState } from '@korajs/core'\nimport type { CollectionRecord } from '../types'\nimport type { MissReason, PredictedChange, PredictedWriteKind } from './predict'\nimport { WriteOrder } from './write-order'\n\n/*\n * The PendingWrites registry (instant-UI stage S2, docs/design/instant-ui-updates.md\n * 4.2, 5.5, 5.6, 11).\n *\n * A plain data structure: entries, a monotonic epoch, caps, lifecycle, a dependency\n * chain and a committed-row cache. It reads no storage, schedules no timers and never\n * touches a subscription; the clock is injected, so every behavior is deterministic in\n * tests. It is tab-local state: nothing here is serialized or broadcast (I11), and the\n * write path never reads it (I1).\n */\n\n/** Where an entry is in its life. */\nexport type EntryState =\n\t/** Predicted; its transaction has not answered. */\n\t| 'pending'\n\t/** Its transaction did not answer in time (or the commit outcome is unknown): kept shown. */\n\t| 'unknown'\n\t/** Its transaction committed; kept (settling) until subscriptions have re-read. */\n\t| 'committed'\n\n/** The outcome of a write, as reported in `store:write-settled`. */\nexport type SettleOutcome = 'committed' | 'rolled-back' | 'unknown'\n\n/** One pending write, as the registry hands it out. Never mutated in place. */\nexport interface PendingEntry {\n\treadonly writeId: string\n\treadonly kind: PredictedWriteKind\n\treadonly collection: string\n\treadonly recordId: string\n\t/** See {@link PredictedChange.patch}. */\n\treadonly patch: Readonly<Record<string, unknown>> | null\n\t/** See {@link PredictedChange.previous}. */\n\treadonly previous: Readonly<Record<string, unknown>> | null\n\t/**\n\t * The record after this write (for a delete: the record as it was). Replaced by the\n\t * committed record once the transaction commits.\n\t */\n\treadonly record: CollectionRecord\n\t/** The write this one was derived from (an earlier pending write of the same record). */\n\treadonly dependsOn: string | null\n\t/**\n\t * Every write this one was derived from, nearest first (bounded): `dependsOn` and its own\n\t * ancestors. The chain survives the retirement of the links in between, so the commit\n\t * verification can tell that a write rests on one that has not reported (or was rolled back).\n\t */\n\treadonly ancestors: readonly string[]\n\t/**\n\t * The transaction this entry belongs to (stage S6a), or null for a single write. Members\n\t * of a group share their fate: they are registered, committed, marked unknown and rolled\n\t * back together, and a subscription applies all of them or none (design 5.9).\n\t */\n\treadonly groupId: string | null\n\treadonly state: EntryState\n\t/** Epoch assigned at commit; null while the write is not committed. */\n\treadonly retiredAt: number | null\n\t/** Registry clock reading when the entry was added. */\n\treadonly registeredAtMs: number\n\t/** Registry clock reading at commit, or null. */\n\treadonly retiredAtMs: number | null\n\t/** Estimated size of the entry, in bytes. */\n\treadonly bytes: number\n\t/** Ids of the operations the write created; empty until it commits. */\n\treadonly operationIds: readonly string[]\n\t/**\n\t * Changes to the collection this registry did not make (a remote apply, a cross-tab\n\t * change, a write that was not predicted) seen when the entry was added. The settle\n\t * check only judges an entry when the count is unchanged: otherwise the database may\n\t * legitimately differ from the prediction.\n\t */\n\treadonly foreignAtAdd: number\n\t/**\n\t * The registry's foreign-change sequence when the entry was added (see\n\t * {@link PendingWrites.invalidate}). A remote apply or another tab's change to this\n\t * record after that point makes the entry's `record` older than the database, so it is no\n\t * longer a base for the next write of the record.\n\t */\n\treadonly foreignSeqAtAdd: number\n\t/** The collection's remote-apply activity when the entry was added (see {@link PendingWrites.foreignSince}). */\n\treadonly foreignActivityAtAdd: number\n\t/**\n\t * When the commit's answer was lost: the content-addressed id of the write's primary\n\t * operation, which decides whether it landed (M2). Null otherwise.\n\t */\n\treadonly lookupOperationId: string | null\n\t/**\n\t * The record's fold state after this write, when the prediction was made on one (a\n\t * fresh insert, an update of an array). The next array write of the record builds on it\n\t * while this entry is unsettled; absent for a write predicted from values alone.\n\t */\n\treadonly foldState: FoldState | null\n}\n\n/**\n * A change to the registry that can alter what a subscription displays (S3). Reported to\n * {@link PendingWrites.onChange} listeners synchronously, after the change is made.\n *\n * - `added`, `rolled-back`, `cleared`: the set of entries that apply changed.\n * - `committed`, `unknown`: the entry is still shown, nothing to recompute (reported so a\n *   listener can track settling).\n */\nexport interface RegistryChange {\n\treadonly kind: 'added' | 'committed' | 'rolled-back' | 'unknown' | 'cleared'\n\t/** Collections whose entries changed. */\n\treadonly collections: readonly string[]\n}\n\n/** Listener for {@link RegistryChange}s. */\nexport type RegistryListener = (change: RegistryChange) => void\n\n/** What a `store:write-pending` describes: one write, or a transaction (an entry group). */\nexport type WriteEventKind = PredictedWriteKind | 'transaction'\n\n/** Events the registry reports (names match docs/design 9.4). */\nexport type OverlayEvent =\n\t| {\n\t\t\treadonly type: 'store:write-pending'\n\t\t\treadonly writeId: string\n\t\t\treadonly collection: string\n\t\t\t/** Every collection of a transaction; absent for a single write. */\n\t\t\treadonly collections?: readonly string[]\n\t\t\treadonly recordIds: readonly string[]\n\t\t\treadonly kind: WriteEventKind\n\t\t\treadonly predicted: true\n\t  }\n\t| {\n\t\t\treadonly type: 'store:write-pending'\n\t\t\treadonly writeId: string\n\t\t\treadonly collection: string\n\t\t\treadonly collections?: readonly string[]\n\t\t\treadonly recordIds: readonly string[]\n\t\t\treadonly kind: WriteEventKind\n\t\t\treadonly predicted: false\n\t\t\treadonly reason: MissReason\n\t  }\n\t| {\n\t\t\treadonly type: 'store:write-settled'\n\t\t\treadonly writeId: string\n\t\t\treadonly collection: string\n\t\t\treadonly collections?: readonly string[]\n\t\t\treadonly outcome: SettleOutcome\n\t\t\treadonly operationIds?: readonly string[]\n\t\t\treadonly pendingMs: number\n\t  }\n\t| {\n\t\t\treadonly type: 'store:overlay-diverged'\n\t\t\treadonly writeId: string\n\t\t\treadonly collection: string\n\t\t\treadonly fields: readonly string[]\n\t  }\n\n/** Registry limits (design section 11) and its clock. */\nexport interface PendingWritesOptions {\n\t/** Pending (uncommitted) entries per tab. Default 256. */\n\treadonly maxPendingWrites?: number\n\t/** Estimated bytes of pending and settling entries. Default 8 MiB. */\n\treadonly maxPendingBytes?: number\n\t/** Records one write may touch. Default 100. */\n\treadonly maxRecordsPerWrite?: number\n\t/** How long a committed entry may wait for subscriptions to re-read. Default 2,000 ms. */\n\treadonly settleMs?: number\n\t/** How long an entry may stay pending before it becomes `unknown`. Default 60,000 ms. */\n\treadonly pendingTtlMs?: number\n\t/** Rows in the committed-row cache (LRU). Default 512. */\n\treadonly rowCacheSize?: number\n\t/** Milliseconds, monotonic. Default `performance.now`. Injected by tests. */\n\treadonly now?: () => number\n\t/** Receives {@link OverlayEvent}s. A throwing listener never affects the registry. */\n\treadonly onEvent?: (event: OverlayEvent) => void\n}\n\n/** Defaults of {@link PendingWritesOptions}. */\nexport const DEFAULT_PENDING_WRITES_OPTIONS = {\n\tmaxPendingWrites: 256,\n\tmaxPendingBytes: 8 * 1024 * 1024,\n\tmaxRecordsPerWrite: 100,\n\tsettleMs: 2_000,\n\tpendingTtlMs: 60_000,\n\trowCacheSize: 512,\n} as const\n\n/** Result of {@link PendingWrites.add}. */\nexport type AddResult =\n\t| { readonly ok: true; readonly entry: PendingEntry }\n\t| { readonly ok: false; readonly reason: MissReason }\n\n/** One write of a transaction, for {@link PendingWrites.addGroup}. */\nexport interface GroupChange {\n\treadonly change: PredictedChange\n\t/** A pending write OUTSIDE the group this write was derived from, or null. */\n\treadonly dependsOn: string | null\n}\n\n/** Result of {@link PendingWrites.addGroup}. */\nexport type AddGroupResult =\n\t| { readonly ok: true; readonly groupId: string; readonly entries: readonly PendingEntry[] }\n\t| { readonly ok: false; readonly reason: MissReason }\n\n/** What the registry knows of a record's current values (5.6). */\nexport type BaseLookup =\n\t/** The newest pending or settling write, or the cache, holds the record. */\n\t| {\n\t\t\treadonly found: 'record'\n\t\t\treadonly record: CollectionRecord\n\t\t\treadonly source: 'pending' | 'cache'\n\t  }\n\t/** The newest pending or settling write deleted the record. */\n\t| { readonly found: 'deleted' }\n\t/** Nothing is known: the caller must read. */\n\t| { readonly found: 'none' }\n\n/** What the registry knows of a record's fold state (S6b), for an array write. */\nexport type FoldStateLookup =\n\t/** The newest unsettled write of the record carries its predicted fold state. */\n\t| { readonly found: 'state'; readonly state: FoldState }\n\t/**\n\t * The newest unsettled write was predicted from values alone: the state after it is\n\t * not known, and the database does not hold it yet either.\n\t */\n\t| { readonly found: 'unknown' }\n\t/** No unsettled write: the caller reads the committed state. */\n\t| { readonly found: 'none' }\n\n/** Committed facts of a write, reported by {@link PendingWrites.commit}. */\nexport interface CommitInfo {\n\t/** The record as stored (`WriteResult.record`); absent for a no-op update. */\n\treadonly record?: CollectionRecord\n\t/** Ids of the operations the write created. */\n\treadonly operationIds?: readonly string[]\n\t/**\n\t * The update wrote nothing (its values were already the record's, as a write that moved\n\t * under it found). Nothing changed in the database, so no read will ever contain this\n\t * entry: it is dropped at commit instead of waiting to be settled, and the display is\n\t * the stored row, not the prediction (and its `updatedAt`).\n\t */\n\treadonly unchanged?: boolean\n}\n\n/** Result of {@link PendingWrites.sweep}. */\nexport interface SweepResult {\n\t/** Entries that stayed pending past the TTL and are now `unknown`. */\n\treadonly expired: readonly PendingEntry[]\n\t/** Committed entries older than the settle window: the caller forces a re-read, then drops them. */\n\treadonly lagging: readonly PendingEntry[]\n}\n\n/** Estimated size of a value, in bytes (JSON length; a rough upper bound). */\nexport function estimateBytes(value: unknown): number {\n\ttry {\n\t\treturn JSON.stringify(value)?.length ?? 0\n\t} catch {\n\t\treturn 1_024\n\t}\n}\n\nconst cacheKey = (collection: string, id: string): string => `${collection}\\u0000${id}`\n\n/**\n * Ancestors an entry remembers. A chain longer than this forgets its oldest links; the\n * commit check then misses an unsettled or rolled-back write that far back, which costs a\n * reported divergence at worst (the circuit breaker's input), never a wrong display. 32\n * writes of one record in flight at once does not happen in practice (the pending cap is\n * 256 across all records).\n */\nconst MAX_ANCESTORS = 32\n\n/** Rolled-back write ids remembered for the verification of writes derived from them. */\nconst MAX_ROLLED_BACK_IDS = 1_024\n\n/** Records with a foreign-change mark kept (older marks fold into a floor). */\nconst MAX_RECORD_MARKS = 4_096\n\n/** Estimated bytes an entry holds: its patch, its record and the fold state it carries. */\nfunction entryBytes(change: PredictedChange): number {\n\treturn (\n\t\testimateBytes(change.patch) +\n\t\testimateBytes(change.record) +\n\t\t(change.foldState ? estimateBytes(change.foldState) : 0)\n\t)\n}\n\n/**\n * Registry of the writes this tab has predicted but not yet seen settle.\n *\n * Lifecycle of an entry: {@link add} (`pending`) then either {@link commit}\n * (`committed`, kept until {@link settleCollection} or {@link drop}), {@link rollback}\n * (removed together with the entries derived from it), or {@link markUnknown} / the TTL\n * in {@link sweep} (`unknown`, kept shown until decided).\n */\n/** Why a commit check judged fewer fields than the whole record. */\nexport type UnverifiedReason =\n\t/** A remote apply in the collection overlapped the write. */\n\t| 'concurrent-remote'\n\t/** A write this one was derived from had not reported, or was rolled back. */\n\t| 'unsettled-base'\n\t/** A field whose base moved could not be predicted again. */\n\t| 'replay-declined'\n\n/** Handle of a remote apply in progress, see {@link PendingWrites.beginForeign}. */\nexport interface ForeignApply {\n\t/** The apply touches this collection from now until `end`. */\n\ttouch(collection: string): void\n\t/** The apply has published its changes (or failed). */\n\tend(): void\n}\n\nexport class PendingWrites {\n\tprivate readonly options: Required<Omit<PendingWritesOptions, 'now' | 'onEvent'>>\n\tprivate readonly now: () => number\n\tprivate readonly onEvent: ((event: OverlayEvent) => void) | undefined\n\t/** Insertion order is registration order. */\n\tprivate readonly entries = new Map<string, PendingEntry>()\n\tprivate readonly cache = new Map<string, CollectionRecord>()\n\tprivate writeCounter = 0\n\tprivate epochCounter = 0\n\tprivate totalBytes = 0\n\tprivate floorWallTime = 0\n\t/** Start order of the writes that have to read before they are predicted (S6b). */\n\treadonly order = new WriteOrder()\n\tprivate readonly missCounts = new Map<MissReason, number>()\n\tprivate readonly changeListeners = new Set<RegistryListener>()\n\tprivate readonly foreignCounts = new Map<string, number>()\n\t/** Bumped by every {@link invalidate}; entries remember the value they were added at. */\n\tprivate foreignSeq = 0\n\t/** Ids of writes that were rolled back, newest last: a retired write may still name one as its base. */\n\tprivate readonly unverifiedCounts = new Map<UnverifiedReason, number>()\n\tprivate readonly rolledBackIds = new Set<string>()\n\t/** Remote applies that have begun and not yet published their change, by collection. */\n\tprivate readonly foreignInFlight = new Map<string, number>()\n\t/** Begin and end events of remote applies, by collection. */\n\tprivate readonly foreignActivity = new Map<string, number>()\n\t/** Foreign sequence of the last change to a record / a whole collection, by key. */\n\tprivate readonly recordMarks = new Map<string, number>()\n\tprivate readonly collectionMarks = new Map<string, number>()\n\t/** Marks dropped for size: an entry older than this is treated as changed. */\n\tprivate markFloor = 0\n\t/** Commits of this registry's own writes, by collection (see {@link seedStamp}). */\n\tprivate readonly commitCounts = new Map<string, number>()\n\t/** Bumped by {@link clear}: a read issued before it must not seed anything. */\n\tprivate generation = 0\n\tprivate seeded = 0\n\t/** Records with a running write that was not predicted, by cache key. */\n\tprivate readonly unpredicted = new Map<string, number>()\n\t/** Callers of {@link whenRecordSettled} waiting for a record's running writes to finish. */\n\tprivate readonly settleWaiters = new Set<{ key: string; resolve: () => void }>()\n\n\tconstructor(options: PendingWritesOptions = {}) {\n\t\tconst { now, onEvent, ...limits } = options\n\t\tthis.options = { ...DEFAULT_PENDING_WRITES_OPTIONS, ...stripUndefined(limits) }\n\t\tthis.now = now ?? (() => performance.now())\n\t\tthis.onEvent = onEvent\n\t}\n\n\t/** Monotonic counter, bumped at every commit. A read's `issuedAt` is the epoch when it was issued. */\n\tget epoch(): number {\n\t\treturn this.epochCounter\n\t}\n\n\t/** Writes shown but not yet committed (`pending` and `unknown`). */\n\tget pendingCount(): number {\n\t\tlet count = 0\n\t\tfor (const entry of this.entries.values()) if (entry.state !== 'committed') count++\n\t\treturn count\n\t}\n\n\t/** Committed entries still waiting for subscriptions to re-read. */\n\tget settlingCount(): number {\n\t\treturn this.entries.size - this.pendingCount\n\t}\n\n\t/** Estimated bytes held by pending and settling entries. */\n\tget bytes(): number {\n\t\treturn this.totalBytes\n\t}\n\n\t/** Rows in the committed-row cache. */\n\tget cachedRows(): number {\n\t\treturn this.cache.size\n\t}\n\n\t/** Rows put in the cache from subscription results over the registry's life (diagnostics). */\n\tget seededRows(): number {\n\t\treturn this.seeded\n\t}\n\n\t/** Counted misses by reason (writes that were not predicted). */\n\tget misses(): ReadonlyMap<MissReason, number> {\n\t\treturn this.missCounts\n\t}\n\n\t/** The configured limits. */\n\tget limits(): Readonly<Required<Omit<PendingWritesOptions, 'now' | 'onEvent'>>> {\n\t\treturn this.options\n\t}\n\n\t/**\n\t * Highest `createdAt` or `updatedAt` this registry has seen committed. A predicted\n\t * wall time is `max(Date.now(), wallTimeFloor())`, so a predicted record sorts where\n\t * the committed one will land (5.3d) even when the device clock is behind its HLC.\n\t */\n\twallTimeFloor(): number {\n\t\treturn this.floorWallTime\n\t}\n\n\t/** Allocate a write id. */\n\tnextWriteId(): string {\n\t\tthis.writeCounter += 1\n\t\treturn `w${this.writeCounter}`\n\t}\n\n\t/**\n\t * Register a predicted write.\n\t *\n\t * Refused (never thrown) when a cap would be exceeded: the write then runs as it does\n\t * today and the miss is counted (I8). Nothing already registered is ever dropped to\n\t * make room.\n\t *\n\t * @param change - The predictor's answer for the write\n\t * @param options - `dependsOn`: the pending write this one was derived from;\n\t *   `recordCount`: records the write touches (default 1); `writeId`: pre-allocated id\n\t */\n\tadd(\n\t\tchange: PredictedChange,\n\t\toptions: { dependsOn?: string | null; recordCount?: number; writeId?: string } = {},\n\t): AddResult {\n\t\tconst recordCount = options.recordCount ?? 1\n\t\tif (recordCount > this.options.maxRecordsPerWrite) return this.refuse(change, 'records-cap')\n\t\tif (this.pendingCount >= this.options.maxPendingWrites) {\n\t\t\treturn this.refuse(change, 'pending-cap')\n\t\t}\n\t\tconst bytes = entryBytes(change)\n\t\tif (this.totalBytes + bytes > this.options.maxPendingBytes) {\n\t\t\treturn this.refuse(change, 'bytes-cap')\n\t\t}\n\t\tconst entry: PendingEntry = {\n\t\t\twriteId: options.writeId ?? this.nextWriteId(),\n\t\t\tkind: change.kind,\n\t\t\tcollection: change.collection,\n\t\t\trecordId: change.recordId,\n\t\t\tpatch: change.patch,\n\t\t\tprevious: change.previous ?? null,\n\t\t\trecord: change.record,\n\t\t\tdependsOn: options.dependsOn ?? null,\n\t\t\tancestors: this.ancestorsOf(options.dependsOn ?? null),\n\t\t\tgroupId: null,\n\t\t\tstate: 'pending',\n\t\t\tretiredAt: null,\n\t\t\tregisteredAtMs: this.now(),\n\t\t\tretiredAtMs: null,\n\t\t\tbytes,\n\t\t\toperationIds: [],\n\t\t\tforeignAtAdd: this.foreignCount(change.collection),\n\t\t\tforeignSeqAtAdd: this.foreignSeq,\n\t\t\tforeignActivityAtAdd: this.activityOf(change.collection),\n\t\t\tlookupOperationId: null,\n\t\t\tfoldState: change.foldState ?? null,\n\t\t}\n\t\tthis.entries.set(entry.writeId, entry)\n\t\tthis.totalBytes += bytes\n\t\tthis.emit({\n\t\t\ttype: 'store:write-pending',\n\t\t\twriteId: entry.writeId,\n\t\t\tcollection: entry.collection,\n\t\t\trecordIds: [entry.recordId],\n\t\t\tkind: entry.kind,\n\t\t\tpredicted: true,\n\t\t})\n\t\tthis.changed('added', [entry.collection])\n\t\treturn { ok: true, entry }\n\t}\n\n\t/**\n\t * Register the entries of one multi-record write (`insertMany`) together or not at all:\n\t * a cap that the whole group would exceed refuses all of it (I8), so a group never\n\t * shows half of its records. One change notification covers the group.\n\t */\n\taddMany(\n\t\tchanges: readonly PredictedChange[],\n\t):\n\t\t| { readonly ok: true; readonly entries: PendingEntry[] }\n\t\t| { readonly ok: false; readonly reason: MissReason } {\n\t\tconst first = changes[0]\n\t\tif (!first) return { ok: true, entries: [] }\n\t\tlet reason: MissReason | null = null\n\t\tlet bytes = 0\n\t\tconst sizes = changes.map(entryBytes)\n\t\tfor (const size of sizes) bytes += size\n\t\tif (changes.length > this.options.maxRecordsPerWrite) reason = 'records-cap'\n\t\telse if (this.pendingCount + changes.length > this.options.maxPendingWrites) {\n\t\t\treason = 'pending-cap'\n\t\t} else if (this.totalBytes + bytes > this.options.maxPendingBytes) reason = 'bytes-cap'\n\t\tif (reason) {\n\t\t\tthis.missCounts.set(reason, (this.missCounts.get(reason) ?? 0) + 1)\n\t\t\tthis.emit({\n\t\t\t\ttype: 'store:write-pending',\n\t\t\t\twriteId: this.nextWriteId(),\n\t\t\t\tcollection: first.collection,\n\t\t\t\trecordIds: changes.map((change) => change.recordId),\n\t\t\t\tkind: first.kind,\n\t\t\t\tpredicted: false,\n\t\t\t\treason,\n\t\t\t})\n\t\t\treturn { ok: false, reason }\n\t\t}\n\t\tconst entries: PendingEntry[] = []\n\t\tchanges.forEach((change, index) => {\n\t\t\tconst entry: PendingEntry = {\n\t\t\t\twriteId: this.nextWriteId(),\n\t\t\t\tkind: change.kind,\n\t\t\t\tcollection: change.collection,\n\t\t\t\trecordId: change.recordId,\n\t\t\t\tpatch: change.patch,\n\t\t\t\tprevious: change.previous ?? null,\n\t\t\t\trecord: change.record,\n\t\t\t\tdependsOn: null,\n\t\t\t\tancestors: [],\n\t\t\t\tgroupId: null,\n\t\t\t\tstate: 'pending',\n\t\t\t\tretiredAt: null,\n\t\t\t\tregisteredAtMs: this.now(),\n\t\t\t\tretiredAtMs: null,\n\t\t\t\tbytes: sizes[index] ?? 0,\n\t\t\t\toperationIds: [],\n\t\t\t\tforeignAtAdd: this.foreignCount(change.collection),\n\t\t\t\tforeignSeqAtAdd: this.foreignSeq,\n\t\t\t\tforeignActivityAtAdd: this.activityOf(change.collection),\n\t\t\t\tlookupOperationId: null,\n\t\t\t\tfoldState: change.foldState ?? null,\n\t\t\t}\n\t\t\tthis.entries.set(entry.writeId, entry)\n\t\t\tthis.totalBytes += entry.bytes\n\t\t\tentries.push(entry)\n\t\t})\n\t\tfor (const entry of entries) {\n\t\t\tthis.emit({\n\t\t\t\ttype: 'store:write-pending',\n\t\t\t\twriteId: entry.writeId,\n\t\t\t\tcollection: entry.collection,\n\t\t\t\trecordIds: [entry.recordId],\n\t\t\t\tkind: entry.kind,\n\t\t\t\tpredicted: true,\n\t\t\t})\n\t\t}\n\t\tthis.changed('added', [...new Set(entries.map((entry) => entry.collection))])\n\t\treturn { ok: true, entries }\n\t}\n\n\t/**\n\t * Register the writes of one transaction as ONE entry group (stage S6a), all of them or\n\t * none: the pending, byte and record caps are checked for the whole group before any\n\t * entry exists (T1), so a group is never partially registered. The entries keep the\n\t * transaction's write order (the order its storage transaction writes them in). One\n\t * `store:write-pending` (`kind: 'transaction'`, `writeId` the group id) and one change\n\t * notification cover the group, so a single patch pass shows all of it.\n\t *\n\t * @param changes - Every write of the transaction, in buffer order, each with the\n\t *   pending write outside the group it was derived from\n\t */\n\taddGroup(changes: readonly GroupChange[]): AddGroupResult {\n\t\tconst first = changes[0]\n\t\tif (!first) return { ok: false, reason: 'unsupported-write' }\n\t\tconst collections = [...new Set(changes.map(({ change }) => change.collection))]\n\t\tconst recordIds = changes.map(({ change }) => change.recordId)\n\t\tconst sizes = changes.map(({ change }) => entryBytes(change))\n\t\tlet bytes = 0\n\t\tfor (const size of sizes) bytes += size\n\t\tlet reason: MissReason | null = null\n\t\tif (changes.length > this.options.maxRecordsPerWrite) reason = 'records-cap'\n\t\telse if (this.pendingCount + changes.length > this.options.maxPendingWrites) {\n\t\t\treason = 'pending-cap'\n\t\t} else if (this.totalBytes + bytes > this.options.maxPendingBytes) reason = 'bytes-cap'\n\t\tif (reason) {\n\t\t\tthis.noteGroupMiss(collections, recordIds, reason)\n\t\t\treturn { ok: false, reason }\n\t\t}\n\t\tconst groupId = this.nextWriteId()\n\t\tconst registeredAtMs = this.now()\n\t\tconst entries: PendingEntry[] = []\n\t\tfor (const [index, { change, dependsOn }] of changes.entries()) {\n\t\t\t// A later write of a record the group already wrote derives from that member, so it\n\t\t\t// rests on whatever the member rests on.\n\t\t\tconst earlier = [...entries]\n\t\t\t\t.reverse()\n\t\t\t\t.find((one) => one.collection === change.collection && one.recordId === change.recordId)\n\t\t\tentries.push({\n\t\t\t\twriteId: this.nextWriteId(),\n\t\t\t\tkind: change.kind,\n\t\t\t\tcollection: change.collection,\n\t\t\t\trecordId: change.recordId,\n\t\t\t\tpatch: change.patch,\n\t\t\t\tprevious: change.previous ?? null,\n\t\t\t\trecord: change.record,\n\t\t\t\tdependsOn,\n\t\t\t\tancestors: earlier ? earlier.ancestors : this.ancestorsOf(dependsOn),\n\t\t\t\tgroupId,\n\t\t\t\tstate: 'pending',\n\t\t\t\tretiredAt: null,\n\t\t\t\tregisteredAtMs,\n\t\t\t\tretiredAtMs: null,\n\t\t\t\tbytes: sizes[index] ?? 0,\n\t\t\t\toperationIds: [],\n\t\t\t\tforeignAtAdd: this.foreignCount(change.collection),\n\t\t\t\tforeignSeqAtAdd: this.foreignSeq,\n\t\t\t\tforeignActivityAtAdd: this.activityOf(change.collection),\n\t\t\t\tlookupOperationId: null,\n\t\t\t\tfoldState: change.foldState ?? null,\n\t\t\t})\n\t\t}\n\t\tfor (const entry of entries) {\n\t\t\tthis.entries.set(entry.writeId, entry)\n\t\t\tthis.totalBytes += entry.bytes\n\t\t}\n\t\tthis.emit({\n\t\t\ttype: 'store:write-pending',\n\t\t\twriteId: groupId,\n\t\t\tcollection: first.change.collection,\n\t\t\tcollections,\n\t\t\trecordIds,\n\t\t\tkind: 'transaction',\n\t\t\tpredicted: true,\n\t\t})\n\t\tthis.changed('added', collections)\n\t\treturn { ok: true, groupId, entries }\n\t}\n\n\t/**\n\t * Report a transaction that is not predicted (one counted miss for the whole group).\n\t * Allocates a write id for the event.\n\t */\n\tnoteGroupMiss(\n\t\tcollections: readonly string[],\n\t\trecordIds: readonly string[],\n\t\treason: MissReason,\n\t): void {\n\t\tthis.missCounts.set(reason, (this.missCounts.get(reason) ?? 0) + 1)\n\t\tthis.emit({\n\t\t\ttype: 'store:write-pending',\n\t\t\twriteId: this.nextWriteId(),\n\t\t\tcollection: collections[0] ?? '',\n\t\t\tcollections: [...collections],\n\t\t\trecordIds,\n\t\t\tkind: 'transaction',\n\t\t\tpredicted: false,\n\t\t\treason,\n\t\t})\n\t}\n\n\t/** The members of a group still in the registry, in registration order. */\n\tgroupMembers(groupId: string): PendingEntry[] {\n\t\tconst out: PendingEntry[] = []\n\t\tfor (const entry of this.entries.values()) if (entry.groupId === groupId) out.push(entry)\n\t\treturn out\n\t}\n\n\t/**\n\t * Report a write that was not predicted (a counted miss, with its reason), so\n\t * DevTools can show why. Allocates a write id for the event.\n\t */\n\tnoteMiss(\n\t\tkind: PredictedWriteKind,\n\t\tcollection: string,\n\t\trecordIds: readonly string[],\n\t\treason: MissReason,\n\t): void {\n\t\tthis.missCounts.set(reason, (this.missCounts.get(reason) ?? 0) + 1)\n\t\tthis.emit({\n\t\t\ttype: 'store:write-pending',\n\t\t\twriteId: this.nextWriteId(),\n\t\t\tcollection,\n\t\t\trecordIds,\n\t\t\tkind,\n\t\t\tpredicted: false,\n\t\t\treason,\n\t\t})\n\t}\n\n\t/**\n\t * The write's transaction committed. The entry gets `retiredAt = ++epoch` and stays\n\t * (its display must not flicker between commit and the SQL re-read, F3); the\n\t * committed record replaces the prediction as the base for later updates, and fills\n\t * the row cache.\n\t *\n\t * @returns The retired entry, or null when it was already removed\n\t */\n\tcommit(writeId: string, info: CommitInfo = {}): PendingEntry | null {\n\t\tconst entry = this.entries.get(writeId)\n\t\tif (!entry || entry.state === 'committed') return null\n\t\tif (entry.groupId !== null) {\n\t\t\t// A member never commits alone (T2): the whole group retires, this member with\n\t\t\t// the facts given, the others with what they hold.\n\t\t\tconst retired = this.commitGroup(entry.groupId, new Map([[writeId, info]]))\n\t\t\treturn retired.find((one) => one.writeId === writeId) ?? null\n\t\t}\n\t\tthis.epochCounter += 1\n\t\tthis.commitCounts.set(entry.collection, (this.commitCounts.get(entry.collection) ?? 0) + 1)\n\t\tconst retired: PendingEntry = {\n\t\t\t...entry,\n\t\t\tstate: 'committed',\n\t\t\tretiredAt: this.epochCounter,\n\t\t\tretiredAtMs: this.now(),\n\t\t\trecord: info.record ?? entry.record,\n\t\t\toperationIds: info.operationIds ?? [],\n\t\t}\n\t\tthis.entries.set(writeId, retired)\n\t\tthis.recordCommitted(retired, info.record)\n\t\tif (info.unchanged === true) this.remove(retired)\n\t\tthis.emit({\n\t\t\ttype: 'store:write-settled',\n\t\t\twriteId,\n\t\t\tcollection: entry.collection,\n\t\t\toutcome: 'committed',\n\t\t\t...(info.operationIds ? { operationIds: info.operationIds } : {}),\n\t\t\tpendingMs: this.now() - entry.registeredAtMs,\n\t\t})\n\t\tthis.changed('committed', [entry.collection])\n\t\treturn retired\n\t}\n\n\t/**\n\t * A transaction committed: every member of the group retires with ONE epoch value, so a\n\t * SQL read either contains the whole group or none of it (design 5.9).\n\t * Members are retired in registration order (the order the transaction wrote them), so\n\t * the committed-row cache ends with each record's last write. One\n\t * `store:write-settled committed` carries every operation id of the group.\n\t *\n\t * @param groupId - The group, from {@link addGroup}\n\t * @param infos - Committed facts per member write id; a member without one keeps its\n\t *   prediction as its record (an outcome decided later by lookup)\n\t * @returns The retired members (empty when the group is gone or already committed)\n\t */\n\tcommitGroup(groupId: string, infos: ReadonlyMap<string, CommitInfo> = new Map()): PendingEntry[] {\n\t\tconst members = this.groupMembers(groupId).filter((entry) => entry.state !== 'committed')\n\t\tconst first = members[0]\n\t\tif (!first) return []\n\t\tthis.epochCounter += 1\n\t\tconst retiredAtMs = this.now()\n\t\tconst retired: PendingEntry[] = []\n\t\tconst operationIds: string[] = []\n\t\tconst collections: string[] = []\n\t\tfor (const entry of members) {\n\t\t\tconst info = infos.get(entry.writeId) ?? {}\n\t\t\tthis.commitCounts.set(entry.collection, (this.commitCounts.get(entry.collection) ?? 0) + 1)\n\t\t\tconst next: PendingEntry = {\n\t\t\t\t...entry,\n\t\t\t\tstate: 'committed',\n\t\t\t\tretiredAt: this.epochCounter,\n\t\t\t\tretiredAtMs,\n\t\t\t\trecord: info.record ?? entry.record,\n\t\t\t\toperationIds: info.operationIds ?? [],\n\t\t\t}\n\t\t\tthis.entries.set(entry.writeId, next)\n\t\t\tthis.recordCommitted(next, info.record)\n\t\t\tif (info.unchanged === true) this.remove(next)\n\t\t\tretired.push(next)\n\t\t\toperationIds.push(...(info.operationIds ?? []))\n\t\t\tif (!collections.includes(entry.collection)) collections.push(entry.collection)\n\t\t}\n\t\tthis.emit({\n\t\t\ttype: 'store:write-settled',\n\t\t\twriteId: groupId,\n\t\t\tcollection: first.collection,\n\t\t\tcollections,\n\t\t\toutcome: 'committed',\n\t\t\toperationIds,\n\t\t\tpendingMs: retiredAtMs - first.registeredAtMs,\n\t\t})\n\t\tthis.changed('committed', collections)\n\t\treturn retired\n\t}\n\n\t/**\n\t * The write failed (nothing was committed). The entry is removed together with every\n\t * entry derived from it, transitively and not yet committed (5.6): a dependent cannot\n\t * succeed, so it is not left showing until its own transaction fails. The caller\n\t * recomputes each affected display from its base (F10).\n\t *\n\t * @returns The removed entries, the rolled-back one first\n\t */\n\trollback(writeId: string): PendingEntry[] {\n\t\tconst root = this.entries.get(writeId)\n\t\tif (!root || root.state === 'committed') return []\n\t\tconst doomed = new Set<string>([writeId])\n\t\tconst doomedGroups = new Set<string>()\n\t\tif (root.groupId !== null) doomedGroups.add(root.groupId)\n\t\t// The closure (T4): entries derived from a doomed entry, and every member of a group\n\t\t// that has a doomed member (a group never stays half shown). Registration order puts\n\t\t// a dependent after the entry it derives from, but a group can be pulled in by its\n\t\t// last member, so iterate to a fixed point.\n\t\tlet grew = true\n\t\twhile (grew) {\n\t\t\tgrew = false\n\t\t\tfor (const entry of this.entries.values()) {\n\t\t\t\tif (entry.state === 'committed' || doomed.has(entry.writeId)) continue\n\t\t\t\tconst derived = entry.dependsOn !== null && doomed.has(entry.dependsOn)\n\t\t\t\tconst grouped = entry.groupId !== null && doomedGroups.has(entry.groupId)\n\t\t\t\tif (!derived && !grouped) continue\n\t\t\t\tdoomed.add(entry.writeId)\n\t\t\t\tif (entry.groupId !== null) doomedGroups.add(entry.groupId)\n\t\t\t\tgrew = true\n\t\t\t}\n\t\t}\n\t\t// The rolled-back entry first, then the rest in registration order.\n\t\tconst removed: PendingEntry[] = [root]\n\t\tfor (const entry of this.entries.values()) {\n\t\t\tif (entry.writeId !== writeId && doomed.has(entry.writeId)) removed.push(entry)\n\t\t}\n\t\tconst reportedGroups = new Set<string>()\n\t\tconst at = this.now()\n\t\tfor (const entry of removed) {\n\t\t\tthis.remove(entry)\n\t\t\tthis.rolledBackIds.add(entry.writeId)\n\t\t\tif (this.rolledBackIds.size > MAX_ROLLED_BACK_IDS) {\n\t\t\t\tconst oldest = this.rolledBackIds.values().next()\n\t\t\t\tif (!oldest.done) this.rolledBackIds.delete(oldest.value)\n\t\t\t}\n\t\t\tif (entry.groupId === null) {\n\t\t\t\tthis.emit({\n\t\t\t\t\ttype: 'store:write-settled',\n\t\t\t\t\twriteId: entry.writeId,\n\t\t\t\t\tcollection: entry.collection,\n\t\t\t\t\toutcome: 'rolled-back',\n\t\t\t\t\tpendingMs: at - entry.registeredAtMs,\n\t\t\t\t})\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\t// One event per group (T7).\n\t\t\tif (reportedGroups.has(entry.groupId)) continue\n\t\t\treportedGroups.add(entry.groupId)\n\t\t\tconst members = removed.filter((one) => one.groupId === entry.groupId)\n\t\t\tthis.emit({\n\t\t\t\ttype: 'store:write-settled',\n\t\t\t\twriteId: entry.groupId,\n\t\t\t\tcollection: entry.collection,\n\t\t\t\tcollections: [...new Set(members.map((one) => one.collection))],\n\t\t\t\toutcome: 'rolled-back',\n\t\t\t\tpendingMs: at - entry.registeredAtMs,\n\t\t\t})\n\t\t}\n\t\tthis.changed('rolled-back', [...new Set(removed.map((entry) => entry.collection))])\n\t\treturn removed\n\t}\n\n\t/**\n\t * The outcome is not known (the commit answer was lost, or the transaction did not\n\t * settle): the entry stays shown and is decided later, never silently rolled back.\n\t */\n\tmarkUnknown(writeId: string, lookupOperationId: string | null = null): PendingEntry | null {\n\t\tconst entry = this.entries.get(writeId)\n\t\tif (entry?.state === 'unknown') return this.learnWitness(entry, lookupOperationId)\n\t\tif (!entry || entry.state !== 'pending') return null\n\t\tif (entry.groupId !== null) return this.markGroupUnknown(entry, lookupOperationId)\n\t\tconst unknown: PendingEntry = { ...entry, state: 'unknown', lookupOperationId }\n\t\tthis.entries.set(writeId, unknown)\n\t\tthis.emit({\n\t\t\ttype: 'store:write-settled',\n\t\t\twriteId,\n\t\t\tcollection: entry.collection,\n\t\t\toutcome: 'unknown',\n\t\t\tpendingMs: this.now() - entry.registeredAtMs,\n\t\t})\n\t\tthis.changed('unknown', [entry.collection])\n\t\treturn unknown\n\t}\n\n\t/**\n\t * An entry already unknown (the sweep expired it before its commit answered) learns the\n\t * operation that witnesses it, so a later read can decide it ({@link resolveUnknown}). No\n\t * event: its outcome was already reported unknown. The whole group learns it.\n\t */\n\tprivate learnWitness(entry: PendingEntry, lookupOperationId: string | null): PendingEntry | null {\n\t\tif (lookupOperationId === null || entry.lookupOperationId !== null) return null\n\t\tconst members = entry.groupId === null ? [entry] : this.groupMembers(entry.groupId)\n\t\tlet result: PendingEntry | null = null\n\t\tfor (const member of members) {\n\t\t\tif (member.state !== 'unknown' || member.lookupOperationId !== null) continue\n\t\t\tconst learned: PendingEntry = { ...member, lookupOperationId }\n\t\t\tthis.entries.set(member.writeId, learned)\n\t\t\tif (member.writeId === entry.writeId) result = learned\n\t\t}\n\t\treturn result\n\t}\n\n\t/** {@link markUnknown} for a member: the whole group becomes unknown, with one event (T2, T7). */\n\tprivate markGroupUnknown(\n\t\tmember: PendingEntry,\n\t\tlookupOperationId: string | null,\n\t): PendingEntry | null {\n\t\tconst groupId = member.groupId ?? ''\n\t\tconst members = this.groupMembers(groupId).filter((entry) => entry.state === 'pending')\n\t\tconst first = members[0]\n\t\tif (!first) return null\n\t\tconst collections: string[] = []\n\t\tlet result: PendingEntry | null = null\n\t\tfor (const entry of members) {\n\t\t\tconst unknown: PendingEntry = { ...entry, state: 'unknown', lookupOperationId }\n\t\t\tthis.entries.set(entry.writeId, unknown)\n\t\t\tif (entry.writeId === member.writeId) result = unknown\n\t\t\tif (!collections.includes(entry.collection)) collections.push(entry.collection)\n\t\t}\n\t\tthis.emit({\n\t\t\ttype: 'store:write-settled',\n\t\t\twriteId: groupId,\n\t\t\tcollection: first.collection,\n\t\t\tcollections,\n\t\t\toutcome: 'unknown',\n\t\t\tpendingMs: this.now() - first.registeredAtMs,\n\t\t})\n\t\tthis.changed('unknown', collections)\n\t\treturn result\n\t}\n\n\t/**\n\t * Apply the time limits: pending entries older than `pendingTtlMs` become `unknown`;\n\t * committed entries older than `settleMs` are reported as lagging (the caller forces a\n\t * re-run of their collections, then {@link drop}s them).\n\t */\n\tsweep(): SweepResult {\n\t\tconst at = this.now()\n\t\tconst expired: PendingEntry[] = []\n\t\tconst lagging: PendingEntry[] = []\n\t\tfor (const entry of [...this.entries.values()]) {\n\t\t\tif (entry.state === 'pending' && at - entry.registeredAtMs >= this.options.pendingTtlMs) {\n\t\t\t\tconst unknown = this.markUnknown(entry.writeId)\n\t\t\t\tif (unknown) expired.push(unknown)\n\t\t\t} else if (\n\t\t\t\tentry.state === 'committed' &&\n\t\t\t\tentry.retiredAtMs !== null &&\n\t\t\t\tat - entry.retiredAtMs >= this.options.settleMs\n\t\t\t) {\n\t\t\t\tlagging.push(entry)\n\t\t\t}\n\t\t}\n\t\treturn { expired, lagging }\n\t}\n\n\t/**\n\t * Every subscription of `collection` has delivered a SQL result issued at or after\n\t * `issuedAt`: committed entries retired at or before it are contained in those\n\t * results and are dropped.\n\t *\n\t * @returns The dropped entries\n\t */\n\tsettleCollection(collection: string, issuedAt: number): PendingEntry[] {\n\t\tconst dropped: PendingEntry[] = []\n\t\tfor (const entry of [...this.entries.values()]) {\n\t\t\tif (\n\t\t\t\tentry.collection === collection &&\n\t\t\t\tentry.state === 'committed' &&\n\t\t\t\tentry.retiredAt !== null &&\n\t\t\t\tentry.retiredAt <= issuedAt\n\t\t\t) {\n\t\t\t\tthis.remove(entry)\n\t\t\t\tdropped.push(entry)\n\t\t\t}\n\t\t}\n\t\treturn dropped\n\t}\n\n\t/** Remove committed entries (after a forced re-run). Unknown ids and uncommitted entries are ignored. */\n\tdrop(entries: readonly PendingEntry[]): void {\n\t\tfor (const entry of entries) {\n\t\t\tconst current = this.entries.get(entry.writeId)\n\t\t\tif (current && current.state === 'committed') this.remove(current)\n\t\t}\n\t}\n\n\t/**\n\t * The entries that apply to a read of `collection` issued when the epoch was\n\t * `issuedAt`, in registration order (5.5):\n\t * `retiredAt === null || retiredAt > issuedAt`. A read issued before an entry's\n\t * commit may not contain it; one issued after contains it.\n\t */\n\tapplicable(collection: string, issuedAt: number): PendingEntry[] {\n\t\tconst out: PendingEntry[] = []\n\t\tfor (const entry of this.entries.values()) {\n\t\t\tif (entry.collection !== collection) continue\n\t\t\tif (entry.retiredAt === null || entry.retiredAt > issuedAt) out.push(entry)\n\t\t}\n\t\treturn out\n\t}\n\n\t/** Whether any committed entry of `collection` still waits for subscriptions to re-read. */\n\thasSettling(collection: string): boolean {\n\t\tfor (const entry of this.entries.values()) {\n\t\t\tif (entry.collection === collection && entry.state === 'committed') return true\n\t\t}\n\t\treturn false\n\t}\n\n\t/** Entries whose outcome is unknown, optionally of one collection, in registration order. */\n\tunknownEntries(collection?: string): PendingEntry[] {\n\t\tconst out: PendingEntry[] = []\n\t\tfor (const entry of this.entries.values()) {\n\t\t\tif (entry.state !== 'unknown') continue\n\t\t\tif (collection === undefined || entry.collection === collection) out.push(entry)\n\t\t}\n\t\treturn out\n\t}\n\n\t/**\n\t * Committed entries of `collection` that a SQL read issued at epoch `to` contains but\n\t * one issued at epoch `from` did not (`from < retiredAt <= to`): the writes whose\n\t * prediction the settle check compares with the database.\n\t */\n\tcrossed(collection: string, from: number, to: number): PendingEntry[] {\n\t\tconst out: PendingEntry[] = []\n\t\tfor (const entry of this.entries.values()) {\n\t\t\tif (entry.collection !== collection || entry.retiredAt === null) continue\n\t\t\tif (entry.retiredAt > from && entry.retiredAt <= to) out.push(entry)\n\t\t}\n\t\treturn out\n\t}\n\n\t/** Changes to `collection` that were not this registry's own predicted writes (see {@link PendingEntry.foreignAtAdd}). */\n\tforeignCount(collection: string): number {\n\t\treturn this.foreignCounts.get(collection) ?? 0\n\t}\n\n\t/** One entry by id. */\n\tget(writeId: string): PendingEntry | undefined {\n\t\treturn this.entries.get(writeId)\n\t}\n\n\t/** All entries, in registration order. */\n\tlist(): PendingEntry[] {\n\t\treturn [...this.entries.values()]\n\t}\n\n\t/** Collections that have at least one entry. */\n\tcollections(): Set<string> {\n\t\tconst out = new Set<string>()\n\t\tfor (const entry of this.entries.values()) out.add(entry.collection)\n\t\treturn out\n\t}\n\n\t/**\n\t * What the registry knows of a record's current values, for predicting the next write\n\t * to it (5.6): the newest entry for the record (pending chains, and settling commits\n\t * the SQL has not yet been read back for), else the committed-row cache.\n\t */\n\tbaseFor(collection: string, id: string): BaseLookup {\n\t\t// A write the overlay did not predict is changing this record: neither a pending\n\t\t// entry nor a cached row describes it any more, so the next write reads it (F21).\n\t\tif ((this.unpredicted.get(cacheKey(collection, id)) ?? 0) > 0) return { found: 'none' }\n\t\tlet newest: PendingEntry | undefined\n\t\tfor (const entry of this.entries.values()) {\n\t\t\tif (entry.collection === collection && entry.recordId === id) newest = entry\n\t\t}\n\t\tif (newest) {\n\t\t\t// A foreign change touched the record after its newest entry was added: that entry is\n\t\t\t// older than the database on fields it did not write, and a cached row is older still\n\t\t\t// (it predates the entry's own write). Only a read sees both, so the next write reads.\n\t\t\tif (this.isOutdated(newest)) return { found: 'none' }\n\t\t\treturn newest.kind === 'delete'\n\t\t\t\t? { found: 'deleted' }\n\t\t\t\t: { found: 'record', record: newest.record, source: 'pending' }\n\t\t}\n\t\tconst key = cacheKey(collection, id)\n\t\tconst cached = this.cache.get(key)\n\t\tif (cached) {\n\t\t\t// LRU: a hit is the most recently used.\n\t\t\tthis.cache.delete(key)\n\t\t\tthis.cache.set(key, cached)\n\t\t\treturn { found: 'record', record: cached, source: 'cache' }\n\t\t}\n\t\treturn { found: 'none' }\n\t}\n\n\t/**\n\t * What the registry knows of a record's fold state (S6b): the newest entry for the\n\t * record carries it (a pending chain, or a settling commit), or the state is unknown\n\t * (the newest pending entry was predicted from values alone), or nothing is registered\n\t * and the committed state has to be read. A committed entry that carries no state is\n\t * `none`: its commit is in the database, so a read issued now contains it.\n\t */\n\tfoldStateFor(collection: string, id: string): FoldStateLookup {\n\t\tif ((this.unpredicted.get(cacheKey(collection, id)) ?? 0) > 0) return { found: 'none' }\n\t\tlet newest: PendingEntry | undefined\n\t\tfor (const entry of this.entries.values()) {\n\t\t\tif (entry.collection === collection && entry.recordId === id) newest = entry\n\t\t}\n\t\tif (!newest || this.isOutdated(newest)) return { found: 'none' }\n\t\tif (newest.foldState) return { found: 'state', state: newest.foldState }\n\t\treturn newest.state === 'committed' ? { found: 'none' } : { found: 'unknown' }\n\t}\n\n\t/**\n\t * A write to existing records that is NOT predicted (a miss) is about to run. Until it\n\t * finishes, the registry cannot say what those records hold: their cached rows are\n\t * dropped, later writes read the record instead of deriving it from an older entry,\n\t * and the settle check skips the collection's pending entries (the record changes\n\t * without a prediction).\n\t *\n\t * @returns Release function; call it once the write has committed, failed or become unknown\n\t */\n\tholdUnpredicted(collection: string, ids: readonly string[]): () => void {\n\t\tconst keys = ids.map((id) => cacheKey(collection, id))\n\t\tfor (const key of keys) {\n\t\t\tthis.cache.delete(key)\n\t\t\tthis.unpredicted.set(key, (this.unpredicted.get(key) ?? 0) + 1)\n\t\t}\n\t\tthis.foreignCounts.set(collection, this.foreignCount(collection) + 1)\n\t\tlet released = false\n\t\treturn () => {\n\t\t\tif (released) return\n\t\t\treleased = true\n\t\t\tfor (const key of keys) {\n\t\t\t\tconst left = (this.unpredicted.get(key) ?? 0) - 1\n\t\t\t\tif (left > 0) this.unpredicted.set(key, left)\n\t\t\t\telse this.unpredicted.delete(key)\n\t\t\t}\n\t\t\tthis.wakeSettled()\n\t\t}\n\t}\n\n\t/** Whether a write the overlay did not predict is changing this record right now. */\n\tisHeld(collection: string, id: string): boolean {\n\t\treturn (this.unpredicted.get(cacheKey(collection, id)) ?? 0) > 0\n\t}\n\n\t/**\n\t * Settles once no write of this record is running: no pending entry and no unpredicted\n\t * write (`null` when none is running now). A base read waits for it: a read issued while\n\t * an earlier write of the record is still queued (or held in its transaction's write\n\t * buffer) sees the record without that write, and a prediction built on it shows the\n\t * record without it until the commit corrects the display.\n\t */\n\twhenRecordSettled(collection: string, id: string): Promise<void> | null {\n\t\tconst key = cacheKey(collection, id)\n\t\tif (!this.isRunning(key)) return null\n\t\treturn new Promise<void>((resolve) => {\n\t\t\tthis.settleWaiters.add({ key, resolve })\n\t\t})\n\t}\n\n\tprivate isRunning(key: string): boolean {\n\t\tif ((this.unpredicted.get(key) ?? 0) > 0) return true\n\t\tfor (const entry of this.entries.values()) {\n\t\t\tif (entry.state === 'pending' && cacheKey(entry.collection, entry.recordId) === key)\n\t\t\t\treturn true\n\t\t}\n\t\treturn false\n\t}\n\n\tprivate wakeSettled(all = false): void {\n\t\tfor (const waiter of this.settleWaiters) {\n\t\t\tif (all || !this.isRunning(waiter.key)) {\n\t\t\t\tthis.settleWaiters.delete(waiter)\n\t\t\t\twaiter.resolve()\n\t\t\t}\n\t\t}\n\t}\n\n\t/** The newest not-committed entry for a record: what a new update would derive from. */\n\tpendingFor(collection: string, id: string): PendingEntry | undefined {\n\t\tlet newest: PendingEntry | undefined\n\t\tfor (const entry of this.entries.values()) {\n\t\t\tif (entry.collection === collection && entry.recordId === id && entry.state !== 'committed') {\n\t\t\t\tnewest = entry\n\t\t\t}\n\t\t}\n\t\treturn newest\n\t}\n\n\t/** Put a row the store itself read into the cache. */\n\tcacheRecord(collection: string, record: CollectionRecord): void {\n\t\tthis.putCache(collection, record)\n\t}\n\n\t/**\n\t * A token for {@link seedFromRead}: take it before a read of `collection` is issued and\n\t * hand it back with the result. It is the sum of three counters that only grow: changes\n\t * to the collection that were not this registry's predicted writes (remote applies,\n\t * cross-tab changes, unpredicted local writes: {@link invalidate}, {@link holdUnpredicted}),\n\t * commits of this registry's own writes to it, and clears. Any of them between the read's\n\t * issue and its delivery changes the token, because any of them can make the result\n\t * older than what the registry already knows.\n\t */\n\tseedStamp(collection: string): number {\n\t\treturn (\n\t\t\tthis.foreignCount(collection) + (this.commitCounts.get(collection) ?? 0) + this.generation\n\t\t)\n\t}\n\n\t/**\n\t * Fill the committed-row cache from rows a subscription's SQL read delivered, so the\n\t * common update or delete (of a row the user is looking at) finds its base without a\n\t * read (S5 follow-up, design 5.6).\n\t *\n\t * A seeded row must never be staler than what the registry could have learned itself, so\n\t * the call does nothing unless `stamp` (taken when the read was issued) still equals\n\t * {@link seedStamp}: the result is then at least as new as every change the registry has\n\t * been told about. Within an accepted result it skips a record that already has a cached\n\t * row (the cache is kept exact by commits and invalidations, so it is never older than\n\t * the result), one with a pending or settling entry (the entry is the base) and one with\n\t * an unpredicted write in flight. Seeds are copies (a subscriber may hold or mutate the\n\t * delivered objects), stop at the cache size, and go in with the first rows of the\n\t * result most recently used.\n\t *\n\t * @param collection - The collection the query reads\n\t * @param rows - The SQL result, in the read shape, from a query without relations\n\t * @param stamp - {@link seedStamp} when the read was issued\n\t * @returns How many rows were added\n\t */\n\tseedFromRead(collection: string, rows: readonly CollectionRecord[], stamp: number): number {\n\t\tconst capacity = this.options.rowCacheSize\n\t\tif (capacity <= 0 || rows.length === 0 || stamp !== this.seedStamp(collection)) return 0\n\t\tlet busy: Set<string> | null = null\n\t\tfor (const entry of this.entries.values()) {\n\t\t\tif (entry.collection !== collection) continue\n\t\t\tbusy ??= new Set()\n\t\t\tbusy.add(entry.recordId)\n\t\t}\n\t\tconst fresh: CollectionRecord[] = []\n\t\tfor (const row of rows) {\n\t\t\tif (fresh.length >= capacity) break\n\t\t\tconst key = cacheKey(collection, row.id)\n\t\t\tif (this.cache.has(key) || busy?.has(row.id) || this.unpredicted.has(key)) continue\n\t\t\tfresh.push(row)\n\t\t}\n\t\t// Reverse: the top of the list ends up most recently used (evicted last).\n\t\tfor (let i = fresh.length - 1; i >= 0; i--) {\n\t\t\tconst row = fresh[i]\n\t\t\tif (row) this.putCache(collection, { ...row })\n\t\t}\n\t\tthis.seeded += fresh.length\n\t\treturn fresh.length\n\t}\n\n\t/**\n\t * Forget cached rows of a collection (or one record). Called when a remote apply or a\n\t * cross-tab change names it: a cached row may then be stale (F21).\n\t */\n\tinvalidate(collection: string, ids: readonly string[] | null = null): void {\n\t\tthis.foreignCounts.set(collection, this.foreignCount(collection) + 1)\n\t\tthis.foreignSeq += 1\n\t\tif (ids === null) this.collectionMarks.set(collection, this.foreignSeq)\n\t\telse {\n\t\t\tfor (const id of ids) {\n\t\t\t\t// Re-inserting moves a hot record to the newest end, so eviction drops cold ones.\n\t\t\t\tconst key = cacheKey(collection, id)\n\t\t\t\tthis.recordMarks.delete(key)\n\t\t\t\tthis.recordMarks.set(key, this.foreignSeq)\n\t\t\t}\n\t\t}\n\t\tthis.boundMarks()\n\t\tif (ids === null) {\n\t\t\tconst prefix = `${collection}\\u0000`\n\t\t\tfor (const key of [...this.cache.keys()]) if (key.startsWith(prefix)) this.cache.delete(key)\n\t\t\treturn\n\t\t}\n\t\tfor (const id of ids) this.cache.delete(cacheKey(collection, id))\n\t}\n\n\t/**\n\t * A remote apply (or an inbound batch) is starting. Its rows can reach the database before\n\t * its post-commit {@link invalidate} runs, so a local write that commits in between reads a\n\t * record some unwritten field of which the prediction could not know. For the collections\n\t * the apply touches, between `touch` and `end`, and for any write that overlapped it,\n\t * verification is limited to the fields the write sets ({@link PendingWrites.foreignSince}).\n\t * Applies in other collections do not weaken the check.\n\t *\n\t * @param collection - The collection of a single operation; omit for a batch and `touch`\n\t *   each collection as its operations are applied\n\t * @returns `touch` marks a collection as being applied (idempotent); call `end` once when\n\t *   the apply has published (or failed)\n\t */\n\tbeginForeign(collection?: string): ForeignApply {\n\t\tconst touched = new Set<string>()\n\t\tconst touch = (name: string): void => {\n\t\t\tif (touched.has(name)) return\n\t\t\ttouched.add(name)\n\t\t\tthis.foreignInFlight.set(name, (this.foreignInFlight.get(name) ?? 0) + 1)\n\t\t\tthis.foreignActivity.set(name, this.activityOf(name) + 1)\n\t\t}\n\t\tif (collection !== undefined) touch(collection)\n\t\tlet ended = false\n\t\treturn {\n\t\t\ttouch,\n\t\t\tend: () => {\n\t\t\t\tif (ended) return\n\t\t\t\tended = true\n\t\t\t\tfor (const name of touched) {\n\t\t\t\t\tconst left = (this.foreignInFlight.get(name) ?? 1) - 1\n\t\t\t\t\tif (left <= 0) this.foreignInFlight.delete(name)\n\t\t\t\t\telse this.foreignInFlight.set(name, left)\n\t\t\t\t\tthis.foreignActivity.set(name, this.activityOf(name) + 1)\n\t\t\t\t}\n\t\t\t},\n\t\t}\n\t}\n\n\tprivate activityOf(collection: string): number {\n\t\treturn this.foreignActivity.get(collection) ?? 0\n\t}\n\n\tprivate ancestorsOf(dependsOn: string | null): readonly string[] {\n\t\tif (dependsOn === null) return []\n\t\tconst base = this.entries.get(dependsOn)\n\t\treturn [dependsOn, ...(base?.ancestors ?? [])].slice(0, MAX_ANCESTORS)\n\t}\n\n\t/** Whether a write was rolled back (recent ones only: the record is bounded). */\n\twasRolledBack(writeId: string): boolean {\n\t\treturn this.rolledBackIds.has(writeId)\n\t}\n\n\t/** Whether a remote apply in the entry's collection overlapped it, or is in flight now. */\n\tforeignSince(entry: PendingEntry): boolean {\n\t\treturn (\n\t\t\tthis.foreignInFlight.has(entry.collection) ||\n\t\t\tthis.activityOf(entry.collection) !== entry.foreignActivityAtAdd\n\t\t)\n\t}\n\n\t/**\n\t * Count a commit check that could not judge every field (the write overlapped a remote\n\t * apply, rested on an unsettled write, or could not be re-predicted). Not an error: the\n\t * fields the write sets are still judged. Lets a test or DevTools see how often the check\n\t * ran at reduced strength instead of the reduction being silent.\n\t */\n\tnoteUnverified(reason: UnverifiedReason): void {\n\t\tthis.unverifiedCounts.set(reason, (this.unverifiedCounts.get(reason) ?? 0) + 1)\n\t}\n\n\t/** Reduced-strength commit checks by reason since the registry was created. */\n\tget unverified(): ReadonlyMap<UnverifiedReason, number> {\n\t\treturn this.unverifiedCounts\n\t}\n\n\t/** Keep the per-record marks bounded; a dropped mark makes older entries count as changed. */\n\tprivate boundMarks(): void {\n\t\twhile (this.recordMarks.size > MAX_RECORD_MARKS) {\n\t\t\tconst oldest = this.recordMarks.entries().next()\n\t\t\tif (oldest.done) break\n\t\t\tthis.markFloor = Math.max(this.markFloor, oldest.value[1])\n\t\t\tthis.recordMarks.delete(oldest.value[0])\n\t\t}\n\t}\n\n\t/**\n\t * Whether a foreign change (a remote apply, another tab) touched the entry's record after\n\t * the entry was added: its `record` is then older than the database on fields it did not\n\t * write, so it must not be the base of the next write. The next write reads the record.\n\t */\n\tprivate isOutdated(entry: PendingEntry): boolean {\n\t\tconst since = entry.foreignSeqAtAdd\n\t\tif (this.markFloor > since) return true\n\t\tif ((this.collectionMarks.get(entry.collection) ?? 0) > since) return true\n\t\treturn (this.recordMarks.get(cacheKey(entry.collection, entry.recordId)) ?? 0) > since\n\t}\n\n\t/**\n\t * Drop everything (store close, user switch, restore, `reloadFromDisk`, full resync:\n\t * invariant I12). No events are emitted: the data the entries described is gone.\n\t *\n\t * @returns The entries that were dropped\n\t */\n\tclear(): PendingEntry[] {\n\t\tconst dropped = this.list()\n\t\tthis.entries.clear()\n\t\tthis.cache.clear()\n\t\tthis.rolledBackIds.clear()\n\t\tthis.generation += 1\n\t\tthis.totalBytes = 0\n\t\tthis.wakeSettled(true)\n\t\tif (dropped.length > 0) {\n\t\t\tthis.changed('cleared', [...new Set(dropped.map((entry) => entry.collection))])\n\t\t}\n\t\treturn dropped\n\t}\n\n\t/**\n\t * Listen to changes that can alter what a subscription displays (S3). The listener runs\n\t * synchronously inside the call that changed the registry (a write's `add`), so it must\n\t * only schedule work. A throwing listener never affects the registry.\n\t *\n\t * @returns An unsubscribe function\n\t */\n\tonChange(listener: RegistryListener): () => void {\n\t\tthis.changeListeners.add(listener)\n\t\treturn () => {\n\t\t\tthis.changeListeners.delete(listener)\n\t\t}\n\t}\n\n\t/**\n\t * Whether `operationId` was created by a write this registry committed and still holds.\n\t * The subscription manager uses it to tell the post-commit publication of a predicted\n\t * local write (the cache already holds its committed row) from every other change\n\t * (which invalidates cached rows, F21).\n\t */\n\townsOperation(operationId: string): boolean {\n\t\tfor (const entry of this.entries.values()) {\n\t\t\tif (entry.operationIds.includes(operationId)) return true\n\t\t}\n\t\treturn false\n\t}\n\n\t/**\n\t * Compare a committed record with the prediction the entry carried (5.3e) and report\n\t * `store:overlay-diverged` on a difference outside `createdAt` and `updatedAt`.\n\t */\n\treportDivergence(entry: PendingEntry, fields: readonly string[]): void {\n\t\tif (fields.length === 0) return\n\t\tthis.emit({\n\t\t\ttype: 'store:overlay-diverged',\n\t\t\twriteId: entry.writeId,\n\t\t\tcollection: entry.collection,\n\t\t\tfields,\n\t\t})\n\t}\n\n\tprivate refuse(change: PredictedChange, reason: MissReason): AddResult {\n\t\tthis.noteMiss(change.kind, change.collection, [change.recordId], reason)\n\t\treturn { ok: false, reason }\n\t}\n\n\tprivate remove(entry: PendingEntry): void {\n\t\tif (this.entries.delete(entry.writeId)) this.totalBytes -= entry.bytes\n\t}\n\n\tprivate recordCommitted(entry: PendingEntry, record: CollectionRecord | undefined): void {\n\t\tif (record) {\n\t\t\tthis.floorWallTime = Math.max(this.floorWallTime, record.createdAt, record.updatedAt)\n\t\t}\n\t\tif (entry.kind === 'delete') {\n\t\t\tthis.cache.delete(cacheKey(entry.collection, entry.recordId))\n\t\t\treturn\n\t\t}\n\t\t// A commit that did not report its row (an outcome decided later by lookup) leaves\n\t\t// the cached row, if any, older than the database: forget it.\n\t\tif (record) this.putCache(entry.collection, record)\n\t\telse this.cache.delete(cacheKey(entry.collection, entry.recordId))\n\t}\n\n\tprivate putCache(collection: string, record: CollectionRecord): void {\n\t\tconst key = cacheKey(collection, record.id)\n\t\tthis.cache.delete(key)\n\t\tthis.cache.set(key, record)\n\t\twhile (this.cache.size > this.options.rowCacheSize) {\n\t\t\tconst oldest = this.cache.keys().next()\n\t\t\tif (oldest.done) break\n\t\t\tthis.cache.delete(oldest.value)\n\t\t}\n\t}\n\n\tprivate changed(kind: RegistryChange['kind'], collections: readonly string[]): void {\n\t\tthis.wakeSettled()\n\t\tfor (const listener of this.changeListeners) {\n\t\t\ttry {\n\t\t\t\tlistener({ kind, collections })\n\t\t\t} catch (error) {\n\t\t\t\tconsole.error('[kora] overlay registry listener failed', error)\n\t\t\t}\n\t\t}\n\t}\n\n\tprivate emit(event: OverlayEvent): void {\n\t\tif (!this.onEvent) return\n\t\ttry {\n\t\t\tthis.onEvent(event)\n\t\t} catch (error) {\n\t\t\t// A failing listener must not affect the registry or the write.\n\t\t\tconsole.error('[kora] overlay event listener failed', error)\n\t\t}\n\t}\n}\n\nfunction stripUndefined<T extends object>(value: T): Partial<T> {\n\tconst out: Partial<T> = {}\n\tfor (const key of Object.keys(value) as Array<keyof T>) {\n\t\tif (value[key] !== undefined) out[key] = value[key]\n\t}\n\treturn out\n}\n","import type { KoraEvent } from '@korajs/core'\nimport { OverlayDivergedError } from '../errors'\nimport { lookupOperation } from '../mutations/commit-outcome'\nimport type { InstantUpdatesOptions, StorageAdapter } from '../types'\nimport {\n\ttype OverlayEvent,\n\ttype PendingEntry,\n\tPendingWrites,\n\ttype PendingWritesOptions,\n} from './pending-writes'\nimport type { WriteOverlay } from './write-overlay'\n\n/*\n * One per store built with `instantUpdates` (instant-UI stage S4,\n * docs/design/instant-ui-updates.md 4.2, 6, 7, 10, 11). It owns the registry and decides\n * everything the registry deliberately does not: which of its events become public\n * events, when a collection stops being predicted (the circuit breaker, I10), how a write\n * whose commit answer was lost is decided later (M2), when pending entries expire, and\n * when the overlay is cleared (I12). Tab-local, never serialized (I11).\n */\n\n/** Divergences of one collection that switch prediction off for it for the session (I10). */\nexport const DIVERGENCE_LIMIT = 3\n\n/** Hooks for tests and benchmarks. Internal: free to change. */\nexport interface OverlayControllerInternals {\n\t/** Wall clock for predicted timestamps; default `Date.now`. */\n\treadonly wallClock?: () => number\n\t/** Reads a record for an update's base; default a `SELECT` on the store's adapter. */\n\treadonly readRecord?: WriteOverlay['readRecord']\n\t/** Reads a record's fold state for an array write's base; default a `SELECT`. */\n\treadonly readFoldState?: WriteOverlay['readFoldState']\n\t/** Longest base read, in ms. */\n\treadonly baseReadTimeoutMs?: number\n\t/** Monotonic milliseconds for the registry. Default `performance.now`. */\n\treadonly now?: () => number\n\t/** Settle window and pending TTL, in ms (registry options). */\n\treadonly settleMs?: number\n\treadonly pendingTtlMs?: number\n\treadonly rowCacheSize?: number\n\t/** Report a divergence loudly; default throws from a microtask in test builds only. */\n\treadonly raise?: (error: Error) => void\n\t/** Raise on divergence. Default: true when `NODE_ENV` is `test`. */\n\treadonly strict?: boolean\n\t/** Divergences before the breaker opens. Default {@link DIVERGENCE_LIMIT}. */\n\treadonly divergenceLimit?: number\n\t/** Schedule the expiry sweep. Default `setTimeout` (unref'd where the runtime has it). */\n\treadonly schedule?: (callback: () => void, delayMs: number) => unknown\n\treadonly cancel?: (handle: unknown) => void\n}\n\n/** What the store gives its controller. */\nexport interface OverlayControllerOptions {\n\treadonly options: InstantUpdatesOptions\n\treadonly adapter: StorageAdapter\n\treadonly emit: (event: KoraEvent) => void\n\t/** True while the adapter refuses writes (the durability-lost state). */\n\treadonly writesRefused: () => boolean\n\t/** Re-run the live queries of a collection (after an unknown outcome was decided). */\n\treadonly refresh: (collection: string) => void\n\treadonly internals?: OverlayControllerInternals\n}\n\n/** A rolled-back write, as `onRollback` listeners get it. */\nexport interface RollbackInfo {\n\treadonly writeId: string\n\treadonly collection: string\n\treadonly recordIds: readonly string[]\n\treadonly error: unknown\n}\n\n/** Whether this process is a test run (Vitest, Jest and most runners set `NODE_ENV=test`). */\nfunction isTestBuild(): boolean {\n\tconst scope = globalThis as { process?: { env?: Record<string, string | undefined> } }\n\treturn scope.process?.env?.NODE_ENV === 'test'\n}\n\n/** Fail loudly without breaking the data path: from a microtask, so it is never swallowed by a write's own handling. */\nfunction raiseFromMicrotask(error: Error): void {\n\tqueueMicrotask(() => {\n\t\tthrow error\n\t})\n}\n\n/** The overlay of one store. */\nexport class OverlayController {\n\treadonly registry: PendingWrites\n\treadonly overlay: WriteOverlay\n\tprivate readonly emit: (event: KoraEvent) => void\n\tprivate readonly adapter: StorageAdapter\n\tprivate readonly refresh: (collection: string) => void\n\tprivate readonly strict: boolean\n\tprivate readonly raise: (error: Error) => void\n\tprivate readonly divergenceLimit: number\n\tprivate readonly divergences = new Map<string, number>()\n\tprivate readonly disabled = new Set<string>()\n\tprivate readonly reported = new Set<string>()\n\tprivate readonly rollbackListeners = new Set<(info: RollbackInfo) => void>()\n\tprivate readonly deciding = new Set<string>()\n\tprivate readonly schedule: (callback: () => void, delayMs: number) => unknown\n\tprivate readonly cancel: (handle: unknown) => void\n\tprivate sweepHandle: unknown = null\n\tprivate sweepEveryMs: number\n\tprivate stopped = false\n\tprivate unsubscribeRegistry: () => void\n\n\tconstructor(config: OverlayControllerOptions) {\n\t\tconst internals = config.internals ?? {}\n\t\tthis.emit = config.emit\n\t\tthis.adapter = config.adapter\n\t\tthis.refresh = config.refresh\n\t\tthis.strict = internals.strict ?? isTestBuild()\n\t\tthis.raise = internals.raise ?? raiseFromMicrotask\n\t\tthis.divergenceLimit = internals.divergenceLimit ?? DIVERGENCE_LIMIT\n\t\tthis.schedule =\n\t\t\tinternals.schedule ??\n\t\t\t((callback, delayMs) => {\n\t\t\t\tconst handle = setTimeout(callback, delayMs)\n\t\t\t\t// A pending sweep must never keep a Node process alive.\n\t\t\t\t;(handle as { unref?: () => void }).unref?.()\n\t\t\t\treturn handle\n\t\t\t})\n\t\tthis.cancel = internals.cancel ?? ((handle) => clearTimeout(handle as never))\n\t\tconst registryOptions: PendingWritesOptions = {\n\t\t\t...(config.options.maxPendingWrites !== undefined\n\t\t\t\t? { maxPendingWrites: config.options.maxPendingWrites }\n\t\t\t\t: {}),\n\t\t\t...(config.options.maxPendingBytes !== undefined\n\t\t\t\t? { maxPendingBytes: config.options.maxPendingBytes }\n\t\t\t\t: {}),\n\t\t\t...(config.options.maxRecordsPerWrite !== undefined\n\t\t\t\t? { maxRecordsPerWrite: config.options.maxRecordsPerWrite }\n\t\t\t\t: {}),\n\t\t\t...(internals.settleMs !== undefined ? { settleMs: internals.settleMs } : {}),\n\t\t\t...(internals.pendingTtlMs !== undefined ? { pendingTtlMs: internals.pendingTtlMs } : {}),\n\t\t\t...(internals.rowCacheSize !== undefined ? { rowCacheSize: internals.rowCacheSize } : {}),\n\t\t\t...(internals.now ? { now: internals.now } : {}),\n\t\t\tonEvent: (event) => this.onRegistryEvent(event),\n\t\t}\n\t\tthis.registry = new PendingWrites(registryOptions)\n\t\tthis.sweepEveryMs = Math.max(250, Math.floor(this.registry.limits.pendingTtlMs / 4))\n\t\tthis.overlay = {\n\t\t\tregistry: this.registry,\n\t\t\twritesRefused: config.writesRefused,\n\t\t\tisCollectionDisabled: (collection) => this.disabled.has(collection),\n\t\t\tonRolledBack: (entries, error) => this.onRolledBack(entries, error),\n\t\t\t...(internals.wallClock ? { wallClock: internals.wallClock } : {}),\n\t\t\t...(internals.readRecord ? { readRecord: internals.readRecord } : {}),\n\t\t\t...(internals.readFoldState ? { readFoldState: internals.readFoldState } : {}),\n\t\t\t...(internals.baseReadTimeoutMs !== undefined\n\t\t\t\t? { baseReadTimeoutMs: internals.baseReadTimeoutMs }\n\t\t\t\t: {}),\n\t\t}\n\t\t// A pending entry needs a deadline: arm the expiry sweep while any exist.\n\t\tthis.unsubscribeRegistry = this.registry.onChange((change) => {\n\t\t\tif (change.kind === 'added') this.armSweep()\n\t\t})\n\t}\n\n\t/** Writes shown but not yet committed (pending, or committed with an unknown outcome). */\n\tget pending(): number {\n\t\treturn this.registry.pendingCount\n\t}\n\n\t/** Whether prediction is switched off for a collection (the breaker is open). */\n\tisDisabled(collection: string): boolean {\n\t\treturn this.disabled.has(collection)\n\t}\n\n\t/** Listen to rolled-back writes. Returns an unsubscribe function. */\n\tonRollback(listener: (info: RollbackInfo) => void): () => void {\n\t\tthis.rollbackListeners.add(listener)\n\t\treturn () => {\n\t\t\tthis.rollbackListeners.delete(listener)\n\t\t}\n\t}\n\n\t/**\n\t * Forget every pending write (I12): the data they described is gone or no longer this\n\t * user's. Runs BEFORE the live queries re-run, so nothing pending is applied over the\n\t * new state. Nothing is emitted for the entries: they are not outcomes.\n\t */\n\tclear(): void {\n\t\tthis.registry.clear()\n\t\tthis.deciding.clear()\n\t\tthis.reported.clear()\n\t\tthis.cancelSweep()\n\t}\n\n\t/** Clear, and never schedule again (store close). */\n\tdispose(): void {\n\t\tthis.stopped = true\n\t\tthis.clear()\n\t\tthis.unsubscribeRegistry()\n\t\tthis.rollbackListeners.clear()\n\t}\n\n\t/**\n\t * Decide writes whose commit answer was lost (M2) with a lookup, now that a SQL read of\n\t * their collection succeeded: the adapter is answering again. Found: committed. Not\n\t * found: rolled back. Still unreadable: they stay shown. Never throws.\n\t *\n\t * @param collection - Only entries of this collection; all when omitted\n\t */\n\tasync resolveUnknown(collection?: string): Promise<void> {\n\t\tconst entries = this.registry.unknownEntries(collection)\n\t\tfor (const entry of entries) {\n\t\t\tif (entry.lookupOperationId === null || this.deciding.has(entry.writeId)) continue\n\t\t\tthis.deciding.add(entry.writeId)\n\t\t\ttry {\n\t\t\t\tconst lookup = await lookupOperation(\n\t\t\t\t\tthis.adapter,\n\t\t\t\t\tentry.collection,\n\t\t\t\t\tentry.lookupOperationId,\n\t\t\t\t)\n\t\t\t\tconst current = this.registry.get(entry.writeId)\n\t\t\t\tif (!current || current.state !== 'unknown') continue\n\t\t\t\tif (lookup.outcome === 'committed') {\n\t\t\t\t\tthis.registry.commit(entry.writeId, { operationIds: [entry.lookupOperationId] })\n\t\t\t\t\tthis.refresh(entry.collection)\n\t\t\t\t} else if (lookup.outcome === 'absent') {\n\t\t\t\t\tconst removed = this.registry.rollback(entry.writeId)\n\t\t\t\t\tthis.onRolledBack(\n\t\t\t\t\t\tremoved,\n\t\t\t\t\t\tnew Error(`The write's commit was not found in the operation log (${entry.writeId}).`),\n\t\t\t\t\t)\n\t\t\t\t\tthis.refresh(entry.collection)\n\t\t\t\t}\n\t\t\t} finally {\n\t\t\t\tthis.deciding.delete(entry.writeId)\n\t\t\t}\n\t\t}\n\t}\n\n\tprivate onRolledBack(entries: readonly PendingEntry[], error: unknown): void {\n\t\tfor (const entry of entries) {\n\t\t\tconst info: RollbackInfo = {\n\t\t\t\twriteId: entry.writeId,\n\t\t\t\tcollection: entry.collection,\n\t\t\t\trecordIds: [entry.recordId],\n\t\t\t\terror,\n\t\t\t}\n\t\t\tfor (const listener of this.rollbackListeners) {\n\t\t\t\ttry {\n\t\t\t\t\tlistener(info)\n\t\t\t\t} catch (failure) {\n\t\t\t\t\tconsole.error('[kora] a storage.writes.onRollback listener failed', failure)\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\n\t/** Public events, one for one with the registry's (names and fields match section 9.4). */\n\tprivate onRegistryEvent(event: OverlayEvent): void {\n\t\tswitch (event.type) {\n\t\t\tcase 'store:write-pending':\n\t\t\t\tthis.emit({\n\t\t\t\t\ttype: 'store:write-pending',\n\t\t\t\t\twriteId: event.writeId,\n\t\t\t\t\tcollection: event.collection,\n\t\t\t\t\t...(event.collections ? { collections: [...event.collections] } : {}),\n\t\t\t\t\trecordIds: [...event.recordIds],\n\t\t\t\t\tkind: event.kind,\n\t\t\t\t\tpredicted: event.predicted,\n\t\t\t\t\t...(event.predicted ? {} : { reason: event.reason }),\n\t\t\t\t})\n\t\t\t\treturn\n\t\t\tcase 'store:write-settled':\n\t\t\t\tthis.emit({\n\t\t\t\t\ttype: 'store:write-settled',\n\t\t\t\t\twriteId: event.writeId,\n\t\t\t\t\tcollection: event.collection,\n\t\t\t\t\t...(event.collections ? { collections: [...event.collections] } : {}),\n\t\t\t\t\toutcome: event.outcome,\n\t\t\t\t\t...(event.operationIds ? { operationIds: [...event.operationIds] } : {}),\n\t\t\t\t\tpendingMs: event.pendingMs,\n\t\t\t\t})\n\t\t\t\treturn\n\t\t\tcase 'store:overlay-diverged':\n\t\t\t\tthis.onDiverged(event.writeId, event.collection, event.fields)\n\t\t\t\treturn\n\t\t}\n\t}\n\n\t/** A prediction the database contradicted: report it, count it, maybe open the breaker (I10). */\n\tprivate onDiverged(writeId: string, collection: string, fields: readonly string[]): void {\n\t\t// One divergence is seen by every subscription that settles it: report it once.\n\t\tconst key = `${writeId}\\u0000${fields.join(',')}`\n\t\tif (this.reported.has(key)) return\n\t\tif (this.reported.size >= 1_024) this.reported.clear()\n\t\tthis.reported.add(key)\n\t\tthis.emit({ type: 'store:overlay-diverged', writeId, collection, fields: [...fields] })\n\t\tconst count = (this.divergences.get(collection) ?? 0) + 1\n\t\tthis.divergences.set(collection, count)\n\t\tif (count >= this.divergenceLimit && !this.disabled.has(collection)) {\n\t\t\tthis.disabled.add(collection)\n\t\t\tthis.emit({ type: 'store:overlay-disabled', collection, divergences: count })\n\t\t}\n\t\tif (this.strict) this.raise(new OverlayDivergedError(collection, fields))\n\t}\n\n\tprivate armSweep(): void {\n\t\tif (this.stopped || this.sweepHandle !== null) return\n\t\tthis.sweepHandle = this.schedule(() => {\n\t\t\tthis.sweepHandle = null\n\t\t\tthis.sweep()\n\t\t}, this.sweepEveryMs)\n\t}\n\n\tprivate cancelSweep(): void {\n\t\tif (this.sweepHandle === null) return\n\t\tthis.cancel(this.sweepHandle)\n\t\tthis.sweepHandle = null\n\t}\n\n\t/** Expire pending entries past their TTL into `unknown`; keep sweeping while any are pending. */\n\tsweep(): void {\n\t\tif (this.stopped) return\n\t\tthis.registry.sweep()\n\t\tif (this.registry.pendingCount > 0) this.armSweep()\n\t}\n\n\t/** Rows of the committed-row cache, for diagnostics. */\n\tget cachedRows(): number {\n\t\treturn this.registry.cachedRows\n\t}\n}\n","import type { CollectionDefinition, SchemaDefinition } from '@korajs/core'\nimport { encodeStoredText, quoteIdent } from '@korajs/core'\nimport { QueryError } from '../errors'\nimport { deserializeRecord } from '../serialization/serializer'\nimport { type ResultsEqual, createResultsEqual } from '../subscription/result-equality'\nimport type { SubscriptionManager } from '../subscription/subscription-manager'\nimport type {\n\tCollectionRecord,\n\tOrderByDirection,\n\tQueryDescriptor,\n\tRawCollectionRow,\n\tStorageAdapter,\n\tSubscribeOptions,\n\tSubscriptionCallback,\n\tWhereClause,\n} from '../types'\nimport { pluralize, singularize } from './pluralize'\nimport { normalizeWhere } from './query-key'\nimport { buildCountQuery, buildSelectQuery } from './sql-builder'\n\nconst RESULTS_EQUAL_CACHE = new WeakMap<CollectionDefinition, ResultsEqual>()\n\n/**\n * Fluent query builder for constructing and executing collection queries.\n * Supports where, orderBy, limit, offset, include, exec, count, and subscribe.\n *\n * The generic parameter `T` defaults to `CollectionRecord` for backward compatibility\n * but can be narrowed to a specific record type for full type inference.\n *\n * @example\n * ```typescript\n * const todos = await app.todos\n *   .where({ completed: false })\n *   .orderBy('createdAt', 'desc')\n *   .limit(10)\n *   .exec()\n * ```\n */\nexport class QueryBuilder<T = CollectionRecord> {\n\tprivate descriptor: QueryDescriptor\n\n\tconstructor(\n\t\tprivate readonly collectionName: string,\n\t\tprivate readonly definition: CollectionDefinition,\n\t\tprivate readonly adapter: StorageAdapter,\n\t\tprivate readonly subscriptionManager: SubscriptionManager,\n\t\tinitialWhere: WhereClause = {},\n\t\tprivate readonly schema?: SchemaDefinition,\n\t) {\n\t\tthis.descriptor = {\n\t\t\tcollection: collectionName,\n\t\t\twhere: normalizeWhere(initialWhere),\n\t\t\torderBy: [],\n\t\t}\n\t}\n\n\t/**\n\t * Add WHERE conditions (AND semantics). Conditions on new fields are added to the\n\t * existing ones; a condition on a field that already has one replaces it.\n\t *\n\t * A field whose value is `undefined` adds no condition (it does not remove an\n\t * earlier one); `null` matches missing values (`IS NULL`). Non-finite numbers are\n\t * refused. See {@link normalizeWhere} (RT-102).\n\t */\n\twhere(conditions: WhereClause): QueryBuilder<T> {\n\t\tconst clone = this.clone()\n\t\tclone.descriptor = {\n\t\t\t...clone.descriptor,\n\t\t\twhere: { ...clone.descriptor.where, ...normalizeWhere(conditions) },\n\t\t}\n\t\treturn clone\n\t}\n\n\t/**\n\t * Add ORDER BY clause.\n\t */\n\torderBy(field: string, direction: OrderByDirection = 'asc'): QueryBuilder<T> {\n\t\tconst clone = this.clone()\n\t\tclone.descriptor = {\n\t\t\t...clone.descriptor,\n\t\t\torderBy: [...clone.descriptor.orderBy, { field, direction }],\n\t\t}\n\t\treturn clone\n\t}\n\n\t/**\n\t * Set result limit.\n\t */\n\tlimit(n: number): QueryBuilder<T> {\n\t\tconst clone = this.clone()\n\t\tclone.descriptor = { ...clone.descriptor, limit: n }\n\t\treturn clone\n\t}\n\n\t/**\n\t * Set result offset.\n\t */\n\toffset(n: number): QueryBuilder<T> {\n\t\tconst clone = this.clone()\n\t\tclone.descriptor = { ...clone.descriptor, offset: n }\n\t\treturn clone\n\t}\n\n\t/**\n\t * Include related records in the query results.\n\t * Follows relations defined in the schema to batch-fetch related data.\n\t *\n\t * @param targets - Relation target names (collection names or relation names)\n\t * @returns A new QueryBuilder with include targets added\n\t *\n\t * @example\n\t * ```typescript\n\t * const todosWithProject = await app.todos\n\t *   .where({ completed: false })\n\t *   .include('project')\n\t *   .exec()\n\t * ```\n\t */\n\tinclude(...targets: string[]): QueryBuilder<T> {\n\t\tconst clone = this.clone()\n\t\tconst existing = clone.descriptor.include ?? []\n\t\tclone.descriptor = {\n\t\t\t...clone.descriptor,\n\t\t\tinclude: [...existing, ...targets],\n\t\t}\n\t\treturn clone\n\t}\n\n\t/**\n\t * Execute the query and return results.\n\t */\n\tasync exec(): Promise<T[]> {\n\t\tconst { sql, params } = buildSelectQuery(this.descriptor, this.definition.fields)\n\t\tconst rows = await this.adapter.query<RawCollectionRow>(sql, params)\n\t\tconst records = rows.map((row) => deserializeRecord(row, this.definition.fields))\n\n\t\t// Resolve includes if any\n\t\tif (this.descriptor.include && this.descriptor.include.length > 0 && this.schema) {\n\t\t\tawait this.resolveIncludes(records)\n\t\t}\n\n\t\treturn records as T[]\n\t}\n\n\t/**\n\t * Count the records this query matches: the length `exec()` would return, so `limit` and\n\t * `offset` apply.\n\t */\n\tasync count(): Promise<number> {\n\t\tconst { sql, params } = buildCountQuery(this.descriptor, this.definition.fields)\n\t\tconst rows = await this.adapter.query<{ count: number }>(sql, params)\n\t\treturn rows[0]?.count ?? 0\n\t}\n\n\t/**\n\t * Subscribe to query results. The callback is called with the current results once the\n\t * initial query resolves (asynchronously), then again whenever the results change.\n\t *\n\t * @returns An unsubscribe function\n\t */\n\tsubscribe(callback: SubscriptionCallback<T>, options?: SubscribeOptions): () => void {\n\t\tconst executeFn = () => this.exec()\n\n\t\t// Resolve includeCollections for subscription tracking\n\t\tconst descriptorCopy = { ...this.descriptor }\n\t\tif (descriptorCopy.include && descriptorCopy.include.length > 0 && this.schema) {\n\t\t\tdescriptorCopy.includeCollections = this.resolveIncludeCollections(descriptorCopy.include)\n\t\t}\n\n\t\t// Use registerAndFetch to execute immediately, set lastResults,\n\t\t// and call callback — ensuring subsequent flushes diff correctly.\n\t\treturn this.subscriptionManager.registerAndFetch(\n\t\t\tdescriptorCopy,\n\t\t\tcallback as SubscriptionCallback<CollectionRecord>,\n\t\t\texecuteFn as () => Promise<CollectionRecord[]>,\n\t\t\t{ onError: options?.onError, resultsEqual: this.getResultsEqual() },\n\t\t)\n\t}\n\n\t/** Comparator built once per collection definition and shared by its queries. */\n\tprivate getResultsEqual(): ResultsEqual {\n\t\tlet cached = RESULTS_EQUAL_CACHE.get(this.definition)\n\t\tif (!cached) {\n\t\t\tcached = createResultsEqual(this.definition.fields)\n\t\t\tRESULTS_EQUAL_CACHE.set(this.definition, cached)\n\t\t}\n\t\treturn cached\n\t}\n\n\t/** Get the internal descriptor (for testing/debugging) */\n\tgetDescriptor(): QueryDescriptor {\n\t\treturn { ...this.descriptor }\n\t}\n\n\tprivate clone(): QueryBuilder<T> {\n\t\tconst qb = new QueryBuilder<T>(\n\t\t\tthis.collectionName,\n\t\t\tthis.definition,\n\t\t\tthis.adapter,\n\t\t\tthis.subscriptionManager,\n\t\t\t{},\n\t\t\tthis.schema,\n\t\t)\n\t\tqb.descriptor = {\n\t\t\t...this.descriptor,\n\t\t\twhere: { ...this.descriptor.where },\n\t\t\torderBy: [...this.descriptor.orderBy],\n\t\t\tinclude: this.descriptor.include ? [...this.descriptor.include] : undefined,\n\t\t\tincludeCollections: this.descriptor.includeCollections\n\t\t\t\t? [...this.descriptor.includeCollections]\n\t\t\t\t: undefined,\n\t\t}\n\t\treturn qb\n\t}\n\n\t/**\n\t * Resolve include targets to their actual collection names for subscription tracking.\n\t */\n\tprivate resolveIncludeCollections(targets: string[]): string[] {\n\t\tif (!this.schema) return []\n\t\tconst collections: string[] = []\n\n\t\tfor (const target of targets) {\n\t\t\tconst relation = this.findRelation(target)\n\t\t\tif (relation) {\n\t\t\t\t// For many-to-one: the related collection is `relation.to`\n\t\t\t\t// For one-to-many: the related collection is `relation.from`\n\t\t\t\tif (relation.from === this.collectionName) {\n\t\t\t\t\tcollections.push(relation.to)\n\t\t\t\t} else {\n\t\t\t\t\tcollections.push(relation.from)\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\treturn collections\n\t}\n\n\t/**\n\t * Resolve includes after primary query, batch-fetching related records.\n\t */\n\tprivate async resolveIncludes(records: CollectionRecord[]): Promise<void> {\n\t\tif (!this.schema || !this.descriptor.include || records.length === 0) return\n\n\t\tfor (const target of this.descriptor.include) {\n\t\t\tconst relation = this.findRelation(target)\n\t\t\tif (!relation) {\n\t\t\t\tthrow new QueryError(\n\t\t\t\t\t`No relation found for include target \"${target}\" on collection \"${this.collectionName}\". ` +\n\t\t\t\t\t\t`Check that a relation is defined in your schema that connects \"${this.collectionName}\" to \"${target}\".`,\n\t\t\t\t)\n\t\t\t}\n\n\t\t\tif (relation.from === this.collectionName) {\n\t\t\t\t// Many-to-one or one-to-one: primary has FK → fetch parent records\n\t\t\t\tawait this.resolveManyToOneInclude(records, relation, target)\n\t\t\t} else {\n\t\t\t\t// One-to-many: related collection has FK → fetch children\n\t\t\t\tawait this.resolveOneToManyInclude(records, relation, target)\n\t\t\t}\n\t\t}\n\t}\n\n\t/**\n\t * Many-to-one: collect FK values from primary results, batch-fetch related, attach as singular.\n\t */\n\tprivate async resolveManyToOneInclude(\n\t\trecords: CollectionRecord[],\n\t\trelation: { from: string; to: string; field: string },\n\t\ttarget: string,\n\t): Promise<void> {\n\t\tconst fkField = relation.field\n\t\tconst fkValues = records\n\t\t\t.map((r) => r[fkField])\n\t\t\t.filter((v): v is string => v !== null && v !== undefined && typeof v === 'string')\n\n\t\tif (fkValues.length === 0) {\n\t\t\t// All null FKs — set property to null on all records\n\t\t\tconst propName = singularize(target)\n\t\t\tfor (const record of records) {\n\t\t\t\t;(record as Record<string, unknown>)[propName] = null\n\t\t\t}\n\t\t\treturn\n\t\t}\n\n\t\tconst uniqueFks = [...new Set(fkValues)]\n\t\tconst relatedCollection = relation.to\n\t\tconst relatedDef = this.schema?.collections[relatedCollection]\n\t\tif (!relatedDef) return\n\n\t\t// Batch fetch: SELECT * FROM <to> WHERE id IN (...) AND _deleted = 0\n\t\tconst placeholders = uniqueFks.map(() => '?').join(', ')\n\t\tconst sql = `SELECT * FROM ${quoteIdent(relatedCollection)} WHERE id IN (${placeholders}) AND _deleted = 0`\n\t\tconst rows = await this.adapter.query<RawCollectionRow>(sql, uniqueFks)\n\t\tconst relatedRecords = rows.map((row) => deserializeRecord(row, relatedDef.fields))\n\n\t\t// Build lookup\n\t\tconst lookup = new Map<string, CollectionRecord>()\n\t\tfor (const r of relatedRecords) {\n\t\t\tlookup.set(r.id, r)\n\t\t}\n\n\t\t// Attach as singular property\n\t\tconst propName = singularize(target)\n\t\tfor (const record of records) {\n\t\t\tconst fk = record[fkField] as string | null\n\t\t\t;(record as Record<string, unknown>)[propName] = fk ? (lookup.get(fk) ?? null) : null\n\t\t}\n\t}\n\n\t/**\n\t * One-to-many: collect primary IDs, batch-fetch children, attach as array.\n\t */\n\tprivate async resolveOneToManyInclude(\n\t\trecords: CollectionRecord[],\n\t\trelation: { from: string; to: string; field: string },\n\t\ttarget: string,\n\t): Promise<void> {\n\t\tconst primaryIds = records.map((r) => r.id)\n\t\tconst relatedCollection = relation.from\n\t\tconst relatedDef = this.schema?.collections[relatedCollection]\n\t\tif (!relatedDef) return\n\n\t\tconst fkField = relation.field\n\t\tconst placeholders = primaryIds.map(() => '?').join(', ')\n\t\tconst sql = `SELECT * FROM ${quoteIdent(relatedCollection)} WHERE ${quoteIdent(fkField)} IN (${placeholders}) AND _deleted = 0`\n\t\tconst rows = await this.adapter.query<RawCollectionRow>(\n\t\t\tsql,\n\t\t\tprimaryIds.map((id) => encodeStoredText(id)),\n\t\t)\n\t\tconst relatedRecords = rows.map((row) => deserializeRecord(row, relatedDef.fields))\n\n\t\t// Group by FK\n\t\tconst grouped = new Map<string, CollectionRecord[]>()\n\t\tfor (const r of relatedRecords) {\n\t\t\tconst fk = r[fkField] as string\n\t\t\tif (!grouped.has(fk)) {\n\t\t\t\tgrouped.set(fk, [])\n\t\t\t}\n\t\t\tgrouped.get(fk)?.push(r)\n\t\t}\n\n\t\t// Attach as array property\n\t\tconst propName = pluralize(target)\n\t\tfor (const record of records) {\n\t\t\t;(record as Record<string, unknown>)[propName] = grouped.get(record.id) ?? []\n\t\t}\n\t}\n\n\t/**\n\t * Find a relation definition matching the include target.\n\t * Searches by relation name, target collection name, and singularized/pluralized variants.\n\t */\n\tprivate findRelation(\n\t\ttarget: string,\n\t): { from: string; to: string; field: string; type: string } | null {\n\t\tif (!this.schema) return null\n\n\t\tfor (const [_name, rel] of Object.entries(this.schema.relations)) {\n\t\t\t// Direct match: target is the related collection name\n\t\t\tif (rel.from === this.collectionName && rel.to === target) return rel\n\t\t\tif (rel.to === this.collectionName && rel.from === target) return rel\n\n\t\t\t// Singularized match: \"project\" matches relation to \"projects\"\n\t\t\tif (rel.from === this.collectionName && rel.to === pluralize(target)) return rel\n\t\t\tif (rel.to === this.collectionName && rel.from === pluralize(target)) return rel\n\n\t\t\t// Pluralized match: \"todos\" matches relation from \"todos\"\n\t\t\tif (rel.from === this.collectionName && rel.to === singularize(target)) return rel\n\t\t\tif (rel.to === this.collectionName && rel.from === singularize(target)) return rel\n\t\t}\n\n\t\treturn null\n\t}\n}\n","import type { FieldDescriptor, FieldKind } from '@korajs/core'\nimport type { CollectionRecord } from '../types'\n\n/** Compares two query result sets; true means subscribers need not be notified. */\nexport type ResultsEqual = (\n\tprev: readonly CollectionRecord[],\n\tnext: readonly CollectionRecord[],\n) => boolean\n\ntype ValueEqual = (a: unknown, b: unknown) => boolean\n\n/**\n * Structural equality for any value a deserialized record can hold: primitives\n * (with `Object.is`, so NaN equals NaN), arrays, byte views (richtext and blob\n * state), Dates and plain objects (own enumerable keys, order-insensitive).\n *\n * Deserialization builds fresh arrays and objects on every query run, so a\n * reference comparison reports every structured field as changed (STORE-12) and\n * every subscriber re-renders on every unrelated write to the collection.\n */\nexport function structurallyEqual(a: unknown, b: unknown): boolean {\n\tif (Object.is(a, b)) return true\n\tif (typeof a !== 'object' || typeof b !== 'object' || a === null || b === null) return false\n\n\tif (ArrayBuffer.isView(a) || ArrayBuffer.isView(b)) {\n\t\tif (!ArrayBuffer.isView(a) || !ArrayBuffer.isView(b)) return false\n\t\treturn bytesEqual(a, b)\n\t}\n\tif (Array.isArray(a) || Array.isArray(b)) {\n\t\tif (!Array.isArray(a) || !Array.isArray(b) || a.length !== b.length) return false\n\t\tfor (let i = 0; i < a.length; i++) {\n\t\t\tif (!structurallyEqual(a[i], b[i])) return false\n\t\t}\n\t\treturn true\n\t}\n\tif (a instanceof Date || b instanceof Date) {\n\t\treturn a instanceof Date && b instanceof Date && Object.is(a.getTime(), b.getTime())\n\t}\n\n\tconst objA = a as Record<string, unknown>\n\tconst objB = b as Record<string, unknown>\n\tconst keysA = Object.keys(objA)\n\tif (keysA.length !== Object.keys(objB).length) return false\n\tfor (const key of keysA) {\n\t\tif (!Object.hasOwn(objB, key)) return false\n\t\tif (!structurallyEqual(objA[key], objB[key])) return false\n\t}\n\treturn true\n}\n\nfunction bytesEqual(a: ArrayBufferView, b: ArrayBufferView): boolean {\n\tif (a.byteLength !== b.byteLength) return false\n\tconst x = new Uint8Array(a.buffer, a.byteOffset, a.byteLength)\n\tconst y = new Uint8Array(b.buffer, b.byteOffset, b.byteLength)\n\tfor (let i = 0; i < x.length; i++) {\n\t\tif (x[i] !== y[i]) return false\n\t}\n\treturn true\n}\n\nfunction scalarEqual(a: unknown, b: unknown): boolean {\n\treturn Object.is(a, b)\n}\n\n/**\n * The comparator for one field kind. Scalars deserialize to primitives, so\n * identity is exact for them; structured kinds deserialize to fresh containers\n * and need a structural comparison.\n */\nfunction equalityForKind(kind: FieldKind): ValueEqual {\n\tswitch (kind) {\n\t\tcase 'string':\n\t\tcase 'number':\n\t\tcase 'boolean':\n\t\tcase 'timestamp':\n\t\tcase 'enum':\n\t\t\treturn scalarEqual\n\t\tcase 'array':\n\t\tcase 'object':\n\t\tcase 'json':\n\t\tcase 'blob':\n\t\tcase 'richtext':\n\t\tcase 'secret':\n\t\t\treturn structurallyEqual\n\t\tdefault:\n\t\t\treturn structurallyEqual\n\t}\n}\n\n/**\n * Build the result-set comparator for a collection's records: per schema field,\n * the comparator for its kind; for every other key (id, createdAt, updatedAt and\n * included relations) a structural comparison.\n *\n * @param fields - The collection's field descriptors\n * @returns A comparator that is true when both result sets hold the same records,\n *   in the same order, with structurally equal values\n */\nexport function createResultsEqual(fields: Record<string, FieldDescriptor>): ResultsEqual {\n\tconst perField = new Map<string, ValueEqual>()\n\tfor (const [name, descriptor] of Object.entries(fields)) {\n\t\tperField.set(name, equalityForKind(descriptor.kind))\n\t}\n\n\tconst recordEqual = (a: CollectionRecord, b: CollectionRecord): boolean => {\n\t\t// Structural sharing (instant-UI S3) hands the same row object to consecutive\n\t\t// results; identity is equality, and skips the field walk.\n\t\tif (a === b) return true\n\t\tconst recA = a as Record<string, unknown>\n\t\tconst recB = b as Record<string, unknown>\n\t\tconst keysA = Object.keys(recA)\n\t\tif (keysA.length !== Object.keys(recB).length) return false\n\t\tfor (const key of keysA) {\n\t\t\tif (!Object.hasOwn(recB, key)) return false\n\t\t\tconst eq = perField.get(key) ?? structurallyEqual\n\t\t\tif (!eq(recA[key], recB[key])) return false\n\t\t}\n\t\treturn true\n\t}\n\n\treturn (prev, next) => {\n\t\tif (prev === next) return true\n\t\tif (prev.length !== next.length) return false\n\t\t// Cheap pass first: a different id at any position means the set changed.\n\t\tfor (let i = 0; i < prev.length; i++) {\n\t\t\tif (prev[i]?.id !== next[i]?.id) return false\n\t\t}\n\t\tfor (let i = 0; i < prev.length; i++) {\n\t\t\tconst a = prev[i]\n\t\t\tconst b = next[i]\n\t\t\tif (a === undefined || b === undefined) return a === b\n\t\t\tif (!recordEqual(a, b)) return false\n\t\t}\n\t\treturn true\n\t}\n}\n\n/**\n * Comparator used when the collection's schema is unknown (a subscription\n * registered directly on the manager): structural comparison of every value.\n */\nexport const defaultResultsEqual: ResultsEqual = createResultsEqual({})\n","/**\n * Minimal pluralization/singularization utilities for relation name resolution.\n * Handles common English patterns — not meant to be exhaustive.\n */\n\nfunction isVowel(char: string | undefined): boolean {\n\tif (!char) return false\n\treturn 'aeiouAEIOU'.includes(char)\n}\n\n/**\n * Pluralize a word using common English rules.\n *\n * @example\n * ```\n * pluralize('project') // 'projects'\n * pluralize('category') // 'categories'\n * pluralize('match') // 'matches'\n * ```\n */\nexport function pluralize(word: string): string {\n\tif (word.endsWith('s')) return word\n\tif (word.endsWith('y') && !isVowel(word[word.length - 2])) {\n\t\treturn `${word.slice(0, -1)}ies`\n\t}\n\tif (word.endsWith('sh') || word.endsWith('ch') || word.endsWith('x') || word.endsWith('z')) {\n\t\treturn `${word}es`\n\t}\n\treturn `${word}s`\n}\n\n/**\n * Singularize a word using common English rules.\n *\n * @example\n * ```\n * singularize('projects') // 'project'\n * singularize('categories') // 'category'\n * singularize('matches') // 'match'\n * ```\n */\nexport function singularize(word: string): string {\n\tif (word.endsWith('ies') && !isVowel(word[word.length - 4])) {\n\t\treturn `${word.slice(0, -3)}y`\n\t}\n\tif (\n\t\tword.endsWith('shes') ||\n\t\tword.endsWith('ches') ||\n\t\tword.endsWith('xes') ||\n\t\tword.endsWith('zes')\n\t) {\n\t\treturn word.slice(0, -2)\n\t}\n\tif (word.endsWith('ses')) {\n\t\treturn word.slice(0, -2)\n\t}\n\tif (word.endsWith('s') && !word.endsWith('ss')) {\n\t\treturn word.slice(0, -1)\n\t}\n\treturn word\n}\n","import type { Operation, SchemaDefinition } from '@korajs/core'\nimport { KoraError, encodeStoredText, quoteIdent } from '@korajs/core'\nimport type { WriteEnv, WriteScope } from '../mutations/write-context'\nimport { writeDeleteInTx, writeUpdateInTx } from '../mutations/write-ops'\nimport type { Transaction } from '../types'\nimport type { IncomingRelation } from './relation-lookup'\nimport { buildRelationLookup, getIncomingRelations } from './relation-lookup'\n\n/**\n * Error thrown when a delete is refused due to a 'restrict' referential integrity policy.\n * The error includes context about which relation caused the restriction and\n * how many referencing records exist.\n */\nexport class ReferentialIntegrityError extends KoraError {\n\tconstructor(\n\t\tcollection: string,\n\t\trecordId: string,\n\t\treferencingCollection: string,\n\t\trelationName: string,\n\t\treferencingCount: number,\n\t) {\n\t\tsuper(\n\t\t\t`Cannot delete record \"${recordId}\" from \"${collection}\": ${referencingCount} record(s) in \"${referencingCollection}\" reference it via relation \"${relationName}\" with onDelete: 'restrict'. Delete or reassign the referencing records first.`,\n\t\t\t'REFERENTIAL_INTEGRITY',\n\t\t\t{\n\t\t\t\tcollection,\n\t\t\t\trecordId,\n\t\t\t\treferencingCollection,\n\t\t\t\trelationName,\n\t\t\t\treferencingCount,\n\t\t\t},\n\t\t)\n\t\tthis.name = 'ReferentialIntegrityError'\n\t}\n}\n\n/**\n * Configuration for the RelationEnforcer.\n */\nexport interface RelationEnforcerConfig {\n\tschema: SchemaDefinition\n}\n\n/**\n * Result of enforcing referential integrity on a delete operation.\n * Contains all additional operations that were created as side effects\n * (cascaded deletes and set-null updates).\n */\nexport interface EnforcementResult {\n\t/** Additional operations created by cascading deletes and set-null updates */\n\toperations: Operation[]\n}\n\n/**\n * Enforces referential integrity constraints during local delete operations.\n *\n * When a record is deleted, this enforcer checks all relations that reference\n * the deleted record's collection and applies the appropriate onDelete policy:\n *\n * - **cascade**: Recursively deletes all referencing records\n * - **set-null**: Sets the foreign key to null on all referencing records\n * - **restrict**: Throws a ReferentialIntegrityError if any references exist\n * - **no-action**: Does nothing (the foreign key is left dangling)\n *\n * The enforcer runs inside the delete's write transaction and writes every side\n * effect through the single local write path (`writeDeleteInTx` /\n * `writeUpdateInTx`), so cascaded operations reserve their sequence numbers in\n * the same contiguous block as the parent and carry per-field version stamps\n * (STORE-2, STORE-3). Every generated operation depends causally on the delete\n * that caused it.\n *\n * @example\n * ```typescript\n * const enforcer = new RelationEnforcer({ schema })\n * // inside a write transaction, after building the parent delete operation:\n * const result = await enforcer.enforceDelete('projects', 'proj-1', scope, env, deleteOp.id)\n * // result.operations contains any cascaded delete/update ops\n * ```\n */\nexport class RelationEnforcer {\n\tprivate readonly lookup: Map<string, IncomingRelation[]>\n\n\tconstructor(config: RelationEnforcerConfig) {\n\t\tthis.lookup = buildRelationLookup(config.schema)\n\t}\n\n\t/**\n\t * Enforce referential integrity for a record being deleted.\n\t *\n\t * @param collection - The collection the deleted record belongs to\n\t * @param recordId - The ID of the deleted record\n\t * @param scope - The active write scope (transaction + causal scope)\n\t * @param env - The write environment of the delete\n\t * @param parentOpId - Id of the delete operation; every side effect depends on it\n\t * @returns All additional operations created as side effects\n\t * @throws {ReferentialIntegrityError} If a 'restrict' policy is violated\n\t */\n\tasync enforceDelete(\n\t\tcollection: string,\n\t\trecordId: string,\n\t\tscope: WriteScope,\n\t\tenv: WriteEnv,\n\t\tparentOpId: string,\n\t): Promise<EnforcementResult> {\n\t\tconst incomingRelations = getIncomingRelations(this.lookup, collection)\n\t\tif (incomingRelations.length === 0) {\n\t\t\treturn { operations: [] }\n\t\t}\n\n\t\tconst allOperations: Operation[] = []\n\n\t\t// Process relations in a deterministic order (sorted by relation name)\n\t\t// to ensure identical results regardless of Map iteration order.\n\t\tconst sortedRelations = [...incomingRelations].sort((a, b) =>\n\t\t\ta.relationName.localeCompare(b.relationName),\n\t\t)\n\n\t\tfor (const incoming of sortedRelations) {\n\t\t\tconst ops = await this.enforceRelation(incoming, recordId, scope, env, parentOpId)\n\t\t\tallOperations.push(...ops)\n\t\t}\n\n\t\treturn { operations: allOperations }\n\t}\n\n\t/**\n\t * Enforce a single relation's onDelete policy.\n\t */\n\tprivate async enforceRelation(\n\t\tincoming: IncomingRelation,\n\t\tdeletedRecordId: string,\n\t\tscope: WriteScope,\n\t\tenv: WriteEnv,\n\t\tparentOpId: string,\n\t): Promise<Operation[]> {\n\t\tswitch (incoming.onDelete) {\n\t\t\tcase 'cascade':\n\t\t\t\treturn this.enforceCascade(incoming, deletedRecordId, scope, env, parentOpId)\n\t\t\tcase 'set-null':\n\t\t\t\treturn this.enforceSetNull(incoming, deletedRecordId, scope, env, parentOpId)\n\t\t\tcase 'restrict':\n\t\t\t\treturn this.enforceRestrict(incoming, deletedRecordId, scope.tx)\n\t\t\tcase 'no-action':\n\t\t\t\treturn []\n\t\t}\n\t}\n\n\t/**\n\t * Cascade: delete every live record that references the deleted record. Each\n\t * cascaded delete runs the full delete path, so it recurses into its own\n\t * referencing records.\n\t */\n\tprivate async enforceCascade(\n\t\tincoming: IncomingRelation,\n\t\tdeletedRecordId: string,\n\t\tscope: WriteScope,\n\t\tenv: WriteEnv,\n\t\tparentOpId: string,\n\t): Promise<Operation[]> {\n\t\tconst referencingIds = await this.findReferencing(incoming, deletedRecordId, scope.tx)\n\t\tconst operations: Operation[] = []\n\t\tfor (const id of referencingIds) {\n\t\t\tconst result = await writeDeleteInTx(env, scope, incoming.sourceCollection, id, {\n\t\t\t\textraCausalDeps: [parentOpId],\n\t\t\t})\n\t\t\tif (result.operation) operations.push(result.operation)\n\t\t\toperations.push(...result.sideEffects)\n\t\t}\n\t\treturn operations\n\t}\n\n\t/**\n\t * Set-null: set the foreign key to null on every live referencing record.\n\t */\n\tprivate async enforceSetNull(\n\t\tincoming: IncomingRelation,\n\t\tdeletedRecordId: string,\n\t\tscope: WriteScope,\n\t\tenv: WriteEnv,\n\t\tparentOpId: string,\n\t): Promise<Operation[]> {\n\t\tconst referencingIds = await this.findReferencing(incoming, deletedRecordId, scope.tx)\n\t\tconst operations: Operation[] = []\n\t\tfor (const id of referencingIds) {\n\t\t\tconst result = await writeUpdateInTx(\n\t\t\t\tenv,\n\t\t\t\tscope,\n\t\t\t\tincoming.sourceCollection,\n\t\t\t\tid,\n\t\t\t\t{ [incoming.foreignKeyField]: null },\n\t\t\t\t[parentOpId],\n\t\t\t)\n\t\t\tif (result.operation) operations.push(result.operation)\n\t\t}\n\t\treturn operations\n\t}\n\n\t/**\n\t * Restrict: refuse the delete if any referencing records exist.\n\t */\n\tprivate async enforceRestrict(\n\t\tincoming: IncomingRelation,\n\t\tdeletedRecordId: string,\n\t\ttx: Transaction,\n\t): Promise<Operation[]> {\n\t\tconst { sourceCollection, foreignKeyField, relationName } = incoming\n\n\t\tconst countRows = await tx.query<{ cnt: number }>(\n\t\t\t`SELECT COUNT(*) as cnt FROM ${quoteIdent(sourceCollection)} WHERE ${quoteIdent(foreignKeyField)} = ? AND _deleted = 0`,\n\t\t\t// The foreign key column holds the stored-text form (RT-65).\n\t\t\t[encodeStoredText(deletedRecordId)],\n\t\t)\n\t\tconst count = countRows[0]?.cnt ?? 0\n\n\t\tif (count > 0) {\n\t\t\tthrow new ReferentialIntegrityError(\n\t\t\t\tincoming.relation.to,\n\t\t\t\tdeletedRecordId,\n\t\t\t\tsourceCollection,\n\t\t\t\trelationName,\n\t\t\t\tcount,\n\t\t\t)\n\t\t}\n\n\t\treturn []\n\t}\n\n\t/** Ids of live records referencing `deletedRecordId`, in id order (deterministic). */\n\tprivate async findReferencing(\n\t\tincoming: IncomingRelation,\n\t\tdeletedRecordId: string,\n\t\ttx: Transaction,\n\t): Promise<string[]> {\n\t\tconst rows = await tx.query<{ id: string }>(\n\t\t\t`SELECT id FROM ${quoteIdent(incoming.sourceCollection)} WHERE ${quoteIdent(incoming.foreignKeyField)} = ? AND _deleted = 0 ORDER BY id`,\n\t\t\t// The foreign key column holds the stored-text form (RT-65).\n\t\t\t[encodeStoredText(deletedRecordId)],\n\t\t)\n\t\treturn rows.map((row) => row.id)\n\t}\n\n\t/**\n\t * Get the relation lookup map for external use (e.g., by the merge engine).\n\t */\n\tgetRelationLookup(): Map<string, IncomingRelation[]> {\n\t\treturn this.lookup\n\t}\n}\n","import type { OnDeleteAction, RelationDefinition, SchemaDefinition } from '@korajs/core'\n\n/**\n * A resolved relation reference: describes a relation that points TO a given collection.\n * When a record in `targetCollection` is deleted, we must handle records in\n * `sourceCollection` that reference it via `foreignKeyField`.\n */\nexport interface IncomingRelation {\n\t/** Name of the relation in the schema */\n\trelationName: string\n\t/** Collection that holds the foreign key (the \"from\" side) */\n\tsourceCollection: string\n\t/** Field in the source collection that references the target */\n\tforeignKeyField: string\n\t/** What to do when the referenced record is deleted */\n\tonDelete: OnDeleteAction\n\t/** The full relation definition */\n\trelation: RelationDefinition\n}\n\n/**\n * Builds an efficient lookup from target collection to all relations that reference it.\n *\n * Given a schema with relations like:\n * ```\n * todoBelongsToProject: { from: 'todos', to: 'projects', field: 'projectId', onDelete: 'cascade' }\n * ```\n *\n * The lookup for 'projects' would return:\n * ```\n * [{ sourceCollection: 'todos', foreignKeyField: 'projectId', onDelete: 'cascade', ... }]\n * ```\n *\n * This enables O(1) lookup when deleting a record to find all dependent relations.\n *\n * @param schema - The full schema definition containing relations\n * @returns A map from target collection name to its incoming relations\n */\nexport function buildRelationLookup(schema: SchemaDefinition): Map<string, IncomingRelation[]> {\n\tconst lookup = new Map<string, IncomingRelation[]>()\n\n\tfor (const [relationName, relation] of Object.entries(schema.relations)) {\n\t\tconst targetCollection = relation.to\n\t\tconst existing = lookup.get(targetCollection) ?? []\n\t\texisting.push({\n\t\t\trelationName,\n\t\t\tsourceCollection: relation.from,\n\t\t\tforeignKeyField: relation.field,\n\t\t\tonDelete: relation.onDelete,\n\t\t\trelation,\n\t\t})\n\t\tlookup.set(targetCollection, existing)\n\t}\n\n\treturn lookup\n}\n\n/**\n * Get all incoming relations for a given collection.\n * Returns an empty array if no relations reference the collection.\n *\n * @param lookup - The pre-built relation lookup map\n * @param collection - The target collection name\n * @returns Array of incoming relations\n */\nexport function getIncomingRelations(\n\tlookup: Map<string, IncomingRelation[]>,\n\tcollection: string,\n): IncomingRelation[] {\n\treturn lookup.get(collection) ?? []\n}\n","import {\n\tHybridLogicalClock,\n\tOperationError,\n\tfoldRecord,\n\tisFoldStateLive,\n\tmaterialize,\n} from '@korajs/core'\nimport type {\n\tCollectionDefinition,\n\tOperation,\n\tOperationTransform,\n\tSchemaDefinition,\n} from '@korajs/core'\nimport { topologicalSort } from '@korajs/core/internal'\nimport { mergeYjsUpdates } from '../fold/record-folder'\nimport { decodeRichtextFieldsFromOpData } from '../serialization/op-data-encoding'\nimport type { CollectionRecord } from '../types'\n\n/**\n * In-memory materialized state at a causal cut in the operation log.\n * Read-only — does not mutate the live store.\n */\nexport interface ReplaySnapshot {\n\t/** The operation whose causal past was replayed (inclusive). */\n\ttargetOperation: Operation\n\t/** Operations applied in causal order (ancestors + target). */\n\toperationsApplied: Operation[]\n\t/** Non-deleted records per collection after replay. */\n\tcollections: Record<string, CollectionRecord[]>\n\t/** Look up a single record at the replay cut. Returns null if deleted or missing. */\n\tfindRecord(collection: string, recordId: string): CollectionRecord | null\n}\n\ninterface MutableReplayRecord {\n\tid: string\n\tfields: Record<string, unknown>\n\tdeleted: boolean\n\tcreatedAt: number\n\tupdatedAt: number\n}\n\ntype ReplayMemoryState = Map<string, Map<string, MutableReplayRecord>>\n\n/**\n * Collect the target operation and all causal ancestors present in `allOps`.\n *\n * @param aliases - Old operation id -> the id it was re-emitted under (a renumbered\n *   version-2 operation, `_kora_seq_conflicts.reemitted_as`). A dependent the server\n *   already stored keeps naming the old id; the alias resolves it.\n */\nexport function collectCausalClosure(\n\tallOps: Operation[],\n\ttargetOperationId: string,\n\taliases: ReadonlyMap<string, string> = new Map(),\n): Operation[] {\n\tconst opMap = new Map<string, Operation>()\n\tfor (const op of allOps) {\n\t\topMap.set(op.id, op)\n\t}\n\n\tconst target = opMap.get(targetOperationId)\n\tif (!target) {\n\t\tthrow new OperationError(\n\t\t\t`Operation \"${targetOperationId}\" not found in the local operation log`,\n\t\t\t{\n\t\t\t\toperationId: targetOperationId,\n\t\t\t},\n\t\t)\n\t}\n\n\tconst included = new Set<string>()\n\tconst stack: string[] = [targetOperationId]\n\n\twhile (stack.length > 0) {\n\t\tconst id = stack.pop()\n\t\tif (id === undefined || included.has(id)) {\n\t\t\tcontinue\n\t\t}\n\t\tincluded.add(id)\n\t\tconst op = opMap.get(id)\n\t\tif (!op) {\n\t\t\tcontinue\n\t\t}\n\t\tfor (const dep of op.causalDeps) {\n\t\t\tlet depId = dep\n\t\t\t// Follow re-emissions (a renumbered op may itself have been renumbered again).\n\t\t\tfor (let hops = 0; !opMap.has(depId) && aliases.has(depId) && hops < 8; hops++) {\n\t\t\t\tdepId = aliases.get(depId) ?? depId\n\t\t\t}\n\t\t\tif (opMap.has(depId)) {\n\t\t\t\tstack.push(depId)\n\t\t\t}\n\t\t}\n\t}\n\n\tconst subset = allOps.filter((op) => included.has(op.id))\n\treturn topologicalSort(subset)\n}\n\n/**\n * Replay a causal subset of operations into an in-memory materialized snapshot.\n * Does not use the merge engine — concurrent ops outside the causal cut are excluded.\n */\nexport function buildReplaySnapshot(\n\tschema: SchemaDefinition,\n\tallOps: Operation[],\n\ttargetOperationId: string,\n\taliases: ReadonlyMap<string, string> = new Map(),\n\ttransforms: readonly OperationTransform[] = [],\n): ReplaySnapshot {\n\tconst operationsApplied = collectCausalClosure(allOps, targetOperationId, aliases)\n\tconst targetOperation = operationsApplied.find((op) => op.id === targetOperationId)\n\tif (!targetOperation) {\n\t\tthrow new OperationError(`Operation \"${targetOperationId}\" not found after causal sort`, {\n\t\t\toperationId: targetOperationId,\n\t\t})\n\t}\n\n\tconst memory = foldIntoMemory(operationsApplied, schema, transforms)\n\n\tconst collections = materializeCollections(schema, memory)\n\n\treturn {\n\t\ttargetOperation,\n\t\toperationsApplied,\n\t\tcollections,\n\t\tfindRecord(collection: string, recordId: string): CollectionRecord | null {\n\t\t\tconst colMap = memory.get(collection)\n\t\t\tconst record = colMap?.get(recordId)\n\t\t\tif (!record || record.deleted) {\n\t\t\t\treturn null\n\t\t\t}\n\t\t\tconst definition = schema.collections[collection]\n\t\t\tif (!definition) {\n\t\t\t\treturn null\n\t\t\t}\n\t\t\treturn toCollectionRecord(record, definition)\n\t\t},\n\t}\n}\n\n/**\n * Fold every record of the causal cut with the W7 fold, exactly as the live store\n * materializes it (the cut may hold concurrent branches: the fold, not the\n * application order, decides).\n */\nfunction foldIntoMemory(\n\tops: readonly Operation[],\n\tschema: SchemaDefinition,\n\ttransforms: readonly OperationTransform[],\n): ReplayMemoryState {\n\tconst byRecord = new Map<string, Operation[]>()\n\tfor (const op of ops) {\n\t\tif (!schema.collections[op.collection]) continue\n\t\tconst key = `${op.collection}\\u0000${op.recordId}`\n\t\tconst list = byRecord.get(key) ?? []\n\t\tlist.push(op)\n\t\tbyRecord.set(key, list)\n\t}\n\tconst state: ReplayMemoryState = new Map()\n\tfor (const recordOps of byRecord.values()) {\n\t\tconst first = recordOps[0] as Operation\n\t\tconst definition = schema.collections[first.collection] as CollectionDefinition\n\t\t// The live store folds with the schema transforms (RT-84): so does time travel.\n\t\tconst folded = foldRecord(recordOps, schema, {\n\t\t\trichtext: mergeYjsUpdates,\n\t\t\t...(transforms.length > 0 ? { transforms } : {}),\n\t\t}).state\n\t\tif (folded === null || folded.cr === null || folded.u === null) continue\n\t\tconst values = materialize({ ...folded, d: null }, { richtext: mergeYjsUpdates }) ?? {}\n\t\tlet colMap = state.get(first.collection)\n\t\tif (!colMap) {\n\t\t\tcolMap = new Map()\n\t\t\tstate.set(first.collection, colMap)\n\t\t}\n\t\tcolMap.set(first.recordId, {\n\t\t\tid: first.recordId,\n\t\t\t// The fold materializes op-data form (tagged binary); snapshots expose\n\t\t\t// record-shaped values (Uint8Array / string).\n\t\t\tfields: decodeRichtextFieldsFromOpData(values, definition.fields),\n\t\t\tdeleted: !isFoldStateLive(folded),\n\t\t\tcreatedAt: HybridLogicalClock.deserialize(folded.cr.t).wallTime,\n\t\t\tupdatedAt: HybridLogicalClock.deserialize(folded.u.t).wallTime,\n\t\t})\n\t}\n\treturn state\n}\n\nfunction materializeCollections(\n\tschema: SchemaDefinition,\n\tmemory: ReplayMemoryState,\n): Record<string, CollectionRecord[]> {\n\tconst collections: Record<string, CollectionRecord[]> = {}\n\n\tfor (const [collectionName, definition] of Object.entries(schema.collections)) {\n\t\tconst colMap = memory.get(collectionName)\n\t\tconst records: CollectionRecord[] = []\n\t\tif (colMap) {\n\t\t\tfor (const record of colMap.values()) {\n\t\t\t\tif (!record.deleted) {\n\t\t\t\t\trecords.push(toCollectionRecord(record, definition))\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\tcollections[collectionName] = records\n\t}\n\n\treturn collections\n}\n\nfunction toCollectionRecord(\n\trecord: MutableReplayRecord,\n\tdefinition: CollectionDefinition,\n): CollectionRecord {\n\tconst result: CollectionRecord = {\n\t\tid: record.id,\n\t\tcreatedAt: record.createdAt,\n\t\tupdatedAt: record.updatedAt,\n\t}\n\tfor (const [fieldName] of Object.entries(definition.fields)) {\n\t\tif (fieldName in record.fields) {\n\t\t\tresult[fieldName] = record.fields[fieldName]\n\t\t}\n\t}\n\treturn result\n}\n","import { createSnapshotState } from '@korajs/core'\nimport type { FieldDescriptor, HLCTimestamp, SchemaDefinition } from '@korajs/core'\nimport { quoteIdent } from '@korajs/core'\nimport {\n\tFOLD_BASE_TABLE,\n\tFOLD_SNAPSHOT_TABLE,\n\tFOLD_STATE_TABLE,\n\tPROVISIONAL_OPS_TABLE,\n\ttype RecordFolder,\n} from '../fold/record-folder'\nimport type { Transaction } from '../types'\n\n/**\n * Seeds (`docs/design/first-visit-parity.md` 5.2): records a read-through\n * answer showed, kept so the device can answer the same queries from its own database before\n * replication has delivered them.\n *\n * A seed is a row snapshot (RT-68) marked in `_kora_seed` with the server frontier it was read at.\n * It is no operation: it has no log entry, no sequence number and is never uploaded. The merge\n * of the staging replica deletes every seed (5.7.4), so the replica that results is exactly\n * what replication alone would have produced.\n */\n\n/** Local-only table marking which row snapshots are seeds. */\nexport const SEED_TABLE = '_kora_seed'\n\n/** DDL of {@link SEED_TABLE}. Idempotent. */\nexport const SEED_TABLE_DDL = `CREATE TABLE IF NOT EXISTS ${SEED_TABLE} (collection TEXT NOT NULL, record_id TEXT NOT NULL, frontier INTEGER NOT NULL, grant_key TEXT NOT NULL, PRIMARY KEY (collection, record_id))`\n\n/** One record to seed: a read-through answer's record in the delivery wire form. */\nexport interface SeedInput {\n\tcollection: string\n\tid: string\n\t/** The schema fields, as a scope entry carries them (binary as `{ $koraBytes }`). */\n\tvalues: Record<string, unknown>\n\t/** The HLC of the write that produced each field's current value. */\n\tfieldVersions: Record<string, HLCTimestamp>\n\tcreated: HLCTimestamp\n\tlatest: HLCTimestamp\n}\n\n/** What the answer was read at. */\nexport interface SeedMeta {\n\t/** The server's delivery counter after the rows were read. */\n\tfrontier: number\n\t/** Hash of the grant the rows were read under. */\n\tgrantKey: string\n}\n\n/** Why a record was not seeded. Nothing is dropped silently: each skip is reported. */\nexport type SeedSkipReason =\n\t/** The collection is not in the schema. */\n\t| 'unknown-collection'\n\t/** The record has history here (operations, fold state, an ordinary snapshot): the store is authoritative. */\n\t| 'has-history'\n\t/** An array holds repeated values: a snapshot cannot say which copy a later local edit removes. */\n\t| 'array-duplicates'\n\t/** The clock refused the record's timestamp (invalid, or too far ahead). */\n\t| 'clock-refused'\n\t/** The record already has a seed read at the same or a later frontier. */\n\t| 'not-newer'\n\t/** This database does not fold records (a legacy-materialized database): it cannot hold seeds. */\n\t| 'fold-inactive'\n\n/** The result of seeding. */\nexport interface SeedOutcome {\n\tseeded: Array<{ collection: string; id: string }>\n\tskipped: Array<{ collection: string; id: string; reason: SeedSkipReason }>\n}\n\n/** A seed marker. */\nexport interface SeedRow {\n\tcollection: string\n\trecordId: string\n\tfrontier: number\n\tgrantKey: string\n}\n\n/**\n * Seed records inside `tx`.\n *\n * @param tx - The write transaction\n * @param folder - The store's record folder\n * @param schema - The schema\n * @param inputs - Records of an answer\n * @param meta - The frontier and grant the answer was read at\n * @param receive - Advances the clock past a record's newest timestamp; false when it is refused\n */\nexport async function seedRecordsInTx(\n\ttx: Transaction,\n\tfolder: RecordFolder,\n\tschema: SchemaDefinition,\n\tinputs: readonly SeedInput[],\n\tmeta: SeedMeta,\n\treceive: (timestamp: HLCTimestamp) => boolean,\n): Promise<SeedOutcome> {\n\tconst outcome: SeedOutcome = { seeded: [], skipped: [] }\n\tfor (const input of inputs) {\n\t\tconst skip = (reason: SeedSkipReason): void => {\n\t\t\toutcome.skipped.push({ collection: input.collection, id: input.id, reason })\n\t\t}\n\t\tconst definition = schema.collections[input.collection]\n\t\tif (definition === undefined) {\n\t\t\tskip('unknown-collection')\n\t\t\tcontinue\n\t\t}\n\t\tif (hasRepeatedArrayValue(input.values, definition.fields)) {\n\t\t\tskip('array-duplicates')\n\t\t\tcontinue\n\t\t}\n\t\tconst existing = await tx.query<{ frontier: number }>(\n\t\t\t`SELECT frontier FROM ${SEED_TABLE} WHERE collection = ? AND record_id = ?`,\n\t\t\t[input.collection, input.id],\n\t\t)\n\t\tconst previous = existing[0]\n\t\tif (previous !== undefined) {\n\t\t\tif (meta.frontier <= previous.frontier) {\n\t\t\t\tskip('not-newer')\n\t\t\t\tcontinue\n\t\t\t}\n\t\t} else if (await hasHistory(tx, input.collection, input.id)) {\n\t\t\tskip('has-history')\n\t\t\tcontinue\n\t\t}\n\t\tif (!receive(input.latest)) {\n\t\t\tskip('clock-refused')\n\t\t\tcontinue\n\t\t}\n\t\tconst snapshot = createSnapshotState(\n\t\t\t{\n\t\t\t\tcollection: input.collection,\n\t\t\t\trecordId: input.id,\n\t\t\t\tvalues: input.values,\n\t\t\t\tfieldVersions: input.fieldVersions,\n\t\t\t\tcreated: input.created,\n\t\t\t\tlatest: input.latest,\n\t\t\t\tdeleted: false,\n\t\t\t},\n\t\t\tschema,\n\t\t)\n\t\t// A newer answer replaces the older snapshot: joining the two could not remove an element\n\t\t// the newer answer no longer shows.\n\t\tawait tx.execute(`DELETE FROM ${FOLD_SNAPSHOT_TABLE} WHERE collection = ? AND record_id = ?`, [\n\t\t\tinput.collection,\n\t\t\tinput.id,\n\t\t])\n\t\tawait folder.saveSnapshot(tx, snapshot)\n\t\tawait tx.execute(\n\t\t\t`INSERT OR REPLACE INTO ${SEED_TABLE} (collection, record_id, frontier, grant_key) VALUES (?, ?, ?, ?)`,\n\t\t\t[input.collection, input.id, meta.frontier, meta.grantKey],\n\t\t)\n\t\tawait folder.refoldInTx(tx, input.collection, input.id)\n\t\toutcome.seeded.push({ collection: input.collection, id: input.id })\n\t}\n\treturn outcome\n}\n\n/** What {@link purgeSeedsInTx} did. */\nexport interface PurgeOutcome {\n\t/** Seeds whose record was removed: the device had never written to it. */\n\tremoved: SeedRow[]\n\t/**\n\t * Seeds the device has written to. The seed marker is gone but the snapshot stays as an\n\t * ordinary row snapshot (RT-68), because without it the record would have no insert and\n\t * the user's own edit would disappear. The caller settles it once the record's real history\n\t * arrives (the merge replays the staged operations), or keeps it and reports it orphaned\n\t * (`read:seed-orphaned`) when none does.\n\t */\n\tretained: SeedRow[]\n}\n\n/**\n * Delete seeds inside `tx` (every seed, or those of `only`).\n *\n * @returns Which seeds were removed with their record and which were retained for local writes\n */\nexport async function purgeSeedsInTx(\n\ttx: Transaction,\n\tonly?: ReadonlyArray<{ collection: string; recordId: string }>,\n\toptions: { writtenSeeds?: 'keep-snapshot' | 'leave' } = {},\n): Promise<PurgeOutcome> {\n\tconst all = await listSeedsInTx(tx)\n\tconst wanted =\n\t\tonly === undefined ? null : new Set(only.map((r) => `${r.collection}\\u0000${r.recordId}`))\n\tconst outcome: PurgeOutcome = { removed: [], retained: [] }\n\tfor (const seed of all) {\n\t\tif (wanted !== null && !wanted.has(`${seed.collection}\\u0000${seed.recordId}`)) continue\n\t\tconst ops = await tx.query<{ n: number }>(\n\t\t\t`SELECT COUNT(*) AS n FROM ${quoteIdent(`_kora_ops_${seed.collection}`)} WHERE record_id = ?`,\n\t\t\t[seed.recordId],\n\t\t)\n\t\t// `leave`: a seed the device wrote to stays exactly as it is (its marker too).\n\t\tif ((ops[0]?.n ?? 0) > 0 && options.writtenSeeds === 'leave') continue\n\t\tawait tx.execute(`DELETE FROM ${SEED_TABLE} WHERE collection = ? AND record_id = ?`, [\n\t\t\tseed.collection,\n\t\t\tseed.recordId,\n\t\t])\n\t\tif ((ops[0]?.n ?? 0) > 0) {\n\t\t\toutcome.retained.push(seed)\n\t\t\tcontinue\n\t\t}\n\t\tawait tx.execute(`DELETE FROM ${FOLD_SNAPSHOT_TABLE} WHERE collection = ? AND record_id = ?`, [\n\t\t\tseed.collection,\n\t\t\tseed.recordId,\n\t\t])\n\t\tawait tx.execute(`DELETE FROM ${FOLD_STATE_TABLE} WHERE collection = ? AND record_id = ?`, [\n\t\t\tseed.collection,\n\t\t\tseed.recordId,\n\t\t])\n\t\tawait tx.execute(`DELETE FROM ${quoteIdent(seed.collection)} WHERE id = ?`, [seed.recordId])\n\t\toutcome.removed.push(seed)\n\t}\n\treturn outcome\n}\n\n/** Every seed marker. */\nexport async function listSeedsInTx(tx: Transaction): Promise<SeedRow[]> {\n\tconst rows = await tx.query<{\n\t\tcollection: string\n\t\trecord_id: string\n\t\tfrontier: number\n\t\tgrant_key: string\n\t}>(\n\t\t`SELECT collection, record_id, frontier, grant_key FROM ${SEED_TABLE} ORDER BY collection, record_id`,\n\t)\n\treturn rows.map((row) => ({\n\t\tcollection: row.collection,\n\t\trecordId: row.record_id,\n\t\tfrontier: row.frontier,\n\t\tgrantKey: row.grant_key,\n\t}))\n}\n\n/** True when the database holds anything of the record that is not a seed. */\nasync function hasHistory(tx: Transaction, collection: string, id: string): Promise<boolean> {\n\tconst found = await tx.query<{ n: number }>(\n\t\t`SELECT (SELECT COUNT(*) FROM ${quoteIdent(`_kora_ops_${collection}`)} WHERE record_id = ?)\n     + (SELECT COUNT(*) FROM ${FOLD_STATE_TABLE} WHERE collection = ? AND record_id = ?)\n     + (SELECT COUNT(*) FROM ${FOLD_BASE_TABLE} WHERE collection = ? AND record_id = ?)\n     + (SELECT COUNT(*) FROM ${FOLD_SNAPSHOT_TABLE} WHERE collection = ? AND record_id = ?)\n     + (SELECT COUNT(*) FROM ${PROVISIONAL_OPS_TABLE} WHERE collection = ? AND record_id = ?)\n     + (SELECT COUNT(*) FROM _kora_scope_retractions WHERE collection = ? AND record_id = ?)\n     + (SELECT COUNT(*) FROM ${quoteIdent(collection)} WHERE id = ?) AS n`,\n\t\t[id, collection, id, collection, id, collection, id, collection, id, collection, id, id],\n\t)\n\treturn (found[0]?.n ?? 0) > 0\n}\n\nfunction hasRepeatedArrayValue(\n\tvalues: Record<string, unknown>,\n\tfields: Record<string, FieldDescriptor>,\n): boolean {\n\tfor (const [name, descriptor] of Object.entries(fields)) {\n\t\tif (descriptor.kind !== 'array') continue\n\t\tconst value = values[name]\n\t\tif (!Array.isArray(value)) continue\n\t\tconst seen = new Set<string>()\n\t\tfor (const element of value) {\n\t\t\tconst key = JSON.stringify(element)\n\t\t\tif (seen.has(key)) return true\n\t\t\tseen.add(key)\n\t\t}\n\t}\n\treturn false\n}\n","import type { SequenceConfig } from '@korajs/core'\nimport { defaultSequenceFormat, formatSequenceValue } from '@korajs/core'\nimport type { StorageAdapter } from '../types'\n\ninterface SequenceRow {\n\tcounter: number\n}\n\n/**\n * Manages offline-safe sequences backed by a `_kora_sequences` table.\n *\n * Each sequence counter is scoped by (name, scope, nodeId), ensuring\n * that different devices never collide. The counter is atomically\n * incremented within a database transaction.\n *\n * @example\n * ```typescript\n * const mgr = new SequenceManager(adapter, 'node-abc')\n *\n * const receipt = await mgr.next('receipt', {\n *   scope: 'store-1',\n *   format: 'S-{date}-{node4}-{seq}',\n * })\n * // → \"S-20260508-node-0001\"\n * ```\n */\nexport class SequenceManager {\n\tprivate readonly adapter: StorageAdapter\n\tprivate readonly nodeId: string\n\n\tconstructor(adapter: StorageAdapter, nodeId: string) {\n\t\tthis.adapter = adapter\n\t\tthis.nodeId = nodeId\n\t}\n\n\t/**\n\t * Get the next value in a sequence, atomically incrementing the counter.\n\t *\n\t * @param name - The sequence name (e.g., 'receipt', 'invoice')\n\t * @param config - Optional configuration for scope, format, and starting value\n\t * @returns The formatted sequence value\n\t */\n\tasync next(name: string, config?: SequenceConfig): Promise<string> {\n\t\tconst scope = config?.scope ?? ''\n\t\tconst startAt = config?.startAt ?? 1\n\t\tconst format = config?.format ?? defaultSequenceFormat(name)\n\n\t\tlet counter = 0\n\n\t\tawait this.adapter.transaction(async (tx) => {\n\t\t\t// Try to read the current counter\n\t\t\tconst rows = await tx.query<SequenceRow>(\n\t\t\t\t'SELECT counter FROM _kora_sequences WHERE name = ? AND scope = ? AND node_id = ?',\n\t\t\t\t[name, scope, this.nodeId],\n\t\t\t)\n\n\t\t\tif (rows.length > 0) {\n\t\t\t\tconst row = rows[0] as SequenceRow\n\t\t\t\tcounter = row.counter + 1\n\t\t\t\tawait tx.execute(\n\t\t\t\t\t'UPDATE _kora_sequences SET counter = ? WHERE name = ? AND scope = ? AND node_id = ?',\n\t\t\t\t\t[counter, name, scope, this.nodeId],\n\t\t\t\t)\n\t\t\t} else {\n\t\t\t\t// First use — initialize with startAt\n\t\t\t\tcounter = startAt\n\t\t\t\tawait tx.execute(\n\t\t\t\t\t'INSERT INTO _kora_sequences (name, scope, node_id, counter) VALUES (?, ?, ?, ?)',\n\t\t\t\t\t[name, scope, this.nodeId, counter],\n\t\t\t\t)\n\t\t\t}\n\t\t})\n\n\t\treturn formatSequenceValue(format, counter, this.nodeId)\n\t}\n\n\t/**\n\t * Get the current counter value without incrementing.\n\t *\n\t * @param name - The sequence name\n\t * @param config - Optional scope\n\t * @returns The current counter value, or 0 if the sequence has never been used\n\t */\n\tasync current(name: string, config?: { scope?: string }): Promise<number> {\n\t\tconst scope = config?.scope ?? ''\n\n\t\tconst rows = await this.adapter.query<SequenceRow>(\n\t\t\t'SELECT counter FROM _kora_sequences WHERE name = ? AND scope = ? AND node_id = ?',\n\t\t\t[name, scope, this.nodeId],\n\t\t)\n\n\t\tif (rows.length > 0) {\n\t\t\treturn (rows[0] as SequenceRow).counter\n\t\t}\n\t\treturn 0\n\t}\n\n\t/**\n\t * Reset a sequence counter.\n\t *\n\t * @param name - The sequence name\n\t * @param config - Optional scope and target value\n\t */\n\tasync reset(name: string, config?: { scope?: string; to?: number }): Promise<void> {\n\t\tconst scope = config?.scope ?? ''\n\t\tconst to = config?.to ?? 0\n\n\t\t// One transaction: a next() issued meanwhile must not run between the delete and\n\t\t// the insert (it would recreate the row and the insert would fail), and a crash\n\t\t// between them must not leave the counter half reset.\n\t\tawait this.adapter.transaction(async (tx) => {\n\t\t\tawait tx.execute('DELETE FROM _kora_sequences WHERE name = ? AND scope = ? AND node_id = ?', [\n\t\t\t\tname,\n\t\t\t\tscope,\n\t\t\t\tthis.nodeId,\n\t\t\t])\n\t\t\tif (to > 0) {\n\t\t\t\tawait tx.execute(\n\t\t\t\t\t'INSERT INTO _kora_sequences (name, scope, node_id, counter) VALUES (?, ?, ?, ?)',\n\t\t\t\t\t[name, scope, this.nodeId, to],\n\t\t\t\t)\n\t\t\t}\n\t\t})\n\t}\n}\n","import { quoteIdent } from '@korajs/core'\nimport type { SchemaDefinition } from '@korajs/core'\nimport type { StorageAdapter } from '../types'\nimport { isRawTextKind } from './serializer'\n\n/** `_kora_meta` key: raw-string columns hold the stored-text codec's form (RT-65). */\nexport const STORED_TEXT_CODEC_META_KEY = 'stored_text_codec'\n\n/** Version of the codec the rows are written with. */\nconst STORED_TEXT_CODEC_VERSION = '1'\n\n/**\n * Once per database: re-encode the U+FFFF of rows written before the stored-text codec\n * (RT-65) so the decoder returns them unchanged. A row written before the codec holds\n * the raw string; the only code unit whose meaning changes under the decoder is the\n * escape introducer U+FFFF (`U+FFFF` -> `U+FFFF F`). NUL needs no rewrite (better-sqlite3\n * stored it as is), and a lone surrogate a pre-codec row held was already replaced by\n * U+FFFD when it was bound, so nothing is left to recover.\n *\n * Every collection table of the schema that exists is rewritten, for the columns of its\n * raw-string fields that exist. One transaction; the meta key makes it idempotent.\n *\n * @param adapter - An open storage adapter\n * @param schema - The schema whose collection tables to migrate\n */\nexport async function ensureStoredTextCodec(\n\tadapter: StorageAdapter,\n\tschema: SchemaDefinition,\n): Promise<void> {\n\tconst rows = await adapter.query<{ value: string }>(\n\t\t'SELECT value FROM _kora_meta WHERE key = ?',\n\t\t[STORED_TEXT_CODEC_META_KEY],\n\t)\n\tif (rows[0]?.value === STORED_TEXT_CODEC_VERSION) return\n\tawait adapter.transaction(async (tx) => {\n\t\tfor (const [name, collection] of Object.entries(schema.collections)) {\n\t\t\tconst columns = new Set(\n\t\t\t\t(await tx.query<{ name: string }>(`PRAGMA table_info(${quoteIdent(name)})`)).map(\n\t\t\t\t\t(column) => column.name,\n\t\t\t\t),\n\t\t\t)\n\t\t\tif (columns.size === 0) continue\n\t\t\tfor (const [field, descriptor] of Object.entries(collection.fields)) {\n\t\t\t\tif (!isRawTextKind(descriptor.kind) || !columns.has(field)) continue\n\t\t\t\tconst column = quoteIdent(field)\n\t\t\t\tawait tx.execute(\n\t\t\t\t\t`UPDATE ${quoteIdent(name)} SET ${column} = replace(${column}, char(65535), char(65535) || 'F') WHERE instr(${column}, char(65535)) > 0`,\n\t\t\t\t)\n\t\t\t}\n\t\t}\n\t\tawait tx.execute('INSERT OR REPLACE INTO _kora_meta (key, value) VALUES (?, ?)', [\n\t\t\tSTORED_TEXT_CODEC_META_KEY,\n\t\t\tSTORED_TEXT_CODEC_VERSION,\n\t\t])\n\t})\n}\n","import type {\n\tKoraEvent,\n\tKoraEventByType,\n\tKoraEventEmitter,\n\tKoraEventListener,\n\tKoraEventType,\n\tOfflineCompletion,\n\tOperation,\n} from '@korajs/core'\nimport { SimpleEventEmitter } from '@korajs/core/internal'\nimport { saveDeliveryWatermarkInTx } from '../sync/sync-state'\nimport type { StorageAdapter } from '../types'\nimport { type StagingMergeHost, type StagingMergeResult, mergeStagingInto } from './staging-merge'\n\n/**\n * Most `operation:applied` events kept for replay (memory bound: each holds its operation).\n * Beyond it they are counted, and the count is reported with the merge, never lost silently.\n */\nconst MAX_APPLIED_EVENTS = 20_000\n/**\n * Most merge, constraint and other events kept. They are what DevTools and the app's conflict\n * handling rely on, so they have their own, larger budget and are never displaced by applies.\n */\nconst MAX_OTHER_EVENTS = 50_000\n/** Events replayed to the live listeners before yielding to the event loop. */\nconst REPLAY_SLICE = 100\n/** How long `discard()` waits for a running merge chunk to end before closing under it. */\nconst MERGE_CANCEL_WAIT_MS = 10_000\n\n/** `collection\\0recordId` of the record an event is about, or null (connection-level events). */\nfunction recordKeyOf(event: KoraEvent): string | null {\n\tconst candidate = event as unknown as {\n\t\toperation?: { collection?: string; recordId?: string }\n\t\toperationA?: { collection?: string; recordId?: string }\n\t\ttrace?: { operationA?: { collection?: string; recordId?: string } }\n\t}\n\tconst operation = candidate.operation ?? candidate.operationA ?? candidate.trace?.operationA\n\tif (!operation?.collection || !operation.recordId) return null\n\treturn `${operation.collection}\\u0000${operation.recordId}`\n}\n\n/** What replaying a buffer did. */\nexport interface ReplicaEventFlush {\n\t/** Events not kept at the caps, by event type (reported, never silently dropped). */\n\tsummarized: Record<string, number>\n\t/** Listener exceptions caught while replaying (a listener must not undo a committed merge). */\n\tlistenerErrors: number\n}\n\n/**\n * The events of a replica's applies (operation applied, merge traces, constraint reports).\n * The replica's operations are not in the live database yet, so nothing is published about\n * them: the events are kept and replayed in order to the live listeners once the merge has\n * committed (\"events after commit only\"), in slices so replaying cannot stall the page.\n * Applies and the rarer, more important merge/constraint events have separate budgets;\n * what exceeds a budget is counted by type and reported with the merge. `query:*` events are\n * not kept (nothing subscribes to the replica; the merge invalidates the live queries itself)\n * and a storage failure of the replica is reported at once.\n */\nexport class ReplicaEventBuffer implements KoraEventEmitter {\n\tprivate readonly inner = new SimpleEventEmitter()\n\tprivate events: KoraEvent[] = []\n\tprivate appliedKept = 0\n\tprivate otherKept = 0\n\tprivate summarized: Record<string, number> = {}\n\n\tconstructor(private readonly live: KoraEventEmitter | null) {}\n\n\ton<T extends KoraEventType>(type: T, listener: KoraEventListener<T>): () => void {\n\t\treturn this.inner.on(type, listener)\n\t}\n\n\toff<T extends KoraEventType>(type: T, listener: KoraEventListener<T>): void {\n\t\tthis.inner.off(type, listener)\n\t}\n\n\temit<T extends KoraEventType>(event: KoraEventByType<T>): void {\n\t\tthis.inner.emit(event)\n\t\tif (event.type === 'store:persistence-error') {\n\t\t\tthis.live?.emit(event)\n\t\t\treturn\n\t\t}\n\t\tif (event.type.startsWith('query:')) return\n\t\tconst applied = event.type === 'operation:applied'\n\t\tif (applied ? this.appliedKept < MAX_APPLIED_EVENTS : this.otherKept < MAX_OTHER_EVENTS) {\n\t\t\tthis.events.push(event)\n\t\t\tif (applied) this.appliedKept += 1\n\t\t\telse this.otherKept += 1\n\t\t} else {\n\t\t\tthis.summarized[event.type] = (this.summarized[event.type] ?? 0) + 1\n\t\t}\n\t}\n\n\t/**\n\t * Replay the kept events to `live` in order. `only` limits the replay to events about\n\t * records it accepts (the records an unfinished merge already made live); events about no\n\t * record are kept only with `keepKeyless`.\n\t */\n\tasync flush(\n\t\tonly?: (recordKey: string) => boolean,\n\t\tkeepKeyless = false,\n\t): Promise<ReplicaEventFlush> {\n\t\tconst events = this.events\n\t\tconst summarized = this.summarized\n\t\tthis.events = []\n\t\tthis.summarized = {}\n\t\tthis.appliedKept = 0\n\t\tthis.otherKept = 0\n\t\tlet listenerErrors = 0\n\t\tif (this.live) {\n\t\t\tlet sinceYield = 0\n\t\t\tfor (const event of events) {\n\t\t\t\tif (only) {\n\t\t\t\t\tconst key = recordKeyOf(event)\n\t\t\t\t\tif (key === null ? !keepKeyless : !only(key)) continue\n\t\t\t\t}\n\t\t\t\ttry {\n\t\t\t\t\tthis.live.emit(event)\n\t\t\t\t} catch {\n\t\t\t\t\t// A throwing listener must not turn a committed merge into a failed one.\n\t\t\t\t\tlistenerErrors += 1\n\t\t\t\t}\n\t\t\t\tsinceYield += 1\n\t\t\t\tif (sinceYield >= REPLAY_SLICE) {\n\t\t\t\t\tsinceYield = 0\n\t\t\t\t\tawait new Promise<void>((resolve) => setTimeout(resolve, 0))\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\treturn { summarized, listenerErrors }\n\t}\n\n\t/** Forget everything kept (the replica was discarded). */\n\tclear(): void {\n\t\tthis.events = []\n\t\tthis.summarized = {}\n\t\tthis.appliedKept = 0\n\t\tthis.otherKept = 0\n\t}\n}\n\n/** Where the merged replica's delivery progress lands in the live database. */\nexport interface StagingProgress {\n\t/** The delivery view (its signature) the staged stream belonged to. */\n\tsignature: string\n\t/** The delivery watermark the staged stream reached: every in-scope operation up to it is staged. */\n\twatermark: number\n\t/** The completion mark of a final batch, written in the same transaction as the watermark. */\n\tcompletion?: OfflineCompletion\n\t/** Whether the position the stream was received at still stands (asked inside every merge transaction). */\n\tisCurrent?: () => boolean\n}\n\n/** What {@link StagingReplica.merge} may do beyond copying. */\nexport interface StagingMergeOptions {\n\t/**\n\t * Apply one staged operation the live database already has history for, exactly as the\n\t * sync engine would (default: `Store.applyRemoteOperation`). `MergeAwareSyncStore` passes\n\t * its pipeline, so referential cascades and constraint reports are the ordinary ones.\n\t */\n\treplay?: (operation: Operation) => Promise<void>\n}\n\n/**\n * A scratch replica of the live database that a large first sync is applied into before it\n * is merged (`docs/design/first-visit-parity.md` 6).\n *\n * `store` is an ordinary {@link import('../store/store').Store} over an in-memory database of\n * the same engine, so `applyRemoteBatch`, the batch prefetch and the fold run unmodified; its\n * delivery watermark, version vector and quarantine rows are its own. Nothing reads it but the\n * merge, and nothing about it survives the page: a crash, a reload or a replaced worker loses\n * it, and replication simply starts again from the live database's watermark (decision D10).\n * Because it is in memory it has no rollback journal to write, which is where the first sync's\n * cost went (docs/design/first-visit-parity.md 6, \"The replica\").\n */\nexport class StagingReplica {\n\tprivate closed = false\n\tprivate cancelled = false\n\tprivate merging = false\n\tprivate mergeRun: Promise<unknown> | null = null\n\t/** Records (`collection\\0id`) a merge that has not finished already copied whole into the live database. */\n\tprivate readonly copiedRecords = new Set<string>()\n\t/** Records (`collection\\0id`) the live database already knew, merged through the ordinary apply path. */\n\tprivate readonly contestedRecords = new Set<string>()\n\n\t/** @internal Created by `Store.beginStaging`. */\n\tconstructor(\n\t\t/** The staging store the engine applies delivery batches into. */\n\t\treadonly store: import('../store/store').Store,\n\t\tprivate readonly staging: StorageAdapter,\n\t\tprivate readonly host: StagingMergeHost,\n\t\tprivate readonly authoritiesUnchanged: () => boolean,\n\t\tprivate readonly release: () => void,\n\t\tprivate readonly events: ReplicaEventBuffer,\n\t\t/** How long `discard()` waits for a running chunk (injectable for tests). */\n\t\tprivate readonly cancelWaitMs: number = MERGE_CANCEL_WAIT_MS,\n\t) {}\n\n\t/** The replica's event buffer: hand it to the replica's merge-aware store as its emitter. */\n\tget emitter(): KoraEventEmitter {\n\t\treturn this.events\n\t}\n\n\t/** Whether the replica was discarded, cancelled or merged away (a running merge stops between chunks). */\n\tisClosed(): boolean {\n\t\treturn this.closed || this.cancelled\n\t}\n\n\t/** Bytes the replica's database holds (pages in use times page size). */\n\tasync sizeBytes(): Promise<number> {\n\t\tconst pages = await this.staging.query<{ page_count: number }>('PRAGMA page_count')\n\t\tconst size = await this.staging.query<{ page_size: number }>('PRAGMA page_size')\n\t\treturn (pages[0]?.page_count ?? 0) * (size[0]?.page_size ?? 0)\n\t}\n\n\t/**\n\t * Merge everything staged into the live database and write `progress` in the last\n\t * transaction. On `merged` the replica is closed. On `unmergeable` it is closed too: the\n\t * caller replicates again from the live watermark (nothing wrong stays behind: the chunks\n\t * that committed hold whole records, and the events of their records are replayed).\n\t */\n\tasync merge(\n\t\tprogress: StagingProgress,\n\t\toptions: StagingMergeOptions = {},\n\t): Promise<StagingMergeResult> {\n\t\tif (this.isClosed()) {\n\t\t\treturn { kind: 'unmergeable', reason: 'the staging replica is closed', cancelled: true }\n\t\t}\n\t\tif (this.merging) return { kind: 'unmergeable', reason: 'a merge is already running' }\n\t\tthis.merging = true\n\t\tconst run = this.runMerge(progress, options)\n\t\tthis.mergeRun = run\n\t\ttry {\n\t\t\treturn await run\n\t\t} finally {\n\t\t\tthis.merging = false\n\t\t\tthis.mergeRun = null\n\t\t\tawait this.finish()\n\t\t}\n\t}\n\n\tprivate async runMerge(\n\t\tprogress: StagingProgress,\n\t\toptions: StagingMergeOptions,\n\t): Promise<StagingMergeResult> {\n\t\tif (!this.authoritiesUnchanged()) {\n\t\t\treturn {\n\t\t\t\tkind: 'unmergeable',\n\t\t\t\treason: \"the server's authoritative node ids changed while the replica was staged\",\n\t\t\t}\n\t\t}\n\t\tconst host: StagingMergeHost = {\n\t\t\t...this.host,\n\t\t\t...(options.replay ? { replay: options.replay } : {}),\n\t\t\tshouldContinue: () => this.host.shouldContinue() && progress.isCurrent?.() !== false,\n\t\t\tnoteChunk: (collection, copied, contested) => {\n\t\t\t\tfor (const id of copied) this.copiedRecords.add(`${collection}\\u0000${id}`)\n\t\t\t\tfor (const id of contested) this.contestedRecords.add(`${collection}\\u0000${id}`)\n\t\t\t},\n\t\t}\n\t\tlet result: StagingMergeResult\n\t\ttry {\n\t\t\tresult = await mergeStagingInto(host, this.staging, {\n\t\t\t\twriteProgress: (tx) =>\n\t\t\t\t\tsaveDeliveryWatermarkInTx(\n\t\t\t\t\t\ttx,\n\t\t\t\t\t\tprogress.signature,\n\t\t\t\t\t\tprogress.watermark,\n\t\t\t\t\t\tprogress.completion,\n\t\t\t\t\t),\n\t\t\t})\n\t\t} catch (error) {\n\t\t\tawait this.events.flush((key) => this.copiedRecords.has(key))\n\t\t\tthrow error\n\t\t}\n\t\tif (result.kind !== 'merged') {\n\t\t\t// Chunks that committed made their records live: their operations were applied.\n\t\t\tawait this.events.flush((key) => this.copiedRecords.has(key))\n\t\t\treturn result\n\t\t}\n\t\t// Committed: now the events of the replica's applies are the live listeners' to see.\n\t\t// Not the contested records': those operations went through the live pipeline, which\n\t\t// reported what it applied and stayed silent about what the live log already held (a\n\t\t// retry after a failed merge replays records an earlier attempt copied).\n\t\tconst flushed = await this.events.flush((key) => !this.contestedRecords.has(key), true)\n\t\tconst eventsDropped = Object.values(flushed.summarized).reduce((a, b) => a + b, 0)\n\t\treturn {\n\t\t\t...result,\n\t\t\t...(eventsDropped > 0 ? { eventsDropped, eventCounts: flushed.summarized } : {}),\n\t\t\t...(flushed.listenerErrors > 0 ? { listenerErrors: flushed.listenerErrors } : {}),\n\t\t}\n\t}\n\n\t/**\n\t * Drop the replica and everything in it. A merge in flight is cancelled and awaited (a\n\t * bounded wait), so no chunk commits after this resolves and the live database's overlay\n\t * guard is not released under a running write. Safe to call more than once.\n\t */\n\tasync discard(): Promise<void> {\n\t\tif (this.closed) return\n\t\tthis.cancelled = true\n\t\tconst run = this.mergeRun\n\t\tif (run) {\n\t\t\tlet settled = false\n\t\t\tlet timer: ReturnType<typeof setTimeout> | undefined\n\t\t\tawait Promise.race([\n\t\t\t\trun.then(\n\t\t\t\t\t() => {\n\t\t\t\t\t\tsettled = true\n\t\t\t\t\t},\n\t\t\t\t\t() => {\n\t\t\t\t\t\tsettled = true\n\t\t\t\t\t},\n\t\t\t\t),\n\t\t\t\tnew Promise<void>((resolve) => {\n\t\t\t\t\ttimer = setTimeout(resolve, this.cancelWaitMs)\n\t\t\t\t}),\n\t\t\t])\n\t\t\tclearTimeout(timer)\n\t\t\t// A chunk that outlives the wait may still be writing: the overlay guard and the\n\t\t\t// scratch database stay up until the merge itself ends (its `finally` finishes the\n\t\t\t// replica), so nothing is released under a running write.\n\t\t\tif (!settled) return\n\t\t}\n\t\tawait this.finish()\n\t}\n\n\tprivate async finish(): Promise<void> {\n\t\tif (this.closed) return\n\t\tthis.closed = true\n\t\tthis.events.clear()\n\t\tthis.release()\n\t\ttry {\n\t\t\tawait this.store.close()\n\t\t} catch {\n\t\t\t// A scratch database that will not close is terminated with its worker or page.\n\t\t}\n\t}\n}\n","import { KoraError, quoteIdent } from '@korajs/core'\nimport type { HLCTimestamp, Operation, SchemaDefinition } from '@korajs/core'\nimport {\n\tdeserializeOperationWithCollection,\n\tnewestStampOfOperationRow,\n} from '../serialization/serializer'\nimport { SEQ_CONFLICTS_TABLE } from '../store/sequence-repair'\nimport type { OperationRow, StorageAdapter, Transaction, TransactionStatement } from '../types'\n\n/** Staging tables that hold one row (or more) per record, keyed by `(collection, record_id)`. */\nconst FOLD_TABLES = ['_kora_fold_state', '_kora_fold_base', '_kora_fold_snapshot'] as const\nconst PROVISIONAL_TABLE = '_kora_provisional_ops'\nconst RETRACTION_TABLE = '_kora_scope_retractions'\n/**\n * The only kind of sequence-conflict row a merge may copy: another node's operation whose\n * (node, sequence) was already held when it was delivered, kept only in the conflicts table\n * and never renumbered. It is exactly what the direct path would have stored for the same\n * delivery. Any other row records a local repair, which a copy could not reproduce.\n */\nconst COPYABLE_CONFLICT_REASON = 'remote-sequence-conflict'\n\n/** Bound variables per INSERT statement (SQLite allows 32,766 since 3.32; stay far below). */\nconst MAX_PARAMS_PER_STATEMENT = 8_000\n/** Records per `IN (...)` list (one parameter each, times the tables of the presence query). */\nconst MAX_IN_LIST = 400\n/** Work one main-database transaction should take, so a foreground write waits at most this long. */\nconst TARGET_CHUNK_MS = 150\nconst MIN_CHUNK_RECORDS = 20\nconst MAX_CHUNK_RECORDS = 1_000\nconst FIRST_CHUNK_RECORDS = 100\n/**\n * Operations one chunk may carry. A record count alone lets a few records with long histories\n * make a chunk as slow as the foreground write budget forbids; the first record of a chunk is\n * always taken, so a single huge record still merges (alone).\n */\nconst MAX_CHUNK_OPERATIONS = 4_000\n\n/**\n * What a merge needs from the store it merges into. The store implements this over its\n * private state, so this module never reaches into the store.\n */\nexport interface StagingMergeHost {\n\treadonly schema: SchemaDefinition\n\t/** Run `fn` as one write transaction on the live database (the store's write gate applies). */\n\ttransaction(fn: (tx: Transaction) => Promise<void>): Promise<void>\n\t/** Node ids this database authors under; their operations never copy (see the merge). */\n\tlocalNodeIds(): Promise<ReadonlySet<string>>\n\t/** The collection's rows are about to change: instant-update verification must not trust them. */\n\ttouchCollection(collection: string): void\n\t/** A merge chunk committed: the version vector in memory follows the one in the database. */\n\tnoteVersionVector(entries: ReadonlyMap<string, number>): void\n\t/** The newest timestamp the merged operations carry; local writes must be stamped after it. */\n\treceiveTimestamp(timestamp: HLCTimestamp): void\n\t/** Re-run live queries over `collection` (once, after the merge). */\n\tinvalidate(collection: string): void\n\t/** Apply one operation exactly as the sync engine would (deduplicates, folds, cascades). */\n\treplay(operation: Operation): Promise<void>\n\t/** Throw when this store may not take a merge now (retired tab, closed store). */\n\tassertWritable(): void\n\t/** The tab is shutting down or the engine gave up the merge: stop between chunks. */\n\tshouldContinue(): boolean\n\t/**\n\t * A chunk committed: these records of `collection` were copied whole (`copied`) or replayed\n\t * through the ordinary path (`contested`). Lets the caller account for what is already live\n\t * when the merge ends early.\n\t */\n\tnoteChunk?(collection: string, copied: readonly string[], contested: readonly string[]): void\n\t/**\n\t * Delete read-through seeds (first-visit parity S4b) inside the merge's own transaction,\n\t * before the merge looks at what the live database holds: a seeded record the device never\n\t * wrote to must be absent, so the staged copy is whole; one it wrote to is kept and\n\t * replayed onto. `ids` null means every seed.\n\t */\n\tpurgeSeeds?(\n\t\ttx: Transaction,\n\t\tcollection: string | null,\n\t\tids: readonly string[] | null,\n\t): Promise<void>\n\t/**\n\t * After the operations of contested records were replayed: drop row snapshots whose record\n\t * now has its real history, and report the ones that still have none (they stay, so the\n\t * user's edit is not hidden).\n\t *\n\t * @returns The ids whose snapshot is still the only history, so they are orphaned\n\t */\n\tsettleSnapshots?(collection: string, ids: readonly string[]): Promise<readonly string[]>\n}\n\n/** Where the merged replica's progress lands, written in the merge's final transaction. */\nexport interface StagingMergeTarget {\n\t/** Statements that persist the watermark (and the completion mark) in `tx`. */\n\twriteProgress(tx: Transaction): Promise<void>\n\t/** Bound variables per INSERT statement (tests make it tiny to split a chunk into many statements). */\n\treadonly maxParamsPerStatement?: number\n}\n\n/** Outcome of {@link mergeStagingInto}. */\nexport type StagingMergeResult =\n\t| {\n\t\t\tkind: 'merged'\n\t\t\t/** Operations copied into the live log (replayed ones excluded). */\n\t\t\toperations: number\n\t\t\t/** Records copied whole. */\n\t\t\trecords: number\n\t\t\t/** Records the live database already knew: their staged operations were replayed. */\n\t\t\tcontestedRecords: number\n\t\t\t/** Staged operations replayed through the ordinary apply path. */\n\t\t\treplayedOperations: number\n\t\t\t/** Quarantine rows copied. */\n\t\t\tquarantined: number\n\t\t\t/** Sequence-conflict rows copied with their records (legacy duplicates of a beta.12 log). */\n\t\t\tsequenceConflicts: number\n\t\t\t/** Main-database transactions the merge used. */\n\t\t\tchunks: number\n\t\t\t/** Apply events the replica buffered beyond its cap and did not replay. */\n\t\t\teventsDropped?: number\n\t\t\t/** `eventsDropped` by event type. */\n\t\t\teventCounts?: Record<string, number>\n\t\t\t/** Exceptions thrown by listeners while the buffered events were replayed (caught). */\n\t\t\tlistenerErrors?: number\n\t\t\tdurationMs: number\n\t  }\n\t| {\n\t\t\tkind: 'unmergeable'\n\t\t\treason: string\n\t\t\t/** The merge stopped because the store closed or the replica was discarded, not because the stream cannot be merged. */\n\t\t\tcancelled?: true\n\t  }\n\n/** Raised inside a chunk to abandon the merge without losing what earlier chunks committed. */\nclass Unmergeable extends KoraError {\n\tconstructor(\n\t\treason: string,\n\t\treadonly cancelled = false,\n\t) {\n\t\tsuper(`The staged replica cannot be merged: ${reason}`, 'STAGING_UNMERGEABLE', { reason })\n\t\tthis.name = 'Unmergeable'\n\t}\n}\n\nfunction inList(count: number): string {\n\treturn Array.from({ length: count }, () => '?').join(', ')\n}\n\nfunction slices<T>(items: readonly T[], size: number): T[][] {\n\tconst out: T[][] = []\n\tfor (let i = 0; i < items.length; i += size) out.push(items.slice(i, i + size))\n\treturn out\n}\n\n/** `INSERT INTO table (columns) VALUES (...), (...)`, split so no statement binds too many values. */\nfunction insertStatements(\n\ttable: string,\n\tcolumns: readonly string[],\n\trows: ReadonlyArray<Record<string, unknown>>,\n\tverb = 'INSERT',\n\tmaxParams = MAX_PARAMS_PER_STATEMENT,\n): TransactionStatement[] {\n\tif (rows.length === 0 || columns.length === 0) return []\n\tconst perStatement = Math.max(1, Math.floor(maxParams / columns.length))\n\tconst head = `${verb} INTO ${quoteIdent(table)} (${columns.map((c) => quoteIdent(c)).join(', ')}) VALUES `\n\tconst out: TransactionStatement[] = []\n\tfor (const group of slices(rows, perStatement)) {\n\t\tconst tuple = `(${columns.map(() => '?').join(', ')})`\n\t\tconst params: unknown[] = []\n\t\tfor (const row of group) for (const column of columns) params.push(row[column] ?? null)\n\t\tout.push({ sql: head + group.map(() => tuple).join(', '), params })\n\t}\n\treturn out\n}\n\nasync function run(tx: Transaction, statements: readonly TransactionStatement[]): Promise<void> {\n\tif (statements.length === 0) return\n\tif (tx.executeBatch) {\n\t\tawait tx.executeBatch(statements)\n\t\treturn\n\t}\n\tfor (const statement of statements) await tx.execute(statement.sql, statement.params)\n}\n\n/** Column names of `table` in `adapter`. */\nasync function columnsOf(adapter: StorageAdapter, table: string): Promise<string[]> {\n\tconst rows = await adapter.query<{ name: string }>(`PRAGMA table_info(${quoteIdent(table)})`)\n\treturn rows.map((row) => row.name)\n}\n\nasync function columnsIn(tx: Transaction, table: string): Promise<string[]> {\n\tconst rows = await tx.query<{ name: string }>(`PRAGMA table_info(${quoteIdent(table)})`)\n\treturn rows.map((row) => row.name)\n}\n\n/**\n * Every record id the staging database holds anything for, in one collection, sorted.\n * A record that has a log but no row (its insert was refused) is included.\n */\nasync function stagedRecordIds(\n\tstaging: StorageAdapter,\n\tcollection: string,\n\tincludeConflicts: boolean,\n): Promise<string[]> {\n\tconst ops = quoteIdent(`_kora_ops_${collection}`)\n\tconst conflicts = includeConflicts\n\t\t? `UNION SELECT record_id FROM ${SEQ_CONFLICTS_TABLE} WHERE collection = ?`\n\t\t: ''\n\tconst rows = await staging.query<{ id: string }>(\n\t\t`SELECT id FROM ${quoteIdent(collection)}\n     UNION SELECT record_id FROM ${ops}\n     UNION SELECT record_id FROM _kora_fold_state WHERE collection = ?\n     UNION SELECT record_id FROM _kora_fold_base WHERE collection = ?\n     UNION SELECT record_id FROM _kora_fold_snapshot WHERE collection = ?\n     UNION SELECT record_id FROM ${PROVISIONAL_TABLE} WHERE collection = ?\n     UNION SELECT record_id FROM ${RETRACTION_TABLE} WHERE collection = ?\n     ${conflicts}\n     ORDER BY 1`,\n\t\tincludeConflicts\n\t\t\t? [collection, collection, collection, collection, collection, collection]\n\t\t\t: [collection, collection, collection, collection, collection],\n\t)\n\treturn rows.map((row) => row.id)\n}\n\n/** The ids, among `ids`, the live database holds anything for. Read inside the chunk's transaction. */\nasync function presentInMain(\n\ttx: Transaction,\n\tcollection: string,\n\tids: readonly string[],\n): Promise<Set<string>> {\n\tconst present = new Set<string>()\n\tconst ops = quoteIdent(`_kora_ops_${collection}`)\n\tfor (const group of slices(ids, MAX_IN_LIST)) {\n\t\tconst list = inList(group.length)\n\t\tconst rows = await tx.query<{ id: string }>(\n\t\t\t`SELECT id FROM ${quoteIdent(collection)} WHERE id IN (${list})\n       UNION SELECT record_id FROM ${ops} WHERE record_id IN (${list})\n       UNION SELECT record_id FROM _kora_fold_state WHERE collection = ? AND record_id IN (${list})\n       UNION SELECT record_id FROM _kora_fold_base WHERE collection = ? AND record_id IN (${list})\n       UNION SELECT record_id FROM _kora_fold_snapshot WHERE collection = ? AND record_id IN (${list})\n       UNION SELECT record_id FROM ${PROVISIONAL_TABLE} WHERE collection = ? AND record_id IN (${list})\n       UNION SELECT record_id FROM ${RETRACTION_TABLE} WHERE collection = ? AND record_id IN (${list})`,\n\t\t\t[\n\t\t\t\t...group,\n\t\t\t\t...group,\n\t\t\t\tcollection,\n\t\t\t\t...group,\n\t\t\t\tcollection,\n\t\t\t\t...group,\n\t\t\t\tcollection,\n\t\t\t\t...group,\n\t\t\t\tcollection,\n\t\t\t\t...group,\n\t\t\t\tcollection,\n\t\t\t\t...group,\n\t\t\t],\n\t\t)\n\t\tfor (const row of rows) present.add(row.id)\n\t}\n\treturn present\n}\n\n/** Staged rows of the given tables for `ids`. */\nasync function readStaged<T>(\n\tstaging: StorageAdapter,\n\tsql: (list: string) => string,\n\tprefix: readonly unknown[],\n\tids: readonly string[],\n): Promise<T[]> {\n\tconst out: T[] = []\n\tfor (const group of slices(ids, MAX_IN_LIST)) {\n\t\tconst rows = await staging.query<T>(sql(inList(group.length)), [...prefix, ...group])\n\t\tout.push(...rows)\n\t}\n\treturn out\n}\n\ninterface StagedOpRow {\n\tid: string\n\tnode_id: string\n\trecord_id: string\n\tsequence_number: number\n\ttimestamp: string\n\t[column: string]: unknown\n}\n\n/** The newest HLC among operation rows, field versions of scope entries included. */\nfunction newestTimestamp(\n\trows: readonly StagedOpRow[],\n\tinto: HLCTimestamp | null,\n): HLCTimestamp | null {\n\tlet best = into\n\tfor (const row of rows) {\n\t\tconst ts = newestStampOfOperationRow(row as unknown as OperationRow)\n\t\tif (ts === null) continue\n\t\tif (\n\t\t\tbest === null ||\n\t\t\tts.wallTime > best.wallTime ||\n\t\t\t(ts.wallTime === best.wallTime && ts.logical > best.logical)\n\t\t) {\n\t\t\tbest = ts\n\t\t}\n\t}\n\treturn best\n}\n\n/**\n * The collections in an order that copies a parent before the children that reference it\n * (a many-to-one relation's `to` before its `from`), so a foreign key is satisfied in every\n * committed chunk. Collections in a cycle keep the schema's order; a cycle that a chunk\n * cannot satisfy fails its commit, and the caller replicates directly (nothing is lost).\n */\nfunction collectionOrder(schema: StagingMergeHost['schema']): string[] {\n\tconst names = Object.keys(schema.collections)\n\tconst parents = new Map<string, Set<string>>()\n\tfor (const relation of Object.values(schema.relations ?? {})) {\n\t\tif (relation.from === relation.to) continue\n\t\tif (!(relation.from in schema.collections) || !(relation.to in schema.collections)) continue\n\t\tconst set = parents.get(relation.from) ?? new Set<string>()\n\t\tset.add(relation.to)\n\t\tparents.set(relation.from, set)\n\t}\n\tconst ordered: string[] = []\n\tconst state = new Map<string, 'visiting' | 'done'>()\n\tconst visit = (name: string): void => {\n\t\tif (state.has(name)) return\n\t\tstate.set(name, 'visiting')\n\t\tfor (const parent of parents.get(name) ?? []) visit(parent)\n\t\tstate.set(name, 'done')\n\t\tordered.push(name)\n\t}\n\tfor (const name of names) visit(name)\n\treturn ordered\n}\n\n/**\n * Orders a collection's record ids so a record comes after the record of the same collection\n * its foreign key names (a self-referencing relation), when both are staged.\n */\nasync function parentsFirst(\n\tstaging: StorageAdapter,\n\tschema: StagingMergeHost['schema'],\n\tcollection: string,\n\tids: string[],\n): Promise<string[]> {\n\tconst fields = Object.values(schema.relations ?? {})\n\t\t.filter((relation) => relation.from === collection && relation.to === collection)\n\t\t.map((relation) => relation.field)\n\tif (fields.length === 0) return ids\n\tconst staged = new Set(ids)\n\tconst parentOf = new Map<string, string[]>()\n\tfor (const field of fields) {\n\t\tconst rows = await staging.query<{ id: string; parent: string | null }>(\n\t\t\t`SELECT id, ${quoteIdent(field)} AS parent FROM ${quoteIdent(collection)} WHERE ${quoteIdent(field)} IS NOT NULL`,\n\t\t)\n\t\tfor (const row of rows) {\n\t\t\tif (row.parent === null || !staged.has(row.parent)) continue\n\t\t\tparentOf.set(row.id, [...(parentOf.get(row.id) ?? []), row.parent])\n\t\t}\n\t}\n\tif (parentOf.size === 0) return ids\n\tconst ordered: string[] = []\n\tconst seen = new Set<string>()\n\tconst visit = (id: string): void => {\n\t\tif (seen.has(id)) return\n\t\tseen.add(id)\n\t\tfor (const parent of parentOf.get(id) ?? []) visit(parent)\n\t\tordered.push(id)\n\t}\n\tfor (const id of ids) visit(id)\n\treturn ordered\n}\n\n/**\n * Merge a staging replica into the live database (`docs/design/first-visit-parity.md` 6, \"The merge\").\n *\n * The staging database holds exactly what applying the same delivery stream to an empty\n * database would hold: per record the operations, the fold state, the materialized row, the\n * retraction marker and the provisional effects, all derived deterministically from the\n * record's set of operations. So a record the live database knows nothing about is **copied\n * whole** (rows, log, fold tables) in one transaction, with no fold work. A record the live\n * database knows something about (a write made on this device while replicating, an operation\n * an earlier crashed merge already copied, an operation under one of this database's own node\n * ids) is **never copied over**: its staged operations are replayed through the ordinary apply\n * path, which deduplicates by id and folds with the live database's own history, so the result\n * is `fold(staged ∪ live)` by the fold's own order-independence.\n *\n * A sequence-conflict row belongs to its record: it can be that record's only history (a\n * legacy log gave two records' operations one (node, sequence)), and record folds read it. So\n * it is copied or replayed with its record, in the same transaction, like the record's log.\n *\n * Every chunk is a set of whole records in one transaction, so a crash leaves each record\n * either untouched or complete (log, state and row together), never a state without its log\n * (which a later re-fold would erase). The version vector moves in the same transaction as\n * the operations it counts. The watermark, the quarantine rows and the completion mark are\n * written last, in one transaction, so the delivery watermark never passes data that is not\n * durable (invariant: gap-free delivery).\n *\n * @returns `unmergeable` (nothing wrong is left behind; chunks already committed hold whole\n *   records) when the staged state cannot be reproduced faithfully by copying: the caller\n *   discards the staging database and replicates again from the live watermark.\n */\nexport async function mergeStagingInto(\n\thost: StagingMergeHost,\n\tstaging: StorageAdapter,\n\ttarget: StagingMergeTarget,\n): Promise<StagingMergeResult> {\n\tconst startedAt = Date.now()\n\tconst insert = (\n\t\ttable: string,\n\t\tcolumns: readonly string[],\n\t\trows: ReadonlyArray<Record<string, unknown>>,\n\t\tverb = 'INSERT',\n\t): TransactionStatement[] =>\n\t\tinsertStatements(table, columns, rows, verb, target.maxParamsPerStatement)\n\tconst schema = host.schema\n\tlet chunks = 0\n\tlet operations = 0\n\tlet records = 0\n\tlet contestedRecords = 0\n\tlet replayedOperations = 0\n\tlet sequenceConflicts = 0\n\tlet newest: HLCTimestamp | null = null\n\tconst touched = new Set<string>()\n\tconst localNodes = await host.localNodeIds()\n\tlet chunkSize = FIRST_CHUNK_RECORDS\n\n\ttry {\n\t\tconst stagedConflictColumns = await columnsOf(staging, SEQ_CONFLICTS_TABLE)\n\t\tlet hasStagedConflicts = false\n\t\tif (stagedConflictColumns.length > 0) {\n\t\t\tconst census = await staging.query<{ total: number; other: number | null }>(\n\t\t\t\t`SELECT COUNT(*) AS total,\n          SUM(CASE WHEN reason = ? AND reemitted_as IS NULL THEN 0 ELSE 1 END) AS other\n         FROM ${SEQ_CONFLICTS_TABLE}`,\n\t\t\t\t[COPYABLE_CONFLICT_REASON],\n\t\t\t)\n\t\t\t// Refused before the first chunk, so a replica that cannot merge copies nothing.\n\t\t\tif ((census[0]?.other ?? 0) > 0) {\n\t\t\t\tthrow new Unmergeable('the staged log holds sequence-conflict rows it repaired locally')\n\t\t\t}\n\t\t\thasStagedConflicts = (census[0]?.total ?? 0) > 0\n\t\t}\n\n\t\tfor (const collection of collectionOrder(schema)) {\n\t\t\tconst rowTable = collection\n\t\t\tconst opsTable = `_kora_ops_${collection}`\n\t\t\tconst stagedRowColumns = await columnsOf(staging, rowTable)\n\t\t\tconst stagedOpColumns = await columnsOf(staging, opsTable)\n\t\t\tconst ids = await parentsFirst(\n\t\t\t\tstaging,\n\t\t\t\tschema,\n\t\t\t\tcollection,\n\t\t\t\tawait stagedRecordIds(staging, collection, hasStagedConflicts),\n\t\t\t)\n\t\t\tif (ids.length === 0) continue\n\t\t\tlet nextIndex = 0\n\n\t\t\twhile (nextIndex < ids.length) {\n\t\t\t\tif (!host.shouldContinue()) throw new Unmergeable('the merge was cancelled', true)\n\t\t\t\thost.assertWritable()\n\t\t\t\tlet page = ids.slice(nextIndex, nextIndex + chunkSize)\n\t\t\t\tconst chunkStarted = Date.now()\n\n\t\t\t\t// Read the page from staging, outside the live transaction (a different database).\n\t\t\t\tlet opRows = await readStaged<StagedOpRow>(\n\t\t\t\t\tstaging,\n\t\t\t\t\t(list) => `SELECT * FROM ${quoteIdent(opsTable)} WHERE record_id IN (${list})`,\n\t\t\t\t\t[],\n\t\t\t\t\tpage,\n\t\t\t\t)\n\t\t\t\tif (opRows.length > MAX_CHUNK_OPERATIONS && page.length > 1) {\n\t\t\t\t\t// Take the records whose operations fit the budget (at least the first one).\n\t\t\t\t\tconst perRecord = new Map<string, number>()\n\t\t\t\t\tfor (const row of opRows)\n\t\t\t\t\t\tperRecord.set(row.record_id, (perRecord.get(row.record_id) ?? 0) + 1)\n\t\t\t\t\tlet total = 0\n\t\t\t\t\tlet keep = 0\n\t\t\t\t\tfor (const id of page) {\n\t\t\t\t\t\tconst n = perRecord.get(id) ?? 0\n\t\t\t\t\t\tif (keep > 0 && total + n > MAX_CHUNK_OPERATIONS) break\n\t\t\t\t\t\ttotal += n\n\t\t\t\t\t\tkeep += 1\n\t\t\t\t\t}\n\t\t\t\t\tpage = page.slice(0, keep)\n\t\t\t\t\tconst kept = new Set(page)\n\t\t\t\t\topRows = opRows.filter((row) => kept.has(row.record_id))\n\t\t\t\t}\n\t\t\t\tnextIndex += page.length\n\t\t\t\tconst conflictRows = hasStagedConflicts\n\t\t\t\t\t? await readStaged<StagedOpRow>(\n\t\t\t\t\t\t\tstaging,\n\t\t\t\t\t\t\t(list) =>\n\t\t\t\t\t\t\t\t`SELECT * FROM ${SEQ_CONFLICTS_TABLE} WHERE collection = ? AND record_id IN (${list})`,\n\t\t\t\t\t\t\t[collection],\n\t\t\t\t\t\t\tpage,\n\t\t\t\t\t\t)\n\t\t\t\t\t: []\n\t\t\t\tconst stampedRows = conflictRows.length > 0 ? [...opRows, ...conflictRows] : opRows\n\t\t\t\tconst rows = await readStaged<Record<string, unknown> & { id: string }>(\n\t\t\t\t\tstaging,\n\t\t\t\t\t(list) => `SELECT * FROM ${quoteIdent(rowTable)} WHERE id IN (${list})`,\n\t\t\t\t\t[],\n\t\t\t\t\tpage,\n\t\t\t\t)\n\t\t\t\tconst foldRows = new Map<\n\t\t\t\t\tstring,\n\t\t\t\t\tArray<{ collection: string; record_id: string; state: string }>\n\t\t\t\t>()\n\t\t\t\tfor (const table of FOLD_TABLES) {\n\t\t\t\t\tfoldRows.set(\n\t\t\t\t\t\ttable,\n\t\t\t\t\t\tawait readStaged(\n\t\t\t\t\t\t\tstaging,\n\t\t\t\t\t\t\t(list) => `SELECT * FROM ${table} WHERE collection = ? AND record_id IN (${list})`,\n\t\t\t\t\t\t\t[collection],\n\t\t\t\t\t\t\tpage,\n\t\t\t\t\t\t),\n\t\t\t\t\t)\n\t\t\t\t}\n\t\t\t\tconst provisionalRows = await readStaged<Record<string, unknown> & { record_id: string }>(\n\t\t\t\t\tstaging,\n\t\t\t\t\t(list) =>\n\t\t\t\t\t\t`SELECT * FROM ${PROVISIONAL_TABLE} WHERE collection = ? AND record_id IN (${list})`,\n\t\t\t\t\t[collection],\n\t\t\t\t\tpage,\n\t\t\t\t)\n\t\t\t\tconst retractionRows = await readStaged<Record<string, unknown> & { record_id: string }>(\n\t\t\t\t\tstaging,\n\t\t\t\t\t(list) =>\n\t\t\t\t\t\t`SELECT * FROM ${RETRACTION_TABLE} WHERE collection = ? AND record_id IN (${list})`,\n\t\t\t\t\t[collection],\n\t\t\t\t\tpage,\n\t\t\t\t)\n\n\t\t\t\tlet contestedOpRows: StagedOpRow[] = []\n\t\t\t\tlet contestedConflictRows: StagedOpRow[] = []\n\t\t\t\tlet copiedConflicts = 0\n\t\t\t\tlet copied = { records: 0, operations: 0 }\n\t\t\t\tlet contested = 0\n\t\t\t\tlet contestedSet = new Set<string>()\n\t\t\t\tconst versionVector = new Map<string, number>()\n\n\t\t\t\t// The local clock moves past every stamp of this chunk BEFORE its rows become readable:\n\t\t\t\t// a local edit made once they are visible must be stamped after what it overwrites.\n\t\t\t\tconst chunkNewest = newestTimestamp(stampedRows, null)\n\t\t\t\tif (chunkNewest !== null) host.receiveTimestamp(chunkNewest)\n\n\t\t\t\tawait host.transaction(async (tx) => {\n\t\t\t\t\t// Asked inside the transaction, before anything is written: the wait for the adapter\n\t\t\t\t\t// is unbounded, and a merge whose position moved meanwhile must write nothing.\n\t\t\t\t\tif (!host.shouldContinue()) throw new Unmergeable('the merge was cancelled', true)\n\t\t\t\t\t// Reset per attempt: the transaction callback may run again after a retry.\n\t\t\t\t\tcontestedOpRows = []\n\t\t\t\t\tcontestedConflictRows = []\n\t\t\t\t\tcopiedConflicts = 0\n\t\t\t\t\tcopied = { records: 0, operations: 0 }\n\t\t\t\t\tcontested = 0\n\t\t\t\t\tversionVector.clear()\n\n\t\t\t\t\t// A foreign key is checked when the chunk commits, so a self-referencing page may\n\t\t\t\t\t// hold a child beside its parent in any order.\n\t\t\t\t\tawait tx.execute('PRAGMA defer_foreign_keys = ON')\n\t\t\t\t\tconst liveRowColumns = await columnsIn(tx, rowTable)\n\t\t\t\t\tconst liveOpColumns = await columnsIn(tx, opsTable)\n\t\t\t\t\tfor (const column of stagedRowColumns) {\n\t\t\t\t\t\tif (!liveRowColumns.includes(column)) {\n\t\t\t\t\t\t\tthrow new Unmergeable(`\"${rowTable}.${column}\" is not a column of the live table`)\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t\tfor (const column of stagedOpColumns) {\n\t\t\t\t\t\tif (!liveOpColumns.includes(column)) {\n\t\t\t\t\t\t\tthrow new Unmergeable(`\"${opsTable}.${column}\" is not a column of the live log`)\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t\tif (hasStagedConflicts) {\n\t\t\t\t\t\tconst liveConflictColumns = await columnsIn(tx, SEQ_CONFLICTS_TABLE)\n\t\t\t\t\t\tfor (const column of stagedConflictColumns) {\n\t\t\t\t\t\t\tif (!liveConflictColumns.includes(column)) {\n\t\t\t\t\t\t\t\tthrow new Unmergeable(\n\t\t\t\t\t\t\t\t\t`\"${SEQ_CONFLICTS_TABLE}.${column}\" is not a column of the live table`,\n\t\t\t\t\t\t\t\t)\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\n\t\t\t\t\tawait host.purgeSeeds?.(tx, collection, page)\n\t\t\t\t\tconst present = await presentInMain(tx, collection, page)\n\t\t\t\t\tconst contestedIds = new Set<string>(present)\n\t\t\t\t\tif (hasStagedConflicts) {\n\t\t\t\t\t\tfor (const group of slices(page, MAX_IN_LIST)) {\n\t\t\t\t\t\t\tconst held = await tx.query<{ record_id: string }>(\n\t\t\t\t\t\t\t\t`SELECT record_id FROM ${SEQ_CONFLICTS_TABLE} WHERE collection = ? AND record_id IN (${inList(group.length)})`,\n\t\t\t\t\t\t\t\t[collection, ...group],\n\t\t\t\t\t\t\t)\n\t\t\t\t\t\t\tfor (const row of held) contestedIds.add(row.record_id)\n\t\t\t\t\t\t}\n\t\t\t\t\t\t// Under this database's own node id the ordinary path has to record it as received.\n\t\t\t\t\t\tfor (const row of conflictRows) {\n\t\t\t\t\t\t\tif (localNodes.has(row.node_id)) contestedIds.add(row.record_id)\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\n\t\t\t\t\t// Operations under this database's own node ids, or under a (node, sequence) the\n\t\t\t\t\t// live log already holds for another id, need the ordinary path's conflict rows.\n\t\t\t\t\tconst wanted = new Map<string, Set<number>>()\n\t\t\t\t\tfor (const row of opRows) {\n\t\t\t\t\t\tif (contestedIds.has(row.record_id)) continue\n\t\t\t\t\t\tif (localNodes.has(row.node_id)) {\n\t\t\t\t\t\t\tcontestedIds.add(row.record_id)\n\t\t\t\t\t\t\tcontinue\n\t\t\t\t\t\t}\n\t\t\t\t\t\tlet seqs = wanted.get(row.node_id)\n\t\t\t\t\t\tif (!seqs) {\n\t\t\t\t\t\t\tseqs = new Set()\n\t\t\t\t\t\t\twanted.set(row.node_id, seqs)\n\t\t\t\t\t\t}\n\t\t\t\t\t\tseqs.add(row.sequence_number)\n\t\t\t\t\t}\n\t\t\t\t\tfor (const [nodeId, seqs] of wanted) {\n\t\t\t\t\t\tfor (const group of slices([...seqs], MAX_IN_LIST)) {\n\t\t\t\t\t\t\tconst taken = await tx.query<{ id: string; sequence_number: number }>(\n\t\t\t\t\t\t\t\t`SELECT id, sequence_number FROM ${quoteIdent(opsTable)} WHERE node_id = ? AND sequence_number IN (${inList(group.length)})`,\n\t\t\t\t\t\t\t\t[nodeId, ...group],\n\t\t\t\t\t\t\t)\n\t\t\t\t\t\t\tif (taken.length === 0) continue\n\t\t\t\t\t\t\tconst held = new Set(taken.map((row) => `${nodeId}\\u0000${row.sequence_number}`))\n\t\t\t\t\t\t\tfor (const row of opRows) {\n\t\t\t\t\t\t\t\tif (row.node_id === nodeId && held.has(`${nodeId}\\u0000${row.sequence_number}`)) {\n\t\t\t\t\t\t\t\t\tcontestedIds.add(row.record_id)\n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\n\t\t\t\t\t// A contested record replays its operations without delivery positions; a\n\t\t\t\t\t// retraction marker (staged or live) needs them, so that record cannot be merged.\n\t\t\t\t\tfor (const row of retractionRows) {\n\t\t\t\t\t\tif (contestedIds.has(row.record_id)) {\n\t\t\t\t\t\t\tthrow new Unmergeable(\n\t\t\t\t\t\t\t\t`\"${collection}\" record ${row.record_id} is retracted and was also written here`,\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\tif (contestedIds.size > 0) {\n\t\t\t\t\t\tconst liveRetractions: Array<{ record_id: string }> = []\n\t\t\t\t\t\tfor (const group of slices([...contestedIds], MAX_IN_LIST)) {\n\t\t\t\t\t\t\tliveRetractions.push(\n\t\t\t\t\t\t\t\t...(await tx.query<{ record_id: string }>(\n\t\t\t\t\t\t\t\t\t`SELECT record_id FROM ${RETRACTION_TABLE} WHERE collection = ? AND record_id IN (${inList(group.length)})`,\n\t\t\t\t\t\t\t\t\t[collection, ...group],\n\t\t\t\t\t\t\t\t)),\n\t\t\t\t\t\t\t)\n\t\t\t\t\t\t}\n\t\t\t\t\t\tif (liveRetractions.length > 0) {\n\t\t\t\t\t\t\tthrow new Unmergeable(\n\t\t\t\t\t\t\t\t`\"${collection}\" record ${liveRetractions[0]?.record_id} is retracted here and was also delivered`,\n\t\t\t\t\t\t\t)\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\n\t\t\t\t\tconst isCopied = (id: string): boolean => !contestedIds.has(id)\n\t\t\t\t\tconst copyRows = rows.filter((row) => isCopied(row.id))\n\t\t\t\t\tconst copyOps = opRows.filter((row) => isCopied(row.record_id))\n\t\t\t\t\tconst copyConflicts = conflictRows.filter((row) => isCopied(row.record_id))\n\t\t\t\t\thost.touchCollection(collection)\n\t\t\t\t\tconst statements: TransactionStatement[] = []\n\t\t\t\t\tstatements.push(...insert(rowTable, stagedRowColumns, copyRows))\n\t\t\t\t\tstatements.push(...insert(opsTable, stagedOpColumns, copyOps))\n\t\t\t\t\tstatements.push(\n\t\t\t\t\t\t...insert(\n\t\t\t\t\t\t\tSEQ_CONFLICTS_TABLE,\n\t\t\t\t\t\t\tstagedConflictColumns,\n\t\t\t\t\t\t\tcopyConflicts,\n\t\t\t\t\t\t\t'INSERT OR IGNORE',\n\t\t\t\t\t\t),\n\t\t\t\t\t)\n\t\t\t\t\tfor (const table of FOLD_TABLES) {\n\t\t\t\t\t\tconst list = (foldRows.get(table) ?? []).filter((row) => isCopied(row.record_id))\n\t\t\t\t\t\tstatements.push(...insert(table, ['collection', 'record_id', 'state'], list))\n\t\t\t\t\t}\n\t\t\t\t\tstatements.push(\n\t\t\t\t\t\t...insert(\n\t\t\t\t\t\t\tPROVISIONAL_TABLE,\n\t\t\t\t\t\t\t['id', 'collection', 'record_id', 'parent_id', 'operation'],\n\t\t\t\t\t\t\tprovisionalRows.filter((row) => isCopied(row.record_id)),\n\t\t\t\t\t\t),\n\t\t\t\t\t)\n\t\t\t\t\tstatements.push(\n\t\t\t\t\t\t...insert(\n\t\t\t\t\t\t\tRETRACTION_TABLE,\n\t\t\t\t\t\t\t['collection', 'record_id', 'position'],\n\t\t\t\t\t\t\tretractionRows.filter((row) => isCopied(row.record_id)),\n\t\t\t\t\t\t),\n\t\t\t\t\t)\n\t\t\t\t\tfor (const row of copyOps) {\n\t\t\t\t\t\tconst previous = versionVector.get(row.node_id) ?? 0\n\t\t\t\t\t\tif (row.sequence_number > previous) versionVector.set(row.node_id, row.sequence_number)\n\t\t\t\t\t}\n\t\t\t\t\tfor (const [nodeId, sequenceNumber] of versionVector) {\n\t\t\t\t\t\tstatements.push({\n\t\t\t\t\t\t\tsql: `INSERT INTO _kora_version_vector (node_id, sequence_number) VALUES (?, ?)\n     ON CONFLICT(node_id) DO UPDATE SET sequence_number = MAX(sequence_number, excluded.sequence_number)`,\n\t\t\t\t\t\t\tparams: [nodeId, sequenceNumber],\n\t\t\t\t\t\t})\n\t\t\t\t\t}\n\t\t\t\t\tawait run(tx, statements)\n\t\t\t\t\t// And once more before it commits: the statements above waited on the database.\n\t\t\t\t\tif (!host.shouldContinue()) throw new Unmergeable('the merge was cancelled', true)\n\n\t\t\t\t\tconst copiedRecordIds = new Set<string>()\n\t\t\t\t\tfor (const id of page) if (isCopied(id)) copiedRecordIds.add(id)\n\t\t\t\t\tcopied = { records: copiedRecordIds.size, operations: copyOps.length }\n\t\t\t\t\tcontested = contestedIds.size\n\t\t\t\t\tcontestedSet = new Set(contestedIds)\n\t\t\t\t\tcontestedOpRows = opRows.filter((row) => contestedIds.has(row.record_id))\n\t\t\t\t\tcontestedConflictRows = conflictRows.filter((row) => contestedIds.has(row.record_id))\n\t\t\t\t\tcopiedConflicts = copyConflicts.length\n\t\t\t\t})\n\n\t\t\t\tchunks += 1\n\t\t\t\trecords += copied.records\n\t\t\t\toperations += copied.operations\n\t\t\t\tsequenceConflicts += copiedConflicts\n\t\t\t\tcontestedRecords += contested\n\t\t\t\tif (copied.records > 0 || copied.operations > 0) touched.add(collection)\n\t\t\t\tnewest = newestTimestamp(stampedRows, newest)\n\t\t\t\tif (versionVector.size > 0) host.noteVersionVector(versionVector)\n\t\t\t\thost.noteChunk?.(\n\t\t\t\t\tcollection,\n\t\t\t\t\tpage.filter((id) => !contestedSet.has(id)),\n\t\t\t\t\tpage.filter((id) => contestedSet.has(id)),\n\t\t\t\t)\n\n\t\t\t\t// The ordinary path for what the live database already knows. After the chunk's\n\t\t\t\t// commit, so a failed replay costs the next attempt only duplicates.\n\t\t\t\tfor (const row of [...contestedOpRows, ...contestedConflictRows]) {\n\t\t\t\t\tif (!host.shouldContinue()) throw new Unmergeable('the merge was cancelled', true)\n\t\t\t\t\tconst operation = deserializeOperationWithCollection(\n\t\t\t\t\t\trow as unknown as OperationRow,\n\t\t\t\t\t\tcollection,\n\t\t\t\t\t)\n\t\t\t\t\tawait host.replay(operation)\n\t\t\t\t\treplayedOperations += 1\n\t\t\t\t\ttouched.add(collection)\n\t\t\t\t}\n\n\t\t\t\tif (host.settleSnapshots && contestedSet.size > 0) {\n\t\t\t\t\tawait host.settleSnapshots(collection, [...contestedSet])\n\t\t\t\t}\n\n\t\t\t\t// Size the next chunk so a transaction takes about TARGET_CHUNK_MS of the live worker.\n\t\t\t\tconst took = Math.max(1, Date.now() - chunkStarted)\n\t\t\t\tconst scaled = Math.round((page.length * TARGET_CHUNK_MS) / took)\n\t\t\t\tchunkSize = Math.min(MAX_CHUNK_RECORDS, Math.max(MIN_CHUNK_RECORDS, scaled))\n\t\t\t}\n\t\t}\n\n\t\t// Everything else in one final transaction: quarantine, markers, progress.\n\t\tif (!host.shouldContinue()) throw new Unmergeable('the merge was cancelled', true)\n\t\thost.assertWritable()\n\t\tconst stagedQuarantine = await staging\n\t\t\t.query<Record<string, unknown>>('SELECT * FROM _kora_unapplied_ops')\n\t\t\t.catch(() => [] as Array<Record<string, unknown>>)\n\t\tconst stagedReceived = await staging\n\t\t\t.query<{ id: string }>('SELECT id FROM _kora_received_local_ops')\n\t\t\t.catch(() => [] as Array<{ id: string }>)\n\t\tconst stagedVector = await staging.query<{ node_id: string; sequence_number: number }>(\n\t\t\t'SELECT node_id, sequence_number FROM _kora_version_vector',\n\t\t)\n\t\tconst vectorUpdate = new Map<string, number>()\n\t\tawait host.transaction(async (tx) => {\n\t\t\tif (!host.shouldContinue()) throw new Unmergeable('the merge was cancelled', true)\n\t\t\tvectorUpdate.clear()\n\t\t\tconst statements: TransactionStatement[] = []\n\t\t\tif (stagedQuarantine.length > 0) {\n\t\t\t\tconst columns = Object.keys(stagedQuarantine[0] ?? {})\n\t\t\t\tstatements.push(\n\t\t\t\t\t...insert('_kora_unapplied_ops', columns, stagedQuarantine, 'INSERT OR IGNORE'),\n\t\t\t\t)\n\t\t\t}\n\t\t\tif (stagedReceived.length > 0) {\n\t\t\t\tstatements.push(\n\t\t\t\t\t...insert('_kora_received_local_ops', ['id'], stagedReceived, 'INSERT OR IGNORE'),\n\t\t\t\t)\n\t\t\t}\n\t\t\tfor (const entry of stagedVector) {\n\t\t\t\tvectorUpdate.set(entry.node_id, entry.sequence_number)\n\t\t\t\tstatements.push({\n\t\t\t\t\tsql: `INSERT INTO _kora_version_vector (node_id, sequence_number) VALUES (?, ?)\n     ON CONFLICT(node_id) DO UPDATE SET sequence_number = MAX(sequence_number, excluded.sequence_number)`,\n\t\t\t\t\tparams: [entry.node_id, entry.sequence_number],\n\t\t\t\t})\n\t\t\t}\n\t\t\tawait run(tx, statements)\n\t\t\t// Every seed goes with the merge, also those of records the staged replica never held\n\t\t\t// (deleted since, or outside the replicated view): none may outlive it (I2).\n\t\t\tawait host.purgeSeeds?.(tx, null, null)\n\t\t\tawait target.writeProgress(tx)\n\t\t\tif (!host.shouldContinue()) throw new Unmergeable('the merge was cancelled', true)\n\t\t})\n\t\tchunks += 1\n\t\thost.noteVersionVector(vectorUpdate)\n\t\tif (newest !== null) host.receiveTimestamp(newest)\n\t\tfor (const collection of touched) host.invalidate(collection)\n\n\t\treturn {\n\t\t\tkind: 'merged',\n\t\t\toperations,\n\t\t\trecords,\n\t\t\tcontestedRecords,\n\t\t\treplayedOperations,\n\t\t\tquarantined: stagedQuarantine.length,\n\t\t\tsequenceConflicts,\n\t\t\tchunks,\n\t\t\tdurationMs: Date.now() - startedAt,\n\t\t}\n\t} catch (error) {\n\t\t// What earlier chunks committed is whole records; the live version vector already\n\t\t// follows it. Tell live queries to re-read what may have appeared.\n\t\tfor (const collection of touched) host.invalidate(collection)\n\t\tif (error instanceof Unmergeable) {\n\t\t\treturn {\n\t\t\t\tkind: 'unmergeable',\n\t\t\t\treason: error.message,\n\t\t\t\t...(error.cancelled ? { cancelled: true as const } : {}),\n\t\t\t}\n\t\t}\n\t\tthrow error\n\t}\n}\n","// The evaluator lives in @korajs/core so the sync server's read-through endpoint judges a\n// query with the very code the client's instant-updates overlay runs (first-visit parity,\n// design section 5.2). This module keeps the store's import path and names.\nexport {\n\ttype PatchRefusalReason,\n\ttype PatchVerdict,\n\tMAX_PATCHABLE_IN_LIST,\n\tPATCH_REFUSAL_REASONS,\n\tcheckPatchable,\n\tcompareQueryRecords as compare,\n\tisPatchable,\n\tmatchesQuery as matches,\n} from '@korajs/core/internal'\n","import { structurallyEqual } from '../subscription/result-equality'\nimport type { CollectionRecord, QueryDescriptor } from '../types'\nimport type { PendingEntry } from './pending-writes'\nimport { compare, matches } from './query-eval'\n\n/*\n * applyOverlay (instant-UI stage S3, docs/design/instant-ui-updates.md 5.4 patch rules,\n * 5.5): the pure function `displayed = f(base, entries)`.\n *\n * `base` is a subscription's last SQL result; `entries` are the pending writes that apply\n * to it (the caller selected them with `PendingWrites.applicable`), in registration order.\n * The result is recomputed from scratch on every call, never mutated incrementally, so a\n * rollback is \"call it again with fewer entries\" (F10, I6). Only call it for a descriptor\n * `isPatchable` accepted: `matches` and `compare` are proven equal to SQLite for that\n * allowlist only.\n *\n * Structural sharing: the input array is returned as is when nothing changed, and rows the\n * entries did not touch keep their object identity, so the subscriber's equality check is\n * a reference scan and bindings can skip re-rendering unchanged rows.\n *\n * A change the evaluator cannot place exactly is SKIPPED, never guessed (5.4): the row is\n * left as the base has it and the SQL settle decides. Once a record has had a change\n * skipped, every later entry for the same record is skipped too, so the display never\n * shows a value built on a step it did not take.\n *\n * Transactions (S6a): the members of an entry group are applied together or not at all.\n * When any member is skipped, the result is recomputed with every member of that group\n * skipped (their records poisoned too), until no further group is excluded, so a list\n * never shows part of a transaction.\n */\n\n/** Why an entry was not applied to a result. */\nexport type SkipReason =\n\t/** A row would leave a full `limit` page: the row that takes its place is not in memory. */\n\t| 'page-removal'\n\t/** A row would move within a full `limit` page and could land where an unseen row belongs. */\n\t| 'page-move'\n\t/** The changed row's sort key equals another row's: SQLite's tie order is not known. */\n\t| 'tie'\n\t/** Without an `orderBy` the rowid position of a row entering by update is not known. */\n\t| 'unordered-entry'\n\t/** An update of a row that matched before but is not in the list (deleted or changed remotely). */\n\t| 'absent-member'\n\t/** An earlier entry for the same record was skipped. */\n\t| 'after-skip'\n\t/**\n\t * Another member of the same transaction (entry group) was skipped in this result: a\n\t * group is applied whole or not at all (S6a, T3).\n\t */\n\t| 'group'\n\n/** One skipped entry. */\nexport interface SkippedEntry {\n\treadonly writeId: string\n\treadonly recordId: string\n\treadonly reason: SkipReason\n}\n\n/** The displayed rows and what could not be applied. */\nexport interface OverlayResult {\n\treadonly rows: CollectionRecord[]\n\treadonly skipped: readonly SkippedEntry[]\n}\n\n/**\n * Whether a row inserted without an `orderBy` can be appended: SQLite returns rowid\n * order only when the `WHERE` leaves the planner no index to choose (no conditions, or\n * only equality and inequality; a range or `IN` over an indexed column returns index\n * order, so appending would be wrong). A freshly inserted row has the largest rowid.\n */\nconst APPEND_CACHE = new WeakMap<object, boolean>()\n\nfunction appendAllowed(descriptor: QueryDescriptor): boolean {\n\tconst cached = APPEND_CACHE.get(descriptor.where)\n\tif (cached !== undefined) return cached\n\tlet allowed = true\n\tfor (const value of Object.values(descriptor.where)) {\n\t\tif (value !== null && typeof value === 'object' && !Array.isArray(value)) {\n\t\t\tfor (const op of Object.keys(value)) {\n\t\t\t\tif (op !== '$eq' && op !== '$ne') allowed = false\n\t\t\t}\n\t\t}\n\t}\n\tAPPEND_CACHE.set(descriptor.where, allowed)\n\treturn allowed\n}\n\n/**\n * Apply pending writes to a base result.\n *\n * @param base - The subscription's last SQL result\n * @param entries - The entries that apply to it, in registration order\n * @param descriptor - A patchable query descriptor\n * @returns The displayed rows (`base` itself when unchanged)\n */\nexport function applyOverlay(\n\tbase: readonly CollectionRecord[],\n\tentries: readonly PendingEntry[],\n\tdescriptor: QueryDescriptor,\n): CollectionRecord[] {\n\treturn applyOverlayReport(base, entries, descriptor).rows\n}\n\n/**\n * {@link applyOverlay} plus the entries it had to skip (for statistics and tests).\n *\n * @param base - The subscription's last SQL result\n * @param entries - The entries that apply to it, in registration order\n * @param descriptor - A patchable query descriptor\n */\nexport function applyOverlayReport(\n\tbase: readonly CollectionRecord[],\n\tentries: readonly PendingEntry[],\n\tdescriptor: QueryDescriptor,\n): OverlayResult {\n\tif (entries.length === 0) return { rows: base as CollectionRecord[], skipped: [] }\n\tlet excluded: Set<string> | null = null\n\t// Each pass either excludes at least one more group or is the last one, so this ends\n\t// after at most (number of groups + 1) passes; without groups it is one pass.\n\tfor (;;) {\n\t\tconst state = new Working(base, descriptor, excluded)\n\t\tfor (const entry of entries) state.apply(entry)\n\t\tlet more: Set<string> | null = null\n\t\tfor (const skip of state.skipped) {\n\t\t\tif (skip.groupId === null || excluded?.has(skip.groupId)) continue\n\t\t\tmore ??= new Set(excluded ?? [])\n\t\t\tmore.add(skip.groupId)\n\t\t}\n\t\tif (more === null) {\n\t\t\treturn {\n\t\t\t\trows: state.result(),\n\t\t\t\tskipped: state.skipped.map(({ writeId, recordId, reason }) => ({\n\t\t\t\t\twriteId,\n\t\t\t\t\trecordId,\n\t\t\t\t\treason,\n\t\t\t\t})),\n\t\t\t}\n\t\t}\n\t\texcluded = more\n\t}\n}\n\n/** A skipped entry plus its group, while the passes decide which groups to exclude. */\ninterface WorkingSkip extends SkippedEntry {\n\treadonly groupId: string | null\n}\n\n/** Copy-on-write list of rows. */\nclass Working {\n\tprivate rows: CollectionRecord[]\n\tprivate copied = false\n\tprivate poisoned: Set<string> | null = null\n\treadonly skipped: WorkingSkip[] = []\n\tprivate readonly limit: number | undefined\n\tprivate readonly ordered: boolean\n\n\tconstructor(\n\t\tprivate readonly base: readonly CollectionRecord[],\n\t\tprivate readonly descriptor: QueryDescriptor,\n\t\t/** Groups none of whose members may be applied (a member was skipped in a pass). */\n\t\tprivate readonly excludedGroups: ReadonlySet<string> | null = null,\n\t) {\n\t\tthis.rows = base as CollectionRecord[]\n\t\tthis.limit = descriptor.limit\n\t\tthis.ordered = descriptor.orderBy.length > 0\n\t}\n\n\tresult(): CollectionRecord[] {\n\t\treturn this.copied ? this.rows : (this.base as CollectionRecord[])\n\t}\n\n\tapply(entry: PendingEntry): void {\n\t\t// LIMIT 0 is always empty: nothing can ever enter.\n\t\tif (this.limit === 0) return\n\t\tif (entry.groupId !== null && this.excludedGroups?.has(entry.groupId)) {\n\t\t\tthis.skip(entry, 'group')\n\t\t\treturn\n\t\t}\n\t\tif (this.poisoned?.has(entry.recordId)) {\n\t\t\tthis.skipped.push({\n\t\t\t\twriteId: entry.writeId,\n\t\t\t\trecordId: entry.recordId,\n\t\t\t\treason: 'after-skip',\n\t\t\t\tgroupId: entry.groupId,\n\t\t\t})\n\t\t\treturn\n\t\t}\n\t\tconst index = this.indexOf(entry.recordId)\n\t\tif (entry.kind === 'delete') {\n\t\t\tthis.applyDelete(entry, index)\n\t\t\treturn\n\t\t}\n\t\tconst current = index >= 0 ? (this.rows[index] as CollectionRecord) : null\n\t\t// An insert is a full record, an update a field patch over the row in the list. An\n\t\t// update of a row that is not in the list uses the full predicted record (5.6).\n\t\tconst patch = entry.kind === 'insert' || current === null ? entry.record : entry.patch\n\t\tconst next = current === null ? entry.record : mergePatch(current, patch)\n\t\tif (current === null) this.applyEntering(entry, next)\n\t\telse this.applyPresent(entry, index, current, next)\n\t}\n\n\tprivate applyDelete(entry: PendingEntry, index: number): void {\n\t\tif (index < 0) return\n\t\tif (this.isFull()) {\n\t\t\tthis.skip(entry, 'page-removal')\n\t\t\treturn\n\t\t}\n\t\tthis.removeAt(index)\n\t}\n\n\t/** The row is not in the list: it enters if it now matches. */\n\tprivate applyEntering(entry: PendingEntry, next: CollectionRecord): void {\n\t\tif (!matches(this.descriptor, next)) return\n\t\tif (entry.kind === 'update' && !this.mayEnter(entry)) {\n\t\t\tthis.skip(entry, 'absent-member')\n\t\t\treturn\n\t\t}\n\t\tif (!this.ordered) {\n\t\t\t// Only a brand new row has the largest rowid; a row entering by update has an\n\t\t\t// unknown rowid position.\n\t\t\tif (entry.kind !== 'insert' || !appendAllowed(this.descriptor)) {\n\t\t\t\tthis.skip(entry, 'unordered-entry')\n\t\t\t\treturn\n\t\t\t}\n\t\t\tif (this.isFull()) return // appended past the page\n\t\t\tthis.insertAt(this.rows.length, next)\n\t\t\treturn\n\t\t}\n\t\tconst position = this.position(next)\n\t\tif (position === null) {\n\t\t\tthis.skip(entry, 'tie')\n\t\t\treturn\n\t\t}\n\t\t// Into a full page: either inside the first `limit` rows or past them; both exact.\n\t\tif (this.limit !== undefined && position >= this.limit) return\n\t\tconst wasFull = this.isFull()\n\t\tthis.insertAt(position, next)\n\t\tif (wasFull) this.truncate()\n\t}\n\n\t/**\n\t * Whether an update of a row that is not in the list may add it. A row that did not\n\t * match before enters (a task marked done appears in the done list). One that did match\n\t * is missing for a reason the entry cannot see: beyond a full `limit` page (it may\n\t * enter, or stay out), or gone (deleted or changed by a remote operation: showing it\n\t * would resurrect it, F21).\n\t */\n\tprivate mayEnter(entry: PendingEntry): boolean {\n\t\tif (entry.previous === null) return false\n\t\tconst before = { ...entry.record, ...entry.previous }\n\t\treturn !matches(this.descriptor, before) || this.isFull()\n\t}\n\n\t/** The row is in the list: it stays, moves, or leaves. */\n\tprivate applyPresent(\n\t\tentry: PendingEntry,\n\t\tindex: number,\n\t\tcurrent: CollectionRecord,\n\t\tnext: CollectionRecord,\n\t): void {\n\t\tif (!matches(this.descriptor, next)) {\n\t\t\tif (this.isFull()) {\n\t\t\t\tthis.skip(entry, 'page-removal')\n\t\t\t\treturn\n\t\t\t}\n\t\t\tthis.removeAt(index)\n\t\t\treturn\n\t\t}\n\t\tif (next === current) return\n\t\tif (!this.ordered || compare(this.descriptor, current, next) === 0) {\n\t\t\tthis.replaceAt(index, next)\n\t\t\treturn\n\t\t}\n\t\t// The sort key changed: take the row out, find its new place among the others.\n\t\tconst full = this.isFull()\n\t\tconst others = this.rows.slice(0, index).concat(this.rows.slice(index + 1))\n\t\tconst position = positionIn(this.descriptor, others, next)\n\t\tif (position === null) {\n\t\t\tthis.skip(entry, 'tie')\n\t\t\treturn\n\t\t}\n\t\t// In a full page the row that follows the others is not in memory: landing after\n\t\t// every remaining row is ambiguous (it may belong behind the unseen row).\n\t\tif (full && position >= others.length) {\n\t\t\tthis.skip(entry, 'page-move')\n\t\t\treturn\n\t\t}\n\t\tothers.splice(position, 0, next)\n\t\tthis.rows = others\n\t\tthis.copied = true\n\t}\n\n\tprivate skip(entry: PendingEntry, reason: SkipReason): void {\n\t\tif (this.poisoned === null) this.poisoned = new Set()\n\t\tthis.poisoned.add(entry.recordId)\n\t\tthis.skipped.push({\n\t\t\twriteId: entry.writeId,\n\t\t\trecordId: entry.recordId,\n\t\t\treason,\n\t\t\tgroupId: entry.groupId,\n\t\t})\n\t}\n\n\tprivate isFull(): boolean {\n\t\treturn this.limit !== undefined && this.rows.length >= this.limit\n\t}\n\n\tprivate indexOf(id: string): number {\n\t\tconst rows = this.rows\n\t\tfor (let i = 0; i < rows.length; i++) if ((rows[i] as CollectionRecord).id === id) return i\n\t\treturn -1\n\t}\n\n\t/** Index to insert `record` at, or null when its sort key ties with a row in the list. */\n\tprivate position(record: CollectionRecord): number | null {\n\t\treturn positionIn(this.descriptor, this.rows, record)\n\t}\n\n\tprivate own(): void {\n\t\tif (!this.copied) {\n\t\t\tthis.rows = this.rows.slice()\n\t\t\tthis.copied = true\n\t\t}\n\t}\n\n\tprivate insertAt(position: number, record: CollectionRecord): void {\n\t\tthis.own()\n\t\tthis.rows.splice(position, 0, record)\n\t}\n\n\tprivate removeAt(index: number): void {\n\t\tthis.own()\n\t\tthis.rows.splice(index, 1)\n\t}\n\n\tprivate replaceAt(index: number, record: CollectionRecord): void {\n\t\tthis.own()\n\t\tthis.rows[index] = record\n\t}\n\n\tprivate truncate(): void {\n\t\tif (this.limit !== undefined && this.rows.length > this.limit) this.rows.length = this.limit\n\t}\n}\n\n/**\n * Where a record sorts in an ordered list (binary search; the list is sorted by the\n * query's order, with ties adjacent). Null when it ties with a row already there.\n */\nfunction positionIn(\n\tdescriptor: QueryDescriptor,\n\trows: readonly CollectionRecord[],\n\trecord: CollectionRecord,\n): number | null {\n\tlet low = 0\n\tlet high = rows.length\n\twhile (low < high) {\n\t\tconst mid = (low + high) >>> 1\n\t\tif (compare(descriptor, rows[mid] as CollectionRecord, record) < 0) low = mid + 1\n\t\telse high = mid\n\t}\n\tif (low < rows.length && compare(descriptor, rows[low] as CollectionRecord, record) === 0) {\n\t\treturn null\n\t}\n\treturn low\n}\n\n/**\n * The row with `patch` applied; the same object when every patched value is already\n * there (re-applying a committed write to a result that contains it changes nothing).\n */\nfunction mergePatch(\n\tcurrent: CollectionRecord,\n\tpatch: Readonly<Record<string, unknown>> | null,\n): CollectionRecord {\n\tif (patch === null) return current\n\tlet merged: CollectionRecord | null = null\n\tfor (const key of Object.keys(patch)) {\n\t\tif (key === 'id') continue\n\t\tif (structurallyEqual(current[key], patch[key])) continue\n\t\tif (merged === null) merged = { ...current }\n\t\tmerged[key] = patch[key]\n\t}\n\treturn merged ?? current\n}\n","/**\n * Bloom filter for fast subscription dependency pre-checking.\n *\n * When the SubscriptionManager has many active subscriptions, checking whether a\n * mutation might affect any subscription requires scanning all subscriptions.\n * This bloom filter provides a fast O(k) pre-check: if the filter says \"definitely\n * not present\", we can skip the subscription entirely. If it says \"maybe present\",\n * we fall through to the precise per-subscription collection matching.\n *\n * Uses FNV-1a for hashing and Kirsch-Mitzenmacker double hashing to derive k\n * hash functions from two base hashes.\n */\n\n// FNV-1a constants for 32-bit hashes\nconst FNV_OFFSET_BASIS = 0x811c9dc5\nconst FNV_PRIME = 0x01000193\n\n/**\n * Compute FNV-1a 32-bit hash of a string.\n *\n * FNV-1a is a non-cryptographic hash function optimized for speed and distribution.\n * It processes one UTF-16 code unit at a time: XOR then multiply, which gives better avalanche\n * behavior than the original FNV-1 (multiply then XOR).\n *\n * @param input - The string to hash\n * @returns A 32-bit unsigned integer hash\n */\nexport function fnv1a32(input: string): number {\n\tlet hash = FNV_OFFSET_BASIS\n\tfor (let i = 0; i < input.length; i++) {\n\t\thash ^= input.charCodeAt(i)\n\t\t// Math.imul gives true 32-bit integer multiplication without overflow issues\n\t\thash = Math.imul(hash, FNV_PRIME)\n\t}\n\t// Ensure unsigned 32-bit result\n\treturn hash >>> 0\n}\n\n/**\n * Calculate the optimal number of bits for a bloom filter.\n *\n * Formula: m = -(n * ln(p)) / (ln(2)^2)\n * Rounded up to the nearest multiple of 32 for Uint32Array alignment.\n *\n * @param expectedItems - Expected number of items to insert\n * @param falsePositiveRate - Desired false positive rate (0-1)\n * @returns Number of bits, rounded to nearest 32-bit multiple (minimum 32)\n */\nexport function optimalBitCount(expectedItems: number, falsePositiveRate: number): number {\n\tif (expectedItems <= 0) return 32\n\tif (falsePositiveRate <= 0 || falsePositiveRate >= 1) return 32\n\n\tconst ln2Squared = Math.LN2 * Math.LN2\n\tconst rawBits = -(expectedItems * Math.log(falsePositiveRate)) / ln2Squared\n\n\t// Round up to nearest 32-bit multiple for Uint32Array alignment\n\tconst aligned = Math.ceil(rawBits / 32) * 32\n\treturn Math.max(32, aligned)\n}\n\n/**\n * Calculate the optimal number of hash functions for a bloom filter.\n *\n * Formula: k = (m/n) * ln(2)\n * Clamped to [1, 30] to avoid degenerate cases.\n *\n * @param bitCount - Total number of bits in the filter\n * @param expectedItems - Expected number of items to insert\n * @returns Number of hash functions, clamped to [1, 30]\n */\nexport function optimalHashCount(bitCount: number, expectedItems: number): number {\n\tif (expectedItems <= 0) return 1\n\tconst raw = (bitCount / expectedItems) * Math.LN2\n\treturn Math.max(1, Math.min(30, Math.round(raw)))\n}\n\n/**\n * Bloom filter for subscription dependency tracking.\n *\n * Each subscription adds its watched collection (and optionally fields) to the\n * filter. When a mutation arrives, we check \"collection\" and \"collection:field\"\n * keys against the filter. A negative result means no subscription cares about\n * this mutation, so we can skip the expensive per-subscription scan.\n *\n * @example\n * ```typescript\n * const filter = new SubscriptionBloomFilter(100, 0.01)\n * filter.add('todos')\n * filter.add('todos', 'completed')\n *\n * filter.mightContain('todos')              // true (definitely added)\n * filter.mightContain('projects')           // false (definitely not added)\n * filter.mightContain('todos', 'completed') // true (definitely added)\n * ```\n */\nexport class SubscriptionBloomFilter {\n\tprivate bits: Uint32Array\n\tprivate readonly bitCount: number\n\tprivate readonly hashCount: number\n\tprivate itemCount = 0\n\n\tconstructor(expectedItems: number, falsePositiveRate = 0.01) {\n\t\tthis.bitCount = optimalBitCount(expectedItems, falsePositiveRate)\n\t\tthis.hashCount = optimalHashCount(this.bitCount, expectedItems)\n\t\tthis.bits = new Uint32Array(this.bitCount / 32)\n\t}\n\n\t/**\n\t * Add a collection (and optional field) to the bloom filter.\n\t *\n\t * @param collection - Collection name (e.g., \"todos\")\n\t * @param field - Optional field name (e.g., \"completed\")\n\t */\n\tadd(collection: string, field?: string): void {\n\t\tconst key = field !== undefined ? `${collection}:${field}` : collection\n\t\tconst positions = this.getPositions(key)\n\t\tfor (const pos of positions) {\n\t\t\tconst wordIndex = pos >>> 5 // equivalent to Math.floor(pos / 32)\n\t\t\tconst bitIndex = pos & 31 // equivalent to pos % 32\n\t\t\tconst current = this.bits[wordIndex] ?? 0\n\t\t\tthis.bits[wordIndex] = current | (1 << bitIndex)\n\t\t}\n\t\tthis.itemCount++\n\t}\n\n\t/**\n\t * Check if a collection (and optional field) might be in the filter.\n\t *\n\t * A return value of `false` means the item is DEFINITELY NOT in the filter.\n\t * A return value of `true` means the item MIGHT be in the filter (possible false positive).\n\t *\n\t * @param collection - Collection name to check\n\t * @param field - Optional field name to check\n\t * @returns false = definitely absent, true = possibly present\n\t */\n\tmightContain(collection: string, field?: string): boolean {\n\t\tconst key = field !== undefined ? `${collection}:${field}` : collection\n\t\tconst positions = this.getPositions(key)\n\t\tfor (const pos of positions) {\n\t\t\tconst wordIndex = pos >>> 5\n\t\t\tconst bitIndex = pos & 31\n\t\t\tif (((this.bits[wordIndex] ?? 0) & (1 << bitIndex)) === 0) {\n\t\t\t\treturn false\n\t\t\t}\n\t\t}\n\t\treturn true\n\t}\n\n\t/**\n\t * Reset the bloom filter, clearing all bits and the item count.\n\t */\n\tclear(): void {\n\t\tthis.bits.fill(0)\n\t\tthis.itemCount = 0\n\t}\n\n\t/**\n\t * Estimate the current false positive rate based on the number of items inserted.\n\t *\n\t * Formula: (1 - e^(-kn/m))^k\n\t * where k = hash count, n = item count, m = bit count.\n\t *\n\t * @returns Estimated false positive rate as a number between 0 and 1\n\t */\n\testimatedFalsePositiveRate(): number {\n\t\tif (this.itemCount === 0) return 0\n\t\tconst exponent = -(this.hashCount * this.itemCount) / this.bitCount\n\t\treturn (1 - Math.exp(exponent)) ** this.hashCount\n\t}\n\n\t/**\n\t * @returns The number of items that have been added to the filter\n\t */\n\tgetItemCount(): number {\n\t\treturn this.itemCount\n\t}\n\n\t/**\n\t * @returns The total number of bits in the filter\n\t */\n\tgetBitCount(): number {\n\t\treturn this.bitCount\n\t}\n\n\t/**\n\t * @returns The number of hash functions used\n\t */\n\tgetHashCount(): number {\n\t\treturn this.hashCount\n\t}\n\n\t/**\n\t * Count the number of bits currently set to 1.\n\t * Uses Brian Kernighan's algorithm: each iteration clears the lowest set bit,\n\t * so the loop runs exactly as many times as there are set bits.\n\t *\n\t * @returns Number of bits set to 1\n\t */\n\tgetSetBitCount(): number {\n\t\tlet count = 0\n\t\tfor (let i = 0; i < this.bits.length; i++) {\n\t\t\tlet word = this.bits[i] ?? 0\n\t\t\twhile (word !== 0) {\n\t\t\t\t// Clear the lowest set bit: n & (n - 1) removes the rightmost 1-bit\n\t\t\t\tword &= word - 1\n\t\t\t\tcount++\n\t\t\t}\n\t\t}\n\t\treturn count\n\t}\n\n\t/**\n\t * Compute k bit positions for a given key using Kirsch-Mitzenmacker double hashing.\n\t *\n\t * Instead of computing k independent hash functions, we compute two base hashes\n\t * (h1 and h2) and derive the rest as: h_i = (h1 + i * h2) mod m.\n\t * This technique is proven to have the same asymptotic false positive rate as\n\t * k independent hash functions.\n\t *\n\t * We derive h1 and h2 from a single FNV-1a hash by splitting and mixing:\n\t * h1 = fnv1a(key), h2 = fnv1a(key + \"\\0salt\") to ensure independence.\n\t */\n\tprivate getPositions(key: string): number[] {\n\t\tconst h1 = fnv1a32(key)\n\t\t// Use a null-byte separator + salt suffix to derive a second independent hash\n\t\tconst h2 = fnv1a32(`${key}\\0bloom`)\n\n\t\tconst positions = new Array<number>(this.hashCount)\n\t\tfor (let i = 0; i < this.hashCount; i++) {\n\t\t\t// Combine h1 and h2 with Kirsch-Mitzenmacker technique\n\t\t\tpositions[i] = ((h1 + Math.imul(i, h2)) >>> 0) % this.bitCount\n\t\t}\n\t\treturn positions\n\t}\n}\n","import type { CollectionDefinition, Operation } from '@korajs/core'\nimport { QueryError } from '../errors'\nimport { activePhaseTimers } from '../instrumentation/phase-timers'\nimport { applyOverlayReport } from '../overlay/apply'\nimport type { PendingEntry, PendingWrites, RegistryChange } from '../overlay/pending-writes'\nimport { divergentFields } from '../overlay/predict'\nimport { isPatchable, matches } from '../overlay/query-eval'\nimport type {\n\tCollectionRecord,\n\tQueryDescriptor,\n\tQueryErrorPhase,\n\tQuerySubscriptionError,\n\tSubscribeOptions,\n\tSubscription,\n\tSubscriptionCallback,\n} from '../types'\nimport { SubscriptionBloomFilter } from './bloom-filter'\nimport { type ResultsEqual, defaultResultsEqual } from './result-equality'\n\n/**\n * Per-subscription options accepted by `register` / `registerAndFetch`.\n */\nexport interface RegisterOptions extends SubscribeOptions {\n\t/** Result-set comparator; defaults to structural comparison of every value. */\n\tresultsEqual?: ResultsEqual\n}\n\nlet nextSubId = 0\n\n/**\n * Default threshold for activating bloom filter-based dependency tracking.\n * Below this count, linear scanning is faster due to bloom filter rebuild overhead.\n */\nconst DEFAULT_BLOOM_THRESHOLD = 100\n\n/**\n * Default expected items for bloom filter sizing.\n * Sized to handle typical subscription dependency counts with headroom.\n */\nconst DEFAULT_BLOOM_EXPECTED_ITEMS = 500\n\n/**\n * Default false positive rate for bloom filter.\n * 1% provides a good balance between filter size and accuracy.\n */\nconst DEFAULT_BLOOM_FALSE_POSITIVE_RATE = 0.01\n\n/**\n * Configuration options for the SubscriptionManager.\n */\nexport interface SubscriptionManagerOptions {\n\t/**\n\t * Minimum number of subscriptions before activating bloom filter.\n\t * Below this threshold, linear scanning is used (bloom filter overhead not worth it).\n\t * @default 100\n\t */\n\tbloomThreshold?: number\n\n\t/**\n\t * Expected number of unique collection+field dependencies for bloom filter sizing.\n\t * @default 500\n\t */\n\tbloomExpectedItems?: number\n\n\t/**\n\t * Target false positive rate for the bloom filter.\n\t * Lower values require more memory but reduce unnecessary precise checks.\n\t * @default 0.01\n\t */\n\tbloomFalsePositiveRate?: number\n\n\t/** Called when a query subscription is registered (e.g. to register sync query subsets). */\n\tonQuerySubscribed?: (descriptor: QueryDescriptor) => () => void\n\n\t/**\n\t * Called for every subscription failure (the store emits `query:error`), in\n\t * addition to the subscriber's own `onError`.\n\t */\n\tonQueryError?: (failure: QuerySubscriptionError) => void\n\n\t/**\n\t * Instant-UI overlay (S3, internal): the registry of pending writes to patch\n\t * subscriptions with, or null. Read each time it is needed, so an overlay installed\n\t * after the manager was created is picked up. Omitted or null: the manager behaves\n\t * exactly as it did before the overlay existed (every code path below is gated on it).\n\t */\n\tpendingWrites?: () => PendingWrites | null\n\n\t/** The collection definition a query reads (decides whether it may be patched). */\n\tgetDefinition?: (collection: string) => CollectionDefinition | undefined\n\n\t/**\n\t * Called after a subscription of `collection` read its query successfully (the SQL\n\t * result is in). The store uses it to decide writes whose commit answer was lost: a\n\t * read that works proves the adapter answers again (M2). Overlay only.\n\t */\n\tonRead?: (collection: string) => void\n\n\t/**\n\t * Called after a patch pass delivered rows built from the overlay (the store emits\n\t * `query:patched`). Overlay only.\n\t */\n\tonPatched?: (info: {\n\t\tqueryId: string\n\t\tcollection: string\n\t\tresultCount: number\n\t\tdurationMs: number\n\t}) => void\n\n\t/** Monotonic milliseconds for the pass budget. Default `performance.now`. Injected by tests. */\n\tnow?: () => number\n\n\t/**\n\t * Longest a patch pass may run before the remaining subscriptions fall back to the\n\t * commit path (design section 11). Default {@link DEFAULT_OVERLAY_PASS_BUDGET_MS}.\n\t */\n\toverlayPassBudgetMs?: number\n}\n\n/** Default budget of one patch pass, in milliseconds (design section 11). */\nexport const DEFAULT_OVERLAY_PASS_BUDGET_MS = 8\n\n/** The entries that apply to one (collection, base epoch), reused across a patch pass. */\ninterface ApplicableCache {\n\tcollection: string\n\tissuedAt: number\n\tentries: PendingEntry[]\n}\n\n/** Counters of the overlay's work, for tests and DevTools (S3). */\nexport interface OverlayStats {\n\t/** Patch passes run. */\n\tpasses: number\n\t/** Callbacks delivered by a patch pass (not by a SQL result). */\n\tpatchedDeliveries: number\n\t/** Subscriptions a pass left to the commit path because it ran out of budget. */\n\tbudgetSkips: number\n\t/** Entries the evaluator declined to apply (limit pages, ties, ...). */\n\tskippedEntries: number\n\t/** Duration of the most recent pass, in milliseconds (by the manager's clock). */\n\tlastPassMs: number\n}\n\n/**\n * A committed change to the rows of one collection that can affect query results\n * (RT-98). Every invalidation the store makes produces one: local writes and remote\n * applies (with the operation), and changes made without a new operation (rejection\n * re-folds, scope retraction, cascade settling, rematerialization, backup restore,\n * held/discarded writes).\n */\nexport interface RecordsChange {\n\t/** Collection whose rows changed */\n\treadonly collection: string\n\t/** Changed record ids, or null when unknown (treat the whole collection as changed) */\n\treadonly ids: readonly string[] | null\n\t/** The operation that caused the change, when there is one */\n\treadonly operation?: Operation\n}\n\n/** Listener for {@link RecordsChange}s made by this runtime (not those relayed from peers). */\nexport type RecordsChangeListener = (change: RecordsChange) => void\n\n/**\n * Performance statistics for monitoring subscription checking efficiency.\n */\nexport interface SubscriptionStats {\n\t/** Total number of mutation notifications processed */\n\ttotalChecks: number\n\t/** Number of times bloom filter said \"maybe\" (proceeded to precise check) */\n\tbloomFilterHits: number\n\t/** Number of times bloom filter said \"definitely not\" (skipped all subscriptions) */\n\tbloomFilterMisses: number\n\t/** Number of times bloom filter said \"maybe\" but precise check found no match */\n\tfalsePositives: number\n\t/** Average time per check in milliseconds */\n\taverageCheckTimeMs: number\n\t/** Whether bloom filter is currently active */\n\tbloomFilterActive: boolean\n\t/** Current subscription count */\n\tsubscriptionCount: number\n}\n\n/**\n * Manages reactive subscriptions with two-level dependency checking.\n *\n * When a mutation occurs on a collection, affected subscriptions are re-evaluated\n * in a microtask batch and callbacks are invoked only if results actually changed.\n *\n * For large subscription counts (>= bloomThreshold), a bloom filter provides O(k)\n * pre-filtering to avoid scanning all subscriptions on every mutation:\n *\n * Level 1 (Bloom filter): Fast O(k) check -- does this mutation potentially affect\n * any subscription? If NO: skip all subscriptions (guaranteed correct).\n * If MAYBE: proceed to Level 2.\n *\n * Level 2 (Precise check): Only evaluate subscriptions that match the mutated\n * collection, including included (related) collection tracking.\n */\nexport class SubscriptionManager {\n\tprivate subscriptions = new Map<string, Subscription>()\n\tprivate pendingCollections = new Set<string>()\n\tprivate flushScheduled = false\n\t/** Internal S0 phase timer: when the oldest unflushed change was recorded (null when none or timers off). */\n\tprivate notifiedAt: number | null = null\n\tprivate readonly onQuerySubscribed?: (descriptor: QueryDescriptor) => () => void\n\tprivate readonly onQueryError?: (failure: QuerySubscriptionError) => void\n\tprivate readonly onRead?: (collection: string) => void\n\tprivate readonly onPatched?: SubscriptionManagerOptions['onPatched']\n\t// Instant-UI overlay state (S3). All of it is inert while `getRegistry` yields null.\n\tprivate getRegistry: (() => PendingWrites | null) | undefined\n\tprivate readonly getDefinition:\n\t\t| ((collection: string) => CollectionDefinition | undefined)\n\t\t| undefined\n\tprivate clock: () => number\n\tprivate passBudgetMs: number\n\tprivate attachedRegistry: PendingWrites | null = null\n\tprivate stopListening: (() => void) | null = null\n\tprivate readonly overlayPending = new Set<string>()\n\tprivate overlayScheduled = false\n\tprivate readonly overlayCounters: OverlayStats = {\n\t\tpasses: 0,\n\t\tpatchedDeliveries: 0,\n\t\tbudgetSkips: 0,\n\t\tskippedEntries: 0,\n\t\tlastPassMs: 0,\n\t}\n\tprivate readonly changeListeners = new Set<RecordsChangeListener>()\n\t/**\n\t * Collections changed before the first change listener attached (a store's open:\n\t * rematerialization, migration backfills). Replayed to that listener, so other tabs\n\t * hear about changes made while this tab was still opening. Bounded by the schema.\n\t */\n\tprivate unheardCollections: Set<string> | null = new Set()\n\n\t// Bloom filter state\n\tprivate bloomFilter: SubscriptionBloomFilter | null = null\n\tprivate bloomDirty = false\n\tprivate readonly bloomThreshold: number\n\tprivate readonly bloomExpectedItems: number\n\tprivate readonly bloomFalsePositiveRate: number\n\n\t// Performance stats\n\tprivate totalChecks = 0\n\tprivate bloomFilterHits = 0\n\tprivate bloomFilterMisses = 0\n\tprivate falsePositives = 0\n\tprivate totalCheckTimeMs = 0\n\n\tconstructor(options?: SubscriptionManagerOptions) {\n\t\tthis.bloomThreshold = options?.bloomThreshold ?? DEFAULT_BLOOM_THRESHOLD\n\t\tthis.bloomExpectedItems = options?.bloomExpectedItems ?? DEFAULT_BLOOM_EXPECTED_ITEMS\n\t\tthis.bloomFalsePositiveRate =\n\t\t\toptions?.bloomFalsePositiveRate ?? DEFAULT_BLOOM_FALSE_POSITIVE_RATE\n\t\tthis.onQuerySubscribed = options?.onQuerySubscribed\n\t\tthis.onQueryError = options?.onQueryError\n\t\tthis.onRead = options?.onRead\n\t\tthis.onPatched = options?.onPatched\n\t\tthis.getRegistry = options?.pendingWrites\n\t\tthis.getDefinition = options?.getDefinition\n\t\tthis.clock = options?.now ?? (() => performance.now())\n\t\tthis.passBudgetMs = options?.overlayPassBudgetMs ?? DEFAULT_OVERLAY_PASS_BUDGET_MS\n\t}\n\n\t/**\n\t * Register a new subscription.\n\t *\n\t * @param descriptor - The query descriptor defining what this subscription watches\n\t * @param callback - Called with results whenever they change\n\t * @param executeFn - Function to re-execute the query and get current results\n\t * @returns An unsubscribe function\n\t */\n\tregister(\n\t\tdescriptor: QueryDescriptor,\n\t\tcallback: SubscriptionCallback<CollectionRecord>,\n\t\texecuteFn: () => Promise<CollectionRecord[]>,\n\t\toptions?: RegisterOptions,\n\t): () => void {\n\t\t// No initial run: the empty baseline counts as delivered, so a flush only\n\t\t// notifies when the results differ from it.\n\t\tconst subscription = this.createSubscription(descriptor, callback, executeFn, options)\n\t\tsubscription.delivered = true\n\t\treturn this.track(subscription)\n\t}\n\n\t/**\n\t * Register a subscription and immediately execute the query.\n\t * The initial results are stored as lastResults so subsequent flushes\n\t * correctly diff against the initial state. A failing initial run is reported\n\t * through `options.onError` and the `query:error` hook, never as an unhandled\n\t * rejection (STORE-12).\n\t *\n\t * @returns An unsubscribe function\n\t */\n\tregisterAndFetch(\n\t\tdescriptor: QueryDescriptor,\n\t\tcallback: SubscriptionCallback<CollectionRecord>,\n\t\texecuteFn: () => Promise<CollectionRecord[]>,\n\t\toptions?: RegisterOptions,\n\t): () => void {\n\t\tconst subscription = this.createSubscription(descriptor, callback, executeFn, options)\n\t\tconst unsubscribe = this.track(subscription)\n\t\tvoid this.run(subscription)\n\t\treturn unsubscribe\n\t}\n\n\tprivate createSubscription(\n\t\tdescriptor: QueryDescriptor,\n\t\tcallback: SubscriptionCallback<CollectionRecord>,\n\t\texecuteFn: () => Promise<CollectionRecord[]>,\n\t\toptions: RegisterOptions | undefined,\n\t): Subscription {\n\t\treturn {\n\t\t\tid: `sub_${++nextSubId}`,\n\t\t\tdescriptor,\n\t\t\tcallback,\n\t\t\texecuteFn,\n\t\t\tlastResults: [],\n\t\t\tresultsEqual: options?.resultsEqual ?? defaultResultsEqual,\n\t\t\tonError: options?.onError,\n\t\t\trunsStarted: 0,\n\t\t\tlastAppliedRun: 0,\n\t\t\terrored: false,\n\t\t\tdelivered: false,\n\t\t}\n\t}\n\n\tprivate track(subscription: Subscription): () => void {\n\t\tconst id = subscription.id\n\t\tthis.subscriptions.set(id, subscription)\n\n\t\t// Mark bloom filter as needing rebuild since dependencies changed\n\t\tthis.bloomDirty = true\n\n\t\tconst externalCleanup = this.onQuerySubscribed?.(subscription.descriptor)\n\t\tthis.registry()\n\n\t\treturn () => {\n\t\t\tif (!this.subscriptions.delete(id)) return\n\t\t\tthis.bloomDirty = true\n\t\t\tif (this.subscriptions.size === 0) this.detachRegistry()\n\t\t\texternalCleanup?.()\n\t\t}\n\t}\n\n\t/**\n\t * Run a subscription's query and deliver the result when it changed. Never\n\t * throws: failures go to the error channel. Runs are numbered so a slow,\n\t * older run never overwrites the result of a newer one.\n\t */\n\tprivate async run(sub: Subscription): Promise<void> {\n\t\tconst runNumber = (sub.runsStarted ?? 0) + 1\n\t\tsub.runsStarted = runNumber\n\t\t// The epoch when this read is issued: a read issued before a write's commit may not\n\t\t// contain it (design 5.5). Taken before `executeFn` starts the query.\n\t\tconst registry = this.registry()\n\t\tconst issuedAt = registry ? registry.epoch : 0\n\t\t// Also before the read: rows it returns may seed the registry's row cache only if\n\t\t// nothing the registry hears of changed the collection meanwhile (S5 follow-up).\n\t\tconst seedStamp = registry ? registry.seedStamp(sub.descriptor.collection) : 0\n\t\tlet results: CollectionRecord[]\n\t\tconst timers = activePhaseTimers()\n\t\tconst rereadStartedAt = timers ? performance.now() : 0\n\t\ttry {\n\t\t\tresults = await sub.executeFn()\n\t\t} catch (error) {\n\t\t\tif (!this.isCurrent(sub, runNumber)) return\n\t\t\tsub.lastAppliedRun = runNumber\n\t\t\tsub.errored = true\n\t\t\tthis.reportError(sub, error, sub.delivered ? 'refresh' : 'initial')\n\t\t\treturn\n\t\t}\n\t\tconst rereadEndedAt = timers ? performance.now() : 0\n\t\tif (timers) {\n\t\t\ttimers.add('reread', rereadEndedAt - rereadStartedAt)\n\t\t\ttimers.noteReread()\n\t\t}\n\t\tif (!this.isCurrent(sub, runNumber)) return\n\t\tsub.lastAppliedRun = runNumber\n\n\t\t// Settling, the read hook and the comparison run per subscription: a failure in one (an\n\t\t// internal bug) is reported on it, and the rest of the flush is still delivered.\n\t\tlet shown: CollectionRecord[]\n\t\ttry {\n\t\t\t// Overlay on: this SQL result is the new base, and pending writes it may not contain\n\t\t\t// are applied on top (design 5.5). Overlay off: `shown` is `results`.\n\t\t\tshown = registry ? this.settleRun(sub, results, issuedAt, registry, seedStamp) : results\n\t\t\tif (registry) this.onRead?.(sub.descriptor.collection)\n\n\t\t\t// After a failure, the next success is always delivered (even when equal to\n\t\t\t// the last results) so bindings can leave their error state.\n\t\t\tconst equal = sub.resultsEqual ?? defaultResultsEqual\n\t\t\tif (sub.delivered && !sub.errored && equal(sub.lastResults, shown)) {\n\t\t\t\ttimers?.add('diffNotify', performance.now() - rereadEndedAt)\n\t\t\t\treturn\n\t\t\t}\n\t\t} catch (error) {\n\t\t\tsub.errored = true\n\t\t\tthis.reportError(sub, error, sub.delivered ? 'refresh' : 'initial')\n\t\t\treturn\n\t\t}\n\n\t\tsub.lastResults = shown\n\t\tsub.delivered = true\n\t\tsub.errored = false\n\t\ttimers?.noteCallback(performance.now())\n\t\ttry {\n\t\t\tsub.callback(shown)\n\t\t} catch (error) {\n\t\t\tthis.reportError(sub, error, 'callback')\n\t\t}\n\t\ttimers?.add('diffNotify', performance.now() - rereadEndedAt)\n\t}\n\n\tprivate isCurrent(sub: Subscription, runNumber: number): boolean {\n\t\treturn this.subscriptions.get(sub.id) === sub && runNumber > (sub.lastAppliedRun ?? 0)\n\t}\n\n\tprivate reportError(sub: Subscription, thrown: unknown, phase: QueryErrorPhase): void {\n\t\tconst error =\n\t\t\tthrown instanceof Error\n\t\t\t\t? thrown\n\t\t\t\t: new QueryError(`Query subscription failed: ${String(thrown)}`, {\n\t\t\t\t\t\tcollection: sub.descriptor.collection,\n\t\t\t\t\t})\n\t\tconst failure: QuerySubscriptionError = {\n\t\t\terror,\n\t\t\tphase,\n\t\t\tcollection: sub.descriptor.collection,\n\t\t\tqueryId: sub.id,\n\t\t}\n\t\ttry {\n\t\t\tthis.onQueryError?.(failure)\n\t\t} catch (hookError) {\n\t\t\tconsole.error('[kora] query:error listener threw', hookError)\n\t\t}\n\t\tif (sub.onError) {\n\t\t\ttry {\n\t\t\t\tsub.onError(failure)\n\t\t\t} catch (handlerError) {\n\t\t\t\tconsole.error('[kora] subscription onError handler threw', handlerError)\n\t\t\t}\n\t\t\treturn\n\t\t}\n\t\t// No subscriber handler: log so the failure is never silent.\n\t\tconsole.error(\n\t\t\t`[kora] Query subscription ${sub.id} on \"${sub.descriptor.collection}\" failed (${phase}). Pass subscribe(cb, { onError }) to handle it.`,\n\t\t\terror,\n\t\t)\n\t}\n\n\t/**\n\t * Notify the manager that a mutation occurred on a collection.\n\t * Schedules a microtask flush to batch multiple mutations in the same tick.\n\t */\n\tnotify(collection: string, operation: Operation): void {\n\t\tthis.recordsChanged({ collection, ids: [operation.recordId], operation })\n\t}\n\n\t/**\n\t * Invalidate a collection after a local-view change that has no domain operation\n\t * (a re-fold, a retraction, a restore). Pass the record ids when known.\n\t */\n\tinvalidate(collection: string, ids: readonly string[] | null = null): void {\n\t\tthis.recordsChanged({ collection, ids })\n\t}\n\n\t/**\n\t * The single entry point for a committed change made by this runtime (RT-98): it\n\t * schedules the affected queries and tells every change listener (the cross-tab\n\t * bus), so no invalidation path can reach this tab's queries without reaching the\n\t * other tabs' too.\n\t */\n\trecordsChanged(change: RecordsChange): void {\n\t\tthis.invalidateCachedRows(change)\n\t\tif (this.notifiedAt === null && activePhaseTimers()) this.notifiedAt = performance.now()\n\t\tthis.pendingCollections.add(change.collection)\n\t\tthis.scheduleFlush()\n\t\tif (this.unheardCollections) this.unheardCollections.add(change.collection)\n\t\tfor (const listener of this.changeListeners) {\n\t\t\ttry {\n\t\t\t\tlistener(change)\n\t\t\t} catch (error) {\n\t\t\t\t// A failing listener must not stop this tab's queries or other listeners.\n\t\t\t\tconsole.error('[kora] records-change listener failed', error)\n\t\t\t}\n\t\t}\n\t}\n\n\t/**\n\t * Invalidate a collection for a change another runtime made to the shared\n\t * database. Not relayed to change listeners (the peer already broadcast it).\n\t */\n\tinvalidateFromPeer(collection: string): void {\n\t\tthis.registry()?.invalidate(collection)\n\t\tthis.pendingCollections.add(collection)\n\t\tthis.scheduleFlush()\n\t}\n\n\t/**\n\t * Listen to every committed change this runtime makes.\n\t *\n\t * @returns An unsubscribe function\n\t */\n\tonRecordsChanged(listener: RecordsChangeListener): () => void {\n\t\tthis.changeListeners.add(listener)\n\t\tconst unheard = this.unheardCollections\n\t\tthis.unheardCollections = null\n\t\tfor (const collection of unheard ?? []) {\n\t\t\ttry {\n\t\t\t\tlistener({ collection, ids: null })\n\t\t\t} catch (error) {\n\t\t\t\tconsole.error('[kora] records-change listener failed', error)\n\t\t\t}\n\t\t}\n\t\treturn () => {\n\t\t\tthis.changeListeners.delete(listener)\n\t\t}\n\t}\n\n\t/**\n\t * Immediately flush all pending notifications.\n\t * Useful for testing. In production, flushing happens via microtask.\n\t */\n\tasync flush(): Promise<void> {\n\t\tif (this.pendingCollections.size === 0) return\n\n\t\tconst timers = activePhaseTimers()\n\t\tconst flushStartedAt = timers ? performance.now() : 0\n\t\tif (timers && this.notifiedAt !== null)\n\t\t\ttimers.add('flushDelay', flushStartedAt - this.notifiedAt)\n\t\tthis.notifiedAt = null\n\n\t\tconst collections = new Set(this.pendingCollections)\n\t\tthis.pendingCollections.clear()\n\t\tthis.flushScheduled = false\n\n\t\t// A committed write the subscriptions have not re-read for too long: force the\n\t\t// re-read (design section 11). Its settle drops the entry.\n\t\tconst registry = this.registry()\n\t\tconst forced = new Set<string>()\n\t\tif (registry) {\n\t\t\tfor (const entry of registry.sweep().lagging) {\n\t\t\t\tcollections.add(entry.collection)\n\t\t\t\tforced.add(entry.collection)\n\t\t\t}\n\t\t}\n\n\t\tconst affected = this.findAffectedSubscriptions(collections)\n\t\ttimers?.add('findAffected', performance.now() - flushStartedAt)\n\n\t\t// Re-execute and diff. run() never throws: failures reach the error channel.\n\t\tfor (const sub of affected) {\n\t\t\tawait this.run(sub)\n\t\t}\n\t\t// A collection nobody patches has no run() to settle its entries; the forced re-read\n\t\t// above is what ends their wait.\n\t\tif (registry) for (const collection of forced) this.settleEntries(collection, registry)\n\t}\n\n\t/**\n\t * Remove all subscriptions. Called on store close.\n\t */\n\tclear(): void {\n\t\tthis.subscriptions.clear()\n\t\tthis.pendingCollections.clear()\n\t\tthis.flushScheduled = false\n\t\tthis.overlayPending.clear()\n\t\tthis.overlayScheduled = false\n\t\tthis.detachRegistry()\n\t\tthis.bloomFilter = null\n\t\tthis.bloomDirty = false\n\t\tthis.totalChecks = 0\n\t\tthis.bloomFilterHits = 0\n\t\tthis.bloomFilterMisses = 0\n\t\tthis.falsePositives = 0\n\t\tthis.totalCheckTimeMs = 0\n\t}\n\n\t/** Number of active subscriptions (for testing/debugging) */\n\tget size(): number {\n\t\treturn this.subscriptions.size\n\t}\n\n\t/**\n\t * Get performance statistics for monitoring subscription checking efficiency.\n\t * Useful for DevTools integration and performance tuning.\n\t */\n\tgetStats(): SubscriptionStats {\n\t\treturn {\n\t\t\ttotalChecks: this.totalChecks,\n\t\t\tbloomFilterHits: this.bloomFilterHits,\n\t\t\tbloomFilterMisses: this.bloomFilterMisses,\n\t\t\tfalsePositives: this.falsePositives,\n\t\t\taverageCheckTimeMs: this.totalChecks > 0 ? this.totalCheckTimeMs / this.totalChecks : 0,\n\t\t\tbloomFilterActive: this.isBloomActive(),\n\t\t\tsubscriptionCount: this.subscriptions.size,\n\t\t}\n\t}\n\n\t/**\n\t * Check if bloom filter is currently active.\n\t * Active when subscription count meets or exceeds the threshold.\n\t */\n\tisBloomActive(): boolean {\n\t\treturn this.subscriptions.size >= this.bloomThreshold\n\t}\n\n\t/**\n\t * Find subscriptions affected by mutations to the given collections.\n\t * Uses two-level checking when bloom filter is active:\n\t *\n\t * Level 1: Bloom filter pre-check -- if no subscription depends on any\n\t * of the mutated collections, skip everything (O(k) per collection).\n\t *\n\t * Level 2: Precise check -- linear scan of subscriptions, matching\n\t * against the mutated collections.\n\t */\n\tprivate findAffectedSubscriptions(collections: Set<string>): Subscription[] {\n\t\tconst startTime = performance.now()\n\t\tthis.totalChecks++\n\n\t\tconst useBloom = this.isBloomActive()\n\n\t\tif (useBloom) {\n\t\t\t// Rebuild bloom filter if dependencies have changed\n\t\t\tif (this.bloomDirty || this.bloomFilter === null) {\n\t\t\t\tthis.rebuildBloomFilter()\n\t\t\t}\n\n\t\t\tconst filter = this.bloomFilter\n\t\t\tif (filter !== null) {\n\t\t\t\t// Level 1: Bloom filter pre-check\n\t\t\t\tlet anyPossibleMatch = false\n\t\t\t\tfor (const col of collections) {\n\t\t\t\t\tif (filter.mightContain(col)) {\n\t\t\t\t\t\tanyPossibleMatch = true\n\t\t\t\t\t\tbreak\n\t\t\t\t\t}\n\t\t\t\t}\n\n\t\t\t\tif (!anyPossibleMatch) {\n\t\t\t\t\t// Bloom filter guarantees no subscription depends on these collections\n\t\t\t\t\tthis.bloomFilterMisses++\n\t\t\t\t\tthis.totalCheckTimeMs += performance.now() - startTime\n\t\t\t\t\treturn []\n\t\t\t\t}\n\n\t\t\t\tthis.bloomFilterHits++\n\t\t\t}\n\t\t}\n\n\t\t// Level 2: Precise check (or only check when bloom is not active)\n\t\tconst affected: Subscription[] = []\n\t\tlet anyPreciseMatch = false\n\n\t\tfor (const sub of this.subscriptions.values()) {\n\t\t\tif (collections.has(sub.descriptor.collection)) {\n\t\t\t\taffected.push(sub)\n\t\t\t\tanyPreciseMatch = true\n\t\t\t} else if (sub.descriptor.includeCollections) {\n\t\t\t\t// Re-evaluate if a mutation affects an included (related) collection\n\t\t\t\tfor (const incCol of sub.descriptor.includeCollections) {\n\t\t\t\t\tif (collections.has(incCol)) {\n\t\t\t\t\t\taffected.push(sub)\n\t\t\t\t\t\tanyPreciseMatch = true\n\t\t\t\t\t\tbreak\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\t// Track false positives: bloom said \"maybe\" but precise check found nothing\n\t\tif (useBloom && !anyPreciseMatch) {\n\t\t\tthis.falsePositives++\n\t\t}\n\n\t\tthis.totalCheckTimeMs += performance.now() - startTime\n\t\treturn affected\n\t}\n\n\t/**\n\t * Rebuild the bloom filter from all current subscriptions.\n\t * Adds collection-level dependencies for every subscription, plus\n\t * any included collection dependencies.\n\t */\n\tprivate rebuildBloomFilter(): void {\n\t\tconst filter = new SubscriptionBloomFilter(this.bloomExpectedItems, this.bloomFalsePositiveRate)\n\n\t\tfor (const sub of this.subscriptions.values()) {\n\t\t\t// Add the primary collection dependency\n\t\t\tfilter.add(sub.descriptor.collection)\n\n\t\t\t// Add included (related) collection dependencies\n\t\t\tif (sub.descriptor.includeCollections) {\n\t\t\t\tfor (const incCol of sub.descriptor.includeCollections) {\n\t\t\t\t\tfilter.add(incCol)\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\tthis.bloomFilter = filter\n\t\tthis.bloomDirty = false\n\t}\n\n\t// --- Instant-UI overlay (S3) ---\n\n\t/**\n\t * A pending write was added, rolled back or cleared for `collection`: recompute what\n\t * its patchable subscriptions display. Coalesced: any number of calls in one task\n\t * produce one pass per subscription, in a microtask (design 11). Never touches the\n\t * worker and never reaches the change listeners (the cross-tab bus, I11, F17).\n\t */\n\toverlayChanged(collection: string): void {\n\t\tthis.overlayPending.add(collection)\n\t\tif (this.overlayScheduled) return\n\t\tthis.overlayScheduled = true\n\t\tqueueMicrotask(() => this.flushOverlay())\n\t}\n\n\t/**\n\t * Run the scheduled patch pass now. Called by the microtask; tests call it directly.\n\t *\n\t * Each affected, patchable subscription with a base recomputes\n\t * `displayed = applyOverlay(base, applicable entries)` and its callback runs when the\n\t * rows changed. A pass that exceeds its budget stops: the remaining subscriptions keep\n\t * what they show and catch up at the commit path (their SQL re-run).\n\t */\n\tflushOverlay(): void {\n\t\tthis.overlayScheduled = false\n\t\tif (this.overlayPending.size === 0) return\n\t\tconst collections = new Set(this.overlayPending)\n\t\tthis.overlayPending.clear()\n\t\tconst registry = this.registry()\n\t\tif (!registry) return\n\t\tthis.overlayCounters.passes++\n\n\t\tconst startedAt = this.clock()\n\t\tconst applicable: ApplicableCache = { collection: '', issuedAt: -1, entries: [] }\n\t\tlet exhausted = false\n\t\tfor (const sub of this.subscriptions.values()) {\n\t\t\tif (!collections.has(sub.descriptor.collection)) continue\n\t\t\tif (exhausted) {\n\t\t\t\tthis.overlayCounters.budgetSkips++\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\tif (this.clock() - startedAt > this.passBudgetMs) {\n\t\t\t\texhausted = true\n\t\t\t\tthis.overlayCounters.budgetSkips++\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\tthis.patch(sub, registry, applicable)\n\t\t}\n\t\tthis.overlayCounters.lastPassMs = this.clock() - startedAt\n\t}\n\n\t/** Counters of the overlay's work. */\n\tgetOverlayStats(): Readonly<OverlayStats> {\n\t\treturn { ...this.overlayCounters }\n\t}\n\n\t/** Replace the pass clock and budget. For tests and benchmarks (deterministic budgets). */\n\tconfigureOverlay(options: {\n\t\tnow?: () => number\n\t\tpassBudgetMs?: number\n\t\tpendingWrites?: () => PendingWrites | null\n\t}): void {\n\t\tif (options.pendingWrites) this.getRegistry = options.pendingWrites\n\t\tif (options.now) this.clock = options.now\n\t\tif (options.passBudgetMs !== undefined) this.passBudgetMs = options.passBudgetMs\n\t}\n\n\t/**\n\t * What every subscription holds, in registration order: its base (last SQL result),\n\t * the epoch that read was issued at, and the rows it last delivered. For tests and\n\t * DevTools; the rows are the live arrays, not copies.\n\t */\n\tinspectOverlay(): Array<{\n\t\treadonly descriptor: QueryDescriptor\n\t\treadonly base: readonly CollectionRecord[] | null\n\t\treadonly baseIssuedAt: number | undefined\n\t\treadonly displayed: readonly CollectionRecord[]\n\t\treadonly patchable: boolean\n\t}> {\n\t\treturn [...this.subscriptions.values()].map((sub) => ({\n\t\t\tdescriptor: sub.descriptor,\n\t\t\tbase: sub.base ?? null,\n\t\t\tbaseIssuedAt: sub.baseIssuedAt,\n\t\t\tdisplayed: sub.lastResults,\n\t\t\tpatchable: this.isPatchableSub(sub),\n\t\t}))\n\t}\n\n\t/** Whether a subscription's query may be patched (decided once). */\n\tprivate isPatchableSub(sub: Subscription): boolean {\n\t\tif (sub.patchable !== undefined) return sub.patchable\n\t\tconst definition = this.getDefinition?.(sub.descriptor.collection)\n\t\tconst verdict = definition !== undefined && isPatchable(sub.descriptor, definition)\n\t\tsub.patchable = verdict\n\t\treturn verdict\n\t}\n\n\t/** Recompute one subscription's display from its base and deliver it when it changed. */\n\tprivate patch(sub: Subscription, registry: PendingWrites, applicable: ApplicableCache): void {\n\t\tconst startedAt = this.onPatched ? this.clock() : 0\n\t\tconst base = sub.base\n\t\tconst issuedAt = sub.baseIssuedAt\n\t\tif (!base || issuedAt === undefined || !this.isPatchableSub(sub)) return\n\t\t// Subscriptions of one collection nearly always share a base epoch: look the\n\t\t// entries up once per (collection, epoch) per pass.\n\t\tconst collection = sub.descriptor.collection\n\t\tif (applicable.collection !== collection || applicable.issuedAt !== issuedAt) {\n\t\t\tapplicable.collection = collection\n\t\t\tapplicable.issuedAt = issuedAt\n\t\t\tapplicable.entries = registry.applicable(collection, issuedAt)\n\t\t}\n\t\tconst shown = this.overlayRows(sub, base, applicable.entries)\n\t\tconst equal = sub.resultsEqual ?? defaultResultsEqual\n\t\tif (sub.delivered && equal(sub.lastResults, shown)) return\n\t\tsub.lastResults = shown\n\t\tsub.delivered = true\n\t\tthis.overlayCounters.patchedDeliveries++\n\t\tactivePhaseTimers()?.noteCallback(performance.now())\n\t\ttry {\n\t\t\tsub.callback(shown)\n\t\t} catch (error) {\n\t\t\tthis.reportError(sub, error, 'callback')\n\t\t}\n\t\tthis.onPatched?.({\n\t\t\tqueryId: sub.id,\n\t\t\tcollection,\n\t\t\tresultCount: shown.length,\n\t\t\tdurationMs: this.clock() - startedAt,\n\t\t})\n\t}\n\n\tprivate overlayRows(\n\t\tsub: Subscription,\n\t\tbase: CollectionRecord[],\n\t\tentries: readonly PendingEntry[],\n\t): CollectionRecord[] {\n\t\tif (entries.length === 0) {\n\t\t\tsub.skippedWrites = undefined\n\t\t\treturn base\n\t\t}\n\t\tconst { rows, skipped } = applyOverlayReport(base, entries, sub.descriptor)\n\t\tthis.overlayCounters.skippedEntries += skipped.length\n\t\tsub.skippedWrites =\n\t\t\tskipped.length > 0 ? new Set(skipped.map((entry) => entry.writeId)) : undefined\n\t\treturn rows\n\t}\n\n\t/**\n\t * A SQL result arrived for `sub`: it becomes the base, the entries it may not contain\n\t * are applied on top, and entries every subscription has now read past are dropped.\n\t *\n\t * @returns The rows to display\n\t */\n\tprivate settleRun(\n\t\tsub: Subscription,\n\t\tresults: CollectionRecord[],\n\t\tissuedAt: number,\n\t\tregistry: PendingWrites,\n\t\tseedStamp: number,\n\t): CollectionRecord[] {\n\t\tif (!this.isPatchableSub(sub)) return results\n\t\t// Patchable means no relations: these are plain rows of the collection, the shape a\n\t\t// base read returns, so the next edit of one of them needs no read.\n\t\tregistry.seedFromRead(sub.descriptor.collection, results, seedStamp)\n\t\t// What the previous display left out (an entry it could not apply was never shown).\n\t\tconst previousIssuedAt = sub.delivered && sub.base ? sub.baseIssuedAt : undefined\n\t\tconst previousSkipped = sub.skippedWrites\n\t\tsub.base = results\n\t\tsub.baseIssuedAt = issuedAt\n\t\tconst collection = sub.descriptor.collection\n\t\tconst shown = this.overlayRows(sub, results, registry.applicable(collection, issuedAt))\n\t\tif (previousIssuedAt !== undefined) {\n\t\t\tthis.verifySettle(sub, registry, results, previousIssuedAt, issuedAt, previousSkipped)\n\t\t}\n\t\tthis.settleEntries(collection, registry)\n\t\treturn shown\n\t}\n\n\t/**\n\t * The self-check (I10): the writes this result newly contains were shown from a\n\t * prediction; compare the prediction with what the database now holds and report a\n\t * difference (`store:overlay-diverged`). It judges only what it can judge exactly:\n\t * the last committed write of each record (a later write legitimately replaces the\n\t * fields of an earlier one), against the SQL result itself (never the display, which\n\t * other pending writes shape), in a collection nothing else touched while the write was\n\t * pending (a remote change, another tab, an unpredicted write may legitimately change\n\t * the record), on the fields the write set. Membership is judged only for a query whose\n\t * membership depends on the record alone: a page limit makes it depend on other rows\n\t * (and on rollbacks of other writes), and the two metadata times are only approximated.\n\t */\n\tprivate verifySettle(\n\t\tsub: Subscription,\n\t\tregistry: PendingWrites,\n\t\tbase: readonly CollectionRecord[],\n\t\tpreviousIssuedAt: number,\n\t\tissuedAt: number,\n\t\tpreviousSkipped: ReadonlySet<string> | undefined,\n\t): void {\n\t\tconst collection = sub.descriptor.collection\n\t\tconst crossed = registry.crossed(collection, previousIssuedAt, issuedAt)\n\t\tif (crossed.length === 0) return\n\t\tconst membershipExact = sub.descriptor.limit === undefined && !timeSensitive(sub.descriptor)\n\t\tconst lastByRecord = new Map<string, PendingEntry>()\n\t\tfor (const entry of crossed) {\n\t\t\tconst seen = lastByRecord.get(entry.recordId)\n\t\t\tif (!seen || (entry.retiredAt ?? 0) >= (seen.retiredAt ?? 0)) {\n\t\t\t\tlastByRecord.set(entry.recordId, entry)\n\t\t\t}\n\t\t}\n\t\tfor (const entry of lastByRecord.values()) {\n\t\t\tif (previousSkipped?.has(entry.writeId)) continue\n\t\t\tif (registry.foreignCount(collection) !== entry.foreignAtAdd) continue\n\t\t\tconst actual = base.find((row) => row.id === entry.recordId)\n\t\t\t// The entry holds the record its own transaction committed: a row stamped differently\n\t\t\t// was changed again since (a remote apply whose notification has not arrived yet).\n\t\t\tif (actual !== undefined && actual.updatedAt !== entry.record.updatedAt) continue\n\t\t\t// A later write of the record whose commit this read may already contain (committed in\n\t\t\t// the database, its epoch not assigned yet) would explain any difference.\n\t\t\tif (\n\t\t\t\tregistry\n\t\t\t\t\t.list()\n\t\t\t\t\t.some(\n\t\t\t\t\t\t(other) =>\n\t\t\t\t\t\t\tother.recordId === entry.recordId &&\n\t\t\t\t\t\t\tother.writeId !== entry.writeId &&\n\t\t\t\t\t\t\t(other.retiredAt === null || other.retiredAt > issuedAt),\n\t\t\t\t\t)\n\t\t\t) {\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\tlet fields: string[] = []\n\t\t\tif (entry.kind === 'delete') {\n\t\t\t\tif (actual !== undefined && membershipExact) fields = ['$membership']\n\t\t\t} else if (actual === undefined) {\n\t\t\t\tif (membershipExact && matches(sub.descriptor, entry.record)) fields = ['$membership']\n\t\t\t} else if (membershipExact && !matches(sub.descriptor, entry.record)) {\n\t\t\t\tfields = ['$membership']\n\t\t\t} else if (entry.patch) {\n\t\t\t\tconst names = Object.keys(entry.patch)\n\t\t\t\tfields = divergentFields(pickFields(entry.record, names), pickFields(actual, names))\n\t\t\t}\n\t\t\tif (fields.length > 0) registry.reportDivergence(entry, fields)\n\t\t}\n\t}\n\n\t/**\n\t * Drop committed entries that every patchable subscription of `collection` has read\n\t * past (its base was issued at or after the entry's commit). A subscription still\n\t * waiting for its first result holds them all.\n\t */\n\tprivate settleEntries(collection: string, registry: PendingWrites): void {\n\t\tif (!registry.hasSettling(collection)) return\n\t\tlet oldest = Number.POSITIVE_INFINITY\n\t\tfor (const sub of this.subscriptions.values()) {\n\t\t\tif (sub.descriptor.collection !== collection || !this.isPatchableSub(sub)) continue\n\t\t\toldest = Math.min(oldest, sub.base ? (sub.baseIssuedAt ?? -1) : -1)\n\t\t}\n\t\tif (oldest >= 0) registry.settleCollection(collection, oldest)\n\t}\n\n\t/**\n\t * Forget cached rows a committed change may have made stale (F21). The post-commit\n\t * publication of a predicted local write is the exception: the registry cached its\n\t * committed row itself.\n\t */\n\tprivate invalidateCachedRows(change: RecordsChange): void {\n\t\tconst registry = this.registry()\n\t\tif (!registry) return\n\t\tif (change.operation && registry.ownsOperation(change.operation.id)) return\n\t\tregistry.invalidate(change.collection, change.ids)\n\t}\n\n\t/**\n\t * The registry in force, attached to while subscriptions exist. Null with the overlay\n\t * off, which is the only thing the hot paths ever test.\n\t */\n\tprivate registry(): PendingWrites | null {\n\t\tconst registry = this.getRegistry?.() ?? null\n\t\tif (registry === this.attachedRegistry) return registry\n\t\tthis.detachRegistry()\n\t\t// A base belongs to the registry whose epochs it was issued under (and a removed\n\t\t// overlay no longer keeps it current): forget them, the next result sets them again.\n\t\tfor (const sub of this.subscriptions.values()) {\n\t\t\tsub.base = null\n\t\t\tsub.baseIssuedAt = undefined\n\t\t}\n\t\tif (registry !== null && this.subscriptions.size > 0) {\n\t\t\tthis.attachedRegistry = registry\n\t\t\tthis.stopListening = registry.onChange((change) => this.onRegistryChange(change))\n\t\t}\n\t\treturn registry\n\t}\n\n\tprivate detachRegistry(): void {\n\t\tthis.stopListening?.()\n\t\tthis.stopListening = null\n\t\tthis.attachedRegistry = null\n\t}\n\n\tprivate onRegistryChange(change: RegistryChange): void {\n\t\t// An unknown outcome changes nothing: the entry stays shown, as it was. A commit\n\t\t// keeps the entry applied (no flicker, F3) but replaces its predicted record by the\n\t\t// stored one, so the display is recomputed: it always equals f(base, entries).\n\t\tif (change.kind === 'unknown') return\n\t\tfor (const collection of change.collections) this.overlayChanged(collection)\n\t}\n\n\tprivate scheduleFlush(): void {\n\t\tif (this.flushScheduled) return\n\t\tthis.flushScheduled = true\n\t\tqueueMicrotask(() => {\n\t\t\t// flush() cannot reject: run() routes every failure to the error channel.\n\t\t\tvoid this.flush()\n\t\t})\n\t}\n}\n\n/** Fields a prediction only approximates (the two metadata times). */\nconst TIME_FIELDS: ReadonlySet<string> = new Set(['createdAt', 'updatedAt'])\n\n/**\n * Whether the query's membership or page depends on `createdAt` / `updatedAt`: the\n * overlay predicts those to within a few milliseconds, so a row on a threshold or at a\n * page edge can legitimately land on the other side at settle.\n */\nfunction timeSensitive(descriptor: QueryDescriptor): boolean {\n\tif (Object.keys(descriptor.where).some((field) => TIME_FIELDS.has(field))) return true\n\treturn descriptor.limit !== undefined && descriptor.orderBy.some((o) => TIME_FIELDS.has(o.field))\n}\n\n/** A record reduced to the named fields (for comparing only what a write set). */\nfunction pickFields(record: CollectionRecord, names: readonly string[]): CollectionRecord {\n\tconst out: CollectionRecord = { id: record.id, createdAt: 0, updatedAt: 0 }\n\tfor (const name of names) if (name in record) out[name] = record[name]\n\treturn out\n}\n","import { OFFLINE_PIN_LIMIT, OfflineKeepError } from '@korajs/core'\nimport type { StorageAdapter, Transaction } from '../types'\n\n/**\n * Pins (`app.offline.keep()`, offline-readiness design 4.3) live in two local-only tables.\n * They are not operations and never sync. Created on first open, so existing databases need\n * no migration.\n */\nexport const OFFLINE_PIN_TABLES_DDL: readonly string[] = [\n\t'CREATE TABLE IF NOT EXISTS _kora_offline_pins (\\n' +\n\t\t'  id TEXT PRIMARY KEY NOT NULL,\\n' +\n\t\t'  collection TEXT NOT NULL,\\n' +\n\t\t'  where_json TEXT NOT NULL,\\n' +\n\t\t'  files INTEGER NOT NULL,\\n' +\n\t\t'  explicit INTEGER NOT NULL,\\n' +\n\t\t'  created_at INTEGER NOT NULL,\\n' +\n\t\t'  completed_at INTEGER\\n' +\n\t\t')',\n\t'CREATE TABLE IF NOT EXISTS _kora_offline_pin_holds (\\n' +\n\t\t'  pin_id TEXT NOT NULL,\\n' +\n\t\t'  holder TEXT NOT NULL,\\n' +\n\t\t'  tab_id TEXT NOT NULL,\\n' +\n\t\t'  tab_lock TEXT,\\n' +\n\t\t'  PRIMARY KEY (pin_id, holder)\\n' +\n\t\t')',\n]\n\n/** A pin as stored. */\nexport interface StoredOfflinePin {\n\tid: string\n\tcollection: string\n\twhere: Record<string, unknown>\n\tfiles: boolean\n\t/** Kept by `keep()` and not yet released. */\n\texplicit: boolean\n\tcreatedAt: number\n\tcompletedAt: number | null\n}\n\n/** A component's hold on a pin, as stored. */\nexport interface StoredOfflinePinHold {\n\tpinId: string\n\t/** This tab's id plus a per-hold id. */\n\tholder: string\n\t/** The holder's tab (the `tabId` of its version-gate tab lock). */\n\ttabId: string\n\t/** The name of the holder's tab lock, when it has one (what a watcher waits on). */\n\ttabLock: string | null\n}\n\n/** What a pin write changed, so callers know whether to tell the sync view. */\nexport interface OfflinePinWriteResult {\n\t/** The pin row was created by this write. */\n\tcreated: boolean\n\t/** The pin row was deleted by this write. */\n\tdeleted: boolean\n}\n\n/** The fields a pin is created with. */\nexport interface NewOfflinePin {\n\tid: string\n\tcollection: string\n\twhere: Record<string, unknown>\n\tfiles: boolean\n}\n\ninterface PinRow {\n\tid: string\n\tcollection: string\n\twhere_json: string\n\tfiles: number\n\texplicit: number\n\tcreated_at: number\n\tcompleted_at: number | null\n}\n\ninterface HoldRow {\n\tpin_id: string\n\tholder: string\n\ttab_id: string\n\ttab_lock: string | null\n}\n\ntype PinTx = Pick<Transaction, 'execute' | 'query'>\n\n/** Create the pin tables if they do not exist. */\nexport async function ensureOfflinePinTables(adapter: StorageAdapter): Promise<void> {\n\tfor (const ddl of OFFLINE_PIN_TABLES_DDL) await adapter.execute(ddl)\n}\n\nfunction parseWhere(raw: string): Record<string, unknown> {\n\ttry {\n\t\tconst value: unknown = JSON.parse(raw)\n\t\treturn value !== null && typeof value === 'object' && !Array.isArray(value)\n\t\t\t? (value as Record<string, unknown>)\n\t\t\t: {}\n\t} catch {\n\t\t// An unreadable filter must not widen what a pin keeps: keep the pin, match everything\n\t\t// in its collection (the over-delivering, never-under-delivering side).\n\t\treturn {}\n\t}\n}\n\nfunction toPin(row: PinRow): StoredOfflinePin {\n\treturn {\n\t\tid: row.id,\n\t\tcollection: row.collection,\n\t\twhere: parseWhere(row.where_json),\n\t\tfiles: row.files === 1,\n\t\texplicit: row.explicit === 1,\n\t\tcreatedAt: row.created_at,\n\t\tcompletedAt: row.completed_at,\n\t}\n}\n\n/** Every pin, oldest first. */\nexport async function loadOfflinePins(\n\tadapter: Pick<StorageAdapter, 'query'>,\n): Promise<StoredOfflinePin[]> {\n\tconst rows = await adapter.query<PinRow>(\n\t\t'SELECT id, collection, where_json, files, explicit, created_at, completed_at FROM _kora_offline_pins ORDER BY created_at, id',\n\t)\n\treturn rows.map(toPin)\n}\n\n/** Every hold of every pin. */\nexport async function loadOfflinePinHolds(\n\tadapter: Pick<StorageAdapter, 'query'>,\n): Promise<StoredOfflinePinHold[]> {\n\tconst rows = await adapter.query<HoldRow>(\n\t\t'SELECT pin_id, holder, tab_id, tab_lock FROM _kora_offline_pin_holds ORDER BY pin_id, holder',\n\t)\n\treturn rows.map((row) => ({\n\t\tpinId: row.pin_id,\n\t\tholder: row.holder,\n\t\ttabId: row.tab_id,\n\t\ttabLock: row.tab_lock,\n\t}))\n}\n\nasync function pinExists(tx: PinTx, id: string): Promise<boolean> {\n\treturn (\n\t\t(await tx.query<{ id: string }>('SELECT id FROM _kora_offline_pins WHERE id = ?', [id]))\n\t\t\t.length > 0\n\t)\n}\n\n/** Create the pin row when it is absent, refusing past the limit. Returns whether it was created. */\nasync function ensurePinInTx(tx: PinTx, pin: NewOfflinePin, now: number): Promise<boolean> {\n\tif (await pinExists(tx, pin.id)) return false\n\tconst [count] = await tx.query<{ n: number }>('SELECT COUNT(*) AS n FROM _kora_offline_pins')\n\tif ((count?.n ?? 0) >= OFFLINE_PIN_LIMIT) {\n\t\tthrow new OfflineKeepError(\n\t\t\t`This database already keeps ${OFFLINE_PIN_LIMIT} pins (the most it can): collection \"${pin.collection}\" was not kept.`,\n\t\t\t'OFFLINE_PIN_LIMIT',\n\t\t\t{\n\t\t\t\tlimit: OFFLINE_PIN_LIMIT,\n\t\t\t\tcollection: pin.collection,\n\t\t\t\tfix: 'Release a pin you no longer need with app.offline.release(), or widen one existing pin instead of adding another.',\n\t\t\t},\n\t\t)\n\t}\n\tawait tx.execute(\n\t\t'INSERT INTO _kora_offline_pins (id, collection, where_json, files, explicit, created_at, completed_at) VALUES (?, ?, ?, ?, 0, ?, NULL)',\n\t\t[pin.id, pin.collection, JSON.stringify(pin.where), pin.files ? 1 : 0, now],\n\t)\n\treturn true\n}\n\n/** Delete a pin that is not explicit and has no hold. Returns whether it was deleted. */\nasync function dropOrphanPinInTx(tx: PinTx, id: string): Promise<boolean> {\n\tconst [row] = await tx.query<{ explicit: number }>(\n\t\t'SELECT explicit FROM _kora_offline_pins WHERE id = ?',\n\t\t[id],\n\t)\n\tif (!row || row.explicit === 1) return false\n\tconst [holds] = await tx.query<{ n: number }>(\n\t\t'SELECT COUNT(*) AS n FROM _kora_offline_pin_holds WHERE pin_id = ?',\n\t\t[id],\n\t)\n\tif ((holds?.n ?? 0) > 0) return false\n\tawait tx.execute('DELETE FROM _kora_offline_pins WHERE id = ?', [id])\n\treturn true\n}\n\n/** `keep()`: create the pin if absent and mark it explicit. Idempotent. */\nexport async function keepOfflinePin(\n\tadapter: StorageAdapter,\n\tpin: NewOfflinePin,\n\tnow: number,\n): Promise<OfflinePinWriteResult> {\n\tlet created = false\n\tawait adapter.transaction(async (tx) => {\n\t\tcreated = await ensurePinInTx(tx, pin, now)\n\t\tawait tx.execute('UPDATE _kora_offline_pins SET explicit = 1 WHERE id = ?', [pin.id])\n\t})\n\treturn { created, deleted: false }\n}\n\n/** `release()`: clear the explicit flag; the pin goes when no component holds it. */\nexport async function releaseOfflinePin(\n\tadapter: StorageAdapter,\n\tid: string,\n\toptions: { stillHeld?: boolean } = {},\n): Promise<OfflinePinWriteResult> {\n\tlet deleted = false\n\tawait adapter.transaction(async (tx) => {\n\t\tawait tx.execute('UPDATE _kora_offline_pins SET explicit = 0 WHERE id = ?', [id])\n\t\t// A hold the store cannot see (explicit mode counts in memory) keeps the pin.\n\t\tdeleted = options.stillHeld === true ? false : await dropOrphanPinInTx(tx, id)\n\t})\n\treturn { created: false, deleted }\n}\n\n/**\n * Create a pin without marking it kept by the app (a component's hold in `explicit` mode,\n * which has no stored hold rows). An existing pin, kept or not, is left as it is.\n */\nexport async function ensureOfflinePin(\n\tadapter: StorageAdapter,\n\tpin: NewOfflinePin,\n\tnow: number,\n): Promise<OfflinePinWriteResult> {\n\tlet created = false\n\tawait adapter.transaction(async (tx) => {\n\t\tcreated = await ensurePinInTx(tx, pin, now)\n\t})\n\treturn { created, deleted: false }\n}\n\n/** A component starts holding a pin (creating it when absent). Idempotent per holder. */\nexport async function addOfflinePinHold(\n\tadapter: StorageAdapter,\n\tpin: NewOfflinePin,\n\thold: Omit<StoredOfflinePinHold, 'pinId'>,\n\tnow: number,\n): Promise<OfflinePinWriteResult> {\n\tlet created = false\n\tawait adapter.transaction(async (tx) => {\n\t\tcreated = await ensurePinInTx(tx, pin, now)\n\t\tawait tx.execute(\n\t\t\t'INSERT OR REPLACE INTO _kora_offline_pin_holds (pin_id, holder, tab_id, tab_lock) VALUES (?, ?, ?, ?)',\n\t\t\t[pin.id, hold.holder, hold.tabId, hold.tabLock],\n\t\t)\n\t})\n\treturn { created, deleted: false }\n}\n\n/** A component stops holding a pin; the pin goes with its last holder unless it is explicit. */\nexport async function removeOfflinePinHold(\n\tadapter: StorageAdapter,\n\tpinId: string,\n\tholder: string,\n): Promise<OfflinePinWriteResult> {\n\tlet deleted = false\n\tawait adapter.transaction(async (tx) => {\n\t\tawait tx.execute('DELETE FROM _kora_offline_pin_holds WHERE pin_id = ? AND holder = ?', [\n\t\t\tpinId,\n\t\t\tholder,\n\t\t])\n\t\tdeleted = await dropOrphanPinInTx(tx, pinId)\n\t})\n\treturn { created: false, deleted }\n}\n\n/**\n * Delete the holds of tabs that no longer exist, in one transaction, and the pins that only\n * those holds kept. `isStale` is asked once per distinct holder tab.\n */\nexport async function pruneOfflinePinHolds(\n\tadapter: StorageAdapter,\n\tisStale: (tabId: string) => boolean,\n): Promise<{ holdsRemoved: number; pinsRemoved: number }> {\n\tlet holdsRemoved = 0\n\tlet pinsRemoved = 0\n\tawait adapter.transaction(async (tx) => {\n\t\tconst holds = await tx.query<HoldRow>(\n\t\t\t'SELECT pin_id, holder, tab_id, tab_lock FROM _kora_offline_pin_holds',\n\t\t)\n\t\tconst verdicts = new Map<string, boolean>()\n\t\tconst touched = new Set<string>()\n\t\tfor (const hold of holds) {\n\t\t\tlet stale = verdicts.get(hold.tab_id)\n\t\t\tif (stale === undefined) {\n\t\t\t\tstale = isStale(hold.tab_id)\n\t\t\t\tverdicts.set(hold.tab_id, stale)\n\t\t\t}\n\t\t\tif (!stale) continue\n\t\t\tawait tx.execute('DELETE FROM _kora_offline_pin_holds WHERE pin_id = ? AND holder = ?', [\n\t\t\t\thold.pin_id,\n\t\t\t\thold.holder,\n\t\t\t])\n\t\t\tholdsRemoved++\n\t\t\ttouched.add(hold.pin_id)\n\t\t}\n\t\tfor (const id of touched) {\n\t\t\tif (await dropOrphanPinInTx(tx, id)) pinsRemoved++\n\t\t}\n\t})\n\treturn { holdsRemoved, pinsRemoved }\n}\n\n/** Record when a pin was last seen complete (display only). */\nexport async function markOfflinePinCompleted(\n\tadapter: StorageAdapter,\n\tid: string,\n\tat: number | null,\n): Promise<void> {\n\tawait adapter.execute('UPDATE _kora_offline_pins SET completed_at = ? WHERE id = ?', [at, id])\n}\n","import { HybridLogicalClock, MAX_LOGICAL, quoteIdent } from '@korajs/core'\nimport type { HLCTimestamp, Operation, SchemaDefinition } from '@korajs/core'\nimport { parseFieldVersions, serializeFieldVersions } from '../lww/field-versions'\nimport { serializeRowVersion } from '../lww/row-version'\nimport { buildInsertQuery } from '../query/sql-builder'\nimport { deserializeOperationWithCollection, serializeOperation } from '../serialization/serializer'\nimport type { OperationRow, RawCollectionRow, StorageAdapter, Transaction } from '../types'\nimport { rehashOperation } from './rehash-operation'\n\n/**\n * Result of re-stamping unsynced operations after a clock correction.\n */\nexport interface ClockRebaseResult {\n\t/** The rewritten operations, in causal order (original HLC total order preserved). */\n\toperations: Operation[]\n\t/** Maps each old (pre-rebase) operation id to its new content-addressed id. */\n\tidMapping: Record<string, string>\n\t/** Number of operations that were re-stamped. */\n\trebasedCount: number\n\t/** Highest timestamp assigned during the rebase, or null when nothing was rebased. */\n\tnewMaxTimestamp: HLCTimestamp | null\n}\n\n/**\n * The serialized logical counter is zero-padded to 5 digits; a logical value\n * needing more digits would break the lexicographic ordering of the stored\n * timestamp / `_version` columns. Overflow spills into wallTime instead.\n * Derived from the clock's own cap so the two can never drift apart.\n */\nconst LOGICAL_COUNTER_LIMIT = MAX_LOGICAL + 1\n\nfunction emptyResult(): ClockRebaseResult {\n\treturn { operations: [], idMapping: {}, rebasedCount: 0, newMaxTimestamp: null }\n}\n\n/**\n * Re-stamp unsynced (never server-acknowledged) operations after a fast device\n * clock was corrected, so sync can resume immediately instead of waiting for\n * real time to catch up with the future timestamps.\n *\n * This is safe for exactly the same reason rewriting unpushed git commits is\n * safe: unacknowledged operations have never been shared, so no other replica\n * can hold a reference to their old ids or timestamps. Acknowledged operations\n * are immutable forever and are never touched here.\n *\n * The relative order of the rebased operations is preserved: they are sorted by\n * their original HLC total order and assigned consecutive logical counters on a\n * single new wall time, chosen to sort after every non-rebased operation in the\n * log (and after corrected \"now\").\n */\nexport async function rebaseUnsyncedOperationsInLog(\n\tadapter: StorageAdapter,\n\tschema: SchemaDefinition,\n\tunsyncedOpIds: string[],\n\tcorrectedNowMs: number,\n\toptions: {\n\t\t/**\n\t\t * Runs last in the rewrite's transaction, with the rewritten operations: what must be\n\t\t * durable with the rewrite (re-folding their records) commits with it.\n\t\t */\n\t\tinTransaction?: (\n\t\t\ttx: Transaction,\n\t\t\toperations: readonly Operation[],\n\t\t\trewrite: { idMapping: Record<string, string>; newMaxTimestamp: HLCTimestamp | null },\n\t\t) => Promise<void>\n\t} = {},\n): Promise<ClockRebaseResult> {\n\tif (unsyncedOpIds.length === 0) {\n\t\treturn emptyResult()\n\t}\n\tlet result: ClockRebaseResult = emptyResult()\n\tawait adapter.transaction(async (tx) => {\n\t\tconst rebaseIds = new Set(unsyncedOpIds)\n\n\t\t// Read phase, inside the transaction (no local write lands between it and the rewrite).\n\t\t// A single full scan per collection serves two purposes at once:\n\t\t// locating the rebased rows and finding the max timestamp of everything else.\n\t\t// This avoids SQL IN-list size limits and keeps the logic trivially correct\n\t\t// (correctness over performance; the op log is compacted periodically anyway).\n\t\tconst rebased: Operation[] = []\n\t\t// Serialized HLC strings sort lexicographically in the same order as\n\t\t// HybridLogicalClock.compare, so a plain string max is a timestamp max.\n\t\tlet maxOtherSerializedTs: string | null = null\n\n\t\tfor (const collectionName of Object.keys(schema.collections)) {\n\t\t\tconst rows = await tx.query<OperationRow>(\n\t\t\t\t`SELECT * FROM ${quoteIdent(`_kora_ops_${collectionName}`)}`,\n\t\t\t)\n\t\t\tfor (const row of rows) {\n\t\t\t\tif (rebaseIds.has(row.id)) {\n\t\t\t\t\trebased.push(deserializeOperationWithCollection(row, collectionName))\n\t\t\t\t} else if (maxOtherSerializedTs === null || row.timestamp > maxOtherSerializedTs) {\n\t\t\t\t\tmaxOtherSerializedTs = row.timestamp\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\tif (rebased.length === 0) return\n\n\t\t// The new wall time must sort after both corrected real time and every\n\t\t// operation that stays in the log, or the rebased ops could lose LWW\n\t\t// conflicts they previously won locally (silent data reordering).\n\t\tconst maxOtherWallTime =\n\t\t\tmaxOtherSerializedTs === null\n\t\t\t\t? Number.NEGATIVE_INFINITY\n\t\t\t\t: HybridLogicalClock.deserialize(maxOtherSerializedTs).wallTime\n\t\tconst baseWallTime = Math.max(correctedNowMs, maxOtherWallTime + 1)\n\n\t\t// Preserve the ORIGINAL total order so causal relationships (dep before\n\t\t// dependent) survive the re-stamp.\n\t\trebased.sort((a, b) => HybridLogicalClock.compare(a.timestamp, b.timestamp))\n\n\t\tconst newTimestamps: HLCTimestamp[] = rebased.map((op, i) => ({\n\t\t\t// Spill into wallTime past the 5-digit logical serialization limit so the\n\t\t\t// serialized order stays correct even for enormous offline queues.\n\t\t\twallTime: baseWallTime + Math.floor(i / LOGICAL_COUNTER_LIMIT),\n\t\t\tlogical: i % LOGICAL_COUNTER_LIMIT,\n\t\t\tnodeId: op.nodeId,\n\t\t}))\n\n\t\t// Recompute content-addressed ids in the original (causal) order. A version-2 id\n\t\t// (protocol v2, CORE-1) covers causalDeps, so each dependency's new id must be known\n\t\t// before its dependents are hashed: deps among the rebased set are remapped first.\n\t\t// Deps on non-rebased (already acknowledged or foreign) operations keep their ids.\n\t\t// Each operation keeps its own hash version: a version-1 operation (written before\n\t\t// beta.13) is re-hashed with version 1. The deserialized `data` has the embedded\n\t\t// metadata keys already stripped, matching exactly what the creation path hashed.\n\t\tconst idMapping: Record<string, string> = {}\n\t\tconst newOperations: Operation[] = []\n\t\tfor (let i = 0; i < rebased.length; i++) {\n\t\t\tconst op = rebased[i]\n\t\t\tconst ts = newTimestamps[i]\n\t\t\tif (!op || !ts) {\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\tconst causalDeps = op.causalDeps.map((dep) => idMapping[dep] ?? dep)\n\t\t\tconst newId = await rehashOperation({ ...op, timestamp: ts, causalDeps })\n\t\t\tidMapping[op.id] = newId\n\t\t\tnewOperations.push({ ...op, id: newId, timestamp: ts, causalDeps })\n\t\t}\n\n\t\t// Write phase, in the same transaction: a crash can never leave the log with a mix of\n\t\t// old and new stamps (which would corrupt causal deps).\n\t\tfor (let i = 0; i < rebased.length; i++) {\n\t\t\tconst oldOp = rebased[i]\n\t\t\tconst newOp = newOperations[i]\n\t\t\tif (!oldOp || !newOp) {\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\tconst opsTable = `_kora_ops_${oldOp.collection}`\n\t\t\tawait tx.execute(`DELETE FROM ${quoteIdent(opsTable)} WHERE id = ?`, [oldOp.id])\n\t\t\tconst opInsert = buildInsertQuery(\n\t\t\t\topsTable,\n\t\t\t\tserializeOperation(newOp) as unknown as Record<string, unknown>,\n\t\t\t)\n\t\t\tawait tx.execute(opInsert.sql, opInsert.params)\n\n\t\t\t// Only touch materialized rows whose current version stamp came from\n\t\t\t// this exact operation — a row last written by a different (newer,\n\t\t\t// non-rebased) op must keep its version, or LWW guards would lie.\n\t\t\tconst oldVersion = serializeRowVersion(oldOp.timestamp)\n\t\t\tconst newVersion = serializeRowVersion(newOp.timestamp)\n\t\t\tawait tx.execute(\n\t\t\t\t`UPDATE ${quoteIdent(oldOp.collection)} SET _version = ?, _updated_at = ? WHERE id = ? AND _version = ?`,\n\t\t\t\t[newVersion, newOp.timestamp.wallTime, oldOp.recordId, oldVersion],\n\t\t\t)\n\n\t\t\t// Per-field versions stamped by this operation carry the same old (pre-\n\t\t\t// rebase) version string, so re-stamp them too — otherwise field-level\n\t\t\t// LWW would keep comparing against the uncorrected timestamp forever.\n\t\t\tconst rows = await tx.query<RawCollectionRow>(\n\t\t\t\t`SELECT _field_versions FROM ${quoteIdent(oldOp.collection)} WHERE id = ?`,\n\t\t\t\t[oldOp.recordId],\n\t\t\t)\n\t\t\tconst fieldVersions = parseFieldVersions(rows[0]?._field_versions)\n\t\t\tlet changed = false\n\t\t\tfor (const [field, version] of Object.entries(fieldVersions)) {\n\t\t\t\tif (version === oldVersion) {\n\t\t\t\t\tfieldVersions[field] = newVersion\n\t\t\t\t\tchanged = true\n\t\t\t\t}\n\t\t\t}\n\t\t\tif (changed) {\n\t\t\t\tawait tx.execute(\n\t\t\t\t\t`UPDATE ${quoteIdent(oldOp.collection)} SET _field_versions = ? WHERE id = ?`,\n\t\t\t\t\t[serializeFieldVersions(fieldVersions), oldOp.recordId],\n\t\t\t\t)\n\t\t\t}\n\n\t\t\t// The insert op also stamped `_created_at` (the developer-visible\n\t\t\t// `createdAt`). Replicas materialize it from the rebased op's corrected\n\t\t\t// wallTime, so the originating device must re-stamp its own row too or\n\t\t\t// `createdAt` diverges forever after a clock rebase. Match on the old\n\t\t\t// (pre-rebase) created time so only rows this op created are touched.\n\t\t\tif (oldOp.type === 'insert') {\n\t\t\t\tawait tx.execute(\n\t\t\t\t\t`UPDATE ${quoteIdent(oldOp.collection)} SET _created_at = ? WHERE id = ? AND _created_at = ?`,\n\t\t\t\t\t[newOp.timestamp.wallTime, oldOp.recordId, oldOp.timestamp.wallTime],\n\t\t\t\t)\n\t\t\t}\n\t\t}\n\t\t// sequenceNumbers are intentionally unchanged, so `_kora_version_vector`\n\t\t// needs no update: the version vector tracks sequences, not timestamps.\n\t\tawait options.inTransaction?.(tx, newOperations, {\n\t\t\tidMapping,\n\t\t\tnewMaxTimestamp: newTimestamps[newTimestamps.length - 1] ?? null,\n\t\t})\n\n\t\tresult = {\n\t\t\toperations: newOperations,\n\t\t\tidMapping,\n\t\t\trebasedCount: newOperations.length,\n\t\t\tnewMaxTimestamp: newTimestamps[newTimestamps.length - 1] ?? null,\n\t\t}\n\t})\n\treturn result\n}\n","import { HybridLogicalClock, KoraError, quoteIdent } from '@korajs/core'\nimport type { Operation, SchemaDefinition } from '@korajs/core'\nimport { parseFieldVersions, serializeFieldVersions } from '../lww/field-versions'\nimport { serializeRowVersion } from '../lww/row-version'\nimport { buildInsertQuery } from '../query/sql-builder'\nimport { deserializeOperationWithCollection, serializeOperation } from '../serialization/serializer'\nimport { allocateNextSequenceInTransaction } from '../store/sequence-allocator'\nimport type { OperationRow, RawCollectionRow, StorageAdapter, Transaction } from '../types'\nimport { rehashOperation } from './rehash-operation'\nimport { NODE_TOKEN_META_KEY } from './sync-state'\n\n/**\n * Every operation id a rotation re-authored, and its new id (`_kora_reauthored_ops`).\n * Kept so (a) an operation rotated in a later transaction that names an earlier-rotated\n * one as a causal dep names its new id, and (b) a queue entry under an old id left by a\n * crash of an earlier release can be recognized as rewritten and dropped\n * ({@link dropRewrittenQueueEntries}).\n */\nexport const REAUTHORED_OPS_TABLE = '_kora_reauthored_ops'\n\nconst REAUTHORED_OPS_DDL = `CREATE TABLE IF NOT EXISTS ${REAUTHORED_OPS_TABLE} (\n  old_id TEXT PRIMARY KEY NOT NULL,\n  new_id TEXT NOT NULL,\n  from_node TEXT NOT NULL,\n  to_node TEXT NOT NULL\n)`\n\n/** Create the id map table (idempotent). */\nexport async function ensureReauthoredOpsTable(adapter: StorageAdapter): Promise<void> {\n\tawait adapter.execute(REAUTHORED_OPS_DDL)\n}\n\n/**\n * Drop outbound-queue entries whose operation a rotation re-authored (the queue holds\n * the new id). A rotation rewrites the queue in its own transaction; this only cleans a\n * database an earlier release left between its two steps.\n */\nexport async function dropRewrittenQueueEntries(adapter: StorageAdapter): Promise<number> {\n\tawait ensureReauthoredOpsTable(adapter)\n\tconst rows = await adapter.query<{ n: number }>(\n\t\t`SELECT COUNT(*) AS n FROM _kora_sync_queue WHERE id IN (SELECT old_id FROM ${REAUTHORED_OPS_TABLE})`,\n\t)\n\tconst n = Number(rows[0]?.n ?? 0)\n\tif (n > 0) {\n\t\tawait adapter.execute(\n\t\t\t`DELETE FROM _kora_sync_queue WHERE id IN (SELECT old_id FROM ${REAUTHORED_OPS_TABLE})`,\n\t\t)\n\t}\n\treturn n\n}\n\n/** Result of {@link rotateUnsyncedOperationsInLog}. */\nexport interface NodeRotationResult {\n\t/** The node id the device uses from now on. */\n\tnodeId: string\n\t/** The rewritten operations under the new node id, in their original causal order. */\n\toperations: Operation[]\n\t/** Maps each old operation id to its new content-addressed id. */\n\tidMapping: Record<string, string>\n}\n\n/**\n * Move a device's never-acknowledged operations to a fresh node id (RT-21).\n *\n * The server refused this device's node id (`NODE_ID_CLAIMED`: another device holds\n * it, typically because the node token issued at the first claim was lost). The\n * device keeps its data by re-authoring its unsynced operations under a new node id:\n * same type, record, data and HLC wall time / counter, but the new node id in both\n * `nodeId` and `timestamp.nodeId`, sequence numbers 1..n in the original order, and\n * recomputed content-addressed ids (causal deps among them remapped). This is safe\n * for the same reason a clock rebase is: unacknowledged operations were never\n * shared, so no replica holds their old ids.\n *\n * Materialized rows are re-stamped so per-field LWW keeps comparing against the\n * rewritten timestamps; the version vector gets the new node's sequence (MAX with the\n * stored value) and the old node's entry is never lowered (W6). Everything, the scan\n * of the rotated operations included, runs in one transaction.\n *\n * @param adapter - The store's adapter\n * @param schema - The store schema (collections to scan)\n * @param unsyncedOpIds - Ids of the old node's operations the server never acknowledged\n * @param oldNodeId - The refused node id\n * @param newNodeId - The fresh node id\n * @param options - `moveDatabaseNode: false` re-authors another local node's operations\n *   without moving the database's own node id or node token (default true). `append:\n *   true` re-authors them under a node that already has operations (the store's own):\n *   they take its next sequence numbers, allocated in this transaction like every local\n *   write's, and the rewrite is refused (`TIMESTAMP_TAKEN`, nothing written) when a\n *   rewritten timestamp equals one the node already used.\n */\nexport async function rotateUnsyncedOperationsInLog(\n\tadapter: StorageAdapter,\n\tschema: SchemaDefinition,\n\tunsyncedOpIds: string[],\n\toldNodeId: string,\n\tnewNodeId: string,\n\toptions: {\n\t\tmoveDatabaseNode?: boolean\n\t\tappend?: boolean\n\t\t/**\n\t\t * Runs last in the rewrite's transaction, with the rewritten operations: what must be\n\t\t * durable with the rewrite (registering the node, binding its user, re-folding the\n\t\t * records) commits with it.\n\t\t */\n\t\tinTransaction?: (tx: Transaction, operations: readonly Operation[]) => Promise<void>\n\t} = {},\n): Promise<NodeRotationResult> {\n\tconst moveDatabaseNode = options.moveDatabaseNode !== false\n\tconst append = options.append === true\n\tconst rotateIds = new Set(unsyncedOpIds)\n\tconst idMapping: Record<string, string> = {}\n\tconst rewritten: Operation[] = []\n\n\tawait ensureReauthoredOpsTable(adapter)\n\t// One transaction from the scan to the last write (W6): the rotated set is read in\n\t// the transaction that rewrites it, so nothing committed in between is missed. The\n\t// persisted outbound queue is rewritten in it too: a crash can never leave an old id\n\t// queued (counted pending forever) beside its re-authored copy.\n\tawait adapter.transaction(async (tx) => {\n\t\t// Ids earlier rotations re-authored, so a dep on one names its new id.\n\t\tconst earlier = new Map<string, string>()\n\t\tfor (const row of await tx.query<{ old_id: string; new_id: string }>(\n\t\t\t`SELECT old_id, new_id FROM ${REAUTHORED_OPS_TABLE}`,\n\t\t)) {\n\t\t\tearlier.set(row.old_id, row.new_id)\n\t\t}\n\t\tconst resolveEarlier = (id: string): string => {\n\t\t\tlet current = id\n\t\t\tfor (let hops = 0; hops < 16; hops++) {\n\t\t\t\tconst next = earlier.get(current)\n\t\t\t\tif (next === undefined) return current\n\t\t\t\tcurrent = next\n\t\t\t}\n\t\t\treturn current\n\t\t}\n\t\tconst rotated: Operation[] = []\n\t\tfor (const collectionName of Object.keys(schema.collections)) {\n\t\t\tconst rows = await tx.query<OperationRow>(\n\t\t\t\t`SELECT * FROM ${quoteIdent(`_kora_ops_${collectionName}`)} WHERE node_id = ?`,\n\t\t\t\t[oldNodeId],\n\t\t\t)\n\t\t\tfor (const row of rows) {\n\t\t\t\tif (rotateIds.has(row.id)) {\n\t\t\t\t\trotated.push(deserializeOperationWithCollection(row, collectionName))\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\t// Original authoring order: sequence numbers are allocated in causal order.\n\t\trotated.sort((a, b) => a.sequenceNumber - b.sequenceNumber)\n\n\t\tif (append && rotated.length > 0) {\n\t\t\t// The node's timestamps are a total order: a rewritten one must not equal one of\n\t\t\t// its own (possible only after the device clock went back).\n\t\t\tconst taken = new Set(\n\t\t\t\trotated.map((op) => HybridLogicalClock.serialize({ ...op.timestamp, nodeId: newNodeId })),\n\t\t\t)\n\t\t\tfor (const collectionName of Object.keys(schema.collections)) {\n\t\t\t\tconst rows = await tx.query<{ timestamp: string }>(\n\t\t\t\t\t`SELECT timestamp FROM ${quoteIdent(`_kora_ops_${collectionName}`)} WHERE node_id = ?`,\n\t\t\t\t\t[newNodeId],\n\t\t\t\t)\n\t\t\t\tfor (const row of rows) {\n\t\t\t\t\tif (taken.has(row.timestamp)) {\n\t\t\t\t\t\tthrow new KoraError(\n\t\t\t\t\t\t\t`A re-authored operation's timestamp is already used by node \"${newNodeId}\".`,\n\t\t\t\t\t\t\t'TIMESTAMP_TAKEN',\n\t\t\t\t\t\t\t{ nodeId: newNodeId, timestamp: row.timestamp },\n\t\t\t\t\t\t)\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\tfor (let i = 0; i < rotated.length; i++) {\n\t\t\tconst op = rotated[i]\n\t\t\tif (!op) continue\n\t\t\tconst timestamp = { ...op.timestamp, nodeId: newNodeId }\n\t\t\t// Deps among the rotated set are remapped BEFORE hashing: a version-2 id covers\n\t\t\t// causalDeps, and sequence order is causal order, so every dep is already\n\t\t\t// mapped. A dep an earlier rotation re-authored (an earlier batch) names its new\n\t\t\t// id. Deps on acknowledged operations keep their ids.\n\t\t\tconst causalDeps = op.causalDeps.map((dep) => idMapping[dep] ?? resolveEarlier(dep))\n\t\t\tconst moved: Operation = {\n\t\t\t\t...op,\n\t\t\t\tnodeId: newNodeId,\n\t\t\t\ttimestamp,\n\t\t\t\tsequenceNumber: append ? await allocateNextSequenceInTransaction(tx, newNodeId) : i + 1,\n\t\t\t\tcausalDeps,\n\t\t\t}\n\t\t\tconst id = await rehashOperation(moved)\n\t\t\tidMapping[op.id] = id\n\t\t\trewritten.push({ ...moved, id })\n\t\t}\n\n\t\tfor (let i = 0; i < rotated.length; i++) {\n\t\t\tconst oldOp = rotated[i]\n\t\t\tconst newOp = rewritten[i]\n\t\t\tif (!oldOp || !newOp) continue\n\t\t\tconst opsTable = `_kora_ops_${oldOp.collection}`\n\t\t\tawait tx.execute(`DELETE FROM ${quoteIdent(opsTable)} WHERE id = ?`, [oldOp.id])\n\t\t\tawait tx.execute(\n\t\t\t\t`INSERT OR REPLACE INTO ${REAUTHORED_OPS_TABLE} (old_id, new_id, from_node, to_node) VALUES (?, ?, ?, ?)`,\n\t\t\t\t[oldOp.id, newOp.id, oldNodeId, newNodeId],\n\t\t\t)\n\t\t\t// A queued old id becomes its new copy in the same transaction.\n\t\t\tconst queued = await tx.query<{ id: string }>(\n\t\t\t\t'SELECT id FROM _kora_sync_queue WHERE id = ?',\n\t\t\t\t[oldOp.id],\n\t\t\t)\n\t\t\tif (queued.length > 0) {\n\t\t\t\tawait tx.execute('DELETE FROM _kora_sync_queue WHERE id = ?', [oldOp.id])\n\t\t\t\tawait tx.execute('INSERT OR REPLACE INTO _kora_sync_queue (id, payload) VALUES (?, ?)', [\n\t\t\t\t\tnewOp.id,\n\t\t\t\t\tJSON.stringify({ ...serializeOperation(newOp), _collection: newOp.collection }),\n\t\t\t\t])\n\t\t\t}\n\t\t\tconst insert = buildInsertQuery(\n\t\t\t\topsTable,\n\t\t\t\tserializeOperation(newOp) as unknown as Record<string, unknown>,\n\t\t\t)\n\t\t\tawait tx.execute(insert.sql, insert.params)\n\n\t\t\t// Re-stamp the row and field versions this operation wrote (the version\n\t\t\t// string carries the node id), exactly like a clock rebase.\n\t\t\tconst oldVersion = serializeRowVersion(oldOp.timestamp)\n\t\t\tconst newVersion = serializeRowVersion(newOp.timestamp)\n\t\t\tawait tx.execute(\n\t\t\t\t`UPDATE ${quoteIdent(oldOp.collection)} SET _version = ? WHERE id = ? AND _version = ?`,\n\t\t\t\t[newVersion, oldOp.recordId, oldVersion],\n\t\t\t)\n\t\t\tconst rows = await tx.query<RawCollectionRow>(\n\t\t\t\t`SELECT _field_versions FROM ${quoteIdent(oldOp.collection)} WHERE id = ?`,\n\t\t\t\t[oldOp.recordId],\n\t\t\t)\n\t\t\tconst fieldVersions = parseFieldVersions(rows[0]?._field_versions)\n\t\t\tlet changed = false\n\t\t\tfor (const [field, version] of Object.entries(fieldVersions)) {\n\t\t\t\tif (version === oldVersion) {\n\t\t\t\t\tfieldVersions[field] = newVersion\n\t\t\t\t\tchanged = true\n\t\t\t\t}\n\t\t\t}\n\t\t\tif (changed) {\n\t\t\t\tawait tx.execute(\n\t\t\t\t\t`UPDATE ${quoteIdent(oldOp.collection)} SET _field_versions = ? WHERE id = ?`,\n\t\t\t\t\t[serializeFieldVersions(fieldVersions), oldOp.recordId],\n\t\t\t\t)\n\t\t\t}\n\t\t}\n\t\tif (moveDatabaseNode) {\n\t\t\tawait tx.execute(\"INSERT OR REPLACE INTO _kora_meta (key, value) VALUES ('node_id', ?)\", [\n\t\t\t\tnewNodeId,\n\t\t\t])\n\t\t\t// The node token belonged to the refused node id.\n\t\t\tawait tx.execute('DELETE FROM _kora_meta WHERE key = ?', [NODE_TOKEN_META_KEY])\n\t\t}\n\t\t// The new node's counter covers the rewritten operations: MAX with the stored\n\t\t// value, in this transaction, like every sequence reservation (W6). Appended ones\n\t\t// reserved theirs one by one above.\n\t\tif (rewritten.length > 0 && !append) {\n\t\t\tawait tx.execute(\n\t\t\t\t`INSERT INTO _kora_version_vector (node_id, sequence_number) VALUES (?, ?)\n     ON CONFLICT(node_id) DO UPDATE SET sequence_number = MAX(sequence_number, excluded.sequence_number)`,\n\t\t\t\t[newNodeId, rewritten.length],\n\t\t\t)\n\t\t}\n\t\t// The old node's counter is left as it is, never lowered: a rotated operation\n\t\t// may have reached the server unacknowledged, and a writer still on the old id\n\t\t// (another tab) must not reuse its number for different content. The numbers the\n\t\t// rotated operations held become holes in the old node's log, which upload\n\t\t// tracking treats as resolved.\n\t\tawait options.inTransaction?.(tx, rewritten)\n\t})\n\n\treturn { nodeId: newNodeId, operations: rewritten, idMapping }\n}\n","import type {\n\tCausalTracker,\n\tCollectionDefinition,\n\tHybridLogicalClock,\n\tOperation,\n\tSchemaDefinition,\n\tSecretKeyProvider,\n} from '@korajs/core'\nimport {\n\tKoraError,\n\tgenerateUUIDv7,\n\tisAtomicOp,\n\tquoteIdent,\n\tresolveAtomicOp,\n\tvalidateRecord,\n} from '@korajs/core'\nimport { RecordNotFoundError } from '../errors'\nimport type { RecordFolder } from '../fold/record-folder'\nimport { lookupCommit } from '../mutations/commit-outcome'\nimport { toAtRestWriteData } from '../mutations/secret-write'\nimport {\n\tCausalScope,\n\ttype LocalDeleteHook,\n\ttype WriteEnv,\n\twaitForCausalHeads,\n\twithWriteScope,\n} from '../mutations/write-context'\nimport {\n\ttype PreparedInsert,\n\ttype WriteResult,\n\tprepareInsert,\n\twriteDeleteInTx,\n\twriteInsertInTx,\n\twriteUpdateInTx,\n} from '../mutations/write-ops'\nimport type { WriteTracker } from '../overlay/write-overlay'\nimport type { RelationEnforcer } from '../relations/relation-enforcer'\nimport { deserializeRecord, toRichtextReadShape } from '../serialization/serializer'\nimport { validateUpdateStateMachine } from '../state-machine/state-validator'\nimport type { CollectionRecord, RawCollectionRow, StorageAdapter } from '../types'\n\n/**\n * A buffered mutation. Buffered entries hold the developer's INTENT, not built\n * operations: they are written at commit, inside the commit's storage\n * transaction, through the same single local write path as single-record writes\n * (W6). That is what gives transaction writes in-transaction sequence\n * reservation, per-field version stamps, state-machine validation and atomic ops\n * resolved against the committed row.\n */\nexport type BufferedEntry =\n\t| { readonly kind: 'insert'; readonly collection: string; readonly insert: PreparedInsert }\n\t| {\n\t\t\treadonly kind: 'update'\n\t\t\treadonly collection: string\n\t\t\treadonly id: string\n\t\t\t/** Schema-validated update data; may contain atomic op descriptors. */\n\t\t\treadonly data: Record<string, unknown>\n\t  }\n\t| { readonly kind: 'delete'; readonly collection: string; readonly id: string }\n\n/** One buffered write of a transaction, as {@link TransactionCommitOptions.prepare} sees it. */\nexport type TransactionWrite = BufferedEntry\n\n/**\n * A committed row the transaction's callback read (through `update`, `delete` or\n * `findById`), BEFORE its own buffered writes were applied, with the\n * {@link TransactionContextConfig.readToken} taken just before the read was issued. Only\n * recorded when the store has instant updates (S6a): the group's predictor may use it as a\n * record's base instead of reading the row again, if the token still matches.\n */\nexport interface ObservedRead {\n\treadonly collection: string\n\treadonly id: string\n\treadonly record: CollectionRecord | null\n\treadonly token: number\n}\n\n/**\n * Registers a sealed transaction with the instant-updates overlay. Called synchronously,\n * immediately before the storage transaction starts, so registration order is transaction\n * order. Returns the tracker of the registered group, or null when nothing was registered.\n */\nexport type TransactionRegistrar = () => WriteTracker | null\n\n/** Options for {@link TransactionContext.commit}. */\nexport interface TransactionCommitOptions {\n\t/**\n\t * Instant updates (S6a): called once the buffer is sealed and before the storage\n\t * transaction starts, with every buffered write in order. It may read (the base records\n\t * of updates and deletes), so it returns a registrar or a promise of one; the registrar\n\t * runs in the same synchronous step as the start of the storage transaction. With a\n\t * tracker, a transaction that rejects after its body finished is looked up by its first\n\t * operation (M2). Must not throw; a failure is treated as \"nothing registered\". Never\n\t * reads back into the write: the statements written are the same with or without it.\n\t */\n\treadonly prepare?: (\n\t\twrites: readonly TransactionWrite[],\n\t\tobserved: ReadonlyMap<string, ObservedRead>,\n\t) => TransactionRegistrar | Promise<TransactionRegistrar>\n}\n\n/**\n * Internal configuration for creating a TransactionContext.\n * Passed from Store to avoid exposing Store internals publicly.\n */\nexport interface TransactionContextConfig {\n\tschema: SchemaDefinition\n\tadapter: StorageAdapter\n\tclock: HybridLogicalClock\n\tnodeId: string\n\trelationEnforcer: RelationEnforcer | null\n\tcausalTracker: CausalTracker | null\n\t/**\n\t * Key provider for `t.secret()` encrypted fields. Transaction writes transform\n\t * secret fields through the same helper as single-record writes (STORE-4).\n\t */\n\tsecretKeyProvider?: SecretKeyProvider\n\t/** Referential hook run for every local delete inside the commit (see {@link LocalDeleteHook}). */\n\tbeforeLocalDelete?: LocalDeleteHook\n\t/** Called when the commit's storage transaction fails, before the error propagates. */\n\tonStorageError?: (error: unknown) => void\n\t/** The W7 record fold (see `WriteEnv.fold`). */\n\tfold?: RecordFolder\n\t/** See `WriteEnv.maxOperationBytes`. */\n\tmaxOperationBytes?: number\n\t/** See `WriteEnv.assertLocalWriteAllowed`. */\n\tassertLocalWriteAllowed?: () => void\n\t/** See `WriteEnv.signedInUser`. */\n\tsignedInUser?: () => string | null\n\t/**\n\t * Instant updates (S6a): a token for the freshness of committed rows of a collection\n\t * (the overlay registry's seed stamp), taken before each committed-row read of the\n\t * callback. Absent (the default): nothing is recorded.\n\t */\n\treadToken?: (collection: string) => number\n}\n\n/**\n * A collection accessor within a transaction.\n * Operations are buffered and committed atomically when the transaction completes.\n */\nexport interface TransactionCollectionAccessor {\n\tinsert(data: Record<string, unknown>): Promise<CollectionRecord>\n\t/**\n\t * Insert several records as part of the transaction, in input order (the same as\n\t * calling `insert` for each). Every row is validated before any is buffered.\n\t */\n\tinsertMany(rows: readonly Record<string, unknown>[]): Promise<CollectionRecord[]>\n\tupdate(id: string, data: Record<string, unknown>): Promise<CollectionRecord>\n\tdelete(id: string): Promise<void>\n\tfindById(id: string): Promise<CollectionRecord | null>\n}\n\n/**\n * TransactionContext provides atomic multi-collection operations.\n *\n * Mutations are validated and buffered when called (so errors surface at the\n * call site and `insert` returns the new id immediately), then written in a\n * single `StorageAdapter.transaction()` at commit. All operations share the\n * same transactionId (UUID v7) and one contiguous block of sequence numbers.\n *\n * Subscription notifications are deferred until after commit.\n *\n * @example\n * ```typescript\n * const { operations, affectedCollections } = await txContext.commit()\n * // Notify subscriptions after commit\n * for (const op of operations) {\n *   subscriptionManager.notify(op.collection, op)\n * }\n * ```\n */\nexport class TransactionContext {\n\tprivate readonly transactionId: string\n\tprivate mutationName: string | undefined\n\tprivate readonly buffer: BufferedEntry[] = []\n\t/** Committed rows the callback read, by `collection\\u0000id` (only with `readToken`). */\n\tprivate readonly observed = new Map<string, ObservedRead>()\n\tprivate committed = false\n\tprivate rolledBack = false\n\tprivate readonly config: TransactionContextConfig\n\n\tconstructor(config: TransactionContextConfig) {\n\t\tthis.config = config\n\t\tthis.transactionId = generateUUIDv7()\n\t}\n\n\t/**\n\t * Set a human-readable mutation name for this transaction.\n\t * Propagated to all operations for DevTools display.\n\t */\n\tsetMutationName(name: string): void {\n\t\tthis.mutationName = name\n\t}\n\n\t/**\n\t * Get the mutation name, if set.\n\t */\n\tgetMutationName(): string | undefined {\n\t\treturn this.mutationName\n\t}\n\n\t/**\n\t * Get a collection accessor for buffered operations within this transaction.\n\t */\n\tcollection(name: string): TransactionCollectionAccessor {\n\t\tconst definition = this.config.schema.collections[name]\n\t\tif (!definition) {\n\t\t\tthrow new KoraError(\n\t\t\t\t`Unknown collection \"${name}\". Available: ${Object.keys(this.config.schema.collections).join(', ')}`,\n\t\t\t\t'UNKNOWN_COLLECTION',\n\t\t\t\t{ collection: name },\n\t\t\t)\n\t\t}\n\n\t\treturn {\n\t\t\tinsert: (data: Record<string, unknown>) => this.insert(name, data),\n\t\t\tinsertMany: (rows: readonly Record<string, unknown>[]) => this.insertMany(name, rows),\n\t\t\tupdate: (id: string, data: Record<string, unknown>) =>\n\t\t\t\tthis.update(name, definition, id, data),\n\t\t\tdelete: (id: string) => this.deleteRecord(name, definition, id),\n\t\t\tfindById: (id: string) => this.getEffectiveRecord(name, definition, id),\n\t\t}\n\t}\n\n\t/**\n\t * Commit all buffered mutations atomically.\n\t *\n\t * Every entry is written, in call order, inside ONE storage transaction through\n\t * the single local write path: sequence numbers are reserved inside the\n\t * transaction (one contiguous block covering referential side effects too) and\n\t * each operation is built only after its number is reserved.\n\t *\n\t * Returns the list of operations and affected collections for subscription notification.\n\t *\n\t * @param options - `prepare`: the instant-updates registration of the group (S6a)\n\t */\n\tasync commit(\n\t\toptions?: TransactionCommitOptions,\n\t): Promise<{ operations: Operation[]; affectedCollections: Set<string> }> {\n\t\tif (this.committed) {\n\t\t\tthrow new KoraError('Transaction already committed.', 'TRANSACTION_COMMITTED', {\n\t\t\t\ttransactionId: this.transactionId,\n\t\t\t})\n\t\t}\n\t\tif (this.rolledBack) {\n\t\t\tthrow new KoraError(\n\t\t\t\t'Transaction was rolled back and cannot be committed.',\n\t\t\t\t'TRANSACTION_ROLLED_BACK',\n\t\t\t\t{ transactionId: this.transactionId },\n\t\t\t)\n\t\t}\n\n\t\tthis.committed = true\n\n\t\tif (this.buffer.length === 0) {\n\t\t\treturn { operations: [], affectedCollections: new Set() }\n\t\t}\n\n\t\tconst env = this.writeEnv()\n\t\t// The buffer is sealed (`committed` is set): what `prepare` sees is what is written.\n\t\tconst register = options?.prepare\n\t\t\t? await prepareSafely(options.prepare, this.buffer, this.observed)\n\t\t\t: null\n\t\t// Not while a clock rebase rewrites operation ids: this write's causalDeps would name them.\n\t\tawait waitForCausalHeads(this.config.causalTracker)\n\t\t// From here to the start of the storage transaction is one synchronous step.\n\t\tconst tracker = register ? registerSafely(register) : null\n\t\tconst causal = new CausalScope(this.config.causalTracker, true)\n\t\tconst operations: Operation[] = []\n\t\tconst results: WriteResult[] = []\n\t\tlet bodyFinished = false\n\n\t\ttry {\n\t\t\tawait this.config.adapter.transaction(async (tx) => {\n\t\t\t\tawait withWriteScope(tx, env.nodeId, causal, async (scope) => {\n\t\t\t\t\tfor (const entry of this.buffer) {\n\t\t\t\t\t\tlet result: WriteResult\n\t\t\t\t\t\tswitch (entry.kind) {\n\t\t\t\t\t\t\tcase 'insert':\n\t\t\t\t\t\t\t\tresult = await writeInsertInTx(env, scope, entry.insert)\n\t\t\t\t\t\t\t\tbreak\n\t\t\t\t\t\t\tcase 'update':\n\t\t\t\t\t\t\t\tresult = await writeUpdateInTx(env, scope, entry.collection, entry.id, entry.data)\n\t\t\t\t\t\t\t\tbreak\n\t\t\t\t\t\t\tcase 'delete':\n\t\t\t\t\t\t\t\tresult = await writeDeleteInTx(env, scope, entry.collection, entry.id)\n\t\t\t\t\t\t\t\tbreak\n\t\t\t\t\t\t}\n\t\t\t\t\t\tresults.push(result)\n\t\t\t\t\t\tif (result.operation) operations.push(result.operation)\n\t\t\t\t\t\toperations.push(...result.sideEffects)\n\t\t\t\t\t}\n\t\t\t\t})\n\t\t\t\tbodyFinished = true\n\t\t\t})\n\t\t} catch (error) {\n\t\t\tif (!tracker) {\n\t\t\t\tthis.config.onStorageError?.(error)\n\t\t\t\tthrow error\n\t\t\t}\n\t\t\t// M2 (instant updates only): the body finished, so the failure came with the\n\t\t\t// COMMIT and the transaction may have landed. It is atomic, so its first\n\t\t\t// operation is a witness for all of it.\n\t\t\tconst lookup = bodyFinished\n\t\t\t\t? await lookupCommit(this.config.adapter, results)\n\t\t\t\t: ({ outcome: 'absent' } as const)\n\t\t\tif (lookup.outcome !== 'committed') {\n\t\t\t\tif (lookup.outcome === 'unknown') tracker.unknown(lookup.operationId)\n\t\t\t\telse tracker.failed(error)\n\t\t\t\tthis.config.onStorageError?.(error)\n\t\t\t\tthrow error\n\t\t\t}\n\t\t\t// It landed: continue as if COMMIT had answered.\n\t\t}\n\n\t\tcausal.publish()\n\t\ttracker?.committed(results)\n\t\tconst affectedCollections = new Set(operations.map((op) => op.collection))\n\t\treturn { operations, affectedCollections }\n\t}\n\n\t/**\n\t * Mark the transaction as rolled back. No operations will be committed.\n\t */\n\trollback(): void {\n\t\tthis.rolledBack = true\n\t\tthis.buffer.length = 0\n\t}\n\n\t/**\n\t * Get the transaction ID shared by all operations in this transaction.\n\t */\n\tgetTransactionId(): string {\n\t\treturn this.transactionId\n\t}\n\n\tprivate writeEnv(): WriteEnv {\n\t\treturn {\n\t\t\tschema: this.config.schema,\n\t\t\tclock: this.config.clock,\n\t\t\tnodeId: this.config.nodeId,\n\t\t\trelationEnforcer: this.config.relationEnforcer,\n\t\t\ttransactionId: this.transactionId,\n\t\t\t...(this.config.secretKeyProvider\n\t\t\t\t? { secretKeyProvider: this.config.secretKeyProvider }\n\t\t\t\t: {}),\n\t\t\t...(this.mutationName !== undefined ? { mutationName: this.mutationName } : {}),\n\t\t\t...(this.config.beforeLocalDelete\n\t\t\t\t? { beforeLocalDelete: this.config.beforeLocalDelete }\n\t\t\t\t: {}),\n\t\t\t...(this.config.fold ? { fold: this.config.fold } : {}),\n\t\t\t...(this.config.maxOperationBytes !== undefined\n\t\t\t\t? { maxOperationBytes: this.config.maxOperationBytes }\n\t\t\t\t: {}),\n\t\t\t...(this.config.assertLocalWriteAllowed\n\t\t\t\t? { assertLocalWriteAllowed: this.config.assertLocalWriteAllowed }\n\t\t\t\t: {}),\n\t\t\t...(this.config.signedInUser ? { signedInUser: this.config.signedInUser } : {}),\n\t\t}\n\t}\n\n\tprivate ensureActive(): void {\n\t\tif (this.committed) {\n\t\t\tthrow new KoraError(\n\t\t\t\t'Cannot perform operations on a committed transaction.',\n\t\t\t\t'TRANSACTION_COMMITTED',\n\t\t\t\t{ transactionId: this.transactionId },\n\t\t\t)\n\t\t}\n\t\tif (this.rolledBack) {\n\t\t\tthrow new KoraError(\n\t\t\t\t'Cannot perform operations on a rolled-back transaction.',\n\t\t\t\t'TRANSACTION_ROLLED_BACK',\n\t\t\t\t{ transactionId: this.transactionId },\n\t\t\t)\n\t\t}\n\t}\n\n\tprivate async insert(\n\t\tcollectionName: string,\n\t\tdata: Record<string, unknown>,\n\t): Promise<CollectionRecord> {\n\t\tthis.ensureActive()\n\t\tconst insert = await prepareInsert(this.writeEnv(), collectionName, data)\n\t\tthis.buffer.push({ kind: 'insert', collection: collectionName, insert })\n\t\tconst now = Date.now()\n\t\t// The returned record carries the at-rest form (secrets hashed/encrypted) and the\n\t\t// read form of richtext (bytes), exactly like a single-record insert.\n\t\tconst fields = this.config.schema.collections[collectionName]?.fields ?? {}\n\t\treturn {\n\t\t\tid: insert.recordId,\n\t\t\t...toRichtextReadShape(insert.data, fields),\n\t\t\tcreatedAt: now,\n\t\t\tupdatedAt: now,\n\t\t}\n\t}\n\n\tprivate async insertMany(\n\t\tcollectionName: string,\n\t\trows: readonly Record<string, unknown>[],\n\t): Promise<CollectionRecord[]> {\n\t\tthis.ensureActive()\n\t\tconst env = this.writeEnv()\n\t\t// Validate (prepare) every row before buffering any, so an invalid row leaves the\n\t\t// transaction's buffer as it was, like the collection's own insertMany.\n\t\tconst prepared: PreparedInsert[] = []\n\t\tfor (const row of rows) prepared.push(await prepareInsert(env, collectionName, row))\n\t\tconst fields = this.config.schema.collections[collectionName]?.fields ?? {}\n\t\tconst now = Date.now()\n\t\treturn prepared.map((insert) => {\n\t\t\tthis.buffer.push({ kind: 'insert', collection: collectionName, insert })\n\t\t\treturn {\n\t\t\t\tid: insert.recordId,\n\t\t\t\t...toRichtextReadShape(insert.data, fields),\n\t\t\t\tcreatedAt: now,\n\t\t\t\tupdatedAt: now,\n\t\t\t}\n\t\t})\n\t}\n\n\tprivate async update(\n\t\tcollectionName: string,\n\t\tdefinition: CollectionDefinition,\n\t\tid: string,\n\t\tdata: Record<string, unknown>,\n\t): Promise<CollectionRecord> {\n\t\tthis.ensureActive()\n\n\t\tconst currentRecord = await this.getEffectiveRecord(collectionName, definition, id)\n\t\tif (!currentRecord) {\n\t\t\tthrow new RecordNotFoundError(collectionName, id)\n\t\t}\n\n\t\tconst validated = validateRecord(collectionName, definition, data, 'update')\n\t\t// Early check so an invalid transition fails at the call site. The commit\n\t\t// re-validates against the row read inside the write transaction, which is\n\t\t// authoritative.\n\t\tconst allowed = validateUpdateStateMachine(\n\t\t\tcollectionName,\n\t\t\tid,\n\t\t\tdefinition,\n\t\t\tcurrentRecord,\n\t\t\tvalidated,\n\t\t)\n\t\tthis.buffer.push({ kind: 'update', collection: collectionName, id, data: validated })\n\n\t\tconst preview = await this.previewUpdate(definition, currentRecord, allowed)\n\t\treturn { ...currentRecord, ...preview, updatedAt: Date.now() } as CollectionRecord\n\t}\n\n\tprivate async deleteRecord(\n\t\tcollectionName: string,\n\t\tdefinition: CollectionDefinition,\n\t\tid: string,\n\t): Promise<void> {\n\t\tthis.ensureActive()\n\n\t\tconst currentRecord = await this.getEffectiveRecord(collectionName, definition, id)\n\t\tif (!currentRecord) {\n\t\t\tthrow new RecordNotFoundError(collectionName, id)\n\t\t}\n\t\tthis.buffer.push({ kind: 'delete', collection: collectionName, id })\n\t}\n\n\t/**\n\t * The values an update will write, resolved against `current` (the effective\n\t * record) for read-your-writes inside the transaction. Secret fields are shown\n\t * in their at-rest form, like the record a committed update returns.\n\t */\n\tprivate async previewUpdate(\n\t\tdefinition: CollectionDefinition,\n\t\tcurrent: CollectionRecord,\n\t\tdata: Record<string, unknown>,\n\t): Promise<Record<string, unknown>> {\n\t\tconst resolved: Record<string, unknown> = {}\n\t\tfor (const [key, value] of Object.entries(data)) {\n\t\t\tresolved[key] = isAtomicOp(value) ? resolveAtomicOp(current[key], value) : value\n\t\t}\n\t\tconst atRest = await toAtRestWriteData(resolved, definition, this.config.secretKeyProvider)\n\t\treturn toRichtextReadShape(atRest, definition.fields)\n\t}\n\n\t/**\n\t * The effective state of a record: the committed row overlaid with this\n\t * transaction's buffered mutations, in call order.\n\t */\n\tprivate async getEffectiveRecord(\n\t\tcollectionName: string,\n\t\tdefinition: CollectionDefinition,\n\t\tid: string,\n\t): Promise<CollectionRecord | null> {\n\t\t// Taken before the read is issued: a change the token counts that lands while the read\n\t\t// is in flight makes the observation unusable (instant updates only).\n\t\tconst token = this.config.readToken?.(collectionName)\n\t\tconst rows = await this.config.adapter.query<RawCollectionRow>(\n\t\t\t`SELECT * FROM ${quoteIdent(collectionName)} WHERE id = ? AND _deleted = 0`,\n\t\t\t[id],\n\t\t)\n\t\tlet record: CollectionRecord | null = rows[0]\n\t\t\t? deserializeRecord(rows[0], definition.fields)\n\t\t\t: null\n\t\tif (token !== undefined) {\n\t\t\tthis.observed.set(`${collectionName}\\u0000${id}`, {\n\t\t\t\tcollection: collectionName,\n\t\t\t\tid,\n\t\t\t\trecord: record ? { ...record } : null,\n\t\t\t\ttoken,\n\t\t\t})\n\t\t}\n\n\t\tfor (const entry of this.buffer) {\n\t\t\tif (entry.collection !== collectionName) continue\n\t\t\tif (entry.kind === 'insert') {\n\t\t\t\tif (entry.insert.recordId !== id) continue\n\t\t\t\tconst now = Date.now()\n\t\t\t\trecord = {\n\t\t\t\t\tid,\n\t\t\t\t\t...toRichtextReadShape(entry.insert.data, definition.fields),\n\t\t\t\t\tcreatedAt: now,\n\t\t\t\t\tupdatedAt: now,\n\t\t\t\t}\n\t\t\t} else if (entry.id === id && entry.kind === 'update') {\n\t\t\t\tif (record) {\n\t\t\t\t\tlet allowed: Record<string, unknown>\n\t\t\t\t\ttry {\n\t\t\t\t\t\tallowed = validateUpdateStateMachine(collectionName, id, definition, record, entry.data)\n\t\t\t\t\t} catch {\n\t\t\t\t\t\t// Already reported to the caller when the update was buffered.\n\t\t\t\t\t\tallowed = {}\n\t\t\t\t\t}\n\t\t\t\t\tconst preview = await this.previewUpdate(definition, record, allowed)\n\t\t\t\t\trecord = { ...record, ...preview, updatedAt: Date.now() }\n\t\t\t\t}\n\t\t\t} else if (entry.id === id) {\n\t\t\t\trecord = null\n\t\t\t}\n\t\t}\n\n\t\treturn record\n\t}\n}\n\n/** Run `prepare`; a throw or rejection means \"nothing registered\", never a failed write. */\nasync function prepareSafely(\n\tprepare: NonNullable<TransactionCommitOptions['prepare']>,\n\twrites: readonly TransactionWrite[],\n\tobserved: ReadonlyMap<string, ObservedRead>,\n): Promise<TransactionRegistrar | null> {\n\ttry {\n\t\tconst registrar = prepare(writes, observed)\n\t\treturn registrar instanceof Promise ? await registrar : registrar\n\t} catch (error) {\n\t\tconsole.error('[kora] instant-updates transaction prepare failed', error)\n\t\treturn null\n\t}\n}\n\nfunction registerSafely(register: TransactionRegistrar): WriteTracker | null {\n\ttry {\n\t\treturn register()\n\t} catch (error) {\n\t\tconsole.error('[kora] instant-updates transaction registration failed', error)\n\t\treturn null\n\t}\n}\n","import { quoteIdent } from '@korajs/core'\nimport type { SchemaDefinition } from '@korajs/core'\nimport { collectionIndexName, legacyCollectionIndexName } from '@korajs/core/internal'\nimport type { StorageAdapter } from '../types'\n\n/**\n * Retire indexes created under the pre-beta.13 naming scheme (STORE-15).\n *\n * `idx_<collection>_<field>` collided across collections (`a_b`.`c` and\n * `a`.`b_c`), so one of the two indexes was silently never created. The schema\n * DDL now creates collision-free names ({@link collectionIndexName}); this pass\n * drops each legacy index that sits on the table and column it was named for,\n * once its replacement exists. A legacy name that belongs to another table is\n * left to that table's own pass, so nothing a collection still needs is dropped.\n *\n * SQLite cannot rename an index; drop-and-recreate is the rename.\n *\n * @param adapter - The opened adapter (schema DDL already applied)\n * @param schema - The schema whose collections are checked\n */\nexport async function dropLegacyIndexes(\n\tadapter: StorageAdapter,\n\tschema: SchemaDefinition,\n): Promise<void> {\n\tconst indexed = new Map<string, Set<string>>()\n\tfor (const [name, definition] of Object.entries(schema.collections)) {\n\t\tindexed.set(name, new Set(definition.indexes))\n\t}\n\tfor (const relation of Object.values(schema.relations)) {\n\t\tindexed.get(relation.from)?.add(relation.field)\n\t}\n\n\tconst existing = await adapter.query<{ name: string; tbl_name: string }>(\n\t\t\"SELECT name, tbl_name FROM sqlite_master WHERE type = 'index' AND name LIKE 'idx_%'\",\n\t)\n\tconst byName = new Map(existing.map((row) => [row.name, row.tbl_name]))\n\n\tfor (const [collection, fields] of indexed) {\n\t\tfor (const field of fields) {\n\t\t\tconst legacy = legacyCollectionIndexName(collection, field)\n\t\t\tconst current = collectionIndexName(collection, field)\n\t\t\tif (legacy === current) continue\n\t\t\tif (byName.get(legacy) !== collection) continue\n\t\t\tif (byName.get(current) !== collection) continue\n\t\t\tconst columns = await adapter.query<{ name: string }>(\n\t\t\t\t`SELECT name FROM pragma_index_info(${sqlString(legacy)})`,\n\t\t\t)\n\t\t\tif (columns.length !== 1 || columns[0]?.name !== field) continue\n\t\t\tawait adapter.execute(`DROP INDEX IF EXISTS ${quoteIdent(legacy)}`)\n\t\t}\n\t}\n}\n\nfunction sqlString(value: string): string {\n\treturn `'${value.replace(/'/g, \"''\")}'`\n}\n","/**\n * Web Locks per local node id (RT-40). Under per-tab isolation every tab writes under\n * its own node id into one shared database; a live tab holds its node's lock for its\n * lifetime, so another tab can tell a closed tab's node (lock free: adopt its unsynced\n * writes) from a live one (lock held: leave it alone). An adopter holds the lock while\n * it uploads, so two tabs never adopt the same node at once.\n *\n * Without the Web Locks API (Node, workers without it) every node is reported free and\n * acquisition is a no-op: there is no other tab to coordinate with.\n */\n\ninterface LockLike {\n\tname?: string\n}\n\ninterface LockManagerLike {\n\trequest(\n\t\tname: string,\n\t\toptions: { mode?: 'exclusive' | 'shared'; ifAvailable?: boolean },\n\t\tcallback: (lock: LockLike | null) => Promise<void> | void,\n\t): Promise<unknown>\n\tquery?(): Promise<{ held?: LockLike[] }>\n}\n\nfunction lockManager(): LockManagerLike | null {\n\tconst nav = (globalThis as { navigator?: { locks?: LockManagerLike; userAgent?: string } })\n\t\t.navigator\n\t// Node 24 exposes `navigator.locks`, but these locks coordinate unrelated in-process\n\t// databases rather than browser tabs sharing one origin. Server/test stores already use\n\t// their database adapter for concurrency, and treating Node as a browser can strand node\n\t// adoption and retired-node repair. Browser workers have a real browser user agent and\n\t// continue to use Web Locks.\n\tif (nav?.userAgent?.startsWith('Node.js/')) return null\n\treturn nav?.locks && typeof nav.locks.request === 'function' ? nav.locks : null\n}\n\n/** Lock name of a node id in a database. */\nexport function nodeLockName(dbName: string, nodeId: string): string {\n\treturn `kora-node:${dbName}:${nodeId}`\n}\n\n/**\n * Hold a node's lock until the returned function is called (its promise settles when the\n * lock is given back). Acquisition is asynchronous (it waits while an adopter holds the\n * lock); the caller never waits.\n * `shared`: several live contexts may hold it at once (the tabs of one database pinned\n * to one node); an exclusive taker (a repair, an adopter) then finds it held.\n */\nexport function acquireNodeLock(\n\tname: string,\n\tmode: 'exclusive' | 'shared' = 'exclusive',\n): () => Promise<void> {\n\treturn requestNodeLock(name, mode).release\n}\n\ninterface NodeLockRequest {\n\t/** Gives the lock back (or abandons the request while it still waits). */\n\trelease: () => Promise<void>\n\t/** Resolves when the lock is granted (at once without the Web Locks API). */\n\tgranted: Promise<void>\n}\n\nfunction requestNodeLock(name: string, mode: 'exclusive' | 'shared'): NodeLockRequest {\n\tconst locks = lockManager()\n\tif (!locks) return { release: async () => {}, granted: Promise.resolve() }\n\tlet release: () => void = () => {}\n\tlet released = false\n\tlet granted = false\n\tlet markGranted: () => void = () => {}\n\tconst grantedPromise = new Promise<void>((resolve) => {\n\t\tmarkGranted = resolve\n\t})\n\tconst held = new Promise<void>((resolve) => {\n\t\trelease = () => {\n\t\t\treleased = true\n\t\t\tresolve()\n\t\t}\n\t})\n\tconst request = locks\n\t\t.request(name, { mode }, async () => {\n\t\t\tif (released) return\n\t\t\tgranted = true\n\t\t\tmarkGranted()\n\t\t\tawait held\n\t\t})\n\t\t.then(\n\t\t\t() => undefined,\n\t\t\t() => {\n\t\t\t\t// A lock that cannot be taken only weakens the liveness hint; never fatal.\n\t\t\t\tmarkGranted()\n\t\t\t},\n\t\t)\n\t// Resolves once a granted lock is given back (a lock still waiting is abandoned at once).\n\treturn {\n\t\trelease: () => {\n\t\t\trelease()\n\t\t\treturn granted ? request : Promise.resolve()\n\t\t},\n\t\tgranted: grantedPromise,\n\t}\n}\n\n/**\n * Take a node's lock and wait until it is granted, for at most `timeoutMs`. A context that\n * writes under a node while a repair holds it exclusively would upload operations the repair\n * is re-authoring, so opening on such a node waits for the repair to finish rather than\n * proceeding on a queued request. Resolves to the release function, or null when the lock\n * was not granted in time (the request is abandoned).\n */\nexport async function acquireNodeLockGranted(\n\tname: string,\n\tmode: 'exclusive' | 'shared',\n\ttimeoutMs: number,\n): Promise<(() => Promise<void>) | null> {\n\tconst request = requestNodeLock(name, mode)\n\tlet timer: ReturnType<typeof setTimeout> | undefined\n\tconst timedOut = new Promise<boolean>((resolve) => {\n\t\ttimer = setTimeout(() => resolve(true), timeoutMs)\n\t})\n\tconst waited = await Promise.race([request.granted.then(() => false), timedOut])\n\tif (timer !== undefined) clearTimeout(timer)\n\tif (waited) {\n\t\tawait request.release()\n\t\treturn null\n\t}\n\treturn request.release\n}\n\n/**\n * Take a node's lock only when it is free. Resolves to a release function, or null\n * when another context (a live tab, another adopter) holds it.\n */\nexport function tryAcquireNodeLock(name: string): Promise<(() => void) | null> {\n\tconst locks = lockManager()\n\tif (!locks) return Promise.resolve(() => {})\n\treturn new Promise((resolveResult) => {\n\t\tlet release: () => void = () => {}\n\t\tconst held = new Promise<void>((resolve) => {\n\t\t\trelease = resolve\n\t\t})\n\t\tlocks\n\t\t\t.request(name, { mode: 'exclusive', ifAvailable: true }, async (lock) => {\n\t\t\t\tif (!lock) {\n\t\t\t\t\tresolveResult(null)\n\t\t\t\t\treturn\n\t\t\t\t}\n\t\t\t\tresolveResult(() => release())\n\t\t\t\tawait held\n\t\t\t})\n\t\t\t.catch(() => resolveResult(null))\n\t})\n}\n\n/** Whether some context holds a node's lock. */\nexport async function isNodeLockHeld(name: string): Promise<boolean> {\n\tconst locks = lockManager()\n\tif (!locks?.query) return false\n\ttry {\n\t\tconst snapshot = await locks.query()\n\t\treturn (snapshot.held ?? []).some((lock) => lock.name === name)\n\t} catch {\n\t\treturn false\n\t}\n}\n","import type { SchemaDefinition } from '@korajs/core'\nimport {\n\ttype SqliteQueryFn,\n\treadSqliteTableCatalog,\n\tsqliteConstraintRelaxationStatements,\n} from '@korajs/core/internal'\nimport type { StorageAdapter } from '../types'\n\n/**\n * One-time migration (RT-101): rebuild collection tables that still carry value-domain\n * constraints (an enum `CHECK`, `NOT NULL` on a schema field) created by beta.12 and\n * earlier DDL. Validation is the single authority for the value domain; a table\n * constraint cannot evolve with the schema, so it refused enum values added later and\n * nulls of fields made optional.\n *\n * Every table is rebuilt in ONE transaction (all or nothing), preserving rows, columns,\n * defaults, keys, indexes and triggers. Foreign key enforcement is switched off around\n * it when the database enforces foreign keys, as SQLite's table-rebuild procedure\n * requires. Idempotent: a relaxed table is left alone, so later opens do nothing;\n * resumable: an interrupted rebuild rolls back and runs again at the next open.\n *\n * Works for every client adapter (better-sqlite3, SQLite WASM/OPFS, and the IndexedDB\n * adapter, which runs SQLite in memory): they all store in SQLite.\n *\n * @param adapter - The opened adapter (schema DDL already applied)\n * @param schema - The schema whose collection tables are checked\n * @returns The collections whose tables were rebuilt\n */\nexport async function relaxValueDomainConstraints(\n\tadapter: StorageAdapter,\n\tschema: SchemaDefinition,\n): Promise<string[]> {\n\tconst collections = Object.keys(schema.collections)\n\t// Only enum checks on the schema's enum fields are Kora's; any other CHECK was added\n\t// by hand and is kept through the rebuild, and never triggers one (RT-111).\n\tconst enumColumns = (collection: string): string[] =>\n\t\tObject.entries(schema.collections[collection]?.fields ?? {})\n\t\t\t.filter(([, descriptor]) => descriptor.kind === 'enum')\n\t\t\t.map(([field]) => field)\n\tconst viaAdapter: SqliteQueryFn = (sql) => adapter.query<Record<string, unknown>>(sql)\n\tconst pending: string[] = []\n\tfor (const collection of collections) {\n\t\tconst catalog = await readSqliteTableCatalog(viaAdapter, collection)\n\t\tif (\n\t\t\tcatalog &&\n\t\t\tsqliteConstraintRelaxationStatements(catalog, enumColumns(collection)).length > 0\n\t\t) {\n\t\t\tpending.push(collection)\n\t\t}\n\t}\n\tif (pending.length === 0) return []\n\n\tconst enforced = await adapter.query<{ foreign_keys: number }>('PRAGMA foreign_keys')\n\tconst foreignKeysOn = Number(enforced[0]?.foreign_keys) === 1\n\tif (foreignKeysOn) await adapter.execute('PRAGMA foreign_keys = OFF')\n\tconst rebuilt: string[] = []\n\ttry {\n\t\tawait adapter.transaction(async (tx) => {\n\t\t\tconst viaTx: SqliteQueryFn = (sql) => tx.query<Record<string, unknown>>(sql)\n\t\t\t// Re-read inside the transaction: another tab may have relaxed a table already.\n\t\t\tfor (const collection of pending) {\n\t\t\t\tconst catalog = await readSqliteTableCatalog(viaTx, collection)\n\t\t\t\tif (!catalog) continue\n\t\t\t\tconst statements = sqliteConstraintRelaxationStatements(catalog, enumColumns(collection))\n\t\t\t\tif (statements.length === 0) continue\n\t\t\t\tfor (const sql of statements) await tx.execute(sql)\n\t\t\t\trebuilt.push(collection)\n\t\t\t}\n\t\t})\n\t} finally {\n\t\tif (foreignKeysOn) await adapter.execute('PRAGMA foreign_keys = ON')\n\t}\n\treturn rebuilt\n}\n","import { generateUUIDv7 } from '@korajs/core'\n\nexport type StoreIsolation = 'shared' | 'per-tab'\n\nfunction perTabStorageKey(dbName: string): string {\n\treturn `kora-tab-node-${dbName}`\n}\n\n/**\n * Load a per-tab node id from sessionStorage (browser only).\n */\nexport function loadPerTabNodeId(dbName: string): string | null {\n\tif (typeof sessionStorage === 'undefined') {\n\t\treturn null\n\t}\n\treturn sessionStorage.getItem(perTabStorageKey(dbName))\n}\n\n/**\n * Persist a per-tab node id for this browser tab.\n */\nexport function savePerTabNodeId(dbName: string, nodeId: string): void {\n\tif (typeof sessionStorage === 'undefined') {\n\t\treturn\n\t}\n\tsessionStorage.setItem(perTabStorageKey(dbName), nodeId)\n}\n\n/**\n * Resolve or create a node id for `per-tab` isolation.\n */\nexport function resolvePerTabNodeId(dbName: string): string {\n\tconst existing = loadPerTabNodeId(dbName)\n\t// Never adopt an id in Kora's reserved `kora:` namespace (RT-61).\n\tif (existing && !existing.startsWith('kora:')) {\n\t\treturn existing\n\t}\n\tconst nodeId = generateUUIDv7()\n\tsavePerTabNodeId(dbName, nodeId)\n\treturn nodeId\n}\n"]}