{"version":3,"sources":["/home/runner/work/kora/kora/packages/store/dist/chunk-VOWZ7MZ2.cjs","../src/sync/offline-marks.ts","../src/sync/sync-state.ts","../src/lww/row-version.ts","../src/query/sql-builder.ts","../src/sync/rehash-operation.ts","../src/store/sequence-allocator.ts","../src/store/sequence-repair.ts","../src/sync/sync-durability.ts","../src/sync/local-sync-records.ts","../src/fold/record-folder.ts","../src/fold/query-terms.ts"],"names":["quoteIdent","HybridLogicalClock"],"mappings":"AAAA;AACE;AACA;AACA;AACA;AACF,wDAA6B;AAC7B;AACE;AACF,wDAA6B;AAC7B;AACE;AACF,wDAA6B;AAC7B;AACA;ACJO,IAAM,wBAAA,EAA0B,mBAAA;AAEhC,IAAM,wBAAA,EAA0B,oBAAA;AAIvC,SAAS,WAAA,CAAY,MAAA,EAAkC;AACtD,EAAA,OAAO,CAAC,MAAA,EAAQ,CAAA,EAAA;AACjB;AAGgB;AACL,EAAA;AACX;AAGgB;AACL,EAAA;AACX;AAImB;AACP,EAAA;AACP,EAAA;AACW,IAAA;AAEH,IAAA;AASH,MAAA;AACR,IAAA;AACO,IAAA;AACK,MAAA;AACA,MAAA;AACD,MAAA;AACD,MAAA;AACC,MAAA;AACC,MAAA;AACX,MAAA;AACU,MAAA;AACX,IAAA;AACO,EAAA;AAEA,IAAA;AACR,EAAA;AACD;AAEmB;AACP,EAAA;AACP,EAAA;AACW,IAAA;AAEH,IAAA;AAOH,MAAA;AACR,IAAA;AACS,IAAA;AACF,EAAA;AAEA,IAAA;AACR,EAAA;AACD;AAEe;AACE,EAAA;AACN,EAAA;AACT,IAAA;AACU,IAAA;AACX,EAAA;AACD;AAMsB;AACJ,EAAA;AACD,IAAA;AACA,IAAA;AACf,EAAA;AACF;AAesB;AAIJ,EAAA;AACA,EAAA;AAEN,+BAAA;AACR,MAAA;AAEI,IAAA;AACP,EAAA;AAGM,EAAA;AAOW,EAAA;AACP,IAAA;AACR,MAAA;AACK,MAAA;AACL,IAAA;AACF,EAAA;AACe,EAAA;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G,IAAA;AACV,EAAA;AAEc,EAAA;AAKA,IAAA;AACZ,MAAA;AACa,MAAA;AACd,IAAA;AACc,IAAA;AACf,EAAA;AAEc,EAAA;AAMA,IAAA;AACZ,MAAA;AACa,MAAA;AACd,IAAA;AACY,IAAA;AACA,IAAA;AACR,IAAA;AACI,MAAA;AACC,IAAA;AAEJ,MAAA;AACE,MAAA;AACP,IAAA;AACD,EAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAQM,EAAA;AACC,IAAA;AACK,IAAA;AACE,MAAA;AACC,MAAA;AACA,MAAA;AACd,IAAA;AACc,IAAA;AAC4C,IAAA;AAC5C,IAAA;AACF,IAAA;AACE,MAAA;AACJ,MAAA;AACF,QAAA;AACK,QAAA;AACL,UAAA;AACI,UAAA;AACT,QAAA;AACF,MAAA;AACD,IAAA;AACW,IAAA;AACC,MAAA;AACA,QAAA;AACX,MAAA;AACD,IAAA;AACW,IAAA;AACJ,MAAA;AACK,MAAA;AACZ,IAAA;AACD,EAAA;AAEc,EAAA;AAKc,IAAA;AAChB,IAAA;AACoB,MAAA;AACpB,MAAA;AACH,QAAA;AACG,QAAA;AACD,UAAA;AACP,UAAA;AACS,UAAA;AACT,QAAA;AACQ,QAAA;AACT,QAAA;AACD,MAAA;AACU,MAAA;AACH,QAAA;AACL,UAAA;AACO,UAAA;AACR,QAAA;AACM,QAAA;AACG,QAAA;AACV,MAAA;AACS,MAAA;AACV,IAAA;AACO,IAAA;AACR,EAAA;AACD;AASS;AACI,EAAA;AACb;AAES;AACA,EAAA;AACT;AVurCmB;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;AACA;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-VOWZ7MZ2.cjs","sourcesContent":[null,"import type {\n\tOfflineCompletion,\n\tOfflineCompletionMark,\n\tOfflineMarksSnapshot,\n\tOfflineUnitKey,\n} from '@korajs/core'\nimport type { MetaRow, StorageAdapter, Transaction } from '../types'\n\n/** `_kora_meta` key prefix of a view's completion mark (offline-readiness design, 4.1). */\nexport const OFFLINE_MARK_KEY_PREFIX = 'offline_complete:'\n/** `_kora_meta` key prefix of an open delivery unit. */\nexport const OFFLINE_UNIT_KEY_PREFIX = 'offline_unit_open:'\n\n// Keys are scanned by range, not LIKE: view signatures contain `%`, `_` and `:`, and `;`\n// is the character after `:` so [prefix, prefix-with-;) covers exactly the prefix.\nfunction prefixRange(prefix: string): [string, string] {\n\treturn [prefix, `${prefix.slice(0, -1)};`]\n}\n\n/** The `_kora_meta` key of a view's completion mark. */\nexport function offlineMarkKey(signature: string): string {\n\treturn `${OFFLINE_MARK_KEY_PREFIX}${signature}`\n}\n\n/** The `_kora_meta` key of one delivery unit (the unit id never contains `:`). */\nexport function offlineUnitKey(signature: string, unitId: string): string {\n\treturn `${OFFLINE_UNIT_KEY_PREFIX}${signature}:${unitId}`\n}\n\ntype MetaTx = Pick<Transaction, 'execute' | 'query'>\n\nfunction parseMark(raw: unknown): OfflineCompletionMark | null {\n\tif (typeof raw !== 'string') return null\n\ttry {\n\t\tconst value = JSON.parse(raw) as Partial<OfflineCompletionMark> | null\n\t\tif (\n\t\t\tvalue === null ||\n\t\t\ttypeof value !== 'object' ||\n\t\t\ttypeof value.signature !== 'string' ||\n\t\t\ttypeof value.watermark !== 'number' ||\n\t\t\ttypeof value.scopeKey !== 'string' ||\n\t\t\t!Array.isArray(value.subsets) ||\n\t\t\ttypeof value.collectionsKey !== 'string' ||\n\t\t\ttypeof value.at !== 'number'\n\t\t) {\n\t\t\treturn null\n\t\t}\n\t\treturn {\n\t\t\tsignature: value.signature,\n\t\t\twatermark: value.watermark,\n\t\t\tscopeKey: value.scopeKey,\n\t\t\tsubsets: value.subsets,\n\t\t\trulesKey: value.rulesKey ?? null,\n\t\t\tprincipal: value.principal ?? null,\n\t\t\tcollectionsKey: value.collectionsKey,\n\t\t\tat: value.at,\n\t\t}\n\t} catch {\n\t\t// An unreadable mark proves nothing: the view reads as incomplete.\n\t\treturn null\n\t}\n}\n\nfunction parseUnit(raw: unknown): OfflineUnitKey | null {\n\tif (typeof raw !== 'string') return null\n\ttry {\n\t\tconst value = JSON.parse(raw) as Partial<OfflineUnitKey> | null\n\t\tif (\n\t\t\tvalue === null ||\n\t\t\ttypeof value !== 'object' ||\n\t\t\ttypeof value.signature !== 'string' ||\n\t\t\ttypeof value.unitId !== 'string' ||\n\t\t\ttypeof value.base !== 'number' ||\n\t\t\ttypeof value.upTo !== 'number'\n\t\t) {\n\t\t\treturn null\n\t\t}\n\t\treturn { signature: value.signature, unitId: value.unitId, base: value.base, upTo: value.upTo }\n\t} catch {\n\t\t// An unreadable unit key is kept (never deleted): its presence blocks `complete`.\n\t\treturn null\n\t}\n}\n\nasync function scan(tx: MetaTx, prefix: string): Promise<Array<{ key: string; value: unknown }>> {\n\tconst [low, high] = prefixRange(prefix)\n\treturn tx.query<MetaRow & { key: string }>(\n\t\t'SELECT key, value FROM _kora_meta WHERE key >= ? AND key < ?',\n\t\t[low, high],\n\t)\n}\n\n/**\n * Record that a delivery unit is about to apply operations (before the first one). Its own\n * committed write: whatever persists an operation of the unit persists this key too.\n */\nexport async function openOfflineUnit(tx: MetaTx, unit: OfflineUnitKey): Promise<void> {\n\tawait tx.execute('INSERT OR REPLACE INTO _kora_meta (key, value) VALUES (?, ?)', [\n\t\tofflineUnitKey(unit.signature, unit.unitId),\n\t\tJSON.stringify(unit),\n\t])\n}\n\n/**\n * Commit a unit's completion through `tx`, in the transaction that advances the view's\n * watermark: set the mark (never backward), close the unit's key and every key of the view\n * the unit covers.\n *\n * A key whose `upTo` is at or below the final watermark belongs to a unit that could only\n * apply operations this unit already applied (it applied every operation of the view up to\n * the watermark, and the fold depends only on the set of operations), so the database is\n * exactly the state at the watermark whatever that unit left. The design also asks for\n * `base >= myBase`; that is dropped here because the engine resumes from the durable\n * watermark, which can lie above a crashed unit's base, and the prefix up to the watermark\n * was already complete.\n */\nexport async function saveOfflineCompletionInTx(\n\ttx: MetaTx,\n\tcompletion: OfflineCompletion,\n): Promise<void> {\n\tconst { mark } = completion\n\tconst existing = parseMark(\n\t\t(\n\t\t\tawait tx.query<MetaRow>('SELECT value FROM _kora_meta WHERE key = ?', [\n\t\t\t\tofflineMarkKey(mark.signature),\n\t\t\t])\n\t\t)[0]?.value,\n\t)\n\t// Marks never go backward: a slower tab finishing an older unit cannot replace a newer\n\t// mark of the same view with an older one.\n\tconst superseded =\n\t\texisting !== null &&\n\t\texisting.watermark > mark.watermark &&\n\t\texisting.scopeKey === mark.scopeKey &&\n\t\texisting.rulesKey === mark.rulesKey &&\n\t\texisting.principal === mark.principal &&\n\t\texisting.collectionsKey === mark.collectionsKey\n\tif (!superseded) {\n\t\tawait tx.execute('INSERT OR REPLACE INTO _kora_meta (key, value) VALUES (?, ?)', [\n\t\t\tofflineMarkKey(mark.signature),\n\t\t\tJSON.stringify(mark),\n\t\t])\n\t}\n\tif (completion.unitId !== null) {\n\t\tawait tx.execute('DELETE FROM _kora_meta WHERE key = ?', [\n\t\t\tofflineUnitKey(mark.signature, completion.unitId),\n\t\t])\n\t}\n\tfor (const row of await scan(tx, OFFLINE_UNIT_KEY_PREFIX)) {\n\t\tconst unit = parseUnit(row.value)\n\t\tif (unit !== null && unit.signature === mark.signature && unit.upTo <= mark.watermark) {\n\t\t\tawait tx.execute('DELETE FROM _kora_meta WHERE key = ?', [row.key])\n\t\t}\n\t}\n}\n\n/** Delete every completion mark (clear-before-apply, and every watermark reset). */\nexport async function clearOfflineMarks(adapter: StorageAdapter): Promise<void> {\n\tconst [low, high] = prefixRange(OFFLINE_MARK_KEY_PREFIX)\n\tawait adapter.execute('DELETE FROM _kora_meta WHERE key >= ? AND key < ?', [low, high])\n}\n\n/** Delete a view's mark and unit keys (its watermark was evicted). */\nexport async function deleteOfflineViewMarks(\n\tadapter: StorageAdapter,\n\tsignature: string,\n): Promise<void> {\n\tawait adapter.transaction(async (tx) => {\n\t\tawait tx.execute('DELETE FROM _kora_meta WHERE key = ?', [offlineMarkKey(signature)])\n\t\tfor (const row of await scan(tx, OFFLINE_UNIT_KEY_PREFIX)) {\n\t\t\tconst unit = parseUnit(row.value)\n\t\t\tif (unit !== null && unit.signature === signature) {\n\t\t\t\tawait tx.execute('DELETE FROM _kora_meta WHERE key = ?', [row.key])\n\t\t\t}\n\t\t}\n\t})\n}\n\n/**\n * Every mark and unit key. An unreadable unit key is reported with `upTo` infinity and an\n * empty signature so it blocks every view (it can only be cleared by a reset).\n */\nexport async function loadOfflineMarks(adapter: StorageAdapter): Promise<OfflineMarksSnapshot> {\n\tconst marks: OfflineCompletionMark[] = []\n\tfor (const row of await scan(adapter, OFFLINE_MARK_KEY_PREFIX)) {\n\t\tconst mark = parseMark(row.value)\n\t\tif (mark !== null) marks.push(mark)\n\t}\n\tconst units: OfflineUnitKey[] = []\n\tfor (const row of await scan(adapter, OFFLINE_UNIT_KEY_PREFIX)) {\n\t\tunits.push(\n\t\t\tparseUnit(row.value) ?? {\n\t\t\t\tsignature: '',\n\t\t\t\tunitId: row.key,\n\t\t\t\tbase: 0,\n\t\t\t\tupTo: Number.POSITIVE_INFINITY,\n\t\t\t},\n\t\t)\n\t}\n\treturn { marks, units }\n}\n","import type { Operation, VersionVector } from '@korajs/core'\nimport { createVersionVector } from '@korajs/core'\nimport type { OfflineCompletion } from '@korajs/core'\nimport type { MetaRow, StorageAdapter, Transaction } from '../types'\nimport { saveOfflineCompletionInTx } from './offline-marks'\n\nexport const LAST_ACKED_SERVER_VECTOR_META_KEY = 'last_acked_server_vector'\nexport const DELTA_CURSOR_META_KEY = 'delta_cursor'\nexport const DELIVERY_WATERMARK_META_KEY = 'delivery_watermark'\nexport const NODE_TOKEN_META_KEY = 'sync_node_token'\nexport const AUTHORITATIVE_NODE_IDS_META_KEY = 'sync_authoritative_node_ids'\n\n/**\n * Serialize a version vector for `_kora_meta` storage.\n */\nexport function serializeVersionVectorToMeta(vector: VersionVector): string {\n\tconst record: Record<string, number> = {}\n\tfor (const [nodeId, seq] of vector) {\n\t\trecord[nodeId] = seq\n\t}\n\treturn JSON.stringify(record)\n}\n\n/**\n * Deserialize a version vector from `_kora_meta`.\n */\nexport function deserializeVersionVectorFromMeta(value: string): VersionVector {\n\tconst parsed = JSON.parse(value) as Record<string, number>\n\tconst vector = createVersionVector()\n\tfor (const [nodeId, seq] of Object.entries(parsed)) {\n\t\tif (typeof seq === 'number' && seq >= 0) {\n\t\t\tvector.set(nodeId, seq)\n\t\t}\n\t}\n\treturn vector\n}\n\n/**\n * Merge two version vectors, keeping the maximum sequence per node.\n */\nexport function mergeVersionVectors(a: VersionVector, b: VersionVector): VersionVector {\n\tconst merged = new Map(a)\n\tfor (const [nodeId, seq] of b) {\n\t\tmerged.set(nodeId, Math.max(merged.get(nodeId) ?? 0, seq))\n\t}\n\treturn merged\n}\n\n/**\n * Operations present locally but not yet on the server (per server version vector).\n */\nexport async function collectOperationsAheadOfServer(\n\tlocalVector: VersionVector,\n\tserverVector: VersionVector,\n\tfetchRange: (nodeId: string, fromSeq: number, toSeq: number) => Promise<Operation[]>,\n): Promise<Operation[]> {\n\tconst missing: Operation[] = []\n\tfor (const [nodeId, localSeq] of localVector) {\n\t\tconst serverSeq = serverVector.get(nodeId) ?? 0\n\t\tif (localSeq > serverSeq) {\n\t\t\tconst ops = await fetchRange(nodeId, serverSeq + 1, localSeq)\n\t\t\tmissing.push(...ops)\n\t\t}\n\t}\n\tmissing.sort((a, b) => a.sequenceNumber - b.sequenceNumber)\n\treturn missing\n}\n\n/**\n * Load persisted last-acked server vector from `_kora_meta`.\n */\nexport async function loadLastAckedServerVector(adapter: StorageAdapter): Promise<VersionVector> {\n\tconst rows = await adapter.query<MetaRow>('SELECT value FROM _kora_meta WHERE key = ?', [\n\t\tLAST_ACKED_SERVER_VECTOR_META_KEY,\n\t])\n\tconst row = rows[0]\n\tif (!row?.value) {\n\t\treturn createVersionVector()\n\t}\n\ttry {\n\t\treturn deserializeVersionVectorFromMeta(row.value)\n\t} catch {\n\t\treturn createVersionVector()\n\t}\n}\n\n/**\n * Persist the last-acked server version vector to `_kora_meta`.\n */\nexport async function saveLastAckedServerVector(\n\tadapter: StorageAdapter,\n\tvector: VersionVector,\n): Promise<void> {\n\tawait adapter.execute('INSERT OR REPLACE INTO _kora_meta (key, value) VALUES (?, ?)', [\n\t\tLAST_ACKED_SERVER_VECTOR_META_KEY,\n\t\tserializeVersionVectorToMeta(vector),\n\t])\n}\n\n/**\n * Load the per-device node token the sync server issued for this node id (RT-12).\n */\nexport async function loadNodeToken(\n\tadapter: StorageAdapter,\n\tnodeId?: string,\n): Promise<string | null> {\n\tif (nodeId !== undefined) {\n\t\tconst own = await adapter.query<MetaRow>('SELECT value FROM _kora_meta WHERE key = ?', [\n\t\t\tnodeTokenKey(nodeId),\n\t\t])\n\t\tif (own[0]) return own[0].value\n\t\t// The legacy single key belongs to the database's node id (`_kora_meta.node_id`).\n\t\tconst meta = await adapter.query<MetaRow>(\"SELECT value FROM _kora_meta WHERE key = 'node_id'\")\n\t\tif (meta[0]?.value !== nodeId) return null\n\t}\n\tconst rows = await adapter.query<MetaRow>('SELECT value FROM _kora_meta WHERE key = ?', [\n\t\tNODE_TOKEN_META_KEY,\n\t])\n\treturn rows[0]?.value ?? null\n}\n\n/** `_kora_meta` key of one node id's token (RT-38/RT-40: a database may use several). */\nexport function nodeTokenKey(nodeId: string): string {\n\treturn `${NODE_TOKEN_META_KEY}:${nodeId}`\n}\n\n/**\n * Persist the per-device node token next to the node id in `_kora_meta`. With a node\n * id, the token is stored under that node's own key: a database that uses several node\n * ids (a rotated identity, per-tab isolation) keeps each node's token.\n */\nexport async function saveNodeToken(\n\tadapter: StorageAdapter,\n\ttoken: string,\n\tnodeId?: string,\n): Promise<void> {\n\tawait adapter.execute('INSERT OR REPLACE INTO _kora_meta (key, value) VALUES (?, ?)', [\n\t\tnodeId === undefined ? NODE_TOKEN_META_KEY : nodeTokenKey(nodeId),\n\t\ttoken,\n\t])\n}\n\n/**\n * Load a persisted delta cursor for resuming paginated initial sync.\n */\nexport async function loadDeltaCursor(adapter: StorageAdapter): Promise<string | null> {\n\tconst rows = await adapter.query<MetaRow>('SELECT value FROM _kora_meta WHERE key = ?', [\n\t\tDELTA_CURSOR_META_KEY,\n\t])\n\treturn rows[0]?.value ?? null\n}\n\n/**\n * Persist or clear the delta cursor in `_kora_meta`.\n */\nexport async function saveDeltaCursor(\n\tadapter: StorageAdapter,\n\tcursor: string | null,\n): Promise<void> {\n\tif (cursor === null) {\n\t\tawait adapter.execute('DELETE FROM _kora_meta WHERE key = ?', [DELTA_CURSOR_META_KEY])\n\t\treturn\n\t}\n\n\tawait adapter.execute('INSERT OR REPLACE INTO _kora_meta (key, value) VALUES (?, ?)', [\n\t\tDELTA_CURSOR_META_KEY,\n\t\tcursor,\n\t])\n}\n\n/**\n * The `_kora_meta` key for a view's delivery watermark. The default (empty) signature\n * uses the bare key for backward compatibility; other views suffix the signature.\n */\nexport function deliveryWatermarkKey(signature: string): string {\n\treturn signature === ''\n\t\t? DELIVERY_WATERMARK_META_KEY\n\t\t: `${DELIVERY_WATERMARK_META_KEY}:${signature}`\n}\n\n/**\n * Load the persisted delivery watermark for a view signature (0 when none recorded).\n */\nexport async function loadDeliveryWatermark(\n\tadapter: StorageAdapter,\n\tsignature: string,\n): Promise<number> {\n\tconst rows = await adapter.query<MetaRow>('SELECT value FROM _kora_meta WHERE key = ?', [\n\t\tdeliveryWatermarkKey(signature),\n\t])\n\tconst value = rows[0]?.value\n\tif (value === undefined || value === null) {\n\t\treturn 0\n\t}\n\tconst parsed = Number(value)\n\treturn Number.isFinite(parsed) && parsed >= 0 ? parsed : 0\n}\n\n/**\n * Persist the delivery watermark for a view signature in `_kora_meta`.\n */\nexport async function saveDeliveryWatermark(\n\tadapter: StorageAdapter,\n\tsignature: string,\n\twatermark: number,\n\tcompletion?: OfflineCompletion,\n): Promise<void> {\n\tif (completion) {\n\t\t// The mark and the watermark commit together (offline-readiness design 4.1).\n\t\tawait adapter.transaction(async (tx) => {\n\t\t\tawait saveDeliveryWatermarkInTx(tx, signature, watermark, completion)\n\t\t})\n\t\treturn\n\t}\n\tawait saveDeliveryWatermarkInTx(adapter, signature, watermark)\n}\n\n/** Persist a view's delivery watermark through `tx` (a transaction, or the adapter). */\nexport async function saveDeliveryWatermarkInTx(\n\ttx: Pick<Transaction, 'execute'> & Partial<Pick<Transaction, 'query'>>,\n\tsignature: string,\n\twatermark: number,\n\tcompletion?: OfflineCompletion,\n): Promise<void> {\n\tawait tx.execute('INSERT OR REPLACE INTO _kora_meta (key, value) VALUES (?, ?)', [\n\t\tdeliveryWatermarkKey(signature),\n\t\tString(watermark),\n\t])\n\tif (completion && tx.query) {\n\t\tawait saveOfflineCompletionInTx(\n\t\t\t{ execute: tx.execute.bind(tx), query: tx.query.bind(tx) },\n\t\t\tcompletion,\n\t\t)\n\t}\n}\n\n/**\n * Delete a persisted view watermark. Dropping a watermark is always safe: the view simply\n * back-fills from 0 (deduplicated) the next time it is visited. This bounds the number of\n * `_kora_meta` rows an app that churns through many distinct views can accumulate.\n */\nexport async function deleteDeliveryWatermark(\n\tadapter: StorageAdapter,\n\tsignature: string,\n): Promise<void> {\n\tawait adapter.execute('DELETE FROM _kora_meta WHERE key = ?', [deliveryWatermarkKey(signature)])\n}\n\n/**\n * Load every persisted view watermark, keyed by signature (the default view is '').\n */\nexport async function loadAllDeliveryWatermarks(\n\tadapter: StorageAdapter,\n): Promise<Record<string, number>> {\n\tconst rows = await adapter.query<MetaRow & { key: string }>(\n\t\t'SELECT key, value FROM _kora_meta WHERE key = ? OR key LIKE ?',\n\t\t[DELIVERY_WATERMARK_META_KEY, `${DELIVERY_WATERMARK_META_KEY}:%`],\n\t)\n\tconst result: Record<string, number> = {}\n\tconst prefix = `${DELIVERY_WATERMARK_META_KEY}:`\n\tfor (const row of rows) {\n\t\tconst signature = row.key === DELIVERY_WATERMARK_META_KEY ? '' : row.key.slice(prefix.length)\n\t\tconst parsed = Number(row.value)\n\t\tif (Number.isFinite(parsed) && parsed >= 0) {\n\t\t\tresult[signature] = parsed\n\t\t}\n\t}\n\treturn result\n}\n\n/**\n * Persist the node ids the sync server named authoritative (protocol v2): their\n * operations are server-authored. Stored as a JSON array in `_kora_meta`.\n */\nexport async function saveAuthoritativeNodeIds(\n\tadapter: StorageAdapter,\n\tnodeIds: string[],\n): Promise<void> {\n\tawait adapter.execute('INSERT OR REPLACE INTO _kora_meta (key, value) VALUES (?, ?)', [\n\t\tAUTHORITATIVE_NODE_IDS_META_KEY,\n\t\tJSON.stringify(nodeIds),\n\t])\n}\n\n/** `_kora_meta` key of the explicit authoritative ids a server revoked (RT-81). */\nconst REVOKED_AUTHORITATIVE_NODE_IDS_META_KEY = 'sync_revoked_authoritative_node_ids'\n\n/**\n * Persist the explicit authoritative node ids a sync server revoked (RT-81). A revoked\n * id is never authoritative again on this device, whatever a later handshake lists.\n */\nexport async function saveRevokedAuthoritativeNodeIds(\n\tadapter: StorageAdapter,\n\tnodeIds: string[],\n): Promise<void> {\n\tawait adapter.execute('INSERT OR REPLACE INTO _kora_meta (key, value) VALUES (?, ?)', [\n\t\tREVOKED_AUTHORITATIVE_NODE_IDS_META_KEY,\n\t\tJSON.stringify(nodeIds),\n\t])\n}\n\n/** Load the persisted revoked authoritative node ids (empty when none, or unreadable). */\nexport async function loadRevokedAuthoritativeNodeIds(adapter: StorageAdapter): Promise<string[]> {\n\tconst rows = await adapter.query<MetaRow>('SELECT value FROM _kora_meta WHERE key = ?', [\n\t\tREVOKED_AUTHORITATIVE_NODE_IDS_META_KEY,\n\t])\n\tconst raw = rows[0]?.value\n\tif (raw === undefined) return []\n\ttry {\n\t\tconst parsed: unknown = JSON.parse(raw)\n\t\tif (Array.isArray(parsed)) return parsed.filter((id): id is string => typeof id === 'string')\n\t} catch {\n\t\t// Unreadable: no revocation known; the next handshake that carries one rewrites it.\n\t}\n\treturn []\n}\n\n/**\n * Load the persisted authoritative node ids, or null when no protocol-2 server ever\n * answered (or the stored value is unreadable).\n */\nexport async function loadAuthoritativeNodeIds(adapter: StorageAdapter): Promise<string[] | null> {\n\tconst rows = await adapter.query<MetaRow>('SELECT value FROM _kora_meta WHERE key = ?', [\n\t\tAUTHORITATIVE_NODE_IDS_META_KEY,\n\t])\n\tconst raw = rows[0]?.value\n\tif (raw === undefined) return null\n\ttry {\n\t\tconst parsed: unknown = JSON.parse(raw)\n\t\tif (Array.isArray(parsed) && parsed.every((id) => typeof id === 'string')) {\n\t\t\treturn parsed as string[]\n\t\t}\n\t} catch {\n\t\t// Unreadable: treated as never received; the next handshake rewrites it.\n\t}\n\treturn null\n}\n","import { type HLCTimestamp, HybridLogicalClock } from '@korajs/core'\nimport type { RawCollectionRow } from '../types'\n\n/** Empty _version means legacy rows (compare by wallTime only via fallback). */\nexport const EMPTY_ROW_VERSION = ''\n\n/**\n * Serialize an HLC timestamp for storage in the `_version` column.\n * Lexicographic order matches {@link HybridLogicalClock.compare}.\n */\nexport function serializeRowVersion(timestamp: HLCTimestamp): string {\n\treturn HybridLogicalClock.serialize(timestamp)\n}\n\n/**\n * Read the version stamp stored on a materialized row.\n * Legacy rows without `_version` fall back to wallTime with logical 0.\n */\nexport function rowVersionFromRecord(\n\trow: Pick<RawCollectionRow, '_updated_at' | '_version'>,\n): HLCTimestamp {\n\tconst version = row._version\n\tif (typeof version === 'string' && version.length > 0) {\n\t\treturn HybridLogicalClock.deserialize(version)\n\t}\n\treturn { wallTime: row._updated_at, logical: 0, nodeId: '' }\n}\n\n/**\n * Returns true when `incoming` is strictly newer than the version on `row`.\n */\nexport function isIncomingNewerThanRow(\n\tincoming: HLCTimestamp,\n\trow: Pick<RawCollectionRow, '_updated_at' | '_version'>,\n): boolean {\n\treturn HybridLogicalClock.compare(incoming, rowVersionFromRecord(row)) > 0\n}\n\n/**\n * SQL fragment and params for LWW guards: apply only when row is missing or older.\n * Uses serialized `_version` for total order (matches HLC compare).\n */\nexport function lwwVersionWhereClause(remoteVersion: string): { sql: string; params: string[] } {\n\treturn {\n\t\tsql: '(_version = ? OR _version < ?)',\n\t\tparams: [EMPTY_ROW_VERSION, remoteVersion],\n\t}\n}\n","import type { FieldDescriptor } from '@korajs/core'\nimport { quoteIdent } from '@korajs/core'\nimport { QueryError } from '../errors'\nimport { lwwVersionWhereClause } from '../lww/row-version'\nimport { encodeStoredFilterValue } from '../serialization/serializer'\nimport type { QueryDescriptor, WhereOperators } from '../types'\n\n/**\n * Result of building a SQL query: the parameterized SQL string and its bound values.\n */\nexport interface SqlQuery {\n\tsql: string\n\tparams: unknown[]\n}\n\n/**\n * Build a SELECT query from a QueryDescriptor.\n * Automatically adds `WHERE _deleted = 0` to exclude soft-deleted records.\n *\n * @param descriptor - The query descriptor\n * @param fields - The field descriptors from the collection schema\n * @returns A parameterized SQL query\n */\nexport function buildSelectQuery(\n\tdescriptor: QueryDescriptor,\n\tfields: Record<string, FieldDescriptor>,\n): SqlQuery {\n\tconst params: unknown[] = []\n\tconst parts = [`SELECT * FROM ${quoteIdent(descriptor.collection)}`]\n\n\tconst whereClause = buildWhereClauseParts(descriptor.where, fields, params)\n\t// Always filter out soft-deleted records\n\tconst deletedFilter = '_deleted = 0'\n\tif (whereClause) {\n\t\tparts.push(`WHERE ${deletedFilter} AND ${whereClause}`)\n\t} else {\n\t\tparts.push(`WHERE ${deletedFilter}`)\n\t}\n\n\tif (descriptor.orderBy.length > 0) {\n\t\tconst orderParts = descriptor.orderBy.map((o) => {\n\t\t\tvalidateFieldName(o.field, fields)\n\t\t\t// SEC-7: the direction is whitelisted to a fixed keyword, never spliced from\n\t\t\t// the caller's string (a runtime value cast to the type is untrusted input).\n\t\t\treturn `${quoteIdent(resolveColumnName(o.field, fields))} ${sqlSortDirection(o.direction, o.field)}`\n\t\t})\n\t\tparts.push(`ORDER BY ${orderParts.join(', ')}`)\n\t}\n\n\tappendLimitOffset(descriptor, parts, params)\n\treturn { sql: parts.join(' '), params }\n}\n\n/**\n * Append the descriptor's LIMIT / OFFSET. SEC-7: both are bound as parameters after a\n * safe-integer check, so a value that only claims to be a number can never become SQL text.\n *\n * @returns Whether either was appended\n */\nfunction appendLimitOffset(\n\tdescriptor: QueryDescriptor,\n\tparts: string[],\n\tparams: unknown[],\n): boolean {\n\tconst limit = descriptor.limit !== undefined ? assertQueryCount(descriptor.limit, 'limit') : null\n\tconst offset =\n\t\tdescriptor.offset !== undefined ? assertQueryCount(descriptor.offset, 'offset') : null\n\tif (limit !== null) {\n\t\tparts.push('LIMIT ?')\n\t\tparams.push(limit)\n\t}\n\tif (offset !== null) {\n\t\t// SQLite accepts OFFSET only after LIMIT; LIMIT -1 means \"no limit\".\n\t\tif (limit === null) parts.push('LIMIT -1')\n\t\tparts.push('OFFSET ?')\n\t\tparams.push(offset)\n\t}\n\treturn limit !== null || offset !== null\n}\n\n/**\n * Build a COUNT query from a QueryDescriptor: the number of records `buildSelectQuery` would\n * return, so `limit` and `offset` apply (over a limited subquery). `orderBy` does not change a\n * count and is left out. Automatically adds `WHERE _deleted = 0`.\n *\n * @param descriptor - The query descriptor\n * @param fields - The field descriptors from the collection schema\n * @returns A parameterized SQL query that returns { count: number }\n */\nexport function buildCountQuery(\n\tdescriptor: QueryDescriptor,\n\tfields: Record<string, FieldDescriptor>,\n): SqlQuery {\n\tconst params: unknown[] = []\n\tconst parts = [`FROM ${quoteIdent(descriptor.collection)}`]\n\n\tconst whereClause = buildWhereClauseParts(descriptor.where, fields, params)\n\tconst deletedFilter = '_deleted = 0'\n\tif (whereClause) {\n\t\tparts.push(`WHERE ${deletedFilter} AND ${whereClause}`)\n\t} else {\n\t\tparts.push(`WHERE ${deletedFilter}`)\n\t}\n\n\tif (appendLimitOffset(descriptor, parts, params)) {\n\t\treturn { sql: `SELECT COUNT(*) as count FROM (SELECT 1 ${parts.join(' ')})`, params }\n\t}\n\treturn { sql: `SELECT COUNT(*) as count ${parts.join(' ')}`, params }\n}\n\n/**\n * Build an INSERT query for a collection record.\n *\n * @param collection - The collection name\n * @param record - The record data (already serialized with id, _created_at, _updated_at)\n * @returns A parameterized SQL query\n */\nexport function buildInsertQuery(collection: string, record: Record<string, unknown>): SqlQuery {\n\tconst columns = Object.keys(record)\n\tconst placeholders = columns.map(() => '?')\n\tconst params = Object.values(record)\n\n\tconst quotedColumns = columns.map((col) => quoteIdent(col))\n\tconst sql = `INSERT INTO ${quoteIdent(collection)} (${quotedColumns.join(', ')}) VALUES (${placeholders.join(', ')})`\n\treturn { sql, params }\n}\n\n/**\n * Build an UPDATE query for a collection record.\n *\n * @param collection - The collection name\n * @param id - The record ID\n * @param changes - The fields to update (already serialized)\n * @returns A parameterized SQL query\n */\nexport function buildUpdateQuery(\n\tcollection: string,\n\tid: string,\n\tchanges: Record<string, unknown>,\n): SqlQuery {\n\tconst setClauses = Object.keys(changes).map((col) => `${quoteIdent(col)} = ?`)\n\tconst params = [...Object.values(changes), id]\n\n\tconst sql = `UPDATE ${quoteIdent(collection)} SET ${setClauses.join(', ')} WHERE id = ?`\n\treturn { sql, params }\n}\n\n/**\n * Build a field-level fast-forward UPDATE: writes the changed field values\n * unconditionally (the caller has already proven per-field that the local value\n * still equals the base the remote wrote from, so the remote is the newest known\n * writer of those fields), while advancing the row's `_version` / `_updated_at`\n * watermark MONOTONICALLY — never regressing it below its current value.\n *\n * This is what makes per-field LWW correct on a per-row `_version` column: a\n * concurrent edit to a different field may have pushed `_version` past this\n * operation's timestamp, but that must not cause this operation's own field\n * change to be dropped, nor may materializing it move the watermark backward\n * (which would let a genuinely stale later operation win).\n *\n * @param collection - The collection name\n * @param id - The record ID\n * @param fieldChanges - Serialized field values to write unconditionally (must NOT include _version / _updated_at)\n * @param remoteVersion - The operation's serialized row version (lexicographically comparable)\n * @param wallTime - The operation's wall-clock time in ms\n * @param options - Optional extras. `maxCreatedAt` advances `_created_at` to the\n *   greater of its current value and the given wall time — used for insert\n *   collisions so every node converges on the max insert wall time regardless\n *   of arrival order.\n */\nexport function buildFieldFastForwardUpdateQuery(\n\tcollection: string,\n\tid: string,\n\tfieldChanges: Record<string, unknown>,\n\tremoteVersion: string,\n\twallTime: number,\n\toptions?: { maxCreatedAt?: number },\n): SqlQuery {\n\tconst fieldClauses = Object.keys(fieldChanges).map((col) => `${quoteIdent(col)} = ?`)\n\t// _version is a lexicographically-sortable string; _updated_at is a number.\n\t// Keep the greater of the current and incoming value for each (monotonic).\n\tconst setClauses = [\n\t\t...fieldClauses,\n\t\t'_version = CASE WHEN _version >= ? THEN _version ELSE ? END',\n\t\t'_updated_at = CASE WHEN _updated_at >= ? THEN _updated_at ELSE ? END',\n\t]\n\tconst params: unknown[] = [\n\t\t...Object.values(fieldChanges),\n\t\tremoteVersion,\n\t\tremoteVersion,\n\t\twallTime,\n\t\twallTime,\n\t]\n\tif (options?.maxCreatedAt !== undefined) {\n\t\tsetClauses.push('_created_at = CASE WHEN _created_at >= ? THEN _created_at ELSE ? END')\n\t\tparams.push(options.maxCreatedAt, options.maxCreatedAt)\n\t}\n\tparams.push(id)\n\tconst sql = `UPDATE ${quoteIdent(collection)} SET ${setClauses.join(', ')} WHERE id = ?`\n\treturn { sql, params }\n}\n\n/**\n * Build a soft-delete query (SET _deleted = 1).\n *\n * @param collection - The collection name\n * @param id - The record ID\n * @param updatedAt - The timestamp to set on _updated_at\n * @returns A parameterized SQL query\n */\nexport function buildSoftDeleteQuery(\n\tcollection: string,\n\tid: string,\n\tupdatedAt: number,\n\tversion?: string,\n): SqlQuery {\n\tif (version !== undefined) {\n\t\treturn {\n\t\t\tsql: `UPDATE ${quoteIdent(collection)} SET _deleted = 1, _updated_at = ?, _version = ? WHERE id = ?`,\n\t\t\tparams: [updatedAt, version, id],\n\t\t}\n\t}\n\treturn {\n\t\tsql: `UPDATE ${quoteIdent(collection)} SET _deleted = 1, _updated_at = ? WHERE id = ?`,\n\t\tparams: [updatedAt, id],\n\t}\n}\n\n/**\n * Build an UPDATE that applies only when the row is missing or older than `remoteVersion`\n * (serialized HLC). Prevents stale remote sync from overwriting newer local materialized state.\n */\nexport function buildLwwUpdateQuery(\n\tcollection: string,\n\tid: string,\n\tchanges: Record<string, unknown>,\n\tremoteVersion: string,\n): SqlQuery {\n\tconst setClauses = Object.keys(changes).map((col) => `${quoteIdent(col)} = ?`)\n\tconst lww = lwwVersionWhereClause(remoteVersion)\n\tconst sql = `UPDATE ${quoteIdent(collection)} SET ${setClauses.join(', ')} WHERE id = ? AND ${lww.sql}`\n\tconst params = [...Object.values(changes), id, ...lww.params]\n\treturn { sql, params }\n}\n\n/**\n * Build a soft-delete that applies only when the row is older than `remoteVersion`.\n */\nexport function buildLwwSoftDeleteQuery(\n\tcollection: string,\n\tid: string,\n\tupdatedAt: number,\n\tversion: string,\n): SqlQuery {\n\tconst lww = lwwVersionWhereClause(version)\n\treturn {\n\t\tsql: `UPDATE ${quoteIdent(collection)} SET _deleted = 1, _updated_at = ?, _version = ? WHERE id = ? AND ${lww.sql}`,\n\t\tparams: [updatedAt, version, id, ...lww.params],\n\t}\n}\n\n/**\n * Build a WHERE clause from conditions, validating field names against the schema.\n *\n * @param where - The where conditions\n * @param fields - The field descriptors from the collection schema\n * @returns The SQL WHERE clause string and params, or null if no conditions\n */\nexport function buildWhereClause(\n\twhere: Record<string, unknown>,\n\tfields: Record<string, FieldDescriptor>,\n): SqlQuery | null {\n\tconst params: unknown[] = []\n\tconst result = buildWhereClauseParts(where, fields, params)\n\tif (!result) return null\n\treturn { sql: result, params }\n}\n\n// --- Internal helpers ---\n\nconst VALID_OPERATORS = new Set(['$eq', '$ne', '$gt', '$gte', '$lt', '$lte', '$in'])\n\nfunction buildWhereClauseParts(\n\twhere: Record<string, unknown>,\n\tfields: Record<string, FieldDescriptor>,\n\tparams: unknown[],\n): string | null {\n\tconst conditions: string[] = []\n\n\tfor (const [fieldName, value] of Object.entries(where)) {\n\t\tvalidateFieldName(fieldName, fields)\n\t\tconst descriptor = fields[fieldName]\n\t\tconst column = resolveColumnName(fieldName, fields)\n\n\t\tif (value !== null && typeof value === 'object' && !Array.isArray(value)) {\n\t\t\t// Operator object: { $gt: 5, $lt: 10 }\n\t\t\tconst ops = value as WhereOperators\n\t\t\tfor (const [op, opValue] of Object.entries(ops)) {\n\t\t\t\tif (!VALID_OPERATORS.has(op)) {\n\t\t\t\t\tthrow new QueryError(`Unknown operator \"${op}\" on field \"${fieldName}\"`, {\n\t\t\t\t\t\tfield: fieldName,\n\t\t\t\t\t\toperator: op,\n\t\t\t\t\t\tvalidOperators: [...VALID_OPERATORS],\n\t\t\t\t\t})\n\t\t\t\t}\n\t\t\t\tconditions.push(buildOperatorCondition(fieldName, column, op, opValue, descriptor, params))\n\t\t\t}\n\t\t} else {\n\t\t\t// Shorthand: { completed: false } means { completed: { $eq: false } }\n\t\t\tconditions.push(buildOperatorCondition(fieldName, column, '$eq', value, descriptor, params))\n\t\t}\n\t}\n\n\tif (conditions.length === 0) return null\n\treturn conditions.join(' AND ')\n}\n\nfunction buildOperatorCondition(\n\tfieldName: string,\n\tcolumnName: string,\n\toperator: string,\n\tvalue: unknown,\n\tdescriptor: FieldDescriptor | undefined,\n\tparams: unknown[],\n): string {\n\t// Serialize boolean values to 0/1 and raw strings to their stored form (RT-65)\n\tconst sqlValue = toSqlFilterValue(value, descriptor)\n\n\tconst column = quoteIdent(columnName)\n\n\tswitch (operator) {\n\t\tcase '$eq':\n\t\t\tif (sqlValue === null) {\n\t\t\t\treturn `${column} IS NULL`\n\t\t\t}\n\t\t\tparams.push(sqlValue)\n\t\t\treturn `${column} = ?`\n\t\tcase '$ne':\n\t\t\tif (sqlValue === null) {\n\t\t\t\treturn `${column} IS NOT NULL`\n\t\t\t}\n\t\t\tparams.push(sqlValue)\n\t\t\treturn `${column} != ?`\n\t\tcase '$gt':\n\t\t\tparams.push(sqlValue)\n\t\t\treturn `${column} > ?`\n\t\tcase '$gte':\n\t\t\tparams.push(sqlValue)\n\t\t\treturn `${column} >= ?`\n\t\tcase '$lt':\n\t\t\tparams.push(sqlValue)\n\t\t\treturn `${column} < ?`\n\t\tcase '$lte':\n\t\t\tparams.push(sqlValue)\n\t\t\treturn `${column} <= ?`\n\t\tcase '$in': {\n\t\t\tif (!Array.isArray(sqlValue)) {\n\t\t\t\tthrow new QueryError(`$in operator requires an array value for field \"${fieldName}\"`, {\n\t\t\t\t\tfield: fieldName,\n\t\t\t\t\treceived: typeof sqlValue,\n\t\t\t\t})\n\t\t\t}\n\t\t\tconst placeholders = sqlValue.map(() => '?')\n\t\t\tfor (const item of sqlValue) {\n\t\t\t\tparams.push(toSqlFilterValue(item, descriptor))\n\t\t\t}\n\t\t\treturn `${column} IN (${placeholders.join(', ')})`\n\t\t}\n\t\tdefault:\n\t\t\tthrow new QueryError(`Unknown operator \"${operator}\"`, { operator })\n\t}\n}\n\nfunction toSqlFilterValue(value: unknown, descriptor: FieldDescriptor | undefined): unknown {\n\tif (descriptor?.kind === 'boolean' && typeof value === 'boolean') return value ? 1 : 0\n\treturn encodeStoredFilterValue(value, descriptor)\n}\n\n/**\n * Record metadata exposed on every record under a camelCase name and backed by a\n * system column (STORE-11): `where({ updatedAt: { $gt: t } })` and\n * `orderBy('createdAt', 'desc')` filter and sort on these columns. A schema field\n * declared with the same name wins and its own column is used instead.\n */\nexport const VIRTUAL_TIMESTAMP_FIELDS = Object.freeze({\n\tcreatedAt: '_created_at',\n\tupdatedAt: '_updated_at',\n} as const)\n\n/** Name of a virtual record-metadata field usable in `where` and `orderBy`. */\nexport type VirtualTimestampField = keyof typeof VIRTUAL_TIMESTAMP_FIELDS\n\n/** Every virtual record-metadata field name, for typing `where` / `orderBy` keys. */\nexport const VIRTUAL_TIMESTAMP_FIELD_NAMES: readonly VirtualTimestampField[] = Object.freeze([\n\t'createdAt',\n\t'updatedAt',\n] as const)\n\nconst SORT_DIRECTIONS: Readonly<Record<string, 'ASC' | 'DESC'>> = Object.freeze({\n\tasc: 'ASC',\n\tdesc: 'DESC',\n})\n\n/** Map a query field name to the column it reads (STORE-11 virtual fields). */\nfunction resolveColumnName(fieldName: string, fields: Record<string, FieldDescriptor>): string {\n\tif (Object.hasOwn(fields, fieldName)) return fieldName\n\tif (fieldName === 'createdAt' || fieldName === 'updatedAt') {\n\t\treturn VIRTUAL_TIMESTAMP_FIELDS[fieldName]\n\t}\n\treturn fieldName\n}\n\nfunction sqlSortDirection(direction: unknown, field: string): 'ASC' | 'DESC' {\n\tconst key = typeof direction === 'string' ? direction.toLowerCase() : ''\n\tconst keyword = Object.hasOwn(SORT_DIRECTIONS, key) ? SORT_DIRECTIONS[key] : undefined\n\tif (keyword === undefined) {\n\t\tthrow new QueryError(`Invalid sort direction for field \"${field}\". Use 'asc' or 'desc'.`, {\n\t\t\tfield,\n\t\t\tdirection: typeof direction === 'string' ? direction.slice(0, 64) : typeof direction,\n\t\t})\n\t}\n\treturn keyword\n}\n\nfunction assertQueryCount(value: unknown, clause: 'limit' | 'offset'): number {\n\tif (typeof value !== 'number' || !Number.isSafeInteger(value) || value < 0) {\n\t\tthrow new QueryError(\n\t\t\t`Invalid ${clause}: expected a non-negative safe integer. Pass a whole number, for example .${clause}(10).`,\n\t\t\t{ clause, received: typeof value === 'number' ? value : typeof value },\n\t\t)\n\t}\n\treturn value\n}\n\nfunction validateFieldName(fieldName: string, fields: Record<string, FieldDescriptor>): void {\n\t// Allow schema fields plus metadata fields that map to query-able columns\n\tconst allowedFields = new Set([\n\t\t...Object.keys(fields),\n\t\t'id',\n\t\t...VIRTUAL_TIMESTAMP_FIELD_NAMES,\n\t\t'_created_at',\n\t\t'_updated_at',\n\t])\n\tif (!allowedFields.has(fieldName)) {\n\t\tthrow new QueryError(\n\t\t\t`Unknown field \"${fieldName}\" in query. Available fields: ${[...allowedFields].join(', ')}`,\n\t\t\t{ field: fieldName },\n\t\t)\n\t}\n}\n","import { quoteIdent } from '@korajs/core'\nimport type { Operation } from '@korajs/core'\nimport { computeOperationId } from '@korajs/core/internal'\nimport { buildInsertQuery } from '../query/sql-builder'\nimport { deserializeOperationWithCollection, serializeOperation } from '../serialization/serializer'\nimport type { OperationRow, Transaction } from '../types'\n\n/** Result of `Store.resequenceOperation` (RT-35 renumbering). */\nexport interface ResequenceResult {\n\t/** The renumbered operation (a version-2 one under a new id). */\n\toperation: Operation\n\t/** Never-sent dependents rewritten to name the new id (re-hashed), in sequence order. */\n\tdependents: Operation[]\n\t/** Old id -> new id, for the operation and every re-hashed dependent. */\n\tidMapping: Record<string, string>\n}\n\n/**\n * The content-addressed id of an operation whose stamp, node, sequence or causal deps\n * were rewritten locally before it was ever shared (clock rebase, node rotation,\n * SEQUENCE_CONFLICT renumbering). Uses the operation's own hash version: a version-2\n * operation (protocol v2) gets a version-2 id over all its semantic fields, and a\n * version-1 operation (written before beta.13) keeps the version-1 hash, so neither\n * fails id verification on its receivers.\n *\n * @param op - The operation with its new content (its `id` is ignored)\n * @returns The id matching that content under the operation's hash version\n */\nexport async function rehashOperation(op: Operation): Promise<string> {\n\treturn computeOperationId(\n\t\t{\n\t\t\tnodeId: op.nodeId,\n\t\t\ttype: op.type,\n\t\t\tcollection: op.collection,\n\t\t\trecordId: op.recordId,\n\t\t\tdata: op.data,\n\t\t\tpreviousData: op.previousData,\n\t\t\ttimestamp: op.timestamp,\n\t\t\tsequenceNumber: op.sequenceNumber,\n\t\t\tcausalDeps: op.causalDeps,\n\t\t\tschemaVersion: op.schemaVersion,\n\t\t\t...(op.atomicOps !== undefined ? { atomicOps: op.atomicOps } : {}),\n\t\t},\n\t\top.hashVersion === 2 ? 2 : 1,\n\t)\n}\n\n/**\n * Give a logged operation row a new sequence number inside `tx` (SEQUENCE_CONFLICT\n * recovery, RT-35; legacy duplicate repair, W6). A version-1 operation keeps its id:\n * its hash never covered the sequence number. A version-2 operation's id does cover it\n * (CORE-1), so it is re-hashed and its row replaced under the new id; it was never\n * stored by the server (that is why it is renumbered), so no replica knows the old id.\n *\n * @returns The operation as it is now logged\n */\nexport async function renumberOperationRow(\n\ttx: Transaction,\n\tcollection: string,\n\trow: OperationRow,\n\tsequenceNumber: number,\n): Promise<Operation> {\n\tconst table = quoteIdent(`_kora_ops_${collection}`)\n\tconst current = deserializeOperationWithCollection(row, collection)\n\tconst renumbered: Operation = { ...current, sequenceNumber }\n\tif (current.hashVersion !== 2) {\n\t\tawait tx.execute(`UPDATE ${table} SET sequence_number = ? WHERE id = ?`, [\n\t\t\tsequenceNumber,\n\t\t\trow.id,\n\t\t])\n\t\treturn renumbered\n\t}\n\tconst id = await rehashOperation(renumbered)\n\tconst moved: Operation = { ...renumbered, id }\n\tawait replaceOperationRow(tx, collection, row.id, moved)\n\treturn moved\n}\n\nasync function replaceOperationRow(\n\ttx: Transaction,\n\tcollection: string,\n\toldId: string,\n\tnext: Operation,\n): Promise<void> {\n\tawait tx.execute(`DELETE FROM ${quoteIdent(`_kora_ops_${collection}`)} WHERE id = ?`, [oldId])\n\tconst insert = buildInsertQuery(\n\t\t`_kora_ops_${collection}`,\n\t\tserializeOperation(next) as unknown as Record<string, unknown>,\n\t)\n\tawait tx.execute(insert.sql, insert.params)\n}\n\n/**\n * After operations were re-hashed under new ids (`idMapping`, old id -> new id), make\n * the local operations that name an old id in `causalDeps` name the new one, inside\n * `tx`. Only operations in `rewritable` are touched: those the server never stored\n * (never sent). Each rewritten operation covers its causalDeps in its id (version 2),\n * so it is re-hashed too and its own dependents follow, transitively, in sequence\n * order (sequence order is authoring order, so a dependency is always rewritten before\n * its dependents). A version-1 operation keeps its id (its hash does not cover\n * causalDeps) but still gets the new dep. `idMapping` is extended in place.\n *\n * An operation outside `rewritable` (already sent: the server may hold it under its\n * id) is never rewritten; its dep on an old id resolves through `_kora_seq_conflicts`\n * (`reemitted_as`) on this device.\n *\n * @returns The rewritten operations, in sequence order\n */\nexport async function rewriteDependentsInTx(\n\ttx: Transaction,\n\tcollections: readonly string[],\n\tnodeId: string,\n\tidMapping: Record<string, string>,\n\trewritable: ReadonlySet<string>,\n): Promise<Operation[]> {\n\tif (rewritable.size === 0) return []\n\tconst candidates: Array<{ collection: string; row: OperationRow; op: Operation }> = []\n\tfor (const collection of collections) {\n\t\tconst rows = await tx.query<OperationRow>(\n\t\t\t`SELECT * FROM ${quoteIdent(`_kora_ops_${collection}`)} WHERE node_id = ?`,\n\t\t\t[nodeId],\n\t\t)\n\t\tfor (const row of rows) {\n\t\t\tif (!rewritable.has(row.id)) continue\n\t\t\tcandidates.push({ collection, row, op: deserializeOperationWithCollection(row, collection) })\n\t\t}\n\t}\n\tcandidates.sort((a, b) => a.op.sequenceNumber - b.op.sequenceNumber)\n\tconst rewritten: Operation[] = []\n\tfor (const { collection, row, op } of candidates) {\n\t\tif (!op.causalDeps.some((dep) => idMapping[dep] !== undefined)) continue\n\t\tconst causalDeps = op.causalDeps.map((dep) => idMapping[dep] ?? dep)\n\t\tconst updated: Operation = { ...op, causalDeps }\n\t\tconst id = op.hashVersion === 2 ? await rehashOperation(updated) : op.id\n\t\tconst next: Operation = { ...updated, id }\n\t\tawait replaceOperationRow(tx, collection, row.id, next)\n\t\tif (id !== op.id) idMapping[op.id] = id\n\t\trewritten.push(next)\n\t}\n\treturn rewritten\n}\n","import { AdapterError } from '../errors'\nimport type { StorageAdapter, Transaction } from '../types'\n\ninterface SequenceRow {\n\tsequence_number: number\n}\n\n/**\n * Reserve the next sequence number for a node inside a write transaction\n * (UPSERT ... RETURNING on `_kora_version_vector`).\n *\n * This is the ONLY way a local operation gets its number: the reservation\n * commits or rolls back with the operation that uses it, and transactions are\n * serialized, so the numbers of one commit are contiguous and never shared. There\n * is deliberately no variant that allocates outside a transaction (W6).\n */\nexport async function allocateNextSequenceInTransaction(\n\ttx: Transaction,\n\tnodeId: string,\n): Promise<number> {\n\tconst rows = await tx.query<SequenceRow>(\n\t\t`INSERT INTO _kora_version_vector (node_id, sequence_number) VALUES (?, 1)\n     ON CONFLICT(node_id) DO UPDATE SET sequence_number = sequence_number + 1\n     RETURNING sequence_number`,\n\t\t[nodeId],\n\t)\n\tconst seq = rows[0]?.sequence_number\n\tif (seq === undefined) {\n\t\tthrow new AdapterError(\n\t\t\t`Failed to allocate sequence number for node \"${nodeId}\" in transaction`,\n\t\t\t{ nodeId },\n\t\t)\n\t}\n\treturn seq\n}\n\n/**\n * Read the current sequence for a node without incrementing.\n */\nexport async function readSequenceNumber(adapter: StorageAdapter, nodeId: string): Promise<number> {\n\tconst rows = await adapter.query<SequenceRow>(\n\t\t'SELECT sequence_number FROM _kora_version_vector WHERE node_id = ?',\n\t\t[nodeId],\n\t)\n\treturn rows[0]?.sequence_number ?? 0\n}\n","import { quoteIdent } from '@korajs/core'\nimport type { SchemaDefinition } from '@korajs/core'\nimport { deserializeOperationWithCollection } from '../serialization/serializer'\nimport { renumberOperationRow } from '../sync/rehash-operation'\nimport type { OperationRow, StorageAdapter, Transaction } from '../types'\nimport { allocateNextSequenceInTransaction } from './sequence-allocator'\n\n/**\n * Audit table for operation rows whose `(node_id, sequence_number)` identity\n * collided with another operation (STORE-1 / STORE-2 duplicates written by\n * beta.12, or a conflicting remote operation). Rows here are never deleted.\n *\n * - `reemitted_as` set: the operation was given a fresh sequence number and still\n *   lives in the operation log under that number (`new_sequence_number`).\n * - `reemitted_as` NULL: the operation is kept ONLY here (another node's\n *   operation whose number this log already holds). It still takes part in\n *   dedup and in record folds, so no data is lost.\n */\nexport const SEQ_CONFLICTS_TABLE = '_kora_seq_conflicts'\n\nconst REPAIR_DONE_META_KEY = 'seq_unique_repair_v1'\n\n/** DDL for {@link SEQ_CONFLICTS_TABLE}. */\nconst CREATE_SEQ_CONFLICTS_SQL = `CREATE TABLE IF NOT EXISTS ${SEQ_CONFLICTS_TABLE} (\n  id TEXT PRIMARY KEY NOT NULL,\n  collection TEXT NOT NULL,\n  node_id TEXT NOT NULL,\n  type TEXT NOT NULL,\n  record_id TEXT NOT NULL,\n  data TEXT,\n  previous_data TEXT,\n  timestamp TEXT NOT NULL,\n  sequence_number INTEGER NOT NULL,\n  causal_deps TEXT NOT NULL,\n  schema_version INTEGER NOT NULL,\n  reason TEXT NOT NULL,\n  reemitted_as TEXT,\n  new_sequence_number INTEGER,\n  recorded_at INTEGER NOT NULL\n)`\n\n/** Name of the unique `(node_id, sequence_number)` index on a collection's op log. */\nexport function uniqueSequenceIndexName(collection: string): string {\n\treturn `uidx_kora_ops_${collection.length}_${collection}_node_seq`\n}\n\n/** Outcome of {@link repairSequenceUniqueness}. */\nexport interface SequenceRepairResult {\n\t/** Own-node operations that were given a fresh sequence number. */\n\tresequenced: number\n\t/** Other nodes' operations moved out of the log into the conflicts table. */\n\tretained: number\n}\n\n/**\n * Make `(node_id, sequence_number)` unique in the local operation log, then\n * enforce it with a UNIQUE index on every operation table (W6 step 2).\n *\n * beta.12 could give two different operations of this device the same sequence\n * number (STORE-1/2). A plain UNIQUE index cannot be created over such a log, and\n * dropping either row would lose a write. The repair, in one transaction:\n *\n * 1. Raises this node's persisted counter to at least the highest sequence number\n *    in its log (beta.12 could leave it behind, which would make the next write\n *    collide).\n * 2. For every duplicated `(node, seq)` — across all collections, since one node\n *    numbers all its operations in one sequence — keeps the first row by id.\n * 3. Every other row of THIS node is re-emitted with a fresh sequence number from\n *    the counter, keeping its id and content (see the note below), and recorded\n *    in {@link SEQ_CONFLICTS_TABLE}.\n * 4. Rows of OTHER nodes (this device cannot number them) move to\n *    {@link SEQ_CONFLICTS_TABLE} with `reemitted_as` NULL; the store keeps using\n *    them for dedup and record folds.\n * 5. Creates the UNIQUE index on every operation table.\n *\n * Why the re-emitted operation keeps its id: protocol v1 content-addresses\n * operations without the sequence number, and changing any hashed content (data\n * or HLC timestamp) would change what the write means under last-write-wins.\n * With the id kept, a server that already stored the operation deduplicates it\n * (acknowledging the new number), and a server that never got it — beta.12 could\n * skip the second of two same-numbered operations — stores it. Either way atomic\n * increments are never applied twice and no write is lost.\n *\n * Idempotent: the scan runs once per database (a meta flag records completion);\n * the index creation runs on every open so collections added later are covered.\n *\n * A database whose pinned node moved (a browser shared between accounts gives each\n * account a device id of its own) still authored under its previous node: that node is\n * passed as one of its own too, so a duplicate under it is renumbered (and later\n * re-authored or found on the server) instead of moved out of the upload path, unless this\n * database recorded it as received under that shared node (another database's write): that\n * one is kept aside like any other device's.\n *\n * @param adapter - The store's adapter (already opened)\n * @param schema - The schema whose operation tables are repaired\n * @param ownNodeIds - This device's node id, or every node id this database authored\n *   its own operations under\n */\nexport async function repairSequenceUniqueness(\n\tadapter: StorageAdapter,\n\tschema: SchemaDefinition,\n\townNodeIds: string | readonly string[],\n): Promise<SequenceRepairResult> {\n\tconst own = new Set(typeof ownNodeIds === 'string' ? [ownNodeIds] : ownNodeIds)\n\tawait adapter.execute(CREATE_SEQ_CONFLICTS_SQL)\n\tconst collections = Object.keys(schema.collections)\n\tconst result: SequenceRepairResult = { resequenced: 0, retained: 0 }\n\n\tconst done = await adapter.query<{ value: string }>(\n\t\t'SELECT value FROM _kora_meta WHERE key = ?',\n\t\t[REPAIR_DONE_META_KEY],\n\t)\n\tif (done.length === 0 && collections.length > 0) {\n\t\tawait runRepair(adapter, collections, own, result)\n\t}\n\n\tfor (const collection of collections) {\n\t\tconst createIndex = `CREATE UNIQUE INDEX IF NOT EXISTS ${quoteIdent(uniqueSequenceIndexName(collection))} ON ${quoteIdent(`_kora_ops_${collection}`)} (node_id, sequence_number)`\n\t\ttry {\n\t\t\tawait adapter.execute(createIndex)\n\t\t} catch (error) {\n\t\t\t// Duplicates written after an earlier repair (for example by an older\n\t\t\t// Kora version opening this database again): repair once more, then\n\t\t\t// create the index. A second failure propagates.\n\t\t\tif (!/UNIQUE/i.test(error instanceof Error ? error.message : String(error))) throw error\n\t\t\tawait runRepair(adapter, collections, own, result)\n\t\t\tawait adapter.execute(createIndex)\n\t\t}\n\t}\n\treturn result\n}\n\nasync function runRepair(\n\tadapter: StorageAdapter,\n\tcollections: string[],\n\town: ReadonlySet<string>,\n\tresult: SequenceRepairResult,\n): Promise<void> {\n\tlet resequenced = 0\n\tlet retained = 0\n\tawait adapter.transaction(async (tx) => {\n\t\tfor (const nodeId of own) await raiseOwnCounterToLog(tx, collections, nodeId)\n\t\tconst repaired = await repairDuplicates(tx, collections, own)\n\t\tresequenced = repaired.resequenced\n\t\tretained = repaired.retained\n\t\tawait tx.execute('INSERT OR REPLACE INTO _kora_meta (key, value) VALUES (?, ?)', [\n\t\t\tREPAIR_DONE_META_KEY,\n\t\t\tString(Date.now()),\n\t\t])\n\t})\n\tresult.resequenced += resequenced\n\tresult.retained += retained\n\tif (resequenced > 0 || retained > 0) {\n\t\tconsole.warn(\n\t\t\t`[kora] Repaired ${resequenced + retained} operation(s) that shared a sequence number (written by an earlier Kora version). ${resequenced} were given fresh sequence numbers; ${retained} from other devices were kept in ${SEQ_CONFLICTS_TABLE}. No data was removed.`,\n\t\t)\n\t}\n}\n\nasync function raiseOwnCounterToLog(\n\ttx: Transaction,\n\tcollections: string[],\n\tnodeId: string,\n): Promise<void> {\n\tlet maxSeq = 0\n\tfor (const collection of collections) {\n\t\tconst rows = await tx.query<{ max_seq: number | null }>(\n\t\t\t`SELECT MAX(sequence_number) AS max_seq FROM ${quoteIdent(`_kora_ops_${collection}`)} WHERE node_id = ?`,\n\t\t\t[nodeId],\n\t\t)\n\t\tmaxSeq = Math.max(maxSeq, rows[0]?.max_seq ?? 0)\n\t}\n\tif (maxSeq > 0) {\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[nodeId, maxSeq],\n\t\t)\n\t}\n}\n\ninterface LoggedIdentity {\n\tcollection: string\n\tid: string\n\tnode_id: string\n\tsequence_number: number\n}\n\nasync function repairDuplicates(\n\ttx: Transaction,\n\tcollections: string[],\n\town: ReadonlySet<string>,\n): Promise<SequenceRepairResult> {\n\t// One node numbers all its operations in one sequence, so duplicates are\n\t// found across every collection's table, not per table.\n\tconst all: LoggedIdentity[] = []\n\tfor (const collection of collections) {\n\t\tconst rows = await tx.query<Omit<LoggedIdentity, 'collection'>>(\n\t\t\t`SELECT id, node_id, sequence_number FROM ${quoteIdent(`_kora_ops_${collection}`)}`,\n\t\t)\n\t\tfor (const row of rows) all.push({ collection, ...row })\n\t}\n\tconst groups = new Map<string, LoggedIdentity[]>()\n\tfor (const row of all) {\n\t\tconst key = `${row.node_id}\\u0000${row.sequence_number}`\n\t\tconst group = groups.get(key)\n\t\tif (group) group.push(row)\n\t\telse groups.set(key, [row])\n\t}\n\n\tconst losers: LoggedIdentity[] = []\n\tfor (const group of groups.values()) {\n\t\tif (group.length < 2) continue\n\t\t// A version-2 operation (beta.13+) keeps its place: renumbering would re-hash it\n\t\t// under a new id, and if the server already stored it under the old id the new\n\t\t// copy would be stored as a second write (an atomic increment applied twice). A\n\t\t// version-1 loser keeps its id, which the server deduplicates (RT-31). Ties by id.\n\t\tconst version2 = new Set<string>()\n\t\tfor (const member of group) {\n\t\t\tif (await isVersion2Row(tx, member)) version2.add(member.id)\n\t\t}\n\t\tgroup.sort((a, b) => {\n\t\t\tconst va = version2.has(a.id) ? 0 : 1\n\t\t\tconst vb = version2.has(b.id) ? 0 : 1\n\t\t\tif (va !== vb) return va - vb\n\t\t\treturn a.id < b.id ? -1 : a.id > b.id ? 1 : 0\n\t\t})\n\t\tlosers.push(...group.slice(1))\n\t}\n\t// Re-emit in original order so the new numbers keep the authoring order.\n\tlosers.sort((a, b) =>\n\t\ta.sequence_number !== b.sequence_number\n\t\t\t? a.sequence_number - b.sequence_number\n\t\t\t: a.id < b.id\n\t\t\t\t? -1\n\t\t\t\t: a.id > b.id\n\t\t\t\t\t? 1\n\t\t\t\t\t: 0,\n\t)\n\n\tconst result: SequenceRepairResult = { resequenced: 0, retained: 0 }\n\tconst now = Date.now()\n\tfor (const loser of losers) {\n\t\tconst table = quoteIdent(`_kora_ops_${loser.collection}`)\n\t\tconst rows = await tx.query<OperationRow>(`SELECT * FROM ${table} WHERE id = ?`, [loser.id])\n\t\tconst row = rows[0]\n\t\tif (!row) continue\n\t\tif (own.has(loser.node_id) && !(await isReceivedUnderLocalNode(tx, loser.id))) {\n\t\t\tconst newSeq = await allocateNextSequenceInTransaction(tx, loser.node_id)\n\t\t\tconst moved = await renumberOperationRow(tx, loser.collection, row, newSeq)\n\t\t\tawait insertConflictRow(\n\t\t\t\ttx,\n\t\t\t\tloser.collection,\n\t\t\t\trow,\n\t\t\t\t'duplicate-sequence',\n\t\t\t\tmoved.id,\n\t\t\t\tnewSeq,\n\t\t\t\tnow,\n\t\t\t)\n\t\t\tresult.resequenced++\n\t\t} else {\n\t\t\tawait insertConflictRow(tx, loser.collection, row, 'duplicate-sequence', null, null, now)\n\t\t\tawait tx.execute(`DELETE FROM ${table} WHERE id = ?`, [loser.id])\n\t\t\tresult.retained++\n\t\t}\n\t}\n\treturn result\n}\n\n/**\n * Whether this database recorded an operation as received under one of its own node ids\n * (another database's write under a node a beta.12 shared browser gave both).\n */\nasync function isReceivedUnderLocalNode(tx: Transaction, id: string): Promise<boolean> {\n\tconst table = await tx.query<{ name: string }>(\n\t\t\"SELECT name FROM sqlite_master WHERE type = 'table' AND name = '_kora_received_local_ops'\",\n\t)\n\tif (table.length === 0) return false\n\treturn (\n\t\t(await tx.query<{ id: string }>('SELECT id FROM _kora_received_local_ops WHERE id = ?', [id]))\n\t\t\t.length > 0\n\t)\n}\n\n/** Whether a logged operation declares content-hash version 2. */\nasync function isVersion2Row(tx: Transaction, identity: LoggedIdentity): Promise<boolean> {\n\tconst rows = await tx.query<OperationRow>(\n\t\t`SELECT * FROM ${quoteIdent(`_kora_ops_${identity.collection}`)} WHERE id = ?`,\n\t\t[identity.id],\n\t)\n\tconst row = rows[0]\n\tif (!row) return false\n\treturn deserializeOperationWithCollection(row, identity.collection).hashVersion === 2\n}\n\n/**\n * Record an operation row in {@link SEQ_CONFLICTS_TABLE}.\n *\n * @param reemittedAs - Id of the operation that carries it in the log, or null\n *   when the row is kept only in the conflicts table\n * @param newSequenceNumber - The sequence number it was re-emitted under\n */\nexport async function insertConflictRow(\n\ttx: Transaction,\n\tcollection: string,\n\trow: OperationRow,\n\treason: string,\n\treemittedAs: string | null,\n\tnewSequenceNumber: number | null,\n\trecordedAt: number,\n): Promise<void> {\n\tawait tx.execute(\n\t\t`INSERT OR IGNORE INTO ${SEQ_CONFLICTS_TABLE} (id, collection, node_id, type, record_id, data, previous_data, timestamp, sequence_number, causal_deps, schema_version, reason, reemitted_as, new_sequence_number, recorded_at)\n     VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`,\n\t\t[\n\t\t\trow.id,\n\t\t\tcollection,\n\t\t\trow.node_id,\n\t\t\trow.type,\n\t\t\trow.record_id,\n\t\t\trow.data,\n\t\t\trow.previous_data,\n\t\t\trow.timestamp,\n\t\t\trow.sequence_number,\n\t\t\trow.causal_deps,\n\t\t\trow.schema_version,\n\t\t\treason,\n\t\t\treemittedAs,\n\t\t\tnewSequenceNumber,\n\t\t\trecordedAt,\n\t\t],\n\t)\n}\n\n/**\n * Operation rows kept only in the conflicts table for a record (other nodes'\n * operations whose sequence number collided). Record folds include them.\n */\nexport async function loadRetainedConflictRows(\n\tquery: <T>(sql: string, params?: unknown[]) => Promise<T[]>,\n\tcollection: string,\n\trecordId: string,\n\ttypes?: readonly string[],\n): Promise<OperationRow[]> {\n\tconst typeFilter =\n\t\ttypes && types.length > 0 ? ` AND type IN (${types.map(() => '?').join(', ')})` : ''\n\treturn query<OperationRow>(\n\t\t`SELECT id, node_id, type, record_id, data, previous_data, timestamp, sequence_number, causal_deps, schema_version FROM ${SEQ_CONFLICTS_TABLE} WHERE collection = ? AND record_id = ? AND reemitted_as IS NULL${typeFilter}`,\n\t\t[collection, recordId, ...(types ?? [])],\n\t)\n}\n\n/** Whether an operation id is already recorded (log or retained conflict). */\nexport async function isOperationLogged(\n\ttx: Transaction,\n\tcollection: string,\n\topId: string,\n): Promise<boolean> {\n\tconst inLog = await tx.query<{ id: string }>(\n\t\t`SELECT id FROM ${quoteIdent(`_kora_ops_${collection}`)} WHERE id = ?`,\n\t\t[opId],\n\t)\n\tif (inLog.length > 0) return true\n\tconst retained = await tx.query<{ id: string }>(\n\t\t`SELECT id FROM ${SEQ_CONFLICTS_TABLE} WHERE id = ? AND reemitted_as IS NULL`,\n\t\t[opId],\n\t)\n\treturn retained.length > 0\n}\n","import type { OfflineCompletion, Operation } from '@korajs/core'\nimport type { MetaRow, StorageAdapter, Transaction } from '../types'\nimport { saveDeliveryWatermarkInTx } from './sync-state'\n\n/** `_kora_meta` key of this device's contiguous acknowledged own-operation prefix (W3). */\nexport const OWN_ACKED_THROUGH_META_KEY = 'own_acked_through'\n/** `_kora_meta` key of the downlink scope the sync server last accepted (SYNC-11). */\nexport const ACCEPTED_DOWNLINK_SCOPE_META_KEY = 'accepted_downlink_scope'\n\n/**\n * Durable inbound quarantine (W4): delivered operations the client deliberately did not\n * apply, kept so they are never silently lost and can be replayed. Created on first use\n * so existing databases need no migration.\n */\nconst UNAPPLIED_OPS_DDL =\n\t'CREATE TABLE IF NOT EXISTS _kora_unapplied_ops (\\n' +\n\t'  op_id TEXT PRIMARY KEY NOT NULL,\\n' +\n\t'  collection TEXT NOT NULL,\\n' +\n\t'  delivery_seq INTEGER,\\n' +\n\t'  code TEXT NOT NULL,\\n' +\n\t'  message TEXT NOT NULL,\\n' +\n\t'  payload TEXT NOT NULL,\\n' +\n\t'  quarantined_at INTEGER NOT NULL\\n' +\n\t')'\n\n/** A delivered operation the client did not apply, as stored in `_kora_unapplied_ops`. */\nexport interface UnappliedOperation {\n\t/** The operation as delivered (still encrypted when decryption failed). */\n\toperation: Operation\n\t/** Delivery sequence of the batch that carried it, or null for a legacy batch. */\n\tdeliverySequence: number | null\n\t/**\n\t * Its own delivery position, when the server sent one (decides whether its replay\n\t * shows a record a later retraction hid). Absent otherwise.\n\t */\n\tposition?: number\n\t/** Machine-readable reason. */\n\tcode: string\n\t/** Human-readable explanation. */\n\tmessage: string\n\t/** Wall-clock time (ms) it was quarantined. Display only. */\n\tquarantinedAt: number\n}\n\ninterface UnappliedRow {\n\top_id: string\n\tdelivery_seq: number | null\n\tposition?: number | null\n\tcode: string\n\tmessage: string\n\tpayload: string\n\tquarantined_at: number\n}\n\nconst ensuredAdapters = new WeakSet<StorageAdapter>()\n\nexport async function ensureUnappliedTable(adapter: StorageAdapter): Promise<void> {\n\tif (ensuredAdapters.has(adapter)) return\n\tawait adapter.execute(UNAPPLIED_OPS_DDL)\n\tconst columns = await adapter.query<{ name: string }>('PRAGMA table_info(_kora_unapplied_ops)')\n\tif (!columns.some((column) => column.name === 'position')) {\n\t\tawait adapter.execute('ALTER TABLE _kora_unapplied_ops ADD COLUMN position REAL')\n\t}\n\tensuredAdapters.add(adapter)\n}\n\n/**\n * Record quarantined operations and, when given, advance a view's delivery watermark in\n * the SAME transaction, so the watermark can never pass an operation that is neither\n * applied nor recorded here (the W4 invariant).\n */\nexport async function saveUnappliedOperations(\n\tadapter: StorageAdapter,\n\tentries: UnappliedOperation[],\n\twatermark?: { signature: string; watermark: number; completion?: OfflineCompletion },\n): Promise<void> {\n\tawait ensureUnappliedTable(adapter)\n\tawait adapter.transaction((tx) => saveUnappliedOperationsInTx(tx, entries, watermark))\n}\n\n/**\n * {@link saveUnappliedOperations} inside a caller's transaction (a delivery batch applied\n * in one transaction, C3). The table must exist ({@link ensureUnappliedTable}): DDL is\n * not run inside the transaction.\n */\nexport async function saveUnappliedOperationsInTx(\n\ttx: Transaction,\n\tentries: UnappliedOperation[],\n\twatermark?: { signature: string; watermark: number; completion?: OfflineCompletion },\n): Promise<void> {\n\tfor (const entry of entries) {\n\t\tawait tx.execute(\n\t\t\t'INSERT OR REPLACE INTO _kora_unapplied_ops (op_id, collection, delivery_seq, position, code, message, payload, quarantined_at) VALUES (?, ?, ?, ?, ?, ?, ?, ?)',\n\t\t\t[\n\t\t\t\tentry.operation.id,\n\t\t\t\tentry.operation.collection,\n\t\t\t\tentry.deliverySequence,\n\t\t\t\tentry.position ?? null,\n\t\t\t\tentry.code,\n\t\t\t\tentry.message,\n\t\t\t\tJSON.stringify(entry.operation),\n\t\t\t\tentry.quarantinedAt,\n\t\t\t],\n\t\t)\n\t}\n\tif (watermark) {\n\t\tawait saveDeliveryWatermarkInTx(\n\t\t\ttx,\n\t\t\twatermark.signature,\n\t\t\twatermark.watermark,\n\t\t\twatermark.completion,\n\t\t)\n\t}\n}\n\n/** Every quarantined operation, oldest delivery first. */\nexport async function loadUnappliedOperations(\n\tadapter: StorageAdapter,\n): Promise<UnappliedOperation[]> {\n\tawait ensureUnappliedTable(adapter)\n\tconst rows = await adapter.query<UnappliedRow>(\n\t\t'SELECT op_id, delivery_seq, position, code, message, payload, quarantined_at FROM _kora_unapplied_ops ORDER BY delivery_seq ASC, quarantined_at ASC',\n\t)\n\treturn rows.map((row) => ({\n\t\toperation: JSON.parse(row.payload) as Operation,\n\t\tdeliverySequence: row.delivery_seq === null ? null : Number(row.delivery_seq),\n\t\t...(row.position === null || row.position === undefined\n\t\t\t? {}\n\t\t\t: { position: Number(row.position) }),\n\t\tcode: row.code,\n\t\tmessage: row.message,\n\t\tquarantinedAt: Number(row.quarantined_at),\n\t}))\n}\n\n/** Remove quarantined operations by operation id (applied on replay, or reconciled). */\nexport async function removeUnappliedOperations(\n\tadapter: StorageAdapter,\n\toperationIds: string[],\n): Promise<void> {\n\tif (operationIds.length === 0) return\n\tawait ensureUnappliedTable(adapter)\n\tconst placeholders = operationIds.map(() => '?').join(', ')\n\tawait adapter.execute(\n\t\t`DELETE FROM _kora_unapplied_ops WHERE op_id IN (${placeholders})`,\n\t\toperationIds,\n\t)\n}\n\n/** `_kora_meta` key of a node's prefix when the legacy single key holds another node's. */\nexport function ownAckedThroughKey(nodeId: string): string {\n\treturn `${OWN_ACKED_THROUGH_META_KEY}:${nodeId}`\n}\n\nfunction parseLegacyPrefix(value: string | undefined): { nodeId: string; sequence: number } | null {\n\tif (value === undefined || value === null) return null\n\ttry {\n\t\tconst parsed = JSON.parse(value) as { nodeId?: unknown; sequence?: unknown }\n\t\tif (typeof parsed.nodeId !== 'string') return null\n\t\tconst sequence =\n\t\t\ttypeof parsed.sequence === 'number' && parsed.sequence >= 0 ? parsed.sequence : null\n\t\treturn sequence === null ? null : { nodeId: parsed.nodeId, sequence }\n\t} catch {\n\t\treturn null\n\t}\n}\n\n/**\n * Load the acknowledged own-operation prefix for a node id. Null when none was ever\n * recorded for this node (an upgrade from a release that persisted a max instead).\n *\n * The first node a database tracks keeps the single legacy key (`own_acked_through`, as\n * earlier releases wrote it); any other local node (a rotated node, another tab's node\n * under per-tab isolation, RT-40) has its own key, so tracking one node never erases\n * another node's prefix.\n */\nexport async function loadOwnAckedThrough(\n\tadapter: StorageAdapter,\n\tnodeId: string,\n): Promise<number | null> {\n\tconst rows = await adapter.query<MetaRow>('SELECT value FROM _kora_meta WHERE key = ?', [\n\t\tOWN_ACKED_THROUGH_META_KEY,\n\t])\n\tconst legacy = parseLegacyPrefix(rows[0]?.value)\n\tif (legacy && legacy.nodeId === nodeId) return legacy.sequence\n\tconst own = await adapter.query<MetaRow>('SELECT value FROM _kora_meta WHERE key = ?', [\n\t\townAckedThroughKey(nodeId),\n\t])\n\tconst value = own[0]?.value\n\tif (value === undefined || value === null) return null\n\tconst sequence = Number(value)\n\treturn Number.isInteger(sequence) && sequence >= 0 ? sequence : null\n}\n\n/** Persist the acknowledged own-operation prefix for a node id. */\nexport async function saveOwnAckedThrough(\n\tadapter: StorageAdapter,\n\tnodeId: string,\n\tsequence: number,\n): Promise<void> {\n\tawait adapter.transaction(async (tx) => {\n\t\tconst rows = await tx.query<MetaRow>('SELECT value FROM _kora_meta WHERE key = ?', [\n\t\t\tOWN_ACKED_THROUGH_META_KEY,\n\t\t])\n\t\tconst legacy = parseLegacyPrefix(rows[0]?.value)\n\t\tif (legacy === null || legacy.nodeId === nodeId) {\n\t\t\tawait tx.execute('INSERT OR REPLACE INTO _kora_meta (key, value) VALUES (?, ?)', [\n\t\t\t\tOWN_ACKED_THROUGH_META_KEY,\n\t\t\t\tJSON.stringify({ nodeId, sequence }),\n\t\t\t])\n\t\t\treturn\n\t\t}\n\t\tawait tx.execute('INSERT OR REPLACE INTO _kora_meta (key, value) VALUES (?, ?)', [\n\t\t\townAckedThroughKey(nodeId),\n\t\t\tString(sequence),\n\t\t])\n\t})\n}\n\n/** Load the downlink scope the sync server last accepted (null when none). */\nexport async function loadAcceptedDownlinkScope(\n\tadapter: StorageAdapter,\n): Promise<Record<string, Record<string, unknown>> | null> {\n\tconst rows = await adapter.query<MetaRow>('SELECT value FROM _kora_meta WHERE key = ?', [\n\t\tACCEPTED_DOWNLINK_SCOPE_META_KEY,\n\t])\n\tconst value = rows[0]?.value\n\tif (value === undefined || value === null) return null\n\ttry {\n\t\tconst parsed = JSON.parse(value) as unknown\n\t\treturn parsed !== null && typeof parsed === 'object'\n\t\t\t? (parsed as Record<string, Record<string, unknown>>)\n\t\t\t: null\n\t} catch {\n\t\treturn null\n\t}\n}\n\n/** Persist (or clear) the downlink scope the sync server last accepted. */\nexport async function saveAcceptedDownlinkScope(\n\tadapter: StorageAdapter,\n\tscope: Record<string, Record<string, unknown>> | null,\n): Promise<void> {\n\tif (scope === null) {\n\t\tawait adapter.execute('DELETE FROM _kora_meta WHERE key = ?', [\n\t\t\tACCEPTED_DOWNLINK_SCOPE_META_KEY,\n\t\t])\n\t\treturn\n\t}\n\tawait adapter.execute('INSERT OR REPLACE INTO _kora_meta (key, value) VALUES (?, ?)', [\n\t\tACCEPTED_DOWNLINK_SCOPE_META_KEY,\n\t\tJSON.stringify(scope),\n\t])\n}\n\n/**\n * Move quarantined operations positioned after `ceiling` back to `watermark` (a delivery\n * run restarted lower, see `Store.rebaseDeliveryRun`): they belong to an earlier run, and\n * the new run re-delivers whatever of them is still in view.\n */\nexport async function rebaseUnappliedOperations(\n\tadapter: StorageAdapter,\n\twatermark: number,\n\tceiling: number,\n): Promise<void> {\n\tawait ensureUnappliedTable(adapter)\n\tawait adapter.execute(\n\t\t'UPDATE _kora_unapplied_ops SET position = ? WHERE position IS NOT NULL AND position > ?',\n\t\t[watermark, ceiling],\n\t)\n}\n","import type { MetaRow, StorageAdapter, Transaction } from '../types'\nimport { OWN_ACKED_THROUGH_META_KEY } from './sync-durability'\nimport { NODE_TOKEN_META_KEY, nodeTokenKey } from './sync-state'\n\n/** What these helpers run statements on: an adapter, or a transaction of one. */\nexport type SqlRunner = Pick<StorageAdapter, 'query' | 'execute'>\n\n/**\n * Durable sync bookkeeping that belongs to the device, not to the app (Phase 2 RT-36,\n * RT-38, RT-40): the operations the server refused for good, and the node ids this\n * database authored operations under.\n *\n * Both tables are created on first use, so existing databases need no migration.\n */\n\n/**\n * Operations the server refused with a non-retriable rejection (RT-36). Unlike\n * `_kora_sync_rejected` (the app's reconciliation list, which `clearRejectedOperations`\n * empties), a row here is never removed: a refused operation stays refused, so a later\n * rescan of the device's own history never submits it again.\n */\nexport const TERMINAL_REJECTIONS_TABLE = '_kora_terminal_rejections'\n\n/**\n * Node ids this database authored operations under (RT-38, RT-40): the node in use,\n * nodes it rotated away from, and other tabs' nodes under per-tab isolation.\n */\nexport const LOCAL_NODES_TABLE = '_kora_local_nodes'\n\n/** Meta key: count of accepted sync handshakes on this database (refusal cycles, RT-38). */\nexport const ACCEPTED_CYCLE_META_KEY = 'sync_accepted_cycle'\n\n/** Meta key: terminal rejections were seeded from the pre-Phase-2 rejected list once. */\nconst TERMINAL_SEED_META_KEY = 'terminal_rejections_seeded_v1'\n\n/**\n * Rejection codes that never become a terminal marker: the operation was not judged on\n * its content, so a later upload of it may be accepted.\n *\n * - `SEQUENCE_CONFLICT`: the device's sequence number collided with an operation the\n *   server holds (a lost local tail, RT-35, or a beta.12 duplicate pair, RT-37); the\n *   operation is renumbered and uploaded again.\n * - `NODE_ID_MISMATCH`: uploaded on another node's session.\n * - `OUT_OF_UPLINK_SCOPE`: judged by the client against the scope it had then.\n */\nexport const NON_TERMINAL_REJECTION_CODES: ReadonlySet<string> = new Set([\n\t'SEQUENCE_CONFLICT',\n\t'NODE_ID_MISMATCH',\n\t'OUT_OF_UPLINK_SCOPE',\n])\n\nconst TERMINAL_REJECTIONS_DDL = `CREATE TABLE IF NOT EXISTS ${TERMINAL_REJECTIONS_TABLE} (\n  operation_id TEXT PRIMARY KEY NOT NULL,\n  node_id TEXT,\n  sequence_number INTEGER,\n  code TEXT NOT NULL,\n  rejected_at INTEGER NOT NULL\n)`\n\nconst LOCAL_NODES_DDL = `CREATE TABLE IF NOT EXISTS ${LOCAL_NODES_TABLE} (\n  node_id TEXT PRIMARY KEY NOT NULL,\n  created_at INTEGER NOT NULL,\n  accepted INTEGER NOT NULL DEFAULT 0,\n  held INTEGER NOT NULL DEFAULT 0,\n  refused_cycle INTEGER,\n  principal TEXT,\n  binding TEXT,\n  refused_principals TEXT,\n  retired INTEGER NOT NULL DEFAULT 0,\n  from_queue INTEGER NOT NULL DEFAULT 0\n)`\n\n/**\n * Operations this database RECEIVED under one of its own local node ids (a node a\n * beta.12 shared browser gave several users' databases). They are another database's\n * writes: a repair never re-authors them as this database's (see\n * {@link findAuthoredHere}). A beta.12 database recorded nothing: it did not need to, since\n * a beta.12 server never delivered a session's own node back to it, so everything such a\n * database holds under its own (now retired) node it wrote itself.\n */\nexport const RECEIVED_LOCAL_OPS_TABLE = '_kora_received_local_ops'\n\nconst RECEIVED_LOCAL_OPS_DDL = `CREATE TABLE IF NOT EXISTS ${RECEIVED_LOCAL_OPS_TABLE} (\n  id TEXT PRIMARY KEY NOT NULL\n)`\n\n/**\n * How a local node's {@link LocalNodeRecord.principal} was learned (RT-50):\n *\n * - `fresh`: the node had no writes when it was bound to the signed-in user, so every\n *   write under it was made by that user.\n * - `server`: a sync handshake as the node was accepted for that user (the server's node\n *   claims are authoritative).\n * - `app`: the app assigned a held node to the signed-in user\n *   (`app.sync.assignHeld`). A guess: cleared if the server refuses the node for them.\n * - `database`: the node was this database's pinned node, and the database belongs to\n *   one user (`store.namespaceByAuthUser`): it is only ever opened for that user, so every\n *   write it authored under the node is theirs.\n */\nexport type LocalNodeBinding = 'fresh' | 'server' | 'app' | 'database'\n\nconst LOCAL_NODE_BINDINGS: readonly LocalNodeBinding[] = ['fresh', 'server', 'app', 'database']\n\n/** At most this many principals are remembered as refused for one node (RT-50). */\nconst MAX_REFUSED_PRINCIPALS = 32\n\n/** Meta key: per-node adoption schedule (parked adoptions, upload progress; RT-46). */\nexport const ADOPTION_SCHEDULE_META_KEY = 'sync_adoption_schedule_v1'\n\n/** Adapters whose `_kora_local_nodes` table is known to have every column (this process). */\nconst migratedAdapters = new WeakSet<object>()\n\n/** A terminal rejection to record (RT-36). */\nexport interface TerminalRejection {\n\toperationId: string\n\t/** Authoring node and sequence, when known (null for rows seeded from the old list). */\n\tnodeId: string | null\n\tsequenceNumber: number | null\n\tcode: string\n\trejectedAt: number\n}\n\n/** A node id this database authored operations under (RT-38, RT-40). */\nexport interface LocalNodeRecord {\n\tnodeId: string\n\t/** Wall-clock time (ms) the node was registered. Display only. */\n\tcreatedAt: number\n\t/** A sync handshake as this node was accepted at least once. */\n\taccepted: boolean\n\t/**\n\t * The server refused this node (`NODE_ID_CLAIMED`) after it had been accepted: it\n\t * belongs to a principal that is not signed in. Its unsynced operations are held for\n\t * that principal, never uploaded under another one.\n\t */\n\theld: boolean\n\t/** {@link ACCEPTED_CYCLE_META_KEY} value when the server last refused it, or null. */\n\trefusedCycle: number | null\n\t/**\n\t * The signed-in user the node's writes belong to (RT-42), or null when the app never\n\t * told the store who was signed in while it was in use. A node bound to one user is\n\t * never used for, uploaded under, or adopted by another user's session.\n\t */\n\tprincipal: string | null\n\t/**\n\t * How {@link principal} was learned (RT-50), or null when unbound, or bound by a release\n\t * that did not record it (treated as a guess).\n\t */\n\tbinding: LocalNodeBinding | null\n\t/**\n\t * Users the server refused this UNBOUND node for (`NODE_ID_CLAIMED`, RT-50): it is\n\t * not theirs, so it is never tried again on their sessions. An unbound node that was\n\t * accepted before belongs to whichever user the server accepts it for.\n\t */\n\trefusedPrincipals: string[]\n\t/**\n\t * The database's pinned node moved off this node (the auth device id of its user\n\t * changed: a browser shared between accounts gives each account its own). The node\n\t * may be shared with another user's database, so it is never used for a session,\n\t * adopted or handed over again: its writes the server does not hold are re-authored\n\t * under a node of the same user (see `Store.reauthorIntoOwnNode`).\n\t */\n\tretired: boolean\n\t/**\n\t * Registered only because outbound-queue entries carried it as their author (at open),\n\t * never as the database's own node. beta.12 put operations a tab RECEIVED from the\n\t * user's other device in its queue when it reloaded, so such a node may be another\n\t * device's: which of its operations the server stores is asked by id, and those are\n\t * settled (see the sync engine's operation probe).\n\t */\n\tfromQueue: boolean\n}\n\ninterface LocalNodeRow {\n\tnode_id: string\n\tcreated_at: number\n\taccepted: number\n\theld: number\n\trefused_cycle: number | null\n\tprincipal: string | null\n\tbinding: string | null\n\trefused_principals: string | null\n\tretired: number | null\n\tfrom_queue: number | null\n}\n\n/** A parked adoption (RT-46): the node made no upload progress in its last session. */\nexport interface ParkedAdoption {\n\t/** {@link AdoptionSchedule.progress} when it was parked: retried once it moves. */\n\tprogressMark: number\n\t/** Wall-clock time (ms) after which it is retried anyway. Scheduling only. */\n\tuntilMs: number\n\t/** Consecutive parks (backoff exponent). */\n\tcount: number\n\t/** Wall-clock time (ms) it was parked. Scheduling only. */\n\tparkedAtMs: number\n}\n\n/**\n * Which local nodes' adoptions are parked (RT-46), and a counter of upload progress on\n * this database: a parked node is retried once anything else uploaded (its deferral may\n * have depended on it) or after its backoff.\n */\nexport interface AdoptionSchedule {\n\tprogress: number\n\tparked: Record<string, ParkedAdoption>\n}\n\n/**\n * Create both tables. `Store.open` runs it (through {@link registerLocalNode}), so the\n * read paths, which run often, assume the tables exist and never issue DDL (on the\n * IndexedDB adapter every statement schedules a snapshot).\n */\nexport async function ensureLocalSyncRecordTables(adapter: SqlRunner): Promise<void> {\n\tawait adapter.execute(TERMINAL_REJECTIONS_DDL)\n\tawait adapter.execute(LOCAL_NODES_DDL)\n\tawait adapter.execute(RECEIVED_LOCAL_OPS_DDL)\n\tif (migratedAdapters.has(adapter)) return\n\t// A table created by an earlier release lacks the principal column (RT-42).\n\t// ... and the binding columns (RT-50).\n\tconst columns = await adapter.query<{ name: string }>(`PRAGMA table_info(${LOCAL_NODES_TABLE})`)\n\tfor (const column of ['principal', 'binding', 'refused_principals']) {\n\t\tif (!columns.some((existing) => existing.name === column)) {\n\t\t\tawait adapter.execute(`ALTER TABLE ${LOCAL_NODES_TABLE} ADD COLUMN ${column} TEXT`)\n\t\t}\n\t}\n\t// ... and the retired flag (a node a shared browser's database moved off).\n\tif (!columns.some((existing) => existing.name === 'retired')) {\n\t\tawait adapter.execute(\n\t\t\t`ALTER TABLE ${LOCAL_NODES_TABLE} ADD COLUMN retired INTEGER NOT NULL DEFAULT 0`,\n\t\t)\n\t}\n\t// ... and whether the node was registered only from outbound-queue entries.\n\tif (!columns.some((existing) => existing.name === 'from_queue')) {\n\t\tawait adapter.execute(\n\t\t\t`ALTER TABLE ${LOCAL_NODES_TABLE} ADD COLUMN from_queue INTEGER NOT NULL DEFAULT 0`,\n\t\t)\n\t}\n\tmigratedAdapters.add(adapter)\n}\n\n/** Record terminal rejections (idempotent by operation id; the first record wins). */\nexport async function recordTerminalRejections(\n\tadapter: StorageAdapter,\n\tentries: TerminalRejection[],\n): Promise<void> {\n\tconst recordable = entries.filter((entry) => !NON_TERMINAL_REJECTION_CODES.has(entry.code))\n\tif (recordable.length === 0) return\n\tawait ensureLocalSyncRecordTables(adapter)\n\tawait adapter.transaction(async (tx) => {\n\t\tfor (const entry of recordable) {\n\t\t\tawait tx.execute(\n\t\t\t\t`INSERT OR IGNORE INTO ${TERMINAL_REJECTIONS_TABLE} (operation_id, node_id, sequence_number, code, rejected_at) VALUES (?, ?, ?, ?, ?)`,\n\t\t\t\t[entry.operationId, entry.nodeId, entry.sequenceNumber, entry.code, entry.rejectedAt],\n\t\t\t)\n\t\t}\n\t})\n}\n\n/** Which of `operationIds` carry a terminal rejection marker. */\nexport async function findTerminalRejections(\n\tadapter: StorageAdapter,\n\toperationIds: string[],\n): Promise<Set<string>> {\n\tconst found = new Set<string>()\n\tif (operationIds.length === 0) return found\n\tconst CHUNK = 500\n\tfor (let i = 0; i < operationIds.length; i += CHUNK) {\n\t\tconst chunk = operationIds.slice(i, i + CHUNK)\n\t\tconst rows = await adapter.query<{ operation_id: string }>(\n\t\t\t`SELECT operation_id FROM ${TERMINAL_REJECTIONS_TABLE} WHERE operation_id IN (${chunk.map(() => '?').join(', ')})`,\n\t\t\tchunk,\n\t\t)\n\t\tfor (const row of rows) found.add(row.operation_id)\n\t}\n\treturn found\n}\n\n/**\n * Seed terminal markers once from `_kora_sync_rejected`, the list earlier releases kept\n * (and the app may have cleared since). Rows whose code is not terminal are skipped:\n * in particular a pre-release device's `SEQUENCE_CONFLICT` rejections (RT-37) stay eligible\n * for the one-time re-upload, which is how those writes reach the server.\n */\nexport async function seedTerminalRejectionsOnce(adapter: StorageAdapter): Promise<void> {\n\tawait ensureLocalSyncRecordTables(adapter)\n\tconst done = await adapter.query<MetaRow>('SELECT value FROM _kora_meta WHERE key = ?', [\n\t\tTERMINAL_SEED_META_KEY,\n\t])\n\tif (done.length > 0) return\n\tconst tables = await adapter.query<{ name: string }>(\n\t\t\"SELECT name FROM sqlite_master WHERE type = 'table' AND name = '_kora_sync_rejected'\",\n\t)\n\tawait adapter.transaction(async (tx) => {\n\t\tif (tables.length > 0) {\n\t\t\tconst placeholders = [...NON_TERMINAL_REJECTION_CODES].map(() => '?').join(', ')\n\t\t\tawait tx.execute(\n\t\t\t\t`INSERT OR IGNORE INTO ${TERMINAL_REJECTIONS_TABLE} (operation_id, node_id, sequence_number, code, rejected_at)\n         SELECT operation_id, NULL, NULL, code, rejected_at FROM _kora_sync_rejected\n         WHERE retriable = 0 AND code NOT IN (${placeholders})`,\n\t\t\t\t[...NON_TERMINAL_REJECTION_CODES],\n\t\t\t)\n\t\t}\n\t\tawait tx.execute('INSERT OR REPLACE INTO _kora_meta (key, value) VALUES (?, ?)', [\n\t\t\tTERMINAL_SEED_META_KEY,\n\t\t\tString(Date.now()),\n\t\t])\n\t})\n}\n\nfunction rowToRecord(row: LocalNodeRow): LocalNodeRecord {\n\treturn {\n\t\tnodeId: row.node_id,\n\t\tcreatedAt: Number(row.created_at),\n\t\taccepted: Number(row.accepted) === 1,\n\t\theld: Number(row.held) === 1,\n\t\trefusedCycle: row.refused_cycle === null ? null : Number(row.refused_cycle),\n\t\tprincipal: typeof row.principal === 'string' ? row.principal : null,\n\t\tbinding:\n\t\t\ttypeof row.principal === 'string' &&\n\t\t\tLOCAL_NODE_BINDINGS.includes(row.binding as LocalNodeBinding)\n\t\t\t\t? (row.binding as LocalNodeBinding)\n\t\t\t\t: null,\n\t\trefusedPrincipals: parsePrincipalList(row.refused_principals),\n\t\tretired: Number(row.retired ?? 0) === 1,\n\t\tfromQueue: Number(row.from_queue ?? 0) === 1,\n\t}\n}\n\nfunction parsePrincipalList(value: string | null): string[] {\n\tif (typeof value !== 'string' || value.length === 0) return []\n\ttry {\n\t\tconst parsed: unknown = JSON.parse(value)\n\t\treturn Array.isArray(parsed)\n\t\t\t? parsed.filter((entry): entry is string => typeof entry === 'string')\n\t\t\t: []\n\t} catch {\n\t\treturn []\n\t}\n}\n\n/**\n * Register a node id this database authors operations under. A node registered for the\n * first time that a claims-aware server already accepted here (a database from a build\n * with node claims) is recorded as accepted, so a later refusal holds its writes\n * instead of re-authoring them under another principal (RT-38).\n *\n * Sync history alone is not that evidence (RT-92): beta.12 and older servers recorded\n * no node claims, so a node only they accepted belongs to nobody on an upgraded server.\n * It registers as not accepted, and a refusal re-authors its never-sent writes under a\n * fresh node (RT-21) instead of holding them for an owner that does not exist.\n */\nexport async function registerLocalNode(\n\tadapter: SqlRunner,\n\tnodeId: string,\n\toptions: { fromQueue?: boolean } = {},\n): Promise<void> {\n\tawait ensureLocalSyncRecordTables(adapter)\n\tconst existing = await adapter.query<{ node_id: string }>(\n\t\t`SELECT node_id FROM ${LOCAL_NODES_TABLE} WHERE node_id = ?`,\n\t\t[nodeId],\n\t)\n\tif (existing.length > 0) return\n\tconst accepted = await hasSyncHistory(adapter, nodeId)\n\tawait adapter.execute(\n\t\t`INSERT OR IGNORE INTO ${LOCAL_NODES_TABLE} (node_id, created_at, accepted, held, refused_cycle, from_queue) VALUES (?, ?, ?, 0, NULL, ?)`,\n\t\t[nodeId, Date.now(), accepted ? 1 : 0, options.fromQueue === true ? 1 : 0],\n\t)\n}\n\n/**\n * Whether a claims-aware server accepted `nodeId` on this database before the registry\n * existed: a node token it issued (anonymous claims), or the acknowledged-prefix record\n * builds with node claims keep. beta.12's `last_acked_server_vector` does not count: its\n * server recorded no claims (RT-92).\n */\nasync function hasSyncHistory(adapter: SqlRunner, nodeId: string): Promise<boolean> {\n\tconst rows = await adapter.query<MetaRow & { key: string }>(\n\t\t'SELECT key, value FROM _kora_meta WHERE key IN (?, ?, ?)',\n\t\t[NODE_TOKEN_META_KEY, nodeTokenKey(nodeId), OWN_ACKED_THROUGH_META_KEY],\n\t)\n\tconst nodeIdRows = await adapter.query<MetaRow>(\n\t\t\"SELECT value FROM _kora_meta WHERE key = 'node_id'\",\n\t)\n\tconst isMetaNode = nodeIdRows[0]?.value === nodeId\n\tfor (const row of rows) {\n\t\tif (row.key === nodeTokenKey(nodeId)) return true\n\t\tif (row.key === NODE_TOKEN_META_KEY) {\n\t\t\tif (isMetaNode) return true\n\t\t\tcontinue\n\t\t}\n\t\ttry {\n\t\t\tconst parsed = JSON.parse(row.value) as Record<string, unknown>\n\t\t\tif (row.key === OWN_ACKED_THROUGH_META_KEY) {\n\t\t\t\tif (parsed.nodeId === nodeId && typeof parsed.sequence === 'number' && parsed.sequence > 0)\n\t\t\t\t\treturn true\n\t\t\t}\n\t\t} catch {\n\t\t\t// An unreadable row is no evidence either way.\n\t\t}\n\t}\n\treturn false\n}\n\n/**\n * A remote operation was applied under one of this database's local node ids: record it\n * as received (never this database's own write). Inside the apply transaction.\n */\nexport async function noteReceivedUnderLocalNode(\n\ttx: Transaction,\n\tnodeId: string,\n\toperationId: string,\n): Promise<void> {\n\tconst local = await tx.query<{ node_id: string }>(\n\t\t`SELECT node_id FROM ${LOCAL_NODES_TABLE} WHERE node_id = ?`,\n\t\t[nodeId],\n\t)\n\tif (local.length === 0) return\n\tawait tx.execute(`INSERT OR IGNORE INTO ${RECEIVED_LOCAL_OPS_TABLE} (id) VALUES (?)`, [\n\t\toperationId,\n\t])\n}\n\n/**\n * Which of `operations` (all of local node `nodeId`) this database authored itself: every\n * one it did not record as received under that node (see {@link RECEIVED_LOCAL_OPS_TABLE}).\n * Whether an operation is still in the outbound queue says nothing: beta.12 dropped the\n * queue entry of a write it wrongly counted as synced (a shared node's version-vector entry\n * raised by another database), and that write is this database's all the same.\n */\nexport async function findAuthoredHere(\n\tadapter: StorageAdapter,\n\t_nodeId: string,\n\toperations: ReadonlyArray<{ id: string; sequenceNumber: number }>,\n): Promise<Set<string>> {\n\tconst authored = new Set(operations.map((op) => op.id))\n\tif (operations.length === 0) return authored\n\tawait ensureLocalSyncRecordTables(adapter)\n\tconst CHUNK = 400\n\tfor (let i = 0; i < operations.length; i += CHUNK) {\n\t\tconst ids = operations.slice(i, i + CHUNK).map((op) => op.id)\n\t\tconst marks = ids.map(() => '?').join(', ')\n\t\tconst received = await adapter.query<{ id: string }>(\n\t\t\t`SELECT id FROM ${RECEIVED_LOCAL_OPS_TABLE} WHERE id IN (${marks})`,\n\t\t\tids,\n\t\t)\n\t\tfor (const row of received) authored.delete(row.id)\n\t}\n\treturn authored\n}\n\n/** Every registered local node, oldest first. */\nexport async function listLocalNodes(adapter: StorageAdapter): Promise<LocalNodeRecord[]> {\n\tconst rows = await adapter.query<LocalNodeRow>(\n\t\t`SELECT node_id, created_at, accepted, held, refused_cycle, principal, binding, refused_principals, retired, from_queue FROM ${LOCAL_NODES_TABLE} ORDER BY created_at ASC, node_id ASC`,\n\t)\n\treturn rows.map(rowToRecord)\n}\n\nasync function readAcceptedCycle(tx: Transaction): Promise<number> {\n\tconst rows = await tx.query<MetaRow>('SELECT value FROM _kora_meta WHERE key = ?', [\n\t\tACCEPTED_CYCLE_META_KEY,\n\t])\n\tconst value = Number(rows[0]?.value ?? 0)\n\treturn Number.isFinite(value) ? value : 0\n}\n\n/**\n * Record an accepted handshake as `nodeId`: the node is accepted and no longer held,\n * and a new refusal cycle starts (every node may be tried again after a refusal).\n */\nexport async function markLocalNodeAccepted(\n\tadapter: StorageAdapter,\n\tnodeId: string,\n): Promise<void> {\n\tawait ensureLocalSyncRecordTables(adapter)\n\tawait adapter.transaction(async (tx) => {\n\t\tconst cycle = await readAcceptedCycle(tx)\n\t\tawait tx.execute(\n\t\t\t`INSERT INTO ${LOCAL_NODES_TABLE} (node_id, created_at, accepted, held, refused_cycle) VALUES (?, ?, 1, 0, NULL)\n       ON CONFLICT(node_id) DO UPDATE SET accepted = 1, held = 0, refused_cycle = NULL`,\n\t\t\t[nodeId, Date.now()],\n\t\t)\n\t\tawait tx.execute('INSERT OR REPLACE INTO _kora_meta (key, value) VALUES (?, ?)', [\n\t\t\tACCEPTED_CYCLE_META_KEY,\n\t\t\tString(cycle + 1),\n\t\t])\n\t})\n}\n\n/**\n * Record that the server refused `nodeId` (`NODE_ID_CLAIMED`) in the current refusal\n * cycle. `held` marks its unsynced operations as held for the principal owning it.\n */\nexport async function markLocalNodeRefused(\n\tadapter: StorageAdapter,\n\tnodeId: string,\n\theld: boolean,\n): Promise<void> {\n\tawait ensureLocalSyncRecordTables(adapter)\n\tawait adapter.transaction(async (tx) => {\n\t\tconst cycle = await readAcceptedCycle(tx)\n\t\tawait tx.execute(\n\t\t\t`INSERT INTO ${LOCAL_NODES_TABLE} (node_id, created_at, accepted, held, refused_cycle) VALUES (?, ?, 0, ?, ?)\n       ON CONFLICT(node_id) DO UPDATE SET held = MAX(held, excluded.held), refused_cycle = excluded.refused_cycle`,\n\t\t\t[nodeId, Date.now(), held ? 1 : 0, cycle],\n\t\t)\n\t})\n}\n\n/**\n * Forget a local node that has nothing left to upload (bounds the registry under per-tab\n * isolation, where every tab adds a node). A node that writes again is registered again\n * when its store opens. Never the database's own node id.\n */\nexport async function forgetLocalNode(adapter: StorageAdapter, nodeId: string): Promise<void> {\n\tawait ensureLocalSyncRecordTables(adapter)\n\tawait adapter.execute(\n\t\t`DELETE FROM ${LOCAL_NODES_TABLE} WHERE node_id = ? AND held = 0 AND node_id NOT IN (SELECT value FROM _kora_meta WHERE key = 'node_id')`,\n\t\t[nodeId],\n\t)\n}\n\n/**\n * Bind a local node to the signed-in user whose writes it carries (RT-42), recording how\n * that was learned (RT-50). The node is registered if it is not yet.\n */\nexport async function setLocalNodePrincipal(\n\tadapter: SqlRunner,\n\tnodeId: string,\n\tprincipal: string,\n\tbinding: LocalNodeBinding,\n): Promise<void> {\n\tawait ensureLocalSyncRecordTables(adapter)\n\tawait adapter.execute(\n\t\t`INSERT INTO ${LOCAL_NODES_TABLE} (node_id, created_at, accepted, held, refused_cycle, principal, binding) VALUES (?, ?, 0, 0, NULL, ?, ?)\n       ON CONFLICT(node_id) DO UPDATE SET principal = excluded.principal, binding = excluded.binding`,\n\t\t[nodeId, Date.now(), principal, binding],\n\t)\n}\n\n/**\n * Retire `nodeId` (see {@link LocalNodeRecord.retired}): the database's pinned node moved\n * off it, or the server refused a node whose writes belong to `owner`. When `owner` is\n * given, an unbound or guessed binding becomes `binding` to them (`database`: the\n * database belongs to that one user, so every write it authored under the node is theirs;\n * `app`: the app assigned them). A binding learned from evidence for another user is kept.\n */\nexport async function retireLocalNode(\n\tadapter: StorageAdapter,\n\tnodeId: string,\n\towner: string | null,\n\tbinding: LocalNodeBinding = 'database',\n): Promise<void> {\n\tawait ensureLocalSyncRecordTables(adapter)\n\tawait adapter.transaction(async (tx) => {\n\t\tconst node = await findLocalNode(tx, nodeId)\n\t\tconst rebind =\n\t\t\towner !== null &&\n\t\t\t(node === null ||\n\t\t\t\tnode.principal === null ||\n\t\t\t\tnode.principal === owner ||\n\t\t\t\tisGuessedBinding(node))\n\t\tawait tx.execute(\n\t\t\t`INSERT INTO ${LOCAL_NODES_TABLE} (node_id, created_at, accepted, held, refused_cycle, retired) VALUES (?, ?, 0, 0, NULL, 1)\n       ON CONFLICT(node_id) DO UPDATE SET retired = 1`,\n\t\t\t[nodeId, Date.now()],\n\t\t)\n\t\tif (rebind) {\n\t\t\tawait tx.execute(\n\t\t\t\t`UPDATE ${LOCAL_NODES_TABLE} SET principal = ?, binding = ?, refused_principals = NULL WHERE node_id = ?`,\n\t\t\t\t[owner, binding, nodeId],\n\t\t\t)\n\t\t}\n\t})\n}\n\n/** The database's pinned node is `nodeId` again: it is no longer retired. */\nexport async function reviveLocalNode(adapter: StorageAdapter, nodeId: string): Promise<void> {\n\tawait ensureLocalSyncRecordTables(adapter)\n\tawait adapter.execute(`UPDATE ${LOCAL_NODES_TABLE} SET retired = 0 WHERE node_id = ?`, [nodeId])\n}\n\n/** A binding that is only a guess: cleared when the server refuses the node (RT-50). */\nfunction isGuessedBinding(node: LocalNodeRecord): boolean {\n\treturn node.principal !== null && (node.binding === null || node.binding === 'app')\n}\n\nasync function findLocalNode(\n\tadapter: StorageAdapter | Transaction,\n\tnodeId: string,\n): Promise<LocalNodeRecord | null> {\n\tconst rows = await adapter.query<LocalNodeRow>(\n\t\t`SELECT node_id, created_at, accepted, held, refused_cycle, principal, binding, refused_principals, retired, from_queue FROM ${LOCAL_NODES_TABLE} WHERE node_id = ?`,\n\t\t[nodeId],\n\t)\n\tconst row = rows[0]\n\treturn row ? rowToRecord(row) : null\n}\n\n/**\n * A sync handshake as `nodeId` was accepted for `principal` (RT-50): the server's node\n * claims say the node is theirs. Binds an unbound node, or replaces a guessed binding,\n * as `server`. A node bound from evidence (`fresh` or `server`) to another user keeps\n * its binding: the engine never runs such a session.\n */\nexport async function confirmLocalNodePrincipal(\n\tadapter: StorageAdapter,\n\tnodeId: string,\n\tprincipal: string,\n): Promise<void> {\n\tawait ensureLocalSyncRecordTables(adapter)\n\tawait adapter.transaction(async (tx) => {\n\t\tconst node = await findLocalNode(tx, nodeId)\n\t\tif (node && node.principal !== null && node.principal !== principal && !isGuessedBinding(node))\n\t\t\treturn\n\t\tawait tx.execute(\n\t\t\t`INSERT INTO ${LOCAL_NODES_TABLE} (node_id, created_at, accepted, held, refused_cycle, principal, binding) VALUES (?, ?, 0, 0, NULL, ?, 'server')\n       ON CONFLICT(node_id) DO UPDATE SET principal = excluded.principal, binding = 'server', refused_principals = NULL`,\n\t\t\t[nodeId, Date.now(), principal],\n\t\t)\n\t})\n}\n\n/**\n * The server refused `nodeId` for `principal` (`NODE_ID_CLAIMED`, RT-50): another user\n * owns it. A guessed binding is cleared (it was wrong), and an unbound node remembers\n * that it is not `principal`'s, so it is tried on another user's session instead.\n */\nexport async function recordLocalNodeRefusedFor(\n\tadapter: StorageAdapter,\n\tnodeId: string,\n\tprincipal: string,\n): Promise<void> {\n\tawait ensureLocalSyncRecordTables(adapter)\n\tawait adapter.transaction(async (tx) => {\n\t\tconst node = await findLocalNode(tx, nodeId)\n\t\tif (!node) return\n\t\tif (node.principal !== null && !isGuessedBinding(node)) return\n\t\tconst refused = node.refusedPrincipals.filter((entry) => entry !== principal)\n\t\trefused.push(principal)\n\t\tawait tx.execute(\n\t\t\t`UPDATE ${LOCAL_NODES_TABLE} SET principal = NULL, binding = NULL, refused_principals = ? WHERE node_id = ?`,\n\t\t\t[JSON.stringify(refused.slice(-MAX_REFUSED_PRINCIPALS)), nodeId],\n\t\t)\n\t})\n}\n\n/**\n * The app assigned a held, unbound local node to `principal` (RT-50,\n * `app.sync.assignHeld`): its writes upload on their sessions from now on. A guess, so\n * a later refusal by the server clears it again.\n *\n * @returns false when the node is unknown, already bound, or was refused for `principal`\n */\nexport async function assignLocalNodePrincipal(\n\tadapter: StorageAdapter,\n\tnodeId: string,\n\tprincipal: string,\n): Promise<boolean> {\n\tawait ensureLocalSyncRecordTables(adapter)\n\tlet assigned = false\n\tawait adapter.transaction(async (tx) => {\n\t\tconst node = await findLocalNode(tx, nodeId)\n\t\tif (!node || node.principal !== null || node.refusedPrincipals.includes(principal)) return\n\t\tawait tx.execute(\n\t\t\t`UPDATE ${LOCAL_NODES_TABLE} SET principal = ?, binding = 'app', held = 0, refused_cycle = NULL WHERE node_id = ?`,\n\t\t\t[principal, nodeId],\n\t\t)\n\t\tassigned = true\n\t})\n\treturn assigned\n}\n\n/** Forget a local node whatever its state (its writes were discarded by the app, RT-50). */\nexport async function dropLocalNode(adapter: StorageAdapter, nodeId: string): Promise<void> {\n\tawait ensureLocalSyncRecordTables(adapter)\n\tawait adapter.execute(\n\t\t`DELETE FROM ${LOCAL_NODES_TABLE} WHERE node_id = ? AND node_id NOT IN (SELECT value FROM _kora_meta WHERE key = 'node_id')`,\n\t\t[nodeId],\n\t)\n}\n\n/** The adoption schedule (RT-46); empty when none was saved. */\nexport async function loadAdoptionSchedule(adapter: StorageAdapter): Promise<AdoptionSchedule> {\n\tconst rows = await adapter.query<MetaRow>('SELECT value FROM _kora_meta WHERE key = ?', [\n\t\tADOPTION_SCHEDULE_META_KEY,\n\t])\n\tconst empty: AdoptionSchedule = { progress: 0, parked: {} }\n\tconst raw = rows[0]?.value\n\tif (!raw) return empty\n\ttry {\n\t\tconst parsed = JSON.parse(raw) as Partial<AdoptionSchedule>\n\t\treturn {\n\t\t\tprogress: typeof parsed.progress === 'number' ? parsed.progress : 0,\n\t\t\tparked: parsed.parked && typeof parsed.parked === 'object' ? parsed.parked : {},\n\t\t}\n\t} catch {\n\t\t// An unreadable schedule only costs an earlier retry of a parked adoption.\n\t\treturn empty\n\t}\n}\n\n/** Persist the adoption schedule (RT-46). */\nexport async function saveAdoptionSchedule(\n\tadapter: StorageAdapter,\n\tschedule: AdoptionSchedule,\n): Promise<void> {\n\tawait adapter.execute('INSERT OR REPLACE INTO _kora_meta (key, value) VALUES (?, ?)', [\n\t\tADOPTION_SCHEDULE_META_KEY,\n\t\tJSON.stringify(schedule),\n\t])\n}\n\n/** The current refusal cycle (count of accepted handshakes on this database). */\nexport async function loadAcceptedCycle(adapter: StorageAdapter): Promise<number> {\n\tconst rows = await adapter.query<MetaRow>('SELECT value FROM _kora_meta WHERE key = ?', [\n\t\tACCEPTED_CYCLE_META_KEY,\n\t])\n\tconst value = Number(rows[0]?.value ?? 0)\n\treturn Number.isFinite(value) ? value : 0\n}\n\n/** Read access to a database (an open adapter, or a reader handed to a delete check). */\nexport interface DatabaseQuery {\n\tquery<T>(sql: string, params?: unknown[]): Promise<T[]>\n}\n\n/**\n * Whether any local node has operations above its contiguous acknowledged prefix that\n * the server did not refuse for good (RT-41): the authoritative \"unsynced\" (W3), which\n * the outbound queue only approximates. A local node is one in the registry, the\n * database's node id, or the node of the legacy prefix key; a node with no recorded\n * prefix counts from 0. Works on a database no store has opened in this release.\n */\nexport async function hasUnsyncedOwnOperations(db: DatabaseQuery): Promise<boolean> {\n\tconst tables = new Set(\n\t\t(await db.query<{ name: string }>(\"SELECT name FROM sqlite_master WHERE type = 'table'\")).map(\n\t\t\t(row) => row.name,\n\t\t),\n\t)\n\tconst opsTables = [...tables].filter((name) => name.startsWith('_kora_ops_'))\n\tif (opsTables.length === 0 || !tables.has('_kora_meta')) return false\n\n\tconst nodes = new Set<string>()\n\tif (tables.has(LOCAL_NODES_TABLE)) {\n\t\tfor (const row of await db.query<{ node_id: string }>(\n\t\t\t`SELECT node_id FROM ${LOCAL_NODES_TABLE}`,\n\t\t)) {\n\t\t\tnodes.add(row.node_id)\n\t\t}\n\t}\n\tconst meta = await db.query<{ key: string; value: string }>(\n\t\t\"SELECT key, value FROM _kora_meta WHERE key = 'node_id' OR key = ? OR key LIKE ?\",\n\t\t[OWN_ACKED_THROUGH_META_KEY, `${OWN_ACKED_THROUGH_META_KEY}:%`],\n\t)\n\tconst prefixes = new Map<string, number>()\n\tfor (const row of meta) {\n\t\tif (row.key === 'node_id') {\n\t\t\tnodes.add(row.value)\n\t\t} else if (row.key === OWN_ACKED_THROUGH_META_KEY) {\n\t\t\ttry {\n\t\t\t\tconst parsed = JSON.parse(row.value) as { nodeId?: unknown; sequence?: unknown }\n\t\t\t\tif (typeof parsed.nodeId === 'string') {\n\t\t\t\t\tnodes.add(parsed.nodeId)\n\t\t\t\t\tif (typeof parsed.sequence === 'number') prefixes.set(parsed.nodeId, parsed.sequence)\n\t\t\t\t}\n\t\t\t} catch {\n\t\t\t\t// Unreadable: the node (if known otherwise) counts from 0.\n\t\t\t}\n\t\t} else {\n\t\t\tconst nodeId = row.key.slice(OWN_ACKED_THROUGH_META_KEY.length + 1)\n\t\t\t// The legacy key wins for its node (loadOwnAckedThrough reads it first).\n\t\t\tconst sequence = Number(row.value)\n\t\t\tif (!prefixes.has(nodeId) && Number.isInteger(sequence)) prefixes.set(nodeId, sequence)\n\t\t}\n\t}\n\tconst exclude = tables.has(TERMINAL_REJECTIONS_TABLE)\n\t\t? ` AND id NOT IN (SELECT operation_id FROM ${TERMINAL_REJECTIONS_TABLE})`\n\t\t: ''\n\tfor (const nodeId of nodes) {\n\t\tconst prefix = prefixes.get(nodeId) ?? 0\n\t\tfor (const table of opsTables) {\n\t\t\tconst rows = await db.query<{ n: number }>(\n\t\t\t\t`SELECT COUNT(*) AS n FROM \"${table.replace(/\"/g, '\"\"')}\" WHERE node_id = ? AND sequence_number > ?${exclude}`,\n\t\t\t\t[nodeId, prefix],\n\t\t\t)\n\t\t\tif (Number(rows[0]?.n ?? 0) > 0) return true\n\t\t}\n\t}\n\treturn false\n}\n","import {\n\tFOLD_STATE_VERSION,\n\ttype FoldOptions,\n\ttype FoldState,\n\tFoldStateError,\n\ttype FoldTrace,\n\tHybridLogicalClock,\n\ttype MergeTrace,\n\ttype Operation,\n\ttype OperationTransform,\n\ttype SchemaDefinition,\n\tadaptFoldState,\n\tbase64ToBytes,\n\tcreateFoldState,\n\tdeserializeFoldState,\n\tgetFoldFieldVersionStrings,\n\tisFoldStateLive,\n\tjoinStates,\n\tmaterialize,\n\tmergeOp,\n\tmismatchedFoldFields,\n\tquoteIdent,\n\ttoMergeTrace,\n} from '@korajs/core'\nimport * as Y from 'yjs'\nimport { buildInsertQuery } from '../query/sql-builder'\nimport { deserializeOperationWithCollection, serializeRecord } from '../serialization/serializer'\nimport { loadRetainedConflictRows } from '../store/sequence-repair'\nimport { TERMINAL_REJECTIONS_TABLE } from '../sync/local-sync-records'\nimport type { OperationRow, RawCollectionRow, Transaction } from '../types'\nimport { runTerms } from './query-terms'\n\n/** Per-record fold state (serialized `FoldState`) of every record this database holds. */\nexport const FOLD_STATE_TABLE = '_kora_fold_state'\n/**\n * Per-record base state of operations no longer in the log (compacted, or a snapshot\n * of a row whose history was compacted or quarantined before W7). A record's state\n * is always `join(base, fold(log))`.\n */\nexport const FOLD_BASE_TABLE = '_kora_fold_base'\n/** Per-node sequence prefix removed by compaction: ids at or below it are duplicates. */\nexport const COMPACTED_THROUGH_TABLE = '_kora_compacted_through'\n/**\n * Per-record row snapshots (RT-68): the base built from a materialized row when the\n * record's history is not all in the log (a pre-W7 compaction, quarantined log rows).\n * Kept apart from `_kora_fold_base` (which holds only exact, operation-built states)\n * so the approximation can be dropped once the record's history is complete again:\n * when the server's fold state arrives in a scope entry, or after a full resync.\n * A record's state is `join(base, snapshot, fold(log))`.\n */\nexport const FOLD_SNAPSHOT_TABLE = '_kora_fold_snapshot'\n/**\n * Local-only provisional side effects (RT-69): the cascades / set-nulls a device\n * derives for a REMOTE delete. They fold into the record like operations but are\n * never logged, sequenced or uploaded (the server derives and relays its own\n * copy); each is retired when the server's copy for the same parent and record\n * arrives, or when the device's delivery stream has caught up.\n\n */\nexport const PROVISIONAL_OPS_TABLE = '_kora_provisional_ops'\n/**\n * Terminal-rejection codes the fold does NOT exclude: the user discarded a held\n * node's writes, or the server was found to store them already (they stay in the local\n * database; only their upload stops).\n */\nconst KEPT_REJECTION_CODES: readonly string[] = ['HELD_DISCARDED', 'SETTLED_ON_SERVER']\n/** `_kora_meta` key recording how the rows of this database are materialized. */\nexport const FOLD_MATERIALIZATION_META_KEY = 'fold_materialization'\n/** Value of {@link FOLD_MATERIALIZATION_META_KEY} once rows are materializations of the current fold. */\nexport const FOLD_MATERIALIZATION_CURRENT = `fold-v${FOLD_STATE_VERSION}`\n/** Value of {@link FOLD_MATERIALIZATION_META_KEY} while the legacy (beta.12) paths write rows. */\nexport const FOLD_MATERIALIZATION_LEGACY = 'legacy'\n\n/** DDL for the fold tables. Idempotent. */\nexport const FOLD_TABLES_DDL: readonly string[] = [\n\t`CREATE TABLE IF NOT EXISTS ${FOLD_STATE_TABLE} (collection TEXT NOT NULL, record_id TEXT NOT NULL, state TEXT NOT NULL, PRIMARY KEY (collection, record_id))`,\n\t`CREATE TABLE IF NOT EXISTS ${FOLD_BASE_TABLE} (collection TEXT NOT NULL, record_id TEXT NOT NULL, state TEXT NOT NULL, PRIMARY KEY (collection, record_id))`,\n\t`CREATE TABLE IF NOT EXISTS ${COMPACTED_THROUGH_TABLE} (node_id TEXT PRIMARY KEY, sequence_number INTEGER NOT NULL)`,\n\t`CREATE TABLE IF NOT EXISTS ${FOLD_SNAPSHOT_TABLE} (collection TEXT NOT NULL, record_id TEXT NOT NULL, state TEXT NOT NULL, PRIMARY KEY (collection, record_id))`,\n\t`CREATE TABLE IF NOT EXISTS ${PROVISIONAL_OPS_TABLE} (id TEXT PRIMARY KEY, collection TEXT NOT NULL, record_id TEXT NOT NULL, parent_id TEXT NOT NULL, operation TEXT NOT NULL)`,\n\t`CREATE INDEX IF NOT EXISTS ${PROVISIONAL_OPS_TABLE}_record ON ${PROVISIONAL_OPS_TABLE} (collection, record_id)`,\n]\n\n/**\n * Merges richtext Yjs updates for the fold (core has no Yjs dependency): applies\n * every update to one fresh document and encodes its state. The encoding depends\n * only on the document's content, not on how it was split into updates, so every\n * replica materializes byte-identical richtext.\n */\nexport function mergeYjsUpdates(updates: Uint8Array[]): Uint8Array {\n\tconst doc = new Y.Doc()\n\tfor (const update of updates) Y.applyUpdate(doc, update)\n\treturn Y.encodeStateAsUpdate(doc)\n}\n\nfunction sameBytes(a: Uint8Array, b: Uint8Array): boolean {\n\tif (a.length !== b.length) return false\n\tfor (let i = 0; i < a.length; i++) if (a[i] !== b[i]) return false\n\treturn true\n}\n\n/**\n * Whether Yjs update `a` adds nothing to update `b` (the fold's richtext space\n * bound): the canonical encoding of `b` alone equals that of `a` and `b` merged.\n */\nexport function yjsSubsumes(a: Uint8Array, b: Uint8Array): boolean {\n\treturn sameBytes(mergeYjsUpdates([b]), mergeYjsUpdates([a, b]))\n}\n\n/**\n * Whether an operation lies in a node's compacted prefix: its row is gone from the\n * log, but its effect is in the record's base state, so it is a duplicate (STORE-14).\n */\nexport async function isCompacted(tx: Transaction, op: Operation): Promise<boolean> {\n\tconst rows = await tx.query<{ sequence_number: number }>(\n\t\t`SELECT sequence_number FROM ${COMPACTED_THROUGH_TABLE} WHERE node_id = ?`,\n\t\t[op.nodeId],\n\t)\n\tconst through = rows[0]?.sequence_number\n\treturn through !== undefined && op.sequenceNumber <= through\n}\n\n/** Which fields of a row to (re)write from the fold state. */\nexport type MaterializeFields = 'all' | ReadonlySet<string>\n\n/** A merge trace whose prior operation is read later, with the others of its batch (C3b). */\nexport interface DeferredPrior {\n\ttrace: MergeTrace\n\tcollection: string\n\tpriorId: string\n}\n\n/** Result of merging one operation into its record. */\nexport interface FoldApplyOutcome {\n\t/** The merge changed the record's state. */\n\tchanged: boolean\n\t/** Merge traces (MergeTrace form), for `merge:*` events. */\n\ttraces: MergeTrace[]\n\t/**\n\t * The record's fold state as the merge read it, before the operation. Set for a local\n\t * write; the overlay's commit check re-predicts arrays from it (S6b).\n\t */\n\tpriorState?: FoldState\n}\n\n/**\n * The client side of the W7 fold: every write to a materialized row — local\n * writes, remote operations, scope entries, rejection re-merges, re-materialization\n * — goes through this class, inside the write transaction that appends the\n * operation (\"append, then merge\"). A row is always the materialization of its\n * record's fold state.\n */\nexport class RecordFolder {\n\tprivate authoritative: ReadonlySet<string> = new Set()\n\n\tconstructor(\n\t\tprivate readonly schema: SchemaDefinition,\n\t\tprivate readonly transforms: readonly OperationTransform[] = [],\n\t) {}\n\n\t/** The schema transforms every merge applies (transforms at fold time, RT-84). */\n\tgetOperationTransforms(): readonly OperationTransform[] {\n\t\treturn this.transforms\n\t}\n\n\t/**\n\t * The fields an operation's merge can change: its own data's keys, or every field\n\t * when the fold reads it through a schema transform (whose view may name others).\n\t */\n\tprivate touchedFields(op: Operation): MaterializeFields {\n\t\tif (this.transforms.length > 0 && op.schemaVersion !== this.schema.version) return 'all'\n\t\treturn new Set(Object.keys(op.data ?? {}))\n\t}\n\n\t/** Node ids whose writes win `merge('server-authoritative')` fields. */\n\tgetAuthoritativeNodeIds(): ReadonlySet<string> {\n\t\treturn this.authoritative\n\t}\n\n\t/** @internal Set by the store from persisted meta / the sync handshake. */\n\tsetAuthoritativeNodeIds(ids: Iterable<string>): void {\n\t\tthis.authoritative = new Set(ids)\n\t}\n\n\t/** Fold options every merge of this database uses. */\n\toptions(traces: FoldOptions['traces'] = 'none'): FoldOptions {\n\t\treturn {\n\t\t\trichtext: mergeYjsUpdates,\n\t\t\trichtextSubsumes: yjsSubsumes,\n\t\t\ttraces,\n\t\t\t...(this.authoritative.size > 0 ? { authoritativeNodeIds: this.authoritative } : {}),\n\t\t\t...(this.transforms.length > 0 ? { transforms: this.transforms } : {}),\n\t\t}\n\t}\n\n\t/** Whether the schema has a `merge('server-authoritative')` field in `collection`. */\n\thasAuthoritativeFields(collection: string): boolean {\n\t\tconst definition = this.schema.collections[collection]\n\t\tif (!definition) return false\n\t\treturn Object.values(definition.fields).some(\n\t\t\t(field) => field.mergeStrategy === 'server-authoritative',\n\t\t)\n\t}\n\n\t/**\n\t * Merge one operation (already appended to the log) into its record and\n\t * re-materialize the row.\n\t *\n\t * @param tx - The write transaction that appended the operation\n\t * @param op - The operation\n\t * @param mode - 'remote' emits merge traces; 'local' does not (a local write is\n\t *   computed from the row it updates, so it is never concurrent with it)\n\t */\n\tasync applyInTx(\n\t\ttx: Transaction,\n\t\top: Operation,\n\t\tmode: 'local' | 'remote',\n\t\toptions: { reveal?: boolean } = {},\n\t): Promise<FoldApplyOutcome> {\n\t\t// Whether this operation shows a record a scope retraction hid was decided by the\n\t\t// caller from delivery order (the store's scopeVisibilityAfter), which also cleared\n\t\t// the marker; a marker that is still there keeps the row hidden. `reveal` forces\n\t\t// the row to be written even when the merge changed nothing.\n\t\tconst reveal = options.reveal === true\n\t\tconst clear = { clearRetraction: false }\n\t\tif (mode === 'remote') {\n\t\t\t// The record's approximations end here: a provisional cascade of this parent\n\t\t\t// is replaced by the real one (RT-69), and a row snapshot by the server's\n\t\t\t// complete fold state (RT-68). The operation is already in the log, so the\n\t\t\t// record is re-folded without them.\n\t\t\tconst retired = await this.deleteProvisional(tx, op.collection, op.recordId, op.causalDeps)\n\t\t\tconst replaced = await this.dropSnapshotForCarriedState(tx, op)\n\t\t\tif (retired > 0 || replaced) {\n\t\t\t\tawait this.refoldInTx(tx, op.collection, op.recordId, clear)\n\t\t\t\treturn { changed: true, traces: [] }\n\t\t\t}\n\t\t}\n\t\t// A local insert has a fresh UUIDv7 record id: no state, log or row precedes it.\n\t\tconst fresh = mode === 'local' && op.type === 'insert'\n\t\tconst prior = fresh\n\t\t\t? { state: createFoldState(op.collection, op.recordId), rebuilt: false }\n\t\t\t: await this.loadOrRebuild(tx, op.collection, op.recordId, op.id)\n\t\tlet result: ReturnType<typeof mergeOp>\n\t\ttry {\n\t\t\tresult = mergeOp(\n\t\t\t\tprior.state,\n\t\t\t\top,\n\t\t\t\tthis.schema,\n\t\t\t\tthis.options(mode === 'remote' ? 'conflicts' : 'none'),\n\t\t\t)\n\t\t} catch (error) {\n\t\t\tif (!(error instanceof FoldStateError)) throw error\n\t\t\t// A stored state the current plan cannot take (RT-63): re-fold the record from\n\t\t\t// its base and log (the operation is already appended) once. A second\n\t\t\t// FoldStateError propagates; the sync engine then quarantines the operation\n\t\t\t// instead of stalling its delivery stream.\n\t\t\tawait this.refoldInTx(tx, op.collection, op.recordId, clear)\n\t\t\treturn { changed: true, traces: [] }\n\t\t}\n\t\tif (!result.changed && !prior.rebuilt && !reveal) {\n\t\t\treturn {\n\t\t\t\tchanged: false,\n\t\t\t\ttraces: await this.toMergeTraces(tx, result.traces),\n\t\t\t\t...(mode === 'local' ? { priorState: prior.state } : {}),\n\t\t\t}\n\t\t}\n\t\tawait this.saveState(tx, result.state)\n\t\tconst revived = isDeadState(prior.state) && !isDeadState(result.state)\n\t\tconst fields: MaterializeFields =\n\t\t\tprior.rebuilt || revived || op.foldState !== undefined ? 'all' : this.touchedFields(op)\n\t\tawait this.materializeRow(tx, result.state, fields, {\n\t\t\t...clear,\n\t\t\t...(fresh ? { absent: true } : {}),\n\t\t})\n\t\treturn {\n\t\t\tchanged: result.changed,\n\t\t\ttraces: await this.toMergeTraces(tx, result.traces),\n\t\t\t...(mode === 'local' ? { priorState: prior.state } : {}),\n\t\t}\n\t}\n\n\t/**\n\t * {@link applyInTx} for a remote operation whose record the caller already knows (C3b,\n\t * `RemoteBatchPrefetch`): the stored state (null for a record with no history at all) and\n\t * the materialized row, with no retraction marker, provisional effect or row snapshot\n\t * around it. Reads nothing the merge does not need, so a delivery batch costs its writes\n\t * only; the result is exactly what `applyInTx(tx, op, 'remote')` writes for such a record.\n\t *\n\t * @returns The outcome, the state that was saved (null when none was) and the row as it\n\t *   is now; `refolded` when the record had to be re-folded from its log (RT-63), after\n\t *   which the caller must not trust what it knew of the record\n\t */\n\tasync applyKnownInTx(\n\t\ttx: Transaction,\n\t\top: Operation,\n\t\tknown: { state: FoldState | null; row: { deleted: boolean } | null },\n\t\tdeferred?: DeferredPrior[],\n\t): Promise<\n\t\tFoldApplyOutcome & {\n\t\t\tsaved: FoldState | null\n\t\t\trow: { deleted: boolean } | null\n\t\t\trefolded: boolean\n\t\t}\n\t> {\n\t\tconst prior = known.state ?? createFoldState(op.collection, op.recordId)\n\t\tlet result: ReturnType<typeof mergeOp>\n\t\ttry {\n\t\t\tresult = mergeOp(prior, op, this.schema, this.options('conflicts'))\n\t\t} catch (error) {\n\t\t\tif (!(error instanceof FoldStateError)) throw error\n\t\t\t// See applyInTx: re-fold the record from its base and log once.\n\t\t\tawait this.refoldInTx(tx, op.collection, op.recordId, { clearRetraction: false })\n\t\t\treturn { changed: true, traces: [], saved: null, row: null, refolded: true }\n\t\t}\n\t\tif (!result.changed) {\n\t\t\treturn {\n\t\t\t\tchanged: false,\n\t\t\t\ttraces: await this.toMergeTraces(tx, result.traces, deferred),\n\t\t\t\tsaved: null,\n\t\t\t\trow: known.row,\n\t\t\t\trefolded: false,\n\t\t\t}\n\t\t}\n\t\tawait this.saveState(tx, result.state)\n\t\tconst revived = isDeadState(prior) && !isDeadState(result.state)\n\t\tconst fields: MaterializeFields =\n\t\t\trevived || op.foldState !== undefined ? 'all' : this.touchedFields(op)\n\t\tawait this.materializeRow(tx, result.state, fields, {\n\t\t\tclearRetraction: false,\n\t\t\tknown: { row: known.row },\n\t\t})\n\t\tconst hidden = result.state.cr === null || result.state.u === null\n\t\tconst row = hidden\n\t\t\t? known.row === null\n\t\t\t\t? null\n\t\t\t\t: { deleted: true }\n\t\t\t: { deleted: isDeadState(result.state) }\n\t\treturn {\n\t\t\tchanged: true,\n\t\t\ttraces: await this.toMergeTraces(tx, result.traces, deferred),\n\t\t\tsaved: result.state,\n\t\t\trow,\n\t\t\trefolded: false,\n\t\t}\n\t}\n\n\t/**\n\t * Fold a record from its base state and its log, leaving out operations the\n\t * server terminally rejected, and re-materialize its row (all fields).\n\t *\n\t * @returns The new state (null when nothing of the record remains)\n\t */\n\tasync refoldInTx(\n\t\ttx: Transaction,\n\t\tcollection: string,\n\t\trecordId: string,\n\t\toptions: { clearRetraction?: boolean } = {},\n\t): Promise<FoldState | null> {\n\t\tconst state = await this.foldFromLog(tx, collection, recordId)\n\t\tif (state === null) {\n\t\t\tawait tx.execute(`DELETE FROM ${FOLD_STATE_TABLE} WHERE collection = ? AND record_id = ?`, [\n\t\t\t\tcollection,\n\t\t\t\trecordId,\n\t\t\t])\n\t\t\t// Nothing of the record remains (its insert was refused): hide the row.\n\t\t\tawait tx.execute(`UPDATE ${quoteIdent(collection)} SET _deleted = 1 WHERE id = ?`, [recordId])\n\t\t\treturn null\n\t\t}\n\t\tawait this.saveState(tx, state)\n\t\tawait this.materializeRow(tx, state, 'all', {\n\t\t\tclearRetraction: options.clearRetraction ?? false,\n\t\t})\n\t\treturn state\n\t}\n\n\t/**\n\t * `join(base, snapshot, fold(log - terminally rejected, provisional effects))`, or\n\t * null when none exists. Base and snapshot are adapted to the current fold plan\n\t * (RT-63): a field whose kind changed is rebuilt from its materialized value.\n\t */\n\tasync foldFromLog(\n\t\ttx: Transaction,\n\t\tcollection: string,\n\t\trecordId: string,\n\t): Promise<FoldState | null> {\n\t\tconst ops = [\n\t\t\t...(await this.loadRecordOperations(tx, collection, recordId)),\n\t\t\t...(await this.loadProvisional(tx, collection, recordId)),\n\t\t]\n\t\tconst rejected = await this.loadTerminalRejections(\n\t\t\ttx,\n\t\t\tops.map((op) => op.id),\n\t\t)\n\t\tconst base = await this.loadBase(tx, collection, recordId)\n\t\tconst snapshot = await this.loadSnapshot(tx, collection, recordId)\n\t\tlet state =\n\t\t\tbase !== null && snapshot !== null\n\t\t\t\t? joinStates(base, snapshot, this.schema)\n\t\t\t\t: (base ?? snapshot)\n\t\tfor (const op of ops) {\n\t\t\tif (rejected.has(op.id)) continue\n\t\t\tstate = mergeOp(\n\t\t\t\tstate ?? createFoldState(collection, recordId),\n\t\t\t\top,\n\t\t\t\tthis.schema,\n\t\t\t\tthis.options(),\n\t\t\t).state\n\t\t}\n\t\treturn state\n\t}\n\n\t/** The record's operations (log + retained sequence-conflict rows). */\n\tasync loadRecordOperations(\n\t\ttx: Transaction,\n\t\tcollection: string,\n\t\trecordId: string,\n\t): Promise<Operation[]> {\n\t\tconst rows = [\n\t\t\t...(await tx.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...(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)),\n\t\t]\n\t\treturn rows.map((row) => deserializeOperationWithCollection(row, collection))\n\t}\n\n\t/**\n\t * Which of `ids` the fold leaves out: operations with a terminal-rejection marker\n\t * from the server (or quarantined by a scope retraction, which the server never\n\t * receives). Writes the user chose to discard from a held node are NOT left out:\n\t * discarding stops the upload, it is not a rollback.\n\t */\n\tasync loadTerminalRejections(tx: Transaction, ids: readonly string[]): Promise<Set<string>> {\n\t\tconst found = new Set<string>()\n\t\tconst CHUNK = 500\n\t\tfor (let i = 0; i < ids.length; i += CHUNK) {\n\t\t\tconst chunk = ids.slice(i, i + CHUNK)\n\t\t\tconst rows = await tx.query<{ operation_id: string }>(\n\t\t\t\t`SELECT operation_id FROM ${TERMINAL_REJECTIONS_TABLE} WHERE code NOT IN (${KEPT_REJECTION_CODES.map(() => '?').join(', ')}) AND operation_id IN (${chunk.map(() => '?').join(', ')})`,\n\t\t\t\t[...KEPT_REJECTION_CODES, ...chunk],\n\t\t\t)\n\t\t\tfor (const row of rows) found.add(row.operation_id)\n\t\t}\n\t\treturn found\n\t}\n\n\t/**\n\t * The record's stored state, or null (none, another format version, or a field\n\t * whose fold kind the schema has changed since: the caller re-folds, RT-63).\n\t */\n\tasync loadState(\n\t\ttx: Transaction,\n\t\tcollection: string,\n\t\trecordId: string,\n\t): Promise<FoldState | null> {\n\t\tconst state = await this.readStateRow(tx, FOLD_STATE_TABLE, collection, recordId)\n\t\tif (state === null || mismatchedFoldFields(state, this.schema).length > 0) return null\n\t\treturn state\n\t}\n\n\t/** The stored state as it is, even when the plan changed (a snapshot seed). */\n\tasync loadStoredState(\n\t\ttx: Transaction,\n\t\tcollection: string,\n\t\trecordId: string,\n\t): Promise<FoldState | null> {\n\t\treturn this.readStateRow(tx, FOLD_STATE_TABLE, collection, recordId)\n\t}\n\n\t/** The record's compacted base, adapted to the current fold plan (RT-63). */\n\tasync loadBase(tx: Transaction, collection: string, recordId: string): Promise<FoldState | null> {\n\t\tconst base = await this.readStateRow(tx, FOLD_BASE_TABLE, collection, recordId)\n\t\treturn base === null ? null : adaptFoldState(base, this.schema, this.options()).state\n\t}\n\n\t/** The record's row snapshot (RT-68), adapted to the current fold plan. */\n\tasync loadSnapshot(\n\t\ttx: Transaction,\n\t\tcollection: string,\n\t\trecordId: string,\n\t): Promise<FoldState | null> {\n\t\tconst snapshot = await this.readStateRow(tx, FOLD_SNAPSHOT_TABLE, collection, recordId)\n\t\treturn snapshot === null ? null : adaptFoldState(snapshot, this.schema, this.options()).state\n\t}\n\n\t/** Store `snapshot` as the record's row snapshot (joined with an existing one). */\n\tasync saveSnapshot(tx: Transaction, snapshot: FoldState): Promise<void> {\n\t\tconst existing = await this.loadSnapshot(tx, snapshot.c, snapshot.r)\n\t\tconst state = existing === null ? snapshot : joinStates(existing, snapshot, this.schema)\n\t\tawait tx.execute(\n\t\t\t`INSERT OR REPLACE INTO ${FOLD_SNAPSHOT_TABLE} (collection, record_id, state) VALUES (?, ?, ?)`,\n\t\t\t[state.c, state.r, persistedForm(state)],\n\t\t)\n\t}\n\n\t/**\n\t * A scope entry carrying the server's fold state (RT-29) replaces the record's row\n\t * snapshot (RT-68): the server's state is built from every operation of the record\n\t * the device was missing, so with the device's own log it is the exact state.\n\t * Only a carried state this schema can read and join counts (otherwise the entry\n\t * merges by its data and the snapshot stays).\n\t *\n\t * @returns Whether a snapshot was dropped\n\t */\n\tprivate async dropSnapshotForCarriedState(tx: Transaction, op: Operation): Promise<boolean> {\n\t\tif (op.type !== 'insert' || op.foldState === undefined) return false\n\t\tconst rows = await tx.query<{ n: number }>(\n\t\t\t`SELECT COUNT(*) AS n FROM ${FOLD_SNAPSHOT_TABLE} WHERE collection = ? AND record_id = ?`,\n\t\t\t[op.collection, op.recordId],\n\t\t)\n\t\tif ((rows[0]?.n ?? 0) === 0) return false\n\t\tlet carried: FoldState\n\t\ttry {\n\t\t\tcarried = deserializeFoldState(op.foldState)\n\t\t} catch (error) {\n\t\t\tif (error instanceof FoldStateError) return false\n\t\t\tthrow error\n\t\t}\n\t\tif (carried.c !== op.collection || carried.r !== op.recordId) return false\n\t\tif (mismatchedFoldFields(carried, this.schema).length > 0) return false\n\t\tawait tx.execute(`DELETE FROM ${FOLD_SNAPSHOT_TABLE} WHERE collection = ? AND record_id = ?`, [\n\t\t\top.collection,\n\t\t\top.recordId,\n\t\t])\n\t\treturn true\n\t}\n\n\t/** Records that still fold against a row snapshot (approximate, RT-68). */\n\tasync listSnapshotRecords(\n\t\ttx: Transaction,\n\t): Promise<Array<{ collection: string; recordId: string }>> {\n\t\tconst rows = await tx.query<{ collection: string; record_id: string }>(\n\t\t\t`SELECT collection, record_id FROM ${FOLD_SNAPSHOT_TABLE} ORDER BY collection, record_id`,\n\t\t)\n\t\treturn rows.map((row) => ({ collection: row.collection, recordId: row.record_id }))\n\t}\n\n\t/**\n\t * After a full resync, a record whose log holds its insert again no longer needs\n\t * its row snapshot: drop it and re-fold the record from base and log (RT-68).\n\t *\n\t * @returns Whether the snapshot was dropped\n\t */\n\tasync settleSnapshotInTx(\n\t\ttx: Transaction,\n\t\tcollection: string,\n\t\trecordId: string,\n\t): Promise<boolean> {\n\t\tconst ops = await this.loadRecordOperations(tx, collection, recordId)\n\t\tconst rejected = await this.loadTerminalRejections(\n\t\t\ttx,\n\t\t\tops.map((op) => op.id),\n\t\t)\n\t\tconst hasInsert = ops.some((op) => op.type === 'insert' && !rejected.has(op.id))\n\t\tconst base = await this.loadBase(tx, collection, recordId)\n\t\tif (!hasInsert && (base?.cr ?? null) === null) return false\n\t\tawait tx.execute(`DELETE FROM ${FOLD_SNAPSHOT_TABLE} WHERE collection = ? AND record_id = ?`, [\n\t\t\tcollection,\n\t\t\trecordId,\n\t\t])\n\t\tawait this.refoldInTx(tx, collection, recordId)\n\t\treturn true\n\t}\n\n\t/**\n\t * Fold a local-only provisional side effect (RT-69) into its record: stored apart\n\t * from the log (never sequenced, never uploaded) and kept until the real copy of\n\t * the effect arrives or the delivery stream catches up.\n\t *\n\t * @param parentId - The remote operation that caused it (the parent delete)\n\t */\n\tasync applyProvisionalInTx(tx: Transaction, op: Operation, parentId: string): Promise<void> {\n\t\tconst existing = await tx.query<{ id: string }>(\n\t\t\t`SELECT id FROM ${PROVISIONAL_OPS_TABLE} WHERE id = ?`,\n\t\t\t[op.id],\n\t\t)\n\t\tif (existing.length > 0) return\n\t\tawait tx.execute(\n\t\t\t`INSERT INTO ${PROVISIONAL_OPS_TABLE} (id, collection, record_id, parent_id, operation) VALUES (?, ?, ?, ?, ?)`,\n\t\t\t[op.id, op.collection, op.recordId, parentId, JSON.stringify(op)],\n\t\t)\n\t\tconst prior = await this.loadOrRebuild(tx, op.collection, op.recordId, op.id)\n\t\tconst result = mergeOp(prior.state, op, this.schema, this.options())\n\t\tif (!result.changed && !prior.rebuilt) return\n\t\tawait this.saveState(tx, result.state)\n\t\tawait this.materializeRow(tx, result.state, prior.rebuilt ? 'all' : this.touchedFields(op), {\n\t\t\tclearRetraction: false,\n\t\t})\n\t}\n\n\t/**\n\t * Remove provisional effects of a record (those caused by one of `parentIds`, or\n\t * all of them when null). The caller re-folds the record.\n\t *\n\t * @returns How many were removed\n\t */\n\tasync deleteProvisional(\n\t\ttx: Transaction,\n\t\tcollection: string,\n\t\trecordId: string,\n\t\tparentIds: readonly string[] | null,\n\t): Promise<number> {\n\t\tif (parentIds !== null && parentIds.length === 0) return 0\n\t\tconst filter =\n\t\t\tparentIds === null ? '' : ` AND parent_id IN (${parentIds.map(() => '?').join(', ')})`\n\t\tconst rows = await tx.query<{ id: string }>(\n\t\t\t`SELECT id FROM ${PROVISIONAL_OPS_TABLE} WHERE collection = ? AND record_id = ?${filter}`,\n\t\t\t[collection, recordId, ...(parentIds ?? [])],\n\t\t)\n\t\tif (rows.length === 0) return 0\n\t\tawait tx.execute(\n\t\t\t`DELETE FROM ${PROVISIONAL_OPS_TABLE} WHERE id IN (${rows.map(() => '?').join(', ')})`,\n\t\t\trows.map((row) => row.id),\n\t\t)\n\t\treturn rows.length\n\t}\n\n\t/** Records with provisional effects. */\n\tasync listProvisionalRecords(\n\t\ttx: Transaction,\n\t): Promise<Array<{ collection: string; recordId: string }>> {\n\t\tconst rows = await tx.query<{ collection: string; record_id: string }>(\n\t\t\t`SELECT DISTINCT collection, record_id FROM ${PROVISIONAL_OPS_TABLE} ORDER BY collection, record_id`,\n\t\t)\n\t\treturn rows.map((row) => ({ collection: row.collection, recordId: row.record_id }))\n\t}\n\n\tprivate async loadProvisional(\n\t\ttx: Transaction,\n\t\tcollection: string,\n\t\trecordId: string,\n\t): Promise<Operation[]> {\n\t\tconst rows = await tx.query<{ operation: string }>(\n\t\t\t`SELECT operation FROM ${PROVISIONAL_OPS_TABLE} WHERE collection = ? AND record_id = ?`,\n\t\t\t[collection, recordId],\n\t\t)\n\t\treturn rows.map((row) => JSON.parse(row.operation) as Operation)\n\t}\n\n\tasync saveState(tx: Transaction, state: FoldState): Promise<void> {\n\t\tawait tx.execute(\n\t\t\t`INSERT OR REPLACE INTO ${FOLD_STATE_TABLE} (collection, record_id, state) VALUES (?, ?, ?)`,\n\t\t\t[state.c, state.r, persistedForm(state)],\n\t\t)\n\t}\n\n\tasync saveBase(tx: Transaction, state: FoldState): Promise<void> {\n\t\tawait tx.execute(\n\t\t\t`INSERT OR REPLACE INTO ${FOLD_BASE_TABLE} (collection, record_id, state) VALUES (?, ?, ?)`,\n\t\t\t[state.c, state.r, persistedForm(state)],\n\t\t)\n\t}\n\n\t/** Join `addition` into the record's base state. */\n\tasync joinIntoBase(tx: Transaction, addition: FoldState): Promise<void> {\n\t\tconst base = await this.loadBase(tx, addition.c, addition.r)\n\t\tawait this.saveBase(tx, base === null ? addition : joinStates(base, addition, this.schema))\n\t}\n\n\t/**\n\t * Write the row of a record from its fold state.\n\t *\n\t * - No insert merged: no row (an existing one is hidden).\n\t * - Otherwise the row holds the fold's values (also while deleted: a tombstone\n\t *   keeps its last values), `_deleted` from the record's liveness, and versions\n\t *   from the state: `_version` / `_updated_at` = newest operation, `_created_at` =\n\t *   creation, `_field_versions` = each field's newest write.\n\t * - Only `fields` are written to an existing row; columns the fold never wrote\n\t *   (a column a schema migration added with a default, a local-only backfill)\n\t *   keep their stored value.\n\t * - A record with a scope-retraction marker stays hidden unless `clearRetraction` is\n\t *   set, also when it has no row yet (its retraction applied before its insert). The\n\t *   remote apply path removes the marker first when delivery order shows the record\n\t *   again (the store's scopeVisibilityAfter).\n\t */\n\tasync materializeRow(\n\t\ttx: Transaction,\n\t\tstate: FoldState,\n\t\tfields: MaterializeFields,\n\t\toptions: {\n\t\t\tclearRetraction: boolean\n\t\t\tabsent?: boolean\n\t\t\t/**\n\t\t\t * The row as the caller already knows it (C3b), and that no retraction marker\n\t\t\t * hides the record: nothing is read.\n\t\t\t */\n\t\t\tknown?: { row: { deleted: boolean } | null }\n\t\t},\n\t): Promise<void> {\n\t\tconst collection = state.c\n\t\tconst definition = this.schema.collections[collection]\n\t\tif (!definition) return\n\t\tconst table = quoteIdent(collection)\n\t\tconst rows: Array<Pick<RawCollectionRow, 'id' | '_deleted'>> = options.known\n\t\t\t? options.known.row\n\t\t\t\t? [{ id: state.r, _deleted: options.known.row.deleted ? 1 : 0 }]\n\t\t\t\t: []\n\t\t\t: options.absent\n\t\t\t\t? []\n\t\t\t\t: await tx.query<RawCollectionRow>(`SELECT id, _deleted FROM ${table} WHERE id = ?`, [\n\t\t\t\t\t\tstate.r,\n\t\t\t\t\t])\n\t\tconst existing = rows[0]\n\t\tif (state.cr === null || state.u === null) {\n\t\t\tif (existing && existing._deleted !== 1) {\n\t\t\t\tawait tx.execute(`UPDATE ${table} SET _deleted = 1 WHERE id = ?`, [state.r])\n\t\t\t}\n\t\t\treturn\n\t\t}\n\t\tconst asLive: FoldState = { ...state, d: null }\n\t\tconst values = materialize(asLive, { richtext: mergeYjsUpdates }) ?? {}\n\t\tconst latest = HybridLogicalClock.deserialize(state.u.t)\n\t\tconst created = HybridLogicalClock.deserialize(state.cr.t)\n\t\t// Sorted keys: replicas holding the same state write byte-identical columns.\n\t\tconst fieldVersions = getFoldFieldVersionStrings(state)\n\t\tlet deleted = isDeadState(state) ? 1 : 0\n\t\tif (!options.absent && !options.known && deleted === 0) {\n\t\t\tconst retracted = await tx.query<{ record_id: string }>(\n\t\t\t\t'SELECT record_id FROM _kora_scope_retractions WHERE collection = ? AND record_id = ?',\n\t\t\t\t[collection, state.r],\n\t\t\t)\n\t\t\tif (retracted.length > 0) {\n\t\t\t\tif (options.clearRetraction) {\n\t\t\t\t\tawait tx.execute(\n\t\t\t\t\t\t'DELETE FROM _kora_scope_retractions WHERE collection = ? AND record_id = ?',\n\t\t\t\t\t\t[collection, state.r],\n\t\t\t\t\t)\n\t\t\t\t} else {\n\t\t\t\t\tdeleted = 1\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\tconst known = Object.keys(definition.fields)\n\t\t// A tombstone keeps the values it had when it was deleted: a write that lost to\n\t\t// the delete never shows, not even in the hidden row. A revival rewrites them all.\n\t\tconst writable =\n\t\t\texisting && deleted === 1\n\t\t\t\t? []\n\t\t\t\t: known.filter((field) => field in state.f && (fields === 'all' || fields.has(field)))\n\t\tconst fieldValues: Record<string, unknown> = {}\n\t\tfor (const field of writable) {\n\t\t\tconst value = values[field] ?? null\n\t\t\t// A richtext field with a single live update materializes as that update's\n\t\t\t// own bytes; re-encode it so every replica stores the same canonical bytes,\n\t\t\t// however its state happens to be split into updates.\n\t\t\tfieldValues[field] =\n\t\t\t\tdefinition.fields[field]?.kind === 'richtext' &&\n\t\t\t\tvalue !== null &&\n\t\t\t\ttypeof value === 'object' &&\n\t\t\t\t'$koraBytes' in value\n\t\t\t\t\t? mergeYjsUpdates([base64ToBytes(String((value as { $koraBytes: string }).$koraBytes))])\n\t\t\t\t\t: value\n\t\t}\n\t\tconst serialized = serializeRecord(fieldValues, definition.fields)\n\t\tconst meta: Record<string, unknown> = {\n\t\t\t_updated_at: latest.wallTime,\n\t\t\t_version: state.u.t,\n\t\t\t_field_versions: JSON.stringify(fieldVersions),\n\t\t\t_deleted: deleted,\n\t\t}\n\t\tif (!existing) {\n\t\t\tconst insert = buildInsertQuery(collection, {\n\t\t\t\tid: state.r,\n\t\t\t\t...serialized,\n\t\t\t\t...meta,\n\t\t\t\t_created_at: created.wallTime,\n\t\t\t})\n\t\t\tawait tx.execute(insert.sql, insert.params)\n\t\t\treturn\n\t\t}\n\t\tconst changes: Record<string, unknown> = {\n\t\t\t...serialized,\n\t\t\t...meta,\n\t\t\t_created_at: created.wallTime,\n\t\t}\n\t\tconst columns = Object.keys(changes)\n\t\tawait tx.execute(\n\t\t\t`UPDATE ${table} SET ${columns.map((c) => `${quoteIdent(c)} = ?`).join(', ')} WHERE id = ?`,\n\t\t\t[...columns.map((c) => changes[c]), state.r],\n\t\t)\n\t}\n\n\t/**\n\t * Load the record's state; rebuild it from base + log when it is missing or in\n\t * another format version. `rebuilt` tells the caller to rewrite the whole row.\n\t */\n\tprivate async loadOrRebuild(\n\t\ttx: Transaction,\n\t\tcollection: string,\n\t\trecordId: string,\n\t\tappendedId: string,\n\t): Promise<{ state: FoldState; rebuilt: boolean }> {\n\t\tconst stored = await this.loadState(tx, collection, recordId)\n\t\tif (stored !== null) return { state: stored, rebuilt: false }\n\t\tconst hasRow = await this.hasStateRow(tx, collection, recordId)\n\t\tconst others = await tx.query<{ n: number }>(\n\t\t\t`SELECT COUNT(*) AS n FROM ${quoteIdent(`_kora_ops_${collection}`)} WHERE record_id = ? AND id != ?`,\n\t\t\t[recordId, appendedId],\n\t\t)\n\t\tconst retained = 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\tconst hasBase =\n\t\t\t(await this.loadBase(tx, collection, recordId)) !== null ||\n\t\t\t(await this.loadSnapshot(tx, collection, recordId)) !== null ||\n\t\t\t(await this.loadProvisional(tx, collection, recordId)).some((p) => p.id !== appendedId)\n\t\tif (\n\t\t\t!hasRow &&\n\t\t\t!hasBase &&\n\t\t\t(others[0]?.n ?? 0) === 0 &&\n\t\t\tretained.every((row) => row.id === appendedId)\n\t\t) {\n\t\t\t// A new record: nothing to rebuild.\n\t\t\treturn { state: createFoldState(collection, recordId), rebuilt: false }\n\t\t}\n\t\tconst rebuilt = await this.foldFromLog(tx, collection, recordId)\n\t\treturn { state: rebuilt ?? createFoldState(collection, recordId), rebuilt: true }\n\t}\n\n\tprivate async hasStateRow(\n\t\ttx: Transaction,\n\t\tcollection: string,\n\t\trecordId: string,\n\t): Promise<boolean> {\n\t\tconst rows = await tx.query<{ n: number }>(\n\t\t\t`SELECT COUNT(*) AS n FROM ${FOLD_STATE_TABLE} WHERE collection = ? AND record_id = ?`,\n\t\t\t[collection, recordId],\n\t\t)\n\t\treturn (rows[0]?.n ?? 0) > 0\n\t}\n\n\tprivate async readStateRow(\n\t\ttx: Transaction,\n\t\ttable: string,\n\t\tcollection: string,\n\t\trecordId: string,\n\t): Promise<FoldState | null> {\n\t\tconst rows = await tx.query<{ state: string }>(\n\t\t\t`SELECT state FROM ${table} WHERE collection = ? AND record_id = ?`,\n\t\t\t[collection, recordId],\n\t\t)\n\t\tconst raw = rows[0]?.state\n\t\tif (raw === undefined) return null\n\t\ttry {\n\t\t\treturn deserializeFoldState(raw)\n\t\t} catch (error) {\n\t\t\t// Another format version: the caller re-folds the record.\n\t\t\tif (error instanceof FoldStateError) return null\n\t\t\tthrow error\n\t\t}\n\t}\n\n\t/**\n\t * Resolve the prior operations {@link applyKnownInTx} left unresolved (`deferred`): one\n\t * query per chunk of ids instead of one per trace. Log rows are immutable, so reading\n\t * them later than the merge gives the same operations. An id that is no longer in the log\n\t * keeps the fallback (the trace's own operation), as a single lookup would.\n\t */\n\tasync resolveDeferredPriors(tx: Transaction, deferred: readonly DeferredPrior[]): Promise<void> {\n\t\tconst byCollection = new Map<string, Set<string>>()\n\t\tfor (const item of deferred) {\n\t\t\tconst ids = byCollection.get(item.collection) ?? new Set<string>()\n\t\t\tids.add(item.priorId)\n\t\t\tbyCollection.set(item.collection, ids)\n\t\t}\n\t\tconst found = new Map<string, Operation>()\n\t\tconst terms: Array<{ sql: string; params: unknown[] }> = []\n\t\tconst CHUNK = 400\n\t\tfor (const [collection, ids] of byCollection) {\n\t\t\tconst all = [...ids]\n\t\t\tfor (let start = 0; start < all.length; start += CHUNK) {\n\t\t\t\tconst chunk = all.slice(start, start + CHUNK)\n\t\t\t\tterms.push({\n\t\t\t\t\tsql: `SELECT ? AS c, id, node_id, type, record_id, data, previous_data, timestamp, sequence_number, causal_deps, schema_version FROM ${quoteIdent(`_kora_ops_${collection}`)} WHERE id IN (${chunk.map(() => '?').join(', ')})`,\n\t\t\t\t\tparams: [collection, ...chunk],\n\t\t\t\t})\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 as unknown as Array<OperationRow & { c: string }>) {\n\t\t\t\tfound.set(`${row.c}\\0${row.id}`, deserializeOperationWithCollection(row, row.c))\n\t\t\t}\n\t\t}\n\t\tfor (const item of deferred) {\n\t\t\tconst prior = found.get(`${item.collection}\\0${item.priorId}`)\n\t\t\tif (prior) item.trace.operationA = prior\n\t\t}\n\t}\n\n\tprivate async toMergeTraces(\n\t\ttx: Transaction,\n\t\ttraces: FoldTrace[],\n\t\tdeferred?: DeferredPrior[],\n\t): Promise<MergeTrace[]> {\n\t\tconst out: MergeTrace[] = []\n\t\tfor (const trace of traces) {\n\t\t\tlet prior: Operation | null = null\n\t\t\tif (trace.priorOperationId !== null && deferred) {\n\t\t\t\tconst merged = toMergeTrace(trace, null)\n\t\t\t\tdeferred.push({\n\t\t\t\t\ttrace: merged,\n\t\t\t\t\tcollection: trace.operation.collection,\n\t\t\t\t\tpriorId: trace.priorOperationId,\n\t\t\t\t})\n\t\t\t\tout.push(merged)\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\tif (trace.priorOperationId !== null) {\n\t\t\t\tconst rows = await tx.query<OperationRow>(\n\t\t\t\t\t`SELECT * FROM ${quoteIdent(`_kora_ops_${trace.operation.collection}`)} WHERE id = ?`,\n\t\t\t\t\t[trace.priorOperationId],\n\t\t\t\t)\n\t\t\t\tconst row = rows[0]\n\t\t\t\tif (row) prior = deserializeOperationWithCollection(row, trace.operation.collection)\n\t\t\t}\n\t\t\tout.push(toMergeTrace(trace, prior))\n\t\t}\n\t\treturn out\n\t}\n}\n\n/** No insert merged yet, or the newest delete is later than the newest write. */\n/**\n * The stored form of a fold state: plain JSON, read back by `deserializeFoldState`.\n * The canonical form (`serializeFoldState`, sorted keys) is for comparing and\n * exchanging states; a local row only needs to round-trip, and plain JSON is several\n * times cheaper on the write path.\n */\nfunction persistedForm(state: FoldState): string {\n\treturn JSON.stringify(state)\n}\n\nfunction isDeadState(state: FoldState): boolean {\n\treturn !isFoldStateLive(state)\n}\n","import type { Transaction } from '../types'\n\n/** Variables per statement. Conservative: older SQLite builds allow 999. */\nexport const MAX_PARAMS = 900\n/** Compound select terms per statement (SQLite allows 500). */\nexport const MAX_TERMS = 100\n\n/** Pack terms into compound selects under the variable and term limits and run them. */\nexport async function runTerms(\n\ttx: Transaction,\n\tterms: ReadonlyArray<{ sql: string; params: unknown[] }>,\n): Promise<Array<Array<Record<string, unknown>>>> {\n\tconst results: Array<Array<Record<string, unknown>>> = []\n\tlet sql: string[] = []\n\tlet params: unknown[] = []\n\tconst flush = async (): Promise<void> => {\n\t\tif (sql.length === 0) return\n\t\tresults.push(await tx.query<Record<string, unknown>>(sql.join('\\nUNION ALL '), params))\n\t\tsql = []\n\t\tparams = []\n\t}\n\tfor (const term of terms) {\n\t\tif (\n\t\t\tsql.length > 0 &&\n\t\t\t(sql.length >= MAX_TERMS || params.length + term.params.length > MAX_PARAMS)\n\t\t) {\n\t\t\tawait flush()\n\t\t}\n\t\tsql.push(term.sql)\n\t\tparams.push(...term.params)\n\t}\n\tawait flush()\n\treturn results\n}\n"]}