@starkeep/storage-sqlite 0.6.2 → 0.6.3

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1 +1 @@
1
- {"version":3,"sources":["../src/index.ts","../src/adapter.ts","../src/serialization.ts","../src/query-builder.ts","../src/schema/bootstrap.ts","../src/row-values.ts","../src/app-syncable/namespace.ts","../src/app-syncable/apply.ts","../src/app-syncable/tables.ts","../src/library-owner.ts"],"sourcesContent":["// `nodeSqliteDriver` is deliberately *not* re-exported here — it lives at\n// `@starkeep/storage-sqlite/node`. Pulling it into this barrel would put a\n// static `node:sqlite` import back in the graph and make the package\n// unbundleable on React Native again. See `./node-driver.ts`.\nexport { SqliteDatabaseAdapter, type SqliteDriver } from \"./adapter.js\";\nexport { compiler as sqliteCompiler } from \"./query-builder.js\";\nexport type { SqliteDatabaseAdapterOptions } from \"./adapter.js\";\nexport { initializeLocalSchema, applyConnectionPragmas } from \"./schema/bootstrap.js\";\nexport {\n appSyncableTableName,\n getAppSyncableNamespace,\n upsertAppSyncableNamespace,\n deleteAppSyncableNamespace,\n listAppSyncableNamespaces,\n SqliteAppSyncableNamespaceStore,\n} from \"./app-syncable/namespace.js\";\nexport type { AppSyncableNamespace, AppSyncableTableInfo } from \"./app-syncable/namespace.js\";\nexport { SqliteAppSyncableApplier } from \"./app-syncable/apply.js\";\nexport {\n createAppSyncableTables,\n createReservedFileRecordsTable,\n appSyncableNamespaceTables,\n registerAppSyncableNamespace,\n type AppSyncableDeclaration,\n type SyncableTableDeclaration,\n} from \"./app-syncable/tables.js\";\nexport {\n boundUserId,\n libraryUserSegment,\n checkLibraryBindable,\n commitLibraryBinding,\n libraryKeyColumns,\n LibraryBoundElsewhereError,\n type LibraryKeyColumn,\n} from \"./library-owner.js\";\n","import type { RawDatabase } from \"@starkeep/storage-adapter\";\nimport { nextCursorFrom } from \"@starkeep/storage-adapter\";\nimport type {\n Category,\n DataRecord,\n HLCTimestamp,\n MetadataRow,\n RecordLabel,\n StarkeepId,\n} from \"@starkeep/protocol-primitives\";\nimport {\n serializeHLC,\n deserializeHLC,\n getCategory,\n isKnownType,\n sqliteMetadataTableName,\n typeCategory,\n METADATA_DISCRIMINANT_COLUMN,\n METADATA_DELETED_AT_COLUMN,\n} from \"@starkeep/protocol-primitives\";\nimport type {\n DatabaseAdapter,\n Query,\n QueryResult,\n BatchOperation,\n Transaction,\n LabelUpsert,\n LabelRetraction,\n LabelValueReplacement,\n FindByLabelQuery,\n FindByLabelResult,\n StoredAvailability,\n RecordTypeCount,\n} from \"@starkeep/storage-adapter\";\nimport {\n StorageError,\n TransactionError,\n buildAppAggregateQuery,\n buildAppRowQuery,\n collectAggregatePage,\n collectRowPage,\n sharedQueryExcludesSoftDeleted,\n sharedQuerySchema,\n sharedQueryTableName,\n SQLITE_APP_QUERY_DIALECT,\n type ParsedQuery,\n type ParsedQueryResult,\n type SharedQueryTarget,\n type WhereClause,\n type SoftDeletedScope,\n buildGetLabel,\n buildBucketDigest,\n buildScanSinceForNode,\n buildNodeWatermarks,\n collectSince,\n mergeDigestBuckets,\n planNodeScans,\n toDigestBuckets,\n DEFAULT_BUCKET_PREFIX_LENGTH,\n type DigestBucket,\n type SincePage,\n buildLabelRetraction,\n buildLabelValueReplacementTombstone,\n buildLabelSnapshotUpsert,\n buildLabelUpsert,\n buildLabelsByRecordIds,\n buildQueryLabels,\n buildTombstoneLabelsForRecord,\n buildRestoreLabelsForRecord,\n groupLabelsByRecordId,\n emptyLabelPage,\n LABEL_QUERY_TARGET,\n labelPageFrom,\n planFindByLabel,\n paginateLabelScan,\n rowToLabel,\n type LabelDialect,\n type LabelRow,\n} from \"@starkeep/storage-adapter\";\nimport { sql as kSql } from \"kysely\";\nimport { recordToRow, rowToRecord, type SqliteRow } from \"./serialization.js\";\nimport {\n buildCountQuery,\n buildSelectQuery,\n buildTypeCountsQuery,\n compiler as qb,\n} from \"./query-builder.js\";\nimport { initializeLocalSchema } from \"./schema/bootstrap.js\";\nimport { booleanColumnNames, fromSqliteRows, toSqliteParam } from \"./row-values.js\";\n\nexport interface SqliteDatabaseAdapterOptions {\n path: string | \":memory:\";\n /**\n * How to open the connection, and how to close it.\n *\n * Injected so a second SQLite driver can back this adapter rather than\n * duplicating it. Everything below this line already speaks only\n * {@link RawDatabase} — `exec` and `prepare` — which is what item 10\n * established; opening the connection was the single remaining line that\n * named `node:sqlite`, and it is the one thing that genuinely cannot be\n * driver-agnostic.\n *\n * **Required, and deliberately without a default.** It used to default to\n * `node:sqlite`, which meant this module imported it statically — and a static\n * `node:` import at module scope makes the whole package unbundleable on React\n * Native, whatever driver the caller then passes. The Node driver now lives at\n * `@starkeep/storage-sqlite/node`, so a Node caller writes one extra import\n * and a handset can bundle this file at all.\n *\n * A default that only works on some platforms is worse than no default: it\n * fails at bundle time, far from the line that chose it.\n *\n * React Native passes an op-sqlite driver; see `src/db/op-sqlite-driver.ts` in\n * the `starkeep-apps` photos-mobile app for why that one emulates `prepare()`\n * rather than using op-sqlite's prepared statements.\n */\n driver: SqliteDriver;\n}\n\nexport interface SqliteDriver {\n open(path: string): RawDatabase;\n /**\n * Separate from the connection because `RawDatabase` deliberately does not\n * carry `close()`. Consumers of a connection have no business closing it —\n * only whoever opened it does, which is this adapter.\n */\n close(db: RawDatabase): void;\n}\n\n/**\n * How labels are spelled on this backend: the table is flat-named, SQLite\n * having no schemas. That is now the only difference — null ordering used to be\n * a second one, and stopped being with `value` NOT NULL. Everything else about\n * label SQL lives in `@starkeep/storage-adapter`.\n */\nconst AVAILABILITY = \"shared_object_availability\";\n\n/** The stored row shape, mapped back to the flat domain type at the boundary. */\ninterface AvailabilityRow {\n object_storage_key: string;\n state: string;\n tier: string | null;\n expected_latency_hours: number | null;\n ready_at_ms: number | null;\n restored_until_ms: number | null;\n observed_at_ms: number;\n}\n\nfunction rowToAvailability(row: AvailabilityRow): StoredAvailability {\n return {\n objectStorageKey: row.object_storage_key,\n state: row.state as StoredAvailability[\"state\"],\n tier: row.tier,\n expectedLatencyHours: row.expected_latency_hours,\n readyAtMs: row.ready_at_ms,\n restoredUntilMs: row.restored_until_ms,\n observedAtMs: row.observed_at_ms,\n };\n}\n\nconst LABELS: LabelDialect = {\n table: \"shared_record_labels\",\n};\n\nconst RECORDS = \"shared_records\";\n\nexport class SqliteDatabaseAdapter implements DatabaseAdapter {\n private database: RawDatabase | null = null;\n private readonly options: SqliteDatabaseAdapterOptions;\n private readonly driver: SqliteDriver;\n\n constructor(options: SqliteDatabaseAdapterOptions) {\n this.options = options;\n this.driver = options.driver;\n }\n\n async init(): Promise<void> {\n if (this.database) return;\n // Note what is *not* here: creating the parent directory. That used to be\n // an unconditional `mkdirSync`, which is Node's filesystem — a phone has no\n // such thing, and its database location is the driver's business rather\n // than a path this layer may create. \"How a connection comes into being\"\n // includes \"making sure there is somewhere to put it\", so both belong to\n // the driver together.\n this.database = this.driver.open(this.options.path);\n initializeLocalSchema(this.database);\n }\n\n async close(): Promise<void> {\n if (this.database) this.driver.close(this.database);\n this.database = null;\n }\n\n async healthCheck(): Promise<boolean> {\n if (!this.database) return false;\n try {\n this.database.prepare(kSql`SELECT 1`.compile(qb).sql).get();\n return true;\n } catch {\n return false;\n }\n }\n\n private getDatabase(): RawDatabase {\n if (!this.database) throw new StorageError(\"Database not initialized. Call init() first.\");\n return this.database;\n }\n\n /**\n * The raw SQLite connection, so sibling subsystems (the sync engine's change\n * log and state store, the resident set) can create side tables in the same\n * database file. Only valid after `init()`.\n *\n * Typed as {@link RawDatabase} rather than `DatabaseSync`: returning the\n * concrete Node type is what made a second driver impossible, since every\n * consumer was then nailed to `node:sqlite`, which React Native does not\n * have. `DatabaseSync` satisfies the narrower interface structurally, so\n * nothing about this connection changes — only what callers may reach for.\n */\n getRawDatabase(): RawDatabase {\n return this.getDatabase();\n }\n\n // The casts these three used to carry named `DatabaseSync[\"prepare\"]` to\n // borrow node:sqlite's parameter types. `RawStatement` declares `unknown[]`\n // directly, so they were already no-ops — and they were the last thing in\n // this file referring to a concrete driver.\n //\n // All three map their parameters through `toSqliteParam`, which is what makes\n // `row-values.ts`'s claim true — every bind on this connection, reads and\n // writes alike. It was true only of the query path until 2026-09-10, so a\n // declared `boolean` written through `putMetadata` reached the driver as a\n // JavaScript boolean and threw \"Provided value cannot be bound to SQLite\n // parameter\". Nothing had exercised it because no metadata column was a\n // boolean until `exif_present`.\n private runStmt(sql: string, ...params: unknown[]): void {\n this.getDatabase()\n .prepare(sql)\n .run(...params.map(toSqliteParam));\n }\n\n private getRow<T = SqliteRow>(sql: string, ...params: unknown[]): T | undefined {\n return this.getDatabase()\n .prepare(sql)\n .get(...params.map(toSqliteParam)) as T | undefined;\n }\n\n private allRows<T = SqliteRow>(sql: string, ...params: unknown[]): T[] {\n return this.getDatabase()\n .prepare(sql)\n .all(...params.map(toSqliteParam)) as T[];\n }\n\n async put(record: DataRecord): Promise<void> {\n const row = recordToRow(record);\n const updateColumns = Object.keys(row).filter((column) => column !== \"id\");\n const query = qb\n .insertInto(\"shared_records\")\n .values({ ...row })\n .onConflict((oc) =>\n oc\n .column(\"id\")\n .doUpdateSet((eb) =>\n Object.fromEntries(\n updateColumns.map((column) => [column, eb.ref(`excluded.${column}`)]),\n ),\n ),\n )\n .compile();\n this.runStmt(query.sql, ...query.parameters);\n }\n\n async get(id: StarkeepId): Promise<DataRecord | null> {\n const query = qb.selectFrom(\"shared_records\").selectAll().where(\"id\", \"=\", id).compile();\n const row = this.getRow<SqliteRow>(query.sql, ...query.parameters);\n return row ? rowToRecord(row) : null;\n }\n\n async delete(id: StarkeepId, hlc: HLCTimestamp): Promise<void> {\n const ts = serializeHLC(hlc);\n const query = qb\n .updateTable(\"shared_records\")\n // A tombstone frees its stand-in slot, the same rule `standInSlot`\n // applies on a full-row write.\n .set({ deleted_at: ts, updated_at: ts, node_id: hlc.nodeId, stand_in_slot: null })\n .where(\"id\", \"=\", id)\n .compile();\n this.runStmt(query.sql, ...query.parameters);\n }\n\n async getNodeWatermarks(): Promise<Record<string, HLCTimestamp>> {\n // Index-only on (node_id, updated_at). See `buildNodeWatermarks`.\n const watermarksQuery = buildNodeWatermarks(qb, RECORDS);\n const rows = this.allRows<{ node_id: string; max_updated_at: string }>(watermarksQuery.sql);\n const out: Record<string, HLCTimestamp> = {};\n for (const row of rows) {\n out[row.node_id] = deserializeHLC(row.max_updated_at);\n }\n return out;\n }\n\n async querySince(\n peerWatermarks: Record<string, HLCTimestamp>,\n limit: number,\n ): Promise<SincePage<DataRecord>> {\n const scans = planNodeScans(await this.getNodeWatermarks(), peerWatermarks);\n const { rows, hasMore, truncated } = await collectSince<SqliteRow>(\n scans,\n limit,\n async (scan, remaining) => {\n const compiled = buildScanSinceForNode(qb, RECORDS, scan, remaining);\n return this.allRows<SqliteRow>(compiled.sql, ...compiled.parameters);\n },\n (row) => deserializeHLC(row[\"updated_at\"] as string),\n );\n return { rows: rows.map(rowToRecord), hasMore, truncated };\n }\n\n async queryLabelsSince(\n peerWatermarks: Record<string, HLCTimestamp>,\n limit: number,\n ): Promise<SincePage<RecordLabel>> {\n const scans = planNodeScans(await this.getLabelNodeWatermarks(), peerWatermarks);\n const { rows, hasMore, truncated } = await collectSince<LabelRow>(\n scans,\n limit,\n async (scan, remaining) => {\n const compiled = buildScanSinceForNode(qb, LABELS.table, scan, remaining);\n return this.allRows<LabelRow>(compiled.sql, ...compiled.parameters);\n },\n (row) => deserializeHLC(row[\"updated_at\"] as string),\n );\n return { rows: rows.map(rowToLabel), hasMore, truncated };\n }\n\n async bucketDigest(prefixLength: number = DEFAULT_BUCKET_PREFIX_LENGTH): Promise<DigestBucket[]> {\n // Records and labels together: they are one channel and one coverage\n // watermark, so a digest over only half of it would report agreement while\n // a label was missing.\n const out: DigestBucket[] = [];\n for (const table of [RECORDS, LABELS.table]) {\n const compiled = buildBucketDigest(qb, table, prefixLength);\n out.push(\n ...toDigestBuckets(\n this.allRows<Record<string, unknown>>(compiled.sql, ...compiled.parameters),\n ),\n );\n }\n return mergeDigestBuckets(out);\n }\n\n async query(query: Query): Promise<QueryResult> {\n const { sql, params } = buildSelectQuery(query);\n const rows = this.allRows<SqliteRow & Record<string, unknown>>(sql, ...params);\n\n const limit = query.limit;\n const hasMore = limit ? rows.length > limit : false;\n const resultRows = hasMore ? rows.slice(0, limit) : rows;\n\n return {\n records: resultRows.map(rowToRecord),\n // Cut from the row itself, ordering values and all — see `nextCursorFrom`.\n // The page carries those values back under reserved aliases precisely so\n // this does not have to recompute what the database ordered on.\n nextCursor: hasMore ? nextCursorFrom(query, resultRows[resultRows.length - 1]) : null,\n hasMore,\n };\n }\n\n async countRecords(query: Query): Promise<number> {\n const { sql, params } = buildCountQuery(query);\n const row = this.getRow<{ total: number }>(sql, ...params);\n return row?.total ?? 0;\n }\n\n async countRecordsByType(query: Query): Promise<RecordTypeCount[]> {\n const { sql, params } = buildTypeCountsQuery(query);\n const rows = this.allRows<{\n type: string;\n count: number;\n latest_updated_at: string | null;\n }>(sql, ...params);\n return rows.map((row) => ({\n type: row.type,\n count: Number(row.count),\n latestUpdatedAt: row.latest_updated_at,\n }));\n }\n\n /**\n * See `DatabaseAdapter.queryShared`. Compiled by the same builder the\n * app-syncable plane uses, against the table the target names on this engine.\n */\n async queryShared(\n target: SharedQueryTarget,\n query: ParsedQuery,\n options: {\n readonly serverWhere?: readonly WhereClause[];\n readonly softDeleted?: SoftDeletedScope;\n } = {},\n ): Promise<ParsedQueryResult> {\n const schema = sharedQuerySchema(target);\n const table = sharedQueryTableName(target, \"sqlite\");\n const build = {\n serverWhere: options.serverWhere,\n excludeSoftDeleted: sharedQueryExcludesSoftDeleted(target),\n ...(options.softDeleted ? { softDeleted: options.softDeleted } : {}),\n };\n // Only the metadata tables declare one today (model3d's two flags), but\n // asking the schema rather than the target is what keeps a column added\n // later from reading back as 0 and 1 from this engine alone.\n const booleans = booleanColumnNames(schema.columns);\n\n if (query.mode === \"aggregate\") {\n const compiled = buildAppAggregateQuery(qb, table, query, SQLITE_APP_QUERY_DIALECT, build);\n return collectAggregatePage(query, fromSqliteRows(this.selectCompiled(compiled), booleans));\n }\n const compiled = buildAppRowQuery(qb, table, query, build);\n // Converted before the page is collected rather than after, so the page\n // token is cut from the same representation the rows carry.\n return collectRowPage(query, fromSqliteRows(this.selectCompiled(compiled), booleans));\n }\n\n /** Bind and run a compiled SELECT, adapting values SQLite cannot bind. */\n private selectCompiled(compiled: {\n sql: string;\n parameters: readonly unknown[];\n }): Record<string, unknown>[] {\n return this.allRows<Record<string, unknown>>(\n compiled.sql,\n ...compiled.parameters.map(toSqliteParam),\n );\n }\n\n async batch(operations: BatchOperation[]): Promise<void> {\n this.getDatabase().exec(\"BEGIN\");\n try {\n for (const operation of operations) {\n if (operation.type === \"put\") {\n await this.put(operation.record);\n } else {\n await this.delete(operation.id, operation.hlc);\n }\n }\n this.getDatabase().exec(\"COMMIT\");\n } catch (error) {\n this.getDatabase().exec(\"ROLLBACK\");\n throw error;\n }\n }\n\n async transaction<T>(callback: (transaction: Transaction) => Promise<T>): Promise<T> {\n this.getDatabase().exec(\"SAVEPOINT starkeep_tx\");\n try {\n const transaction: Transaction = {\n put: async (record) => this.put(record),\n get: async (id) => this.get(id),\n delete: async (id, hlc) => this.delete(id, hlc),\n query: async (query) => this.query(query),\n };\n const result = await callback(transaction);\n this.getDatabase().exec(\"RELEASE SAVEPOINT starkeep_tx\");\n return result;\n } catch (error) {\n this.getDatabase().exec(\"ROLLBACK TO SAVEPOINT starkeep_tx\");\n this.getDatabase().exec(\"RELEASE SAVEPOINT starkeep_tx\");\n throw new TransactionError(\"Transaction failed\", error);\n }\n }\n\n async putMetadata(recordType: string, row: MetadataRow): Promise<void> {\n const table = sqliteMetadataTableName(recordType);\n const values = metadataValues(recordType, row);\n const updateColumns = Object.keys(values).filter((c) => c !== \"record_id\");\n const query = qb\n .insertInto(table)\n .values(values)\n .onConflict((oc) =>\n updateColumns.length > 0\n ? oc\n .column(\"record_id\")\n .doUpdateSet((eb) =>\n Object.fromEntries(updateColumns.map((c) => [c, eb.ref(`excluded.${c}`)])),\n )\n : oc.column(\"record_id\").doNothing(),\n )\n .compile();\n this.runStmt(query.sql, ...query.parameters);\n }\n\n async getMetadata(typeId: string, recordId: StarkeepId): Promise<MetadataRow | null> {\n const table = sqliteMetadataTableName(typeId);\n const query = qb.selectFrom(table).selectAll().where(\"record_id\", \"=\", recordId).compile();\n const row = this.getRow<Record<string, unknown>>(query.sql, ...query.parameters);\n if (!row) return null;\n return columnsToMetadataRow(recordId, typeId, row);\n }\n\n async getMetadataByIds(\n typeId: string,\n recordIds: StarkeepId[],\n ): Promise<Map<StarkeepId, MetadataRow>> {\n const result = new Map<StarkeepId, MetadataRow>();\n if (recordIds.length === 0) return result;\n const table = sqliteMetadataTableName(typeId);\n const query = qb.selectFrom(table).selectAll().where(\"record_id\", \"in\", recordIds).compile();\n const rows = this.allRows<Record<string, unknown>>(query.sql, ...query.parameters);\n for (const row of rows) {\n const recordId = row[\"record_id\"] as StarkeepId;\n result.set(recordId, columnsToMetadataRow(recordId, typeId, row));\n }\n return result;\n }\n\n async deleteMetadata(typeId: string, recordId: StarkeepId): Promise<void> {\n const table = sqliteMetadataTableName(typeId);\n const query = qb.deleteFrom(table).where(\"record_id\", \"=\", recordId).compile();\n this.runStmt(query.sql, ...query.parameters);\n }\n\n async tombstoneMetadata(typeId: string, recordId: StarkeepId, hlc: HLCTimestamp): Promise<void> {\n this.setMetadataTombstone(typeId, recordId, serializeHLC(hlc));\n }\n\n async restoreMetadata(typeId: string, recordId: StarkeepId): Promise<void> {\n this.setMetadataTombstone(typeId, recordId, null);\n }\n\n private setMetadataTombstone(typeId: string, recordId: StarkeepId, value: string | null): void {\n const table = sqliteMetadataTableName(typeId);\n const query = qb\n .updateTable(table)\n .set({ [METADATA_DELETED_AT_COLUMN]: value })\n .where(\"record_id\", \"=\", recordId)\n .compile();\n this.runStmt(query.sql, ...query.parameters);\n }\n\n // ---- Cross-app record labels -------------------------------------------\n //\n // The SQL for all of these is built in `@starkeep/storage-adapter`, shared\n // with the DSQL adapter: same columns, same ON CONFLICT set, same cursor\n // predicate, same paging. Only the table name is this backend's business,\n // and it lives in LABELS above.\n\n async upsertLabels(labels: LabelUpsert[]): Promise<void> {\n if (labels.length === 0) return;\n const query = buildLabelUpsert(qb, LABELS, labels);\n this.runStmt(query.sql, ...query.parameters);\n }\n\n async retractLabels(retractions: LabelRetraction[]): Promise<void> {\n for (const r of retractions) {\n const query = buildLabelRetraction(qb, LABELS, r);\n this.runStmt(query.sql, ...query.parameters);\n }\n }\n\n async replaceLabelValues(replacements: LabelValueReplacement[]): Promise<void> {\n if (replacements.length === 0) return;\n // Tombstone-then-upsert per key, all in one transaction: a reader must never\n // see the moment where the old values are gone and the new ones are not yet\n // there, which for a single-valued key is the key appearing to be unset.\n this.getDatabase().exec(\"BEGIN\");\n try {\n for (const r of replacements) {\n const tombstone = buildLabelValueReplacementTombstone(qb, LABELS, r);\n this.runStmt(tombstone.sql, ...tombstone.parameters);\n if (r.values.length > 0) {\n const upsert = buildLabelUpsert(\n qb,\n LABELS,\n r.values.map((value) => ({\n recordId: r.recordId,\n appId: r.appId,\n key: r.key,\n value,\n recordType: r.recordType,\n hlc: r.hlc,\n })),\n );\n this.runStmt(upsert.sql, ...upsert.parameters);\n }\n }\n this.getDatabase().exec(\"COMMIT\");\n } catch (error) {\n this.getDatabase().exec(\"ROLLBACK\");\n throw error;\n }\n }\n\n async getLabelsByRecordIds(recordIds: StarkeepId[]): Promise<Map<StarkeepId, RecordLabel[]>> {\n if (recordIds.length === 0) return new Map();\n const query = buildLabelsByRecordIds(qb, LABELS, recordIds);\n return groupLabelsByRecordId(this.allRows<LabelRow>(query.sql, ...query.parameters));\n }\n\n /**\n * The reverse label read, run through the query grammar — see\n * `label-find.ts`. The grant rides in as `serverWhere` rather than as one of\n * the caller's own predicates, which is the separation every other shared\n * query draws.\n */\n async findByLabel(query: FindByLabelQuery): Promise<FindByLabelResult> {\n // `null` means the query cannot match anything — a caller with no readable\n // types — so there is nothing to ask the database.\n const plan = planFindByLabel(query);\n if (!plan) return emptyLabelPage();\n return labelPageFrom(\n await this.queryShared(LABEL_QUERY_TARGET, plan.query, {\n serverWhere: plan.serverWhere,\n }),\n );\n }\n\n // ---- Label sync ---------------------------------------------------------\n\n async putLabel(label: RecordLabel): Promise<void> {\n const query = buildLabelSnapshotUpsert(qb, LABELS, label);\n this.runStmt(query.sql, ...query.parameters);\n }\n\n async getLabel(\n recordId: StarkeepId,\n appId: string,\n key: string,\n value: string,\n ): Promise<RecordLabel | null> {\n const query = buildGetLabel(qb, LABELS, recordId, appId, key, value);\n const row = this.getRow<LabelRow>(query.sql, ...query.parameters);\n return row ? rowToLabel(row) : null;\n }\n\n async queryLabels(query: { limit?: number; cursor?: string }): Promise<{\n labels: RecordLabel[];\n nextCursor: string | null;\n hasMore: boolean;\n }> {\n const compiled = buildQueryLabels(qb, LABELS, query);\n const rows = this.allRows<LabelRow>(compiled.sql, ...compiled.parameters);\n return paginateLabelScan(rows, query.limit);\n }\n\n async getLabelNodeWatermarks(): Promise<Record<string, HLCTimestamp>> {\n const query = buildNodeWatermarks(qb, LABELS.table);\n const rows = this.allRows<{ node_id: string; max_updated_at: string }>(query.sql);\n const out: Record<string, HLCTimestamp> = {};\n for (const row of rows) out[row.node_id] = deserializeHLC(row.max_updated_at);\n return out;\n }\n\n // ---- Object availability ------------------------------------------------\n\n async getAvailability(objectStorageKeys: string[]): Promise<Map<string, StoredAvailability>> {\n const out = new Map<string, StoredAvailability>();\n if (objectStorageKeys.length === 0) return out;\n const compiled = qb\n .selectFrom(AVAILABILITY)\n .selectAll()\n .where(\"object_storage_key\", \"in\", objectStorageKeys)\n .compile();\n const rows = this.allRows<AvailabilityRow>(compiled.sql, ...compiled.parameters);\n for (const row of rows) out.set(row.object_storage_key, rowToAvailability(row));\n return out;\n }\n\n async putAvailability(row: StoredAvailability): Promise<void> {\n const compiled = qb\n .insertInto(AVAILABILITY)\n .values({\n object_storage_key: row.objectStorageKey,\n state: row.state,\n tier: row.tier,\n expected_latency_hours: row.expectedLatencyHours,\n ready_at_ms: row.readyAtMs,\n restored_until_ms: row.restoredUntilMs,\n observed_at_ms: row.observedAtMs,\n })\n .onConflict((oc) =>\n oc.column(\"object_storage_key\").doUpdateSet((eb) => ({\n state: eb.ref(\"excluded.state\"),\n tier: eb.ref(\"excluded.tier\"),\n expected_latency_hours: eb.ref(\"excluded.expected_latency_hours\"),\n ready_at_ms: eb.ref(\"excluded.ready_at_ms\"),\n restored_until_ms: eb.ref(\"excluded.restored_until_ms\"),\n observed_at_ms: eb.ref(\"excluded.observed_at_ms\"),\n })),\n )\n .compile();\n this.runStmt(compiled.sql, ...compiled.parameters);\n }\n\n async countRestoringObjects(): Promise<{ objectCount: number; bytes: number }> {\n // Joined to records for the byte total: availability is keyed by object,\n // and only the record row knows how big the object is.\n const compiled = qb\n .selectFrom(AVAILABILITY)\n .innerJoin(\n \"shared_records\",\n \"shared_records.object_storage_key\",\n `${AVAILABILITY}.object_storage_key`,\n )\n .select(({ fn }) => [\n fn.count<number>(`${AVAILABILITY}.object_storage_key`).as(\"object_count\"),\n fn.sum<number>(\"shared_records.size_bytes\").as(\"bytes\"),\n ])\n .where(`${AVAILABILITY}.state`, \"=\", kSql.lit(\"restoring\"))\n .compile();\n const row = this.getRow<{ object_count: number; bytes: number | null }>(\n compiled.sql,\n ...compiled.parameters,\n );\n return { objectCount: row?.object_count ?? 0, bytes: row?.bytes ?? 0 };\n }\n\n async tombstoneLabelsForRecord(recordId: StarkeepId, hlc: HLCTimestamp): Promise<void> {\n const query = buildTombstoneLabelsForRecord(qb, LABELS, recordId, hlc);\n this.runStmt(query.sql, ...query.parameters);\n }\n\n async restoreLabelsForRecord(\n recordId: StarkeepId,\n deletedAt: HLCTimestamp,\n hlc: HLCTimestamp,\n ): Promise<void> {\n const query = buildRestoreLabelsForRecord(qb, LABELS, recordId, deletedAt, hlc);\n this.runStmt(query.sql, ...query.parameters);\n }\n}\n\n/**\n * One stored metadata row, with SQLite's integers turned back into the booleans\n * the column declares.\n *\n * The read half of the boolean boundary, for the same reason as\n * `fromSqliteRows`: DSQL returns `true` and SQLite returns `1` for the same\n * logical row, and a metadata row rides the sync wire in whatever shape its\n * engine returned. Without this, `exif_present` would mean two things depending\n * on which node answered.\n */\nfunction columnsToMetadataRow(\n recordId: StarkeepId,\n typeId: string,\n columns: Record<string, unknown>,\n): MetadataRow {\n const category = typeCategory(typeId) ?? (typeId as Category);\n const booleans = booleanColumnNames(getCategory(category)?.metadataColumns);\n const row: MetadataRow = { recordId };\n for (const [key, value] of Object.entries(columns)) {\n // `deleted_at` is the server's, like the discriminant: a caller reading a\n // metadata row has no business seeing it, and nothing on the wire carries it.\n if (key === \"record_id\" || key === METADATA_DELETED_AT_COLUMN) continue;\n row[key] = booleans?.has(key) && typeof value === \"number\" ? value !== 0 : value;\n }\n return row;\n}\n\n/**\n * The values to write, with the grant discriminant derived from `recordType`.\n *\n * `recordType` is the record's own `<category>/<format>` id, not a bare\n * category, and a bare one is refused here rather than stored. A metadata row\n * labelled with the wrong discriminant is readable by the wrong app, so a\n * caller that had only a category has lost the thing this column exists to\n * carry and must go and read the record's type.\n *\n * Never taken from `row`: metadata rides the wire as a sync passenger, and a\n * peer supplying this column would be asserting who may read the row. See\n * METADATA_DISCRIMINANT_COLUMN.\n */\nfunction metadataValues(recordType: string, row: MetadataRow): Record<string, unknown> {\n if (!isKnownType(recordType)) {\n throw new StorageError(\n `putMetadata needs the record's own type, not \"${recordType}\": the ` +\n `${METADATA_DISCRIMINANT_COLUMN} column gates every read of this row`,\n );\n }\n const values: Record<string, unknown> = {\n record_id: row.recordId,\n [METADATA_DISCRIMINANT_COLUMN]: recordType,\n // Writing metadata asserts the row is live. Without this an app re-reporting\n // a restored record's dimensions would write into a row still carrying its\n // tombstone, and the one read that filters on the stamp would keep answering\n // nothing. Server-owned either way: a wire row carrying it is ignored below.\n [METADATA_DELETED_AT_COLUMN]: null,\n };\n for (const [key, value] of Object.entries(row)) {\n // `recordId` is spelled `record_id` above, and the discriminant is the\n // server's to set — a wire row carrying one is ignored, not honoured.\n if (\n key === \"recordId\" ||\n key === METADATA_DISCRIMINANT_COLUMN ||\n key === METADATA_DELETED_AT_COLUMN\n ) {\n continue;\n }\n values[key] = value;\n }\n return values;\n}\n","import type { DataRecord, MetadataRow, StarkeepId } from \"@starkeep/protocol-primitives\";\nimport {\n serializeHLC,\n deserializeHLC,\n createStarkeepId,\n isStandInRole,\n standInSlot,\n} from \"@starkeep/protocol-primitives\";\n\nexport interface SqliteRow {\n id: string;\n type: string;\n created_at: string;\n updated_at: string;\n /** Denormalized `updatedAt.nodeId`; must be rewritten with `updated_at`. */\n node_id: string;\n deleted_at: string | null;\n version: number;\n content_hash: string;\n object_storage_key: string;\n mime_type: string | null;\n size_bytes: number;\n original_filename: string | null;\n origin_app_id: string;\n parent_id: string | null;\n stand_in_role: string | null;\n fidelity: number | null;\n canonical_threshold: number | null;\n /** Null on a row written before the column existed, which reads as false. */\n self_canonical: number | null;\n /**\n * Derived from the three columns above and `deleted_at` on every write — see\n * `standInSlot`. Never read back into a record: it exists only so one\n * ordinary unique index can carry both stand-in uniqueness rules.\n */\n stand_in_slot: string | null;\n}\n\nexport function recordToRow(record: DataRecord): SqliteRow {\n return {\n id: record.id,\n type: record.type,\n created_at: serializeHLC(record.createdAt),\n updated_at: serializeHLC(record.updatedAt),\n node_id: record.updatedAt.nodeId,\n deleted_at: record.deletedAt ? serializeHLC(record.deletedAt) : null,\n version: record.version,\n content_hash: record.contentHash,\n object_storage_key: record.objectStorageKey,\n mime_type: record.mimeType,\n size_bytes: record.sizeBytes,\n original_filename: record.originalFilename,\n origin_app_id: record.originAppId,\n parent_id: record.parentId,\n stand_in_role: record.standInRole,\n fidelity: record.fidelity,\n canonical_threshold: record.canonicalThreshold,\n self_canonical: record.selfCanonical ? 1 : 0,\n stand_in_slot: standInSlot(record),\n };\n}\n\nexport function rowToRecord(row: SqliteRow): DataRecord {\n return {\n id: createStarkeepId(row.id),\n kind: \"data\",\n type: row.type,\n createdAt: deserializeHLC(row.created_at),\n updatedAt: deserializeHLC(row.updated_at),\n deletedAt: row.deleted_at ? deserializeHLC(row.deleted_at) : null,\n version: row.version,\n contentHash: row.content_hash,\n objectStorageKey: row.object_storage_key,\n mimeType: row.mime_type,\n sizeBytes: row.size_bytes,\n originalFilename: row.original_filename,\n originAppId: row.origin_app_id,\n parentId: row.parent_id ? createStarkeepId(row.parent_id) : null,\n standInRole: isStandInRole(row.stand_in_role) ? row.stand_in_role : null,\n // DSQL returns a bigint column as a string; the value is small, so a\n // Number is exact.\n fidelity: row.fidelity === null || row.fidelity === undefined ? null : Number(row.fidelity),\n canonicalThreshold:\n row.canonical_threshold === null || row.canonical_threshold === undefined\n ? null\n : Number(row.canonical_threshold),\n selfCanonical: row.self_canonical === 1,\n };\n}\n\n/**\n * Label rows are identical on both backends, so their row type and both\n * conversions live in `@starkeep/storage-adapter` — re-exported here for the\n * adapter that used to own them.\n */\nexport { rowToLabel, labelToRow, type LabelRow as SqliteLabelRow } from \"@starkeep/storage-adapter\";\n\n/**\n * Convert SQLite column-keyed row data into a MetadataRow keyed by recordId\n * plus camelCase or snake_case columns. We pass columns through as-is from\n * the DB so callers can address them however they prefer.\n */\nexport function metadataRowFromColumns(\n recordId: StarkeepId,\n columns: Record<string, unknown>,\n): MetadataRow {\n const row: MetadataRow = { recordId };\n for (const [key, value] of Object.entries(columns)) {\n if (key === \"record_id\") continue;\n row[key] = value;\n }\n return row;\n}\n","import type { Query } from \"@starkeep/storage-adapter\";\nimport {\n buildRecordCount,\n buildRecordSelect,\n buildRecordTypeCounts,\n type RecordDialect,\n} from \"@starkeep/storage-adapter\";\nimport { sqliteMetadataTableName } from \"@starkeep/protocol-primitives\";\nimport {\n DummyDriver,\n Kysely,\n SqliteAdapter,\n SqliteIntrospector,\n SqliteQueryCompiler,\n} from \"kysely\";\n\n// Single dynamic-schema Kysely instance used only to compile SQL — never\n// executes. The DummyDriver lets us reuse Kysely's compiler without pulling\n// in a real connection. `any` keeps it dialect-agnostic at the row level;\n// column names are validated against the live SQLite schema at runtime.\nexport type DB = Record<string, Record<string, unknown>>;\nexport const compiler = new Kysely<DB>({\n dialect: {\n createAdapter: () => new SqliteAdapter(),\n createDriver: () => new DummyDriver(),\n createIntrospector: (db) => new SqliteIntrospector(db),\n createQueryCompiler: () => new SqliteQueryCompiler(),\n },\n});\n\n/**\n * What SQLite calls the tables the shared record queries read.\n *\n * The queries themselves live in `@starkeep/storage-adapter`'s\n * `record-queries.ts`, for the reason stated there: this file and its DSQL twin\n * held two copies of one query and drifted in the ways that mattered.\n */\nconst DIALECT: RecordDialect = {\n records: \"shared_records\",\n labels: \"shared_record_labels\",\n metadataTable: sqliteMetadataTableName,\n};\n\nexport interface BuiltQuery {\n sql: string;\n params: unknown[];\n}\n\nexport function buildSelectQuery(query: Query): BuiltQuery {\n const compiled = buildRecordSelect(compiler, DIALECT, query);\n return { sql: compiled.sql, params: [...compiled.parameters] };\n}\n\nexport function buildCountQuery(query: Query): BuiltQuery {\n const compiled = buildRecordCount(compiler, DIALECT, query);\n return { sql: compiled.sql, params: [...compiled.parameters] };\n}\n\nexport function buildTypeCountsQuery(query: Query): BuiltQuery {\n const compiled = buildRecordTypeCounts(compiler, DIALECT, query);\n return { sql: compiled.sql, params: [...compiled.parameters] };\n}\n","import type { RawDatabase } from \"@starkeep/storage-adapter\";\nimport { sql } from \"kysely\";\nimport {\n CATEGORIES,\n sqliteMetadataDdl,\n metadataIndexDdls,\n hasMetadataTable,\n} from \"@starkeep/protocol-primitives\";\nimport { compiler as qb } from \"../query-builder.js\";\n\n/**\n * Local sqlite schema bootstrap.\n *\n * Layout follows desired-state-roles-and-permissions.md \"DSQL DDL ... Local\n * SQLite asymmetry\" section: prefix-named tables in one file instead of\n * separate schemas. Only tables that something in phase 1 actually reads or\n * writes are created here — promotion, metadata enrichment, and the janitor\n * land as separate workstreams with their own DDL.\n *\n * - shared_records — all shared data, all types (file-backed only)\n * - shared_record_<category>_metadata — per-category metadata rows (typed columns)\n * - shared_record_labels — cross-app assertions about shared records\n * - shared_access_grants — per-app, per-type permissions\n * - shared_app_label_keys — manifest-declared label keys, per app\n * - shared_app_registry — installed apps + HMAC secrets\n * - shared_app_install_steps — idempotent install/uninstall ledger\n *\n * No migration system: this is a fresh-start schema. The user removes\n * ~/.starkeep/data.db (or the local-data-server's STARKEEP_DIR is fresh)\n * before this code runs.\n */\n/**\n * Connection settings the query grammar's portability depends on.\n *\n * Separate from the schema DDL and exported because a connection can be opened\n * without the full local schema — the conformance harness creates one table and\n * nothing else — and a setting that the real server has and the conformance\n * suite does not is a setting whose divergence the suite cannot catch.\n *\n * `case_sensitive_like` is the whole list today. SQLite's LIKE folds ASCII case\n * by default and Postgres's does not, so `like: \"photo%\"` would otherwise match\n * `PHOTO123` locally and not in the cloud. DSQL uses the `C` collation only, so\n * with the fold turned off the two agree byte for byte. Turning it off also\n * lets SQLite use a btree index for an anchored pattern, which the fold rules\n * out.\n */\nexport function applyConnectionPragmas(db: RawDatabase): void {\n db.exec(\"PRAGMA case_sensitive_like = ON\");\n}\n\nfunction applyLocalSchemaDdl(db: RawDatabase): void {\n db.exec(\"PRAGMA journal_mode = WAL\");\n db.exec(\"PRAGMA foreign_keys = ON\");\n applyConnectionPragmas(db);\n\n // shared_records: node_id is denormalized from updated_at (its nodeId\n // component) on every write — it feeds the sync responder's per-node\n // coverage watermark via the (node_id, updated_at) index without scanning\n // the table. label is an advisory appId/purpose interest-filter marker\n // (e.g. photos/thumbnail); NULL = general interest. See DataRecord.label.\n db.exec(\n qb.schema\n .createTable(\"shared_records\")\n .ifNotExists()\n .addColumn(\"id\", \"text\", (c) => c.primaryKey())\n .addColumn(\"type\", \"text\", (c) => c.notNull())\n .addColumn(\"created_at\", \"text\", (c) => c.notNull())\n .addColumn(\"updated_at\", \"text\", (c) => c.notNull())\n .addColumn(\"node_id\", \"text\", (c) => c.notNull())\n .addColumn(\"deleted_at\", \"text\")\n .addColumn(\"version\", \"integer\", (c) => c.notNull().defaultTo(1))\n .addColumn(\"content_hash\", \"text\", (c) => c.notNull())\n .addColumn(\"object_storage_key\", \"text\", (c) => c.notNull())\n .addColumn(\"mime_type\", \"text\")\n .addColumn(\"size_bytes\", \"integer\", (c) => c.notNull())\n .addColumn(\"original_filename\", \"text\")\n .addColumn(\"origin_app_id\", \"text\", (c) => c.notNull())\n .addColumn(\"parent_id\", \"text\")\n // Stand-ins: a role, a reported fidelity, and the derived slot the unique\n // index below keys on. See `stand-ins/rules.ts` in protocol-primitives.\n .addColumn(\"stand_in_role\", \"text\", (c) =>\n c.check(sql`stand_in_role IN ('canonical', 'smaller')`),\n )\n .addColumn(\"fidelity\", \"integer\")\n // The threshold the platform judged an original by, and whether it\n // stands in for itself because no canonical encode could shrink it.\n // Platform-owned, like `fidelity` on an original.\n .addColumn(\"canonical_threshold\", \"integer\")\n .addColumn(\"self_canonical\", \"integer\")\n .addColumn(\"stand_in_slot\", \"text\")\n .compile().sql,\n );\n const sharedRecordsIndexes = [\n qb.schema\n .createIndex(\"idx_shared_records_type\")\n .ifNotExists()\n .on(\"shared_records\")\n .column(\"type\"),\n qb.schema\n .createIndex(\"idx_shared_records_node_watermark\")\n .ifNotExists()\n .on(\"shared_records\")\n .columns([\"node_id\", \"updated_at\"]),\n qb.schema\n .createIndex(\"idx_shared_records_origin_app\")\n .ifNotExists()\n .on(\"shared_records\")\n .column(\"origin_app_id\"),\n qb.schema\n .createIndex(\"idx_shared_records_parent_id\")\n .ifNotExists()\n .on(\"shared_records\")\n .column(\"parent_id\"),\n // Record-level dedup: \"is there already a live record for these bytes\n // under this parent?\", asked on **every** registration.\n //\n // The (filename, content_hash) unique index below cannot serve it — its\n // leading column is the filename, so a hash-only lookup would scan the\n // table once per write. Leading with content_hash is what makes the dedup\n // check affordable enough to be unconditional, and unconditional is what\n // makes \"one object key, one record\" an invariant rather than a hope.\n qb.schema\n .createIndex(\"idx_shared_records_content_hash\")\n .ifNotExists()\n .on(\"shared_records\")\n .columns([\"content_hash\", \"parent_id\", \"deleted_at\"]),\n ];\n for (const index of sharedRecordsIndexes) {\n db.exec(index.compile().sql);\n }\n\n // One live canonical stand-in per original, and one live stand-in per size.\n //\n // A plain column index rather than SQLite's partial index, so both engines\n // hold one index shape: DSQL rejects `WHERE` on CREATE INDEX, and the\n // serializers compute `stand_in_slot` — null on every record the rules do\n // not cover, including tombstones — so the partial predicate lives in the\n // column instead. NULL is distinct from NULL in a SQLite unique index, which\n // is exactly the reading wanted here: ordinary records never collide.\n db.exec(\n qb.schema\n .createIndex(\"uq_shared_records_stand_in_slot\")\n .ifNotExists()\n .unique()\n .on(\"shared_records\")\n .columns([\"parent_id\", \"stand_in_slot\"])\n .compile().sql,\n );\n\n // Duplicate-file prevention: (parent + filename + bytes) is unique among live\n // records. Tombstoned rows (deleted_at IS NOT NULL) are excluded so a\n // re-upload after delete is allowed.\n //\n // **This predicate is also the id rule.** `createDataRecord`\n // content-addresses a record's id from exactly these columns, so that two\n // nodes producing one file produce one row instead of colliding here. The two\n // are the same decision written in two languages: widen or narrow this index\n // and `identifiers/content-id.ts` has to move with it, or the class of record\n // that stops matching gets the sync wedge back. The DSQL index in\n // `admin-installer/src/dsql-schema-init.ts` is the third place, and says the\n // same thing.\n //\n // `parent_id` is in the key because the store cannot represent a shared\n // child: `parent_id` is one scalar column, so two originals whose derived\n // files are byte-identical under one name do not come to share a rendition —\n // the second registration overwrites the first record's parentage. Without\n // parentage in the key that overwrite is silent, and it needs no sync and no\n // carelessness to happen. See\n // `~/projects/starkeep/sync-duplicate-derivation-wedge-2026-08-29.md`.\n //\n // Both nullable columns are wrapped in `COALESCE`, which is why this is an\n // expression index rather than a column list. SQLite follows the standard and\n // treats NULL as distinct from NULL in a unique index, so naming `parent_id`\n // directly would silently stop constraining every top-level record — the\n // exact rows the constraint was originally written for. Coalescing to the\n // empty string makes a missing value equal to itself, which is what DSQL's\n // `NULLS NOT DISTINCT` does there and what `content-id.ts` does when it\n // hashes.\n //\n // Nothing drops the `uq_shared_records_filename_hash` this replaces: the\n // schema is fresh-start (see the note at the top of this file), so an\n // existing `data.db` is removed rather than migrated. A database carrying the\n // superseded index would keep enforcing the narrower rule and reject exactly\n // the derived children this key exists to separate.\n db.exec(\n qb.schema\n .createIndex(\"uq_shared_records_parent_filename_hash\")\n .ifNotExists()\n .unique()\n .on(\"shared_records\")\n .expression(sql`COALESCE(parent_id, ''), COALESCE(original_filename, ''), content_hash`)\n .where(sql.ref(\"deleted_at\"), \"is\", null)\n .compile().sql,\n );\n\n db.exec(\n qb.schema\n .createTable(\"shared_access_grants\")\n .ifNotExists()\n .addColumn(\"app_id\", \"text\", (c) => c.notNull())\n .addColumn(\"type_id\", \"text\", (c) => c.notNull())\n .addColumn(\"access\", \"text\", (c) => c.notNull().check(sql`access IN ('read', 'readwrite')`))\n .addColumn(\"metadata_write\", \"integer\", (c) => c.notNull().defaultTo(0))\n .addColumn(\"created_at\", \"text\", (c) => c.notNull().defaultTo(sql`(datetime('now'))`))\n .addPrimaryKeyConstraint(\"pk_shared_access_grants\", [\"app_id\", \"type_id\"] as never[])\n .compile().sql,\n );\n db.exec(\n qb.schema\n .createIndex(\"idx_shared_access_grants_app\")\n .ifNotExists()\n .on(\"shared_access_grants\")\n .column(\"app_id\")\n .compile().sql,\n );\n\n // shared_record_labels — cross-app assertions about shared records; the\n // local mirror of DSQL's shared.record_labels. See records/labels.ts in\n // protocol-primitives for what a label is and why app_id is a column rather\n // than a string prefix.\n db.exec(\n qb.schema\n .createTable(\"shared_record_labels\")\n .ifNotExists()\n .addColumn(\"record_id\", \"text\", (c) => c.notNull())\n .addColumn(\"app_id\", \"text\", (c) => c.notNull())\n .addColumn(\"key\", \"text\", (c) => c.notNull())\n // In the primary key, so a key is set-valued (faces=Alice and faces=Bob\n // are two rows), and therefore NOT NULL — a bare flag is \"\". See the\n // matching comment in dsql-schema-init.ts.\n .addColumn(\"value\", \"text\", (c) => c.notNull())\n // Denormalized from shared_records.type (immutable), so read gating\n // never joins back — on the reverse path that join is unbounded.\n .addColumn(\"record_type\", \"text\", (c) => c.notNull())\n .addColumn(\"created_at\", \"text\", (c) => c.notNull())\n .addColumn(\"updated_at\", \"text\", (c) => c.notNull())\n .addColumn(\"node_id\", \"text\", (c) => c.notNull())\n .addColumn(\"deleted_at\", \"text\")\n .addPrimaryKeyConstraint(\"pk_shared_record_labels\", [\n \"record_id\",\n \"app_id\",\n \"key\",\n \"value\",\n ] as never[])\n .compile().sql,\n );\n const sharedRecordLabelsIndexes = [\n // The reverse path. Column order mirrors DSQL's idx_record_labels_reverse\n // exactly — see the long comment there for why each column is where it is.\n // SQLite *does* support partial indexes, so `deleted_at` could have been a\n // WHERE clause here; it is a key column instead so the two backends have\n // one index shape between them and a query planned on one is planned the\n // same on the other.\n qb.schema\n .createIndex(\"idx_shared_record_labels_reverse\")\n .ifNotExists()\n .on(\"shared_record_labels\")\n .columns([\"app_id\", \"key\", \"deleted_at\", \"value\", \"record_id\"]),\n qb.schema\n .createIndex(\"idx_shared_record_labels_node_watermark\")\n .ifNotExists()\n .on(\"shared_record_labels\")\n .columns([\"node_id\", \"updated_at\"]),\n ];\n for (const index of sharedRecordLabelsIndexes) {\n db.exec(index.compile().sql);\n }\n\n // shared_object_availability — whether this node can serve an object's bytes\n // right now.\n //\n // Keyed by object key rather than record id: keys are content-addressed, so\n // two records legitimately share one object, and readability is a property of\n // the object. Per-record rows could disagree about one blob.\n //\n // Rows exist only for objects something has told us about; absence means the\n // default (instant). That is what \"maintained, not computed\" buys — a listing\n // costs one batched read instead of a HeadObject per record.\n db.exec(\n qb.schema\n .createTable(\"shared_object_availability\")\n .ifNotExists()\n .addColumn(\"object_storage_key\", \"text\", (c) => c.primaryKey())\n .addColumn(\"state\", \"text\", (c) => c.notNull())\n .addColumn(\"tier\", \"text\")\n .addColumn(\"expected_latency_hours\", \"integer\")\n .addColumn(\"ready_at_ms\", \"integer\")\n .addColumn(\"restored_until_ms\", \"integer\")\n .addColumn(\"observed_at_ms\", \"integer\", (c) => c.notNull())\n .compile().sql,\n );\n\n // shared_app_label_keys — manifest-declared label keys, written by the\n // installer and readable by every app. Cross-app readability is the point:\n // discoverability is why keys are declared in a manifest rather than counted\n // at runtime. Local mirror of DSQL's shared.app_label_keys.\n db.exec(\n qb.schema\n .createTable(\"shared_app_label_keys\")\n .ifNotExists()\n .addColumn(\"app_id\", \"text\", (c) => c.notNull())\n .addColumn(\"key\", \"text\", (c) => c.notNull())\n .addColumn(\"description\", \"text\")\n .addColumn(\"created_at\", \"text\", (c) => c.notNull().defaultTo(sql`(datetime('now'))`))\n .addPrimaryKeyConstraint(\"pk_shared_app_label_keys\", [\"app_id\", \"key\"] as never[])\n .compile().sql,\n );\n\n db.exec(\n qb.schema\n .createTable(\"shared_app_registry\")\n .ifNotExists()\n .addColumn(\"app_id\", \"text\", (c) => c.primaryKey())\n .addColumn(\"name\", \"text\", (c) => c.notNull())\n .addColumn(\"version\", \"text\", (c) => c.notNull())\n .addColumn(\"tier\", \"text\", (c) => c.notNull().defaultTo(\"app\"))\n .addColumn(\"manifest\", \"text\", (c) => c.notNull())\n .addColumn(\"status\", \"text\", (c) => c.notNull().defaultTo(\"installing\"))\n .addColumn(\"hmac_secret\", \"text\", (c) => c.notNull())\n .addColumn(\"installed_at\", \"text\", (c) => c.notNull().defaultTo(sql`(datetime('now'))`))\n .addColumn(\"updated_at\", \"text\", (c) => c.notNull().defaultTo(sql`(datetime('now'))`))\n .compile().sql,\n );\n\n db.exec(\n qb.schema\n .createTable(\"shared_app_install_steps\")\n .ifNotExists()\n .addColumn(\"app_id\", \"text\", (c) => c.notNull())\n .addColumn(\"operation\", \"text\", (c) =>\n c.notNull().check(sql`operation IN ('install', 'uninstall')`),\n )\n .addColumn(\"step\", \"text\", (c) => c.notNull())\n .addColumn(\"status\", \"text\", (c) =>\n c.notNull().check(sql`status IN ('pending', 'done', 'failed')`),\n )\n .addColumn(\"error\", \"text\")\n .addColumn(\"updated_at\", \"text\", (c) => c.notNull().defaultTo(sql`(datetime('now'))`))\n .addPrimaryKeyConstraint(\"pk_shared_app_install_steps\", [\n \"app_id\",\n \"operation\",\n \"step\",\n ] as never[])\n .compile().sql,\n );\n\n // App-specific syncable namespace registry. One row per installed app that\n // declared `infraRequirements.appSpecificSyncable`. Lists the tables the\n // installer materialized as `<app_id>_syncable_<name>` and whether the app\n // opted into the `apps/<app_id>/syncable/` file prefix. Read by the SDK to\n // gate row CRUD/file ops and by the sync engine to enumerate what to sync.\n db.exec(\n qb.schema\n .createTable(\"app_syncable_namespaces\")\n .ifNotExists()\n .addColumn(\"app_id\", \"text\", (c) => c.primaryKey())\n .addColumn(\"tables_json\", \"text\", (c) => c.notNull())\n .addColumn(\"files_enabled\", \"integer\", (c) => c.notNull().defaultTo(0))\n .addColumn(\"created_at\", \"text\", (c) => c.notNull().defaultTo(sql`(datetime('now'))`))\n .compile().sql,\n );\n\n // Per-category metadata tables on parity with DSQL. Generated from CATEGORIES\n // so adding a category or a column is a single edit in @starkeep/protocol-primitives's\n // core-types.ts. `other` has no metadata columns and gets no table.\n for (const c of CATEGORIES) {\n if (!hasMetadataTable(c.id)) continue;\n db.exec(sqliteMetadataDdl(c));\n // Same index as the DSQL side, so a predicate that seeks in the cloud\n // seeks locally too.\n for (const index of metadataIndexDdls(c, \"sqlite\")) db.exec(index.sql);\n }\n}\n\nexport function initializeLocalSchema(db: RawDatabase): void {\n try {\n applyLocalSchemaDdl(db);\n } catch (err) {\n // The DDL above is all `CREATE ... IF NOT EXISTS`, so it is a no-op against\n // an up-to-date DB and cannot fail on a fresh one. In practice the way it\n // DOES fail is a pre-existing DB written before a column was added: the\n // table already exists (so it is not recreated, and never gains the\n // column), and the first statement referencing the new column dies with a\n // bare \"no such column: x\". That message names the symptom, not the cause,\n // and the cause is the fresh-start contract in this file's header. Say so.\n throw new Error(\n `Local schema bootstrap failed: ${(err as Error).message}. This usually ` +\n `means the SQLite DB predates the current schema. There is no ` +\n `migration system by design — delete the DB ($STARKEEP_DIR/data.db, ` +\n `default ~/.starkeep/data.db) and it will be rebuilt on next start.`,\n { cause: err },\n );\n }\n}\n","/**\n * The `boolean` boundary on the SQLite side.\n *\n * SQLite stores a declared `boolean` as an integer, Postgres stores it as a\n * native boolean and returns one, and a row travels the sync wire exactly as\n * its engine returned it. Without a conversion at each engine's own boundary\n * the same logical row reads as `1` from the local server and `true` from the\n * cloud, and the wire form of a boolean would depend on which node happened to\n * send it. This module is what makes the JSON boolean the one app-facing and\n * on-the-wire form of the type.\n *\n * The Postgres counterpart is `pg-timestamps.ts` in `storage-aurora-dsql`,\n * which converts the two types *that* driver hands back in its own shape. Each\n * engine converts exactly what it would otherwise get wrong; neither converts\n * what the other does.\n */\n\n/** A column, as any table description in this system spells one. */\ninterface DeclaredColumn {\n readonly name: string;\n readonly type: string;\n}\n\n/**\n * The names of a table's declared `boolean` columns, or null when it has none.\n *\n * Null rather than an empty set so the caller can skip the row walk entirely,\n * which is most tables.\n */\nexport function booleanColumnNames(\n columns: readonly DeclaredColumn[] | null | undefined,\n): Set<string> | null {\n if (!columns) return null;\n const names = columns.filter((c) => c.type === \"boolean\").map((c) => c.name);\n return names.length > 0 ? new Set(names) : null;\n}\n\n/**\n * The read half of the boolean conversion: `0` and `1` back to `false` and\n * `true`.\n *\n * Applies to every row leaving this engine: query rows, aggregate group keys\n * (the parser forbids an aggregate output from colliding with a column name, so\n * matching by name is unambiguous), and rows bound for the wire.\n */\nexport function fromSqliteRows(\n rows: Record<string, unknown>[],\n booleanColumns: ReadonlySet<string> | null,\n): Record<string, unknown>[] {\n if (!booleanColumns || booleanColumns.size === 0) return rows;\n return rows.map((row) => {\n const out: Record<string, unknown> = { ...row };\n for (const name of booleanColumns) {\n const value = out[name];\n if (typeof value === \"number\") out[name] = value !== 0;\n }\n return out;\n });\n}\n\n/** SQLite's bindable parameter types. */\nexport type SqlParam = null | number | bigint | string | Uint8Array;\n\n/**\n * SQLite binds no booleans.\n *\n * A boolean column's value is normalized to a real boolean before it reaches\n * either engine — by the parser for a predicate, by `validateRow` for a written\n * row — so both engines are handed one thing, and this is where that one thing\n * becomes the integer SQLite stores. Postgres takes the boolean unchanged,\n * which is the whole reason the normalization happens upstream rather than here.\n *\n * Every bind on this connection goes through it, reads and writes alike. A\n * conversion applied to only half the traffic is the bug this replaced.\n */\nexport function toSqliteParam(value: unknown): SqlParam {\n if (typeof value === \"boolean\") return value ? 1 : 0;\n return value as SqlParam;\n}\n","import type { RawDatabase } from \"@starkeep/storage-adapter\";\nimport { compiler as qb } from \"../query-builder.js\";\nimport type {\n AppSyncableNamespace,\n AppSyncableTableInfo,\n AppSyncableNamespaceStore,\n} from \"@starkeep/shared-space-api\";\nimport { parseAppSyncableTables } from \"@starkeep/shared-space-api\";\n\nexport type { AppSyncableNamespace, AppSyncableTableInfo };\n\n// `<appId>_syncable_<table>` is what the manifest convention pins, but appIds\n// may contain dashes (e.g. \"cloud-data-server\") which aren't legal SQLite\n// identifiers. Normalize the same way as cloud-side PG roles.\nfunction normalizeAppId(appId: string): string {\n return appId.toLowerCase().replace(/-/g, \"_\");\n}\n\nexport function appSyncableTableName(appId: string, tableName: string): string {\n return `${normalizeAppId(appId)}_syncable_${tableName}`;\n}\n\nfunction rowToNamespace(r: {\n app_id: string;\n tables_json: string;\n files_enabled: number;\n}): AppSyncableNamespace {\n const tables = parseAppSyncableTables(r.app_id, r.tables_json);\n return {\n appId: r.app_id,\n tables,\n filesEnabled: r.files_enabled === 1,\n tableNames: tables.map((t) => t.name),\n };\n}\n\nexport function upsertAppSyncableNamespace(\n db: RawDatabase,\n appId: string,\n tables: AppSyncableTableInfo[],\n filesEnabled: boolean,\n): void {\n const query = qb\n .insertInto(\"app_syncable_namespaces\")\n .values({\n app_id: appId,\n tables_json: JSON.stringify(tables),\n files_enabled: filesEnabled ? 1 : 0,\n })\n .onConflict((oc) =>\n oc.column(\"app_id\").doUpdateSet((eb) => ({\n tables_json: eb.ref(\"excluded.tables_json\"),\n files_enabled: eb.ref(\"excluded.files_enabled\"),\n })),\n )\n .compile();\n db.prepare(query.sql).run(...(query.parameters as (string | number)[]));\n}\n\nexport function deleteAppSyncableNamespace(db: RawDatabase, appId: string): void {\n const query = qb.deleteFrom(\"app_syncable_namespaces\").where(\"app_id\", \"=\", appId).compile();\n db.prepare(query.sql).run(...(query.parameters as string[]));\n}\n\nexport function getAppSyncableNamespace(\n db: RawDatabase,\n appId: string,\n): AppSyncableNamespace | null {\n const query = qb\n .selectFrom(\"app_syncable_namespaces\")\n .select([\"app_id\", \"tables_json\", \"files_enabled\"])\n .where(\"app_id\", \"=\", appId)\n .compile();\n const row = db.prepare(query.sql).get(...(query.parameters as string[])) as\n | { app_id: string; tables_json: string; files_enabled: number }\n | undefined;\n if (!row) return null;\n return rowToNamespace(row);\n}\n\nexport function listAppSyncableNamespaces(db: RawDatabase): AppSyncableNamespace[] {\n const query = qb\n .selectFrom(\"app_syncable_namespaces\")\n .select([\"app_id\", \"tables_json\", \"files_enabled\"])\n .compile();\n const rows = db.prepare(query.sql).all() as Array<{\n app_id: string;\n tables_json: string;\n files_enabled: number;\n }>;\n return rows.map(rowToNamespace);\n}\n\n/**\n * Object-oriented wrapper over the free functions above — implements the\n * `AppSyncableNamespaceStore` interface required by `createAppSpecificFactory`\n * and the sync applier.\n */\nexport class SqliteAppSyncableNamespaceStore implements AppSyncableNamespaceStore {\n constructor(private readonly db: RawDatabase) {}\n\n get(appId: string): AppSyncableNamespace | null {\n return getAppSyncableNamespace(this.db, appId);\n }\n\n list(): AppSyncableNamespace[] {\n return listAppSyncableNamespaces(this.db);\n }\n}\n","import type { RawDatabase } from \"@starkeep/storage-adapter\";\nimport { sql, type CompiledQuery } from \"kysely\";\nimport type { HLCTimestamp } from \"@starkeep/protocol-primitives\";\nimport { serializeHLC, deserializeHLC } from \"@starkeep/protocol-primitives\";\nimport type {\n AppSyncableApplier,\n AppSyncableRowEntry,\n AppSyncableNamespaceStore,\n ScanCapableApplier,\n ScanSincePage,\n} from \"@starkeep/shared-space-api\";\nimport {\n buildAppAggregateQuery,\n buildAppRowQuery,\n collectAggregatePage,\n collectRowPage,\n SQLITE_APP_QUERY_DIALECT,\n type BuildOptions,\n type ParsedQuery,\n type ParsedQueryResult,\n buildBucketDigest,\n buildNodeWatermarks,\n buildScanSinceForNode,\n collectSince,\n planNodeScans,\n requireKeyedWhere,\n rowToWireEntry,\n toDigestBuckets,\n DEFAULT_BUCKET_PREFIX_LENGTH,\n type DigestBucket,\n} from \"@starkeep/storage-adapter\";\nimport { compiler as qb } from \"../query-builder.js\";\nimport { appSyncableTableName } from \"./namespace.js\";\nimport { booleanColumnNames, fromSqliteRows, toSqliteParam } from \"../row-values.js\";\n\n// Both go through `toSqliteParam` for the reason the read path does: SQLite\n// binds no boolean, and a declared `boolean` column reaches here as one from\n// either writer — an app's own write, normalized by `validateRow`, or a peer's\n// row off the sync wire, which Postgres returns as a real boolean. The casts\n// these two used to carry admitted a boolean and left the driver to reject it.\nfunction runCompiled(db: RawDatabase, compiled: CompiledQuery): void {\n db.prepare(compiled.sql).run(...compiled.parameters.map(toSqliteParam));\n}\n\nfunction allCompiled<T>(db: RawDatabase, compiled: CompiledQuery): T[] {\n return db.prepare(compiled.sql).all(...compiled.parameters.map(toSqliteParam)) as T[];\n}\n\n/**\n * SQLite-backed implementation of `AppSyncableApplier`.\n *\n * All writes use the LWW (last-write-wins) rule based on the HLC-serialized\n * `updated_at` column: an incoming entry is only applied if its timestamp is\n * strictly greater than the row's current `updated_at`. This makes the applier\n * idempotent — replaying the same entry twice is a no-op.\n *\n * Delete is soft: the `deleted_at` column is set rather than removing the row\n * so that the inline-HLC pull path can propagate tombstones to other clients.\n */\nexport class SqliteAppSyncableApplier implements AppSyncableApplier, ScanCapableApplier {\n constructor(\n private readonly db: RawDatabase,\n private readonly namespace: AppSyncableNamespaceStore,\n ) {}\n\n apply(entry: AppSyncableRowEntry): void {\n const ns = this.namespace.get(entry.appId);\n if (!ns) {\n throw new Error(`SqliteAppSyncableApplier: app \"${entry.appId}\" not installed`);\n }\n const tableInfo = ns.tables.find((t) => t.name === entry.table);\n if (!tableInfo) {\n throw new Error(\n `SqliteAppSyncableApplier: table \"${entry.table}\" not declared for app \"${entry.appId}\"`,\n );\n }\n\n const fullName = appSyncableTableName(entry.appId, entry.table);\n const { pkColumns } = tableInfo;\n\n if (entry.op === \"insert\") {\n this.applyInsert(fullName, pkColumns, entry);\n } else if (entry.op === \"update\") {\n this.applyUpdate(fullName, pkColumns, entry);\n } else {\n this.applyDelete(fullName, pkColumns, entry);\n }\n }\n\n private applyInsert(fullName: string, pkColumns: string[], entry: AppSyncableRowEntry): void {\n const row = withNodeId(entry.row ?? {}, entry);\n const cols = Object.keys(row);\n if (cols.length === 0) return;\n\n const updateCols = cols.filter((c) => !pkColumns.includes(c));\n if (pkColumns.length === 0 || updateCols.length === 0) {\n // No PK declared (or nothing beyond it) — just insert, ignoring duplicates.\n runCompiled(\n this.db,\n qb\n .insertInto(fullName)\n .orIgnore()\n .values({ ...row })\n .compile(),\n );\n return;\n }\n\n // UPSERT with LWW: only overwrite if the incoming updated_at is newer.\n runCompiled(\n this.db,\n qb\n .insertInto(fullName)\n .values({ ...row })\n .onConflict((oc) =>\n oc\n .columns(pkColumns as never[])\n .doUpdateSet((eb) =>\n Object.fromEntries(updateCols.map((c) => [c, eb.ref(`excluded.${c}`)])),\n )\n .where(sql.ref(\"excluded.updated_at\"), \">\", sql.ref(`${fullName}.updated_at`)),\n )\n .compile(),\n );\n }\n\n private applyUpdate(\n fullName: string,\n pkColumns: readonly string[],\n entry: AppSyncableRowEntry,\n ): void {\n // node_id rides along whenever updated_at changes (it's derived from it).\n const rawPatch = entry.row ?? {};\n const patch = rawPatch[\"updated_at\"] ? withNodeId(rawPatch, entry) : rawPatch;\n const where = requireKeyedWhere(entry, \"update\", pkColumns);\n const patchCols = Object.keys(patch);\n const whereCols = Object.keys(where);\n if (patchCols.length === 0) return;\n\n // Only apply if the incoming updated_at is strictly newer (LWW).\n const incomingUpdatedAt = patch[\"updated_at\"] as string | undefined;\n let query = qb.updateTable(fullName).set({ ...patch });\n for (const c of whereCols) {\n query = query.where(c, \"=\", where[c]);\n }\n if (incomingUpdatedAt) {\n // `updated_at IS NULL OR updated_at < ?`, matching `applyDelete`. A bare\n // `<` is unknown against NULL, so a row with no position silently refused\n // every update while accepting every tombstone — the two halves of the\n // same LWW rule disagreeing about what \"older than everything\" means.\n // The column is NOT NULL wherever the installer created the table, which\n // is exactly why the inconsistency could sit here unnoticed.\n query = query.where((eb) =>\n eb.or([eb(\"updated_at\", \"is\", null), eb(\"updated_at\", \"<\", incomingUpdatedAt)]),\n );\n }\n runCompiled(this.db, query.compile());\n }\n\n private applyDelete(\n fullName: string,\n pkColumns: readonly string[],\n entry: AppSyncableRowEntry,\n ): void {\n const where = requireKeyedWhere(entry, \"delete\", pkColumns);\n const whereCols = Object.keys(where);\n // Soft-delete: set deleted_at and updated_at (and node_id with it).\n const incomingUpdatedAt = entry.row?.[\"updated_at\"] as string | undefined;\n const ts = incomingUpdatedAt ?? serializeHLC(entry.timestamp);\n\n // A tombstone that arrived over sync carries the whole row (see\n // `rowToWireEntry`), and it has to *land* even on a node that never held\n // the row it retracts.\n //\n // As an UPDATE alone it did not: the statement matched nothing and the\n // deletion evaporated. Both sides then held different numbers of rows for\n // the same author bucket — tombstones are counted, deliberately, because a\n // deletion is a row the peer must also hold — so `verify()` reported a\n // permanent hole, armed a repair, and the repair re-shipped the same\n // tombstone into the same nothing. Forever. The nodes that hit it are\n // exactly the ones repair exists for: one that joined after the delete, or\n // one that lost the row and is being filled back in.\n //\n // Upserting is safe precisely because the wire form carries every column,\n // so nothing has to be invented for a NOT NULL the app declared. A delete\n // issued locally through the API carries only its key and its timestamp,\n // and that one still goes through the UPDATE below — the row is here by\n // construction, and inventing a half-empty row for it would be wrong.\n const carriesFullRow =\n entry.row !== undefined &&\n pkColumns.length > 0 &&\n pkColumns.every((column) => entry.row?.[column] !== undefined);\n if (carriesFullRow) {\n const row = withNodeId({ ...entry.row, updated_at: ts, deleted_at: ts }, entry);\n const updateCols = Object.keys(row).filter((c) => !pkColumns.includes(c));\n runCompiled(\n this.db,\n qb\n .insertInto(fullName)\n .values({ ...row })\n .onConflict((oc) =>\n oc\n .columns(pkColumns as never[])\n .doUpdateSet((eb) =>\n Object.fromEntries(updateCols.map((c) => [c, eb.ref(`excluded.${c}`)])),\n )\n // The same LWW guard the UPDATE path carries, and for the same\n // reason: a replayed tombstone must not move a newer row back.\n .where(sql.ref(\"excluded.updated_at\"), \">\", sql.ref(`${fullName}.updated_at`)),\n )\n .compile(),\n );\n return;\n }\n\n let query = qb\n .updateTable(fullName)\n .set({ deleted_at: ts, updated_at: ts, node_id: nodeIdOf(ts, entry) });\n for (const c of whereCols) {\n query = query.where(c, \"=\", where[c]);\n }\n // LWW guard: tombstone only rows the incoming timestamp supersedes.\n query = query.where((eb) => eb.or([eb(\"updated_at\", \"is\", null), eb(\"updated_at\", \"<\", ts)]));\n runCompiled(this.db, query.compile());\n }\n\n /**\n * Whether this table exists in *this* database.\n *\n * Asked before the digest rather than inferred from a failed read, because\n * those are two different answers and only one of them is `[]`. An app that\n * is not installed here genuinely holds nothing; a table that is locked,\n * corrupt or unreadable holds an unknown number of rows, and reporting zero\n * for it is the loudest possible false alarm — every bucket in it reads as a\n * hole, in whichever direction the comparison runs.\n *\n * `sqlite_master` is the cheapest question that separates them, and asking it\n * cannot itself fail for a reason worth swallowing: a database whose schema\n * table will not read is not one whose app tables are merely absent.\n */\n private tableExists(fullName: string): boolean {\n const row = this.db\n .prepare(`SELECT name FROM sqlite_master WHERE type = 'table' AND name = ?`)\n .all(fullName);\n return row.length > 0;\n }\n\n /**\n * See `ScanCapableApplier.bucketDigest`. Missing table → `[]`; a table that\n * exists and will not read **throws**, so the caller's `supported: false`\n * path can do its job.\n *\n * This used to be `try { … } catch { return [] }`, which is the same mistake\n * `scanSince` made: `[]` is the wire value for \"this table holds nothing\", not\n * for \"I could not count it\". It made both engine-side \"could not count ⇒\n * supported: false\" guards unreachable on every production path, because no\n * real applier ever threw.\n */\n async bucketDigest(\n appId: string,\n table: string,\n prefixLength: number = DEFAULT_BUCKET_PREFIX_LENGTH,\n ): Promise<DigestBucket[]> {\n const fullName = appSyncableTableName(appId, table);\n if (!this.tableExists(fullName)) return [];\n const compiled = buildBucketDigest(qb, fullName, prefixLength);\n return toDigestBuckets(allCompiled<Record<string, unknown>>(this.db, compiled));\n }\n\n /**\n * See `ScanCapableApplier.getNodeWatermarks`. Missing table → `{}`; a table\n * that exists and will not read **throws**.\n *\n * The distinction matters more here than the `{}` return suggests, because\n * `scanSince` plans its authors from this map: an unreadable table that\n * answered `{}` produced no scans, and the scan then reported \"nothing owed,\n * every author complete\" — the exact silent-loss shape `scanSince`'s own catch\n * was written to prevent, reached one frame earlier.\n */\n async getNodeWatermarks(appId: string, table: string): Promise<Record<string, HLCTimestamp>> {\n const fullName = appSyncableTableName(appId, table);\n // Table might not exist yet (app not installed locally).\n if (!this.tableExists(fullName)) return {};\n const rows = allCompiled<{ node_id: string; max_updated_at: string }>(\n this.db,\n buildNodeWatermarks(qb, fullName),\n );\n const out: Record<string, HLCTimestamp> = {};\n for (const row of rows) {\n out[row.node_id] = deserializeHLC(row.max_updated_at);\n }\n return out;\n }\n\n /**\n * Pull-side synthesis: rows the peer hasn't seen, per author, seeking the\n * `(node_id, updated_at)` index rather than reading the table and filtering.\n * See `ScanCapableApplier.scanSince` for the contract and\n * `storage-adapter/src/database/since-queries.ts` for why it is a loop.\n */\n async scanSince(\n appId: string,\n table: string,\n peerWatermarks: Record<string, HLCTimestamp>,\n limit: number,\n ): Promise<ScanSincePage> {\n const fullName = appSyncableTableName(appId, table);\n // A missing table (app not installed locally) reads as \"nothing owed\"\n // rather than an error, the same fail-safe direction getNodeWatermarks\n // takes: understating only causes a re-ship. That case is settled *here*,\n // by getNodeWatermarks returning {} so no author is planned — which is why\n // nothing below needs a catch for it.\n const scans = planNodeScans(await this.getNodeWatermarks(appId, table), peerWatermarks);\n const pkColumns =\n this.namespace.get(appId)?.tables.find((t) => t.name === table)?.pkColumns ?? [];\n try {\n const { rows, hasMore, truncated } = await collectSince<Record<string, unknown>>(\n scans,\n limit,\n async (scan, remaining) => {\n const compiled = buildScanSinceForNode(qb, fullName, scan, remaining);\n return allCompiled<Record<string, unknown>>(this.db, compiled);\n },\n (row) => deserializeHLC(row[\"updated_at\"] as string),\n );\n return {\n // Converted before the row becomes a wire entry: what goes on the wire\n // is what the app sees, and a peer's applier binds a boolean it can.\n rows: fromSqliteRows(rows, this.booleanColumnsOf(appId, table))\n .map((row) => rowToWireEntry(appId, table, row, pkColumns, deserializeHLC))\n .filter((entry): entry is AppSyncableRowEntry => entry !== null),\n hasMore,\n truncated,\n };\n } catch (err) {\n // A read that failed part-way has enumerated *nothing it can vouch for*,\n // and `truncated: {}` is the wire value for the opposite — \"every author\n // complete, no ceiling\". Returning that lets the round ship rows whose\n // HLCs sit above the ones this scan never reached, which is the exact\n // silent-loss shape `round-cut.ts` exists to prevent.\n //\n // So every planned author gets a `null` ceiling: nothing is safe to ship\n // for any of them, and `hasMore` asks for the round to be retried.\n console.warn(\n `[app-syncable] scanSince failed for ${appId}.${table}: ${(err as Error).message}`,\n );\n const truncated: Record<string, HLCTimestamp | null> = {};\n for (const scan of scans) truncated[scan.nodeId] = null;\n return { rows: [], hasMore: true, truncated };\n }\n }\n\n /**\n * Run a parsed query. The read half of the app-data plane.\n *\n * Compiled by the shared builder rather than here, so the SQL this emits and\n * the SQL the DSQL applier emits are one piece of code — the two hand-written\n * read grammars this replaces had already drifted on their limit defaults\n * alone.\n */\n async runQuery(\n appId: string,\n table: string,\n query: ParsedQuery,\n options: BuildOptions = {},\n ): Promise<ParsedQueryResult> {\n const fullName = appSyncableTableName(appId, table);\n\n const booleanColumns = this.booleanColumnsOf(appId, table);\n\n if (query.mode === \"aggregate\") {\n const compiled = buildAppAggregateQuery(\n qb,\n fullName,\n query,\n SQLITE_APP_QUERY_DIALECT,\n options,\n );\n return collectAggregatePage(query, fromSqliteRows(this.selectRows(compiled), booleanColumns));\n }\n\n const compiled = buildAppRowQuery(qb, fullName, query, options);\n // `node:sqlite` has no streaming cursor, so the fetch budget is applied\n // over an array rather than over an iterator here. The row limit bounds what\n // that array can hold, and the response budget engages only on pathological\n // rows — so what is given up is that a page of 1 MiB text values is\n // materialized before being cut, on a server running on the operator's own\n // machine.\n // Converted before the page is collected rather than after, so the token\n // and the rows are computed from one representation.\n return collectRowPage(query, fromSqliteRows(this.selectRows(compiled), booleanColumns));\n }\n\n /** The names of a declared table's `boolean` columns, or null when it has none. */\n private booleanColumnsOf(appId: string, table: string): Set<string> | null {\n return booleanColumnNames(\n this.namespace.get(appId)?.tables.find((t) => t.name === table)?.columns,\n );\n }\n\n /** Bind and run a compiled SELECT, adapting values SQLite cannot bind. */\n private selectRows(compiled: CompiledQuery): Record<string, unknown>[] {\n return this.db.prepare(compiled.sql).all(...compiled.parameters.map(toSqliteParam)) as Record<\n string,\n unknown\n >[];\n }\n}\n\n/**\n * Return `row` with `node_id` set from its `updated_at` (falling back to the\n * entry timestamp). Writers can't be trusted to carry the column — locally\n * authored entries and older wire rows don't — so the applier derives it at\n * write time, keeping the NOT NULL invariant without touching every producer.\n */\nfunction withNodeId(\n row: Record<string, unknown>,\n entry: AppSyncableRowEntry,\n): Record<string, unknown> {\n return { ...row, node_id: nodeIdOf(row[\"updated_at\"], entry) };\n}\n\n/** nodeId from a serialized-HLC `updated_at`, or the entry timestamp's. */\nfunction nodeIdOf(updatedAt: unknown, entry: AppSyncableRowEntry): string {\n if (typeof updatedAt === \"string\") {\n try {\n return deserializeHLC(updatedAt).nodeId;\n } catch {\n // Not a serialized HLC — fall through to the entry timestamp.\n }\n }\n return entry.timestamp.nodeId;\n}\n\n// The wire-entry shape is shared with the DSQL applier — see\n// `storage-adapter/src/database/app-syncable-rows.ts`. It was duplicated here,\n// and both copies emitted keyless tombstones.\n","import type { RawDatabase } from \"@starkeep/storage-adapter\";\nimport { sql } from \"kysely\";\nimport {\n FILE_RECORDS_COLUMNS,\n FILE_RECORDS_TABLE,\n FILE_RECORDS_TABLE_INFO,\n appSyncableTableInfo,\n syncableIndexName,\n type AppSyncableTableInfo,\n type DeclaredColumn,\n} from \"@starkeep/shared-space-api\";\nimport { sqliteColumnType } from \"@starkeep/protocol-primitives\";\nimport { compiler as k } from \"../query-builder.js\";\nimport { appSyncableTableName, upsertAppSyncableNamespace } from \"./namespace.js\";\n\n/**\n * One syncable table as an app's manifest declares it: the structural shape of\n * admin-manifest's `SyncableTable`, so this package needs no manifest schema\n * and a phone can pass the block straight from the manifest JSON.\n */\nexport interface SyncableTableDeclaration {\n readonly name: string;\n readonly columns: readonly DeclaredColumn[];\n readonly indexes?: readonly { readonly columns: readonly string[] }[];\n}\n\n/** A manifest's `infraRequirements.appSpecificSyncable` block. */\nexport interface AppSyncableDeclaration {\n readonly tables: readonly SyncableTableDeclaration[];\n readonly files?: boolean;\n}\n\ninterface SyncableColumnDef {\n name: string;\n /** The emitted SQL type, from `sqliteColumnType`. */\n type: string;\n notNull: boolean;\n primaryKey: boolean;\n /**\n * True when the app declared this column `boolean`.\n *\n * `sqliteColumnType` maps `boolean` onto INTEGER, since SQLite has no\n * boolean type, and the physical type is all the rest of this shape needs.\n * The domain constraint does need the distinction, so it is carried\n * separately rather than recovered by guessing which integers are flags.\n */\n boolean?: boolean;\n}\n\n/**\n * Emits the CREATE TABLE / CREATE INDEX statements shared by manifest-declared\n * syncable tables and the reserved file-records table. updated_at, node_id\n * (denormalized from updated_at by the applier) and deleted_at are reserved by\n * the sync runtime for inline-HLC change tracking; they are appended\n * automatically and must not be declared in the manifest. (node_id, updated_at)\n * backs the responder's per-node coverage watermark query.\n */\nfunction createSyncableTable(\n db: RawDatabase,\n fullName: string,\n columns: SyncableColumnDef[],\n indexes: readonly { readonly columns: readonly string[] }[] = [],\n): void {\n let tb = k.schema.createTable(fullName).ifNotExists();\n for (const c of columns) {\n tb = tb.addColumn(c.name, sql.raw(c.type), (col) => {\n const withNull = c.notNull || c.primaryKey ? col.notNull() : col;\n // A declared `boolean` is physically an INTEGER here, so nothing but this\n // holds it to 0 and 1. The platform's own write path already checks the\n // value, but the sync-apply path does not: a wire row goes straight to the\n // applier, so a peer running different code can put anything in the\n // column. DSQL needs no equivalent — its native `boolean` *is* the domain\n // — and DSQL could not gain one later anyway, since it rejects\n // `ALTER TABLE ADD CONSTRAINT` (probed 2026-09-10).\n return c.boolean ? withNull.check(sql`${sql.ref(c.name)} in (0, 1)`) : withNull;\n });\n }\n tb = tb\n .addColumn(\"updated_at\", \"text\", (col) => col.notNull())\n .addColumn(\"node_id\", \"text\", (col) => col.notNull())\n .addColumn(\"deleted_at\", \"text\");\n // `syncableTableSchema` refuses a table with no primary key\n // (`admin-manifest/src/schema.ts`), so this branch is now unreachable through\n // any manifest-driven install. It stays because a table created without a\n // constraint is *silently* wrong rather than loudly wrong: the applier's\n // UPSERT would have nothing to conflict on, so every replay of a wire entry —\n // a repair round, a re-ship after a lost response, a watermark reset —\n // inserts the row again, and a tombstone could never name the row it retracts.\n const pks = columns.filter((c) => c.primaryKey).map((c) => c.name);\n if (pks.length > 0) {\n tb = tb.addPrimaryKeyConstraint(`pk_${fullName}`, pks as never[]);\n }\n db.exec(tb.compile().sql);\n db.exec(\n k.schema\n .createIndex(`idx_${fullName}_updated_at`)\n .ifNotExists()\n .on(fullName)\n .column(\"updated_at\")\n .compile().sql,\n );\n db.exec(\n k.schema\n .createIndex(`idx_${fullName}_node_watermark`)\n .ifNotExists()\n .on(fullName)\n .columns([\"node_id\", \"updated_at\"])\n .compile().sql,\n );\n // App-declared indexes. The query grammar makes an expensive question cheap\n // to ask; these are what make it cheap to answer, and without a matching one\n // a new filter or a grouped count is a full scan.\n //\n // Named the same way the DSQL side names them, so the two backends carry the\n // same index under the same name and a reader comparing them is comparing\n // like with like.\n for (const index of indexes) {\n db.exec(\n k.schema\n .createIndex(syncableIndexName(fullName, [...index.columns]))\n .ifNotExists()\n .on(fullName)\n .columns([...index.columns])\n .compile().sql,\n );\n }\n}\n\nexport function createAppSyncableTables(\n db: RawDatabase,\n appId: string,\n tables: readonly SyncableTableDeclaration[],\n): void {\n for (const table of tables) {\n createSyncableTable(\n db,\n appSyncableTableName(appId, table.name),\n table.columns.map((c) => ({\n name: c.name,\n type: sqliteColumnType(c.type),\n notNull: Boolean(c.notNull),\n primaryKey: Boolean(c.primaryKey),\n boolean: c.type === \"boolean\",\n })),\n table.indexes,\n );\n }\n}\n\n/**\n * Create the framework-owned `_starkeep_sync_records` table for an app that\n * opted into `filesEnabled`. Same column shape as the manifest-declared\n * syncable tables (plus the standard updated_at/deleted_at HLC columns) so\n * the LWW applier can treat it uniformly.\n */\nexport function createReservedFileRecordsTable(db: RawDatabase, appId: string): void {\n createSyncableTable(\n db,\n appSyncableTableName(appId, FILE_RECORDS_TABLE),\n // Through the one mapping, like `createAppSyncableTables` above. This was a\n // hand-written ternary whose Postgres twin in `dsql-ddl.ts` answered\n // `bigint` where this one answered `integer`, for one declared type.\n FILE_RECORDS_COLUMNS.map((c) => ({\n name: c.name,\n type: sqliteColumnType(c.type),\n notNull: Boolean(c.notNull),\n primaryKey: Boolean(c.primaryKey),\n })),\n );\n}\n\n/**\n * The namespace registry's description of an app's tables: the declared ones,\n * plus the reserved file-records table when files are enabled. Derived from\n * the declaration rather than read back from SQLite, because a declared type\n * is not recoverable from a physical column, and it runs in the data server,\n * which never sees a manifest.\n */\nexport function appSyncableNamespaceTables(\n syncable: AppSyncableDeclaration,\n): AppSyncableTableInfo[] {\n const declared = syncable.tables.map((t) => appSyncableTableInfo(t.name, t.columns));\n return syncable.files ? [...declared, FILE_RECORDS_TABLE_INFO] : declared;\n}\n\n/**\n * Create an app's syncable tables and register its namespace, from its\n * manifest's `appSpecificSyncable` block. Idempotent, so a node may run it on\n * every start.\n *\n * The desktop's local installer runs the same two halves as separate ledger\n * steps; a node that holds an app's private data without installing the app,\n * as Photos Mobile does, calls this once at bring-up. Both therefore create\n * identical tables.\n */\nexport function registerAppSyncableNamespace(\n db: RawDatabase,\n appId: string,\n syncable: AppSyncableDeclaration,\n): void {\n createAppSyncableTables(db, appId, syncable.tables);\n if (syncable.files) createReservedFileRecordsTable(db, appId);\n upsertAppSyncableNamespace(\n db,\n appId,\n appSyncableNamespaceTables(syncable),\n syncable.files === true,\n );\n}\n","/**\n * Which user a node's library belongs to, and the database half of binding it.\n *\n * One node serves one cloud user. Every object key carries its owner's segment\n * (`shared/<userId>/...`, `apps/<appId>/<userId>/syncable/...`), and a library\n * no cloud has bound yet writes under `LOCAL_USER_SEGMENT`. The first time the\n * node signs in, the ID token's `sub` names the user, and binding renames the\n * `local` segment to that user's id before the first sync:\n * on disk, which each host does its own way, and in every stored key, which\n * this file does for every host. After that, a cloud that names a different\n * user stops sync rather than mixing two users' data.\n *\n * ## The order a host binds in\n *\n * 1. {@link checkLibraryBindable}, which refuses a library bound elsewhere.\n * 2. Move the files under `local` to the user's segment.\n * 3. {@link commitLibraryBinding}, which rewrites the stored keys and stores\n * the user last, in one transaction.\n *\n * A crash part-way leaves the library unbound, so the next start runs the\n * pass again. Every step is idempotent: a file move merges into one already\n * made, and the key rewrites match only keys that still carry `local`.\n *\n * ## The sweep\n *\n * The pass also runs for a library already bound to the same user. A write\n * that built its key under `local` before the pass and landed after it is\n * moved and rewritten by the next pass.\n *\n * See `~/projects/starkeep/plan-multi-user-roles-2026-10-16.md`, step 4.9.\n */\n\nimport { sql } from \"kysely\";\nimport type { RawDatabase } from \"@starkeep/storage-adapter\";\nimport { LOCAL_USER_SEGMENT, USER_SEGMENT_PATTERN } from \"@starkeep/protocol-primitives\";\nimport { compiler as qb } from \"./query-builder.js\";\n\nconst OWNER_TABLE = \"library_owner\";\n\nfunction ensureOwnerTable(db: RawDatabase): void {\n db.exec(\n qb.schema\n .createTable(OWNER_TABLE)\n .ifNotExists()\n .addColumn(\"id\", \"integer\", (c) => c.primaryKey())\n .addColumn(\"user_id\", \"text\", (c) => c.notNull())\n .compile().sql,\n );\n}\n\n/** The user this library is bound to, or null while unbound. */\nexport function boundUserId(db: RawDatabase): string | null {\n ensureOwnerTable(db);\n const row = db\n .prepare(\n qb.selectFrom(OWNER_TABLE).select(\"user_id\").where(\"id\", \"=\", sql.lit(0)).compile().sql,\n )\n .get() as { user_id: string } | undefined;\n return row?.user_id ?? null;\n}\n\n/** The segment this library writes keys under: its bound user, or `local`. */\nexport function libraryUserSegment(db: RawDatabase): string {\n return boundUserId(db) ?? LOCAL_USER_SEGMENT;\n}\n\n/** A column that can hold a `local` key. */\nexport interface LibraryKeyColumn {\n readonly table: string;\n readonly column: string;\n /** Whether the column is the table's primary key, so a rewrite can collide. */\n readonly primaryKey: boolean;\n}\n\n/**\n * The key columns every SQLite node has: records, availability, the resident\n * set, and each app's file index, which stores the full key as its row id.\n * Only the tables this database holds.\n */\nexport function libraryKeyColumns(db: RawDatabase): LibraryKeyColumn[] {\n return coreKeyColumns(db).filter(({ table }) => tableExists(db, table));\n}\n\nfunction coreKeyColumns(db: RawDatabase): LibraryKeyColumn[] {\n const columns: LibraryKeyColumn[] = [\n { table: \"shared_records\", column: \"object_storage_key\", primaryKey: false },\n { table: \"shared_object_availability\", column: \"object_storage_key\", primaryKey: true },\n { table: \"resident_keys\", column: \"object_storage_key\", primaryKey: true },\n { table: \"resident_keys\", column: \"record_id\", primaryKey: false },\n ];\n const tables = db\n .prepare(\n qb.selectFrom(\"sqlite_master\").select(\"name\").where(\"type\", \"=\", sql.lit(\"table\")).compile()\n .sql,\n )\n .all() as Array<{ name: string }>;\n for (const { name } of tables) {\n if (name.endsWith(\"__starkeep_sync_records\")) {\n columns.push(\n { table: name, column: \"id\", primaryKey: true },\n { table: name, column: \"object_storage_key\", primaryKey: false },\n );\n }\n }\n return columns;\n}\n\nfunction tableExists(db: RawDatabase, table: string): boolean {\n return (\n db\n .prepare(\n qb\n .selectFrom(\"sqlite_master\")\n .select(\"name\")\n .where(\"type\", \"=\", sql.lit(\"table\"))\n .where(\"name\", \"=\", sql.lit(table))\n .compile().sql,\n )\n .get() !== undefined\n );\n}\n\n/**\n * The two key namespaces, each as the pattern a `local` key matches and the\n * same key under `userId`.\n */\nfunction namespaces(column: string, userId: string) {\n return [\n {\n local: sql.lit(`shared/${LOCAL_USER_SEGMENT}/%`),\n // Keeps the slash after `local`, so `shared/local/x` becomes `shared/<userId>/x`.\n rebound: sql<string>`'shared/' || ${sql.lit(userId)} || substr(${sql.ref(column)}, ${sql.lit(`shared/${LOCAL_USER_SEGMENT}`.length + 1)})`,\n },\n // apps/<appId>/local/syncable/... — the app id is the segment before `local`.\n {\n local: sql.lit(`apps/%/${LOCAL_USER_SEGMENT}/syncable/%`),\n rebound: sql<string>`replace(${sql.ref(column)}, ${sql.lit(`/${LOCAL_USER_SEGMENT}/syncable/`)}, ${sql.lit(`/${userId}/syncable/`)})`,\n },\n ];\n}\n\n/**\n * Rewrite one key column from the `local` segment to `userId`, in both key\n * namespaces. Keys without the `local` segment are untouched. In a primary-key\n * column, a `local` row whose rewritten key already exists is a duplicate a\n * sweep found, and is dropped: the same key names the same object.\n */\nfunction rebindColumn(\n db: RawDatabase,\n { table, column, primaryKey }: LibraryKeyColumn,\n userId: string,\n): number {\n let changed = 0;\n for (const { local, rebound } of namespaces(column, userId)) {\n if (primaryKey) {\n const duplicates = qb\n .deleteFrom(table)\n .where(sql.ref(column), \"like\", local)\n .where(\n sql<boolean>`${rebound} in (${qb.selectFrom(table).select(sql.ref(column).as(\"k\"))})`,\n )\n .compile();\n db.prepare(duplicates.sql).run(...duplicates.parameters);\n }\n const update = qb\n .updateTable(table)\n .set({ [column]: rebound })\n .where(sql.ref(column), \"like\", local)\n .compile();\n const result = db.prepare(update.sql).run(...update.parameters) as {\n changes?: number | bigint;\n };\n changed += Number(result.changes ?? 0);\n }\n return changed;\n}\n\n/** The cloud names a different user than the one this library belongs to. */\nexport class LibraryBoundElsewhereError extends Error {\n constructor(\n readonly boundTo: string,\n readonly cloudSays: string,\n ) {\n super(\n `This library belongs to user ${boundTo}, but the cloud says this device syncs for user ${cloudSays}. ` +\n `Sync stays off so the two libraries do not mix.`,\n );\n this.name = \"LibraryBoundElsewhereError\";\n }\n}\n\n/**\n * Refuse to bind the library to `userId` when it cannot be: the id is not a\n * user segment, or the library belongs to someone else. Runs before a host\n * moves any file.\n */\nexport function checkLibraryBindable(db: RawDatabase, userId: string): void {\n if (!USER_SEGMENT_PATTERN.test(userId) || userId === LOCAL_USER_SEGMENT) {\n throw new Error(`cannot bind the library to ${JSON.stringify(userId)}`);\n }\n const current = boundUserId(db);\n if (current !== null && current !== userId) throw new LibraryBoundElsewhereError(current, userId);\n}\n\n/**\n * Rewrite every stored key from `local` to `userId`, then store the user, in\n * one transaction. A host passes the key columns of its own tables in\n * `extraKeyColumns`. Returns how many keys changed.\n */\nexport function commitLibraryBinding(\n db: RawDatabase,\n userId: string,\n extraKeyColumns: readonly LibraryKeyColumn[] = [],\n): number {\n checkLibraryBindable(db, userId);\n const columns = [...coreKeyColumns(db), ...extraKeyColumns].filter(({ table }) =>\n tableExists(db, table),\n );\n let rewritten = 0;\n db.exec(\"BEGIN\");\n try {\n for (const column of columns) rewritten += rebindColumn(db, column, userId);\n db.prepare(\n qb\n .insertInto(OWNER_TABLE)\n .values({ id: sql.lit(0), user_id: sql.raw(\"?\") })\n .onConflict((oc) =>\n oc.column(\"id\").doUpdateSet((eb) => ({ user_id: eb.ref(\"excluded.user_id\") })),\n )\n .compile().sql,\n ).run(userId);\n db.exec(\"COMMIT\");\n } catch (err) {\n db.exec(\"ROLLBACK\");\n throw err;\n }\n return rewritten;\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;;;ACCA,IAAAA,0BAA+B;AAS/B,IAAAC,8BASO;AAeP,IAAAD,0BA4CO;AACP,IAAA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AAe,EAAE;AAAA,IAAO,CAAC,EAAE,MAAM,MAC1E,YAAY,IAAI,KAAK;AAAA,EACvB;AACA,MAAI,YAAY;AAChB,KAAG,KAAK,OAAO;AACf,MAAI;AACF,eAAW,UAAU,QAAS,cAAa,aAAa,IAAI,QAAQ,MAAM;AAC1E,OAAG;AAAA,MACD,SACG,WAAW,WAAW,EACtB,OAAO,EAAE,IAAI,mBAAI,IAAI,CAAC,GAAG,SAAS,mBAAI,IAAI,GAAG,EAAE,CAAC,EAChD;AAAA,QAAW,CAAC,OACX,GAAG,OAAO,IAAI,EAAE,YAAY,CAAC,QAAQ,EAAE,SAAS,GAAG,IAAI,kBAAkB,EAAE,EAAE;AAAA,MAC/E,EACC,QAAQ,EAAE;AAAA,IACf,EAAE,IAAI,MAAM;AACZ,OAAG,KAAK,QAAQ;AAAA,EAClB,SAAS,KAAK;AACZ,OAAG,KAAK,UAAU;AAClB,UAAM;AAAA,EACR;AACA,SAAO;AACT;","names":["import_storage_adapter","import_protocol_primitives","import_kysely","import_storage_adapter","import_protocol_primitives","import_kysely","import_protocol_primitives","kSql","sql","compiled","import_kysely","import_protocol_primitives","import_storage_adapter","compiled","import_kysely","import_shared_space_api","import_protocol_primitives","import_kysely","import_protocol_primitives"]}
1
+ {"version":3,"sources":["../src/index.ts","../src/adapter.ts","../src/serialization.ts","../src/query-builder.ts","../src/schema/bootstrap.ts","../src/row-values.ts","../src/app-syncable/namespace.ts","../src/app-syncable/apply.ts","../src/app-syncable/tables.ts","../src/library-owner.ts"],"sourcesContent":["// `nodeSqliteDriver` is deliberately *not* re-exported here — it lives at\n// `@starkeep/storage-sqlite/node`. Pulling it into this barrel would put a\n// static `node:sqlite` import back in the graph and make the package\n// unbundleable on React Native again. See `./node-driver.ts`.\nexport { SqliteDatabaseAdapter, type SqliteDriver } from \"./adapter.js\";\nexport { compiler as sqliteCompiler } from \"./query-builder.js\";\nexport type { SqliteDatabaseAdapterOptions } from \"./adapter.js\";\nexport { initializeLocalSchema, applyConnectionPragmas } from \"./schema/bootstrap.js\";\nexport {\n appSyncableTableName,\n getAppSyncableNamespace,\n upsertAppSyncableNamespace,\n deleteAppSyncableNamespace,\n listAppSyncableNamespaces,\n SqliteAppSyncableNamespaceStore,\n} from \"./app-syncable/namespace.js\";\nexport type { AppSyncableNamespace, AppSyncableTableInfo } from \"./app-syncable/namespace.js\";\nexport { SqliteAppSyncableApplier } from \"./app-syncable/apply.js\";\nexport {\n createAppSyncableTables,\n createReservedFileRecordsTable,\n appSyncableNamespaceTables,\n registerAppSyncableNamespace,\n type AppSyncableDeclaration,\n type SyncableTableDeclaration,\n} from \"./app-syncable/tables.js\";\nexport {\n boundUserId,\n libraryUserSegment,\n checkLibraryBindable,\n commitLibraryBinding,\n libraryKeyColumns,\n LibraryBoundElsewhereError,\n type LibraryKeyColumn,\n} from \"./library-owner.js\";\n","import type { RawDatabase } from \"@starkeep/storage-adapter\";\nimport { nextCursorFrom } from \"@starkeep/storage-adapter\";\nimport type {\n Category,\n DataRecord,\n HLCTimestamp,\n MetadataRow,\n RecordLabel,\n StarkeepId,\n} from \"@starkeep/protocol-primitives\";\nimport {\n serializeHLC,\n deserializeHLC,\n getCategory,\n isKnownType,\n sqliteMetadataTableName,\n typeCategory,\n METADATA_DISCRIMINANT_COLUMN,\n METADATA_DELETED_AT_COLUMN,\n} from \"@starkeep/protocol-primitives\";\nimport type {\n DatabaseAdapter,\n Query,\n QueryResult,\n BatchOperation,\n Transaction,\n LabelUpsert,\n LabelRetraction,\n LabelValueReplacement,\n FindByLabelQuery,\n FindByLabelResult,\n StoredAvailability,\n RecordTypeCount,\n} from \"@starkeep/storage-adapter\";\nimport {\n StorageError,\n TransactionError,\n buildAppAggregateQuery,\n buildAppRowQuery,\n collectAggregatePage,\n collectRowPage,\n sharedQueryExcludesSoftDeleted,\n sharedQuerySchema,\n sharedQueryTableName,\n SQLITE_APP_QUERY_DIALECT,\n type ParsedQuery,\n type ParsedQueryResult,\n type SharedQueryTarget,\n type WhereClause,\n type SoftDeletedScope,\n buildGetLabel,\n buildBucketDigest,\n buildScanSinceForNode,\n buildNodeWatermarks,\n collectSince,\n mergeDigestBuckets,\n planNodeScans,\n toDigestBuckets,\n DEFAULT_BUCKET_PREFIX_LENGTH,\n type DigestBucket,\n type SincePage,\n buildLabelRetraction,\n buildLabelValueReplacementTombstone,\n buildLabelSnapshotUpsert,\n buildLabelUpsert,\n buildLabelsByRecordIds,\n buildQueryLabels,\n buildTombstoneLabelsForRecord,\n buildRestoreLabelsForRecord,\n groupLabelsByRecordId,\n emptyLabelPage,\n LABEL_QUERY_TARGET,\n labelPageFrom,\n planFindByLabel,\n paginateLabelScan,\n rowToLabel,\n type LabelDialect,\n type LabelRow,\n} from \"@starkeep/storage-adapter\";\nimport { sql as kSql } from \"kysely\";\nimport { recordToRow, rowToRecord, type SqliteRow } from \"./serialization.js\";\nimport {\n buildCountQuery,\n buildSelectQuery,\n buildTypeCountsQuery,\n compiler as qb,\n} from \"./query-builder.js\";\nimport { initializeLocalSchema } from \"./schema/bootstrap.js\";\nimport { booleanColumnNames, fromSqliteRows, toSqliteParam } from \"./row-values.js\";\n\nexport interface SqliteDatabaseAdapterOptions {\n path: string | \":memory:\";\n /**\n * How to open the connection, and how to close it.\n *\n * Injected so a second SQLite driver can back this adapter rather than\n * duplicating it. Everything below this line already speaks only\n * {@link RawDatabase} — `exec` and `prepare` — which is what item 10\n * established; opening the connection was the single remaining line that\n * named `node:sqlite`, and it is the one thing that genuinely cannot be\n * driver-agnostic.\n *\n * **Required, and deliberately without a default.** It used to default to\n * `node:sqlite`, which meant this module imported it statically — and a static\n * `node:` import at module scope makes the whole package unbundleable on React\n * Native, whatever driver the caller then passes. The Node driver now lives at\n * `@starkeep/storage-sqlite/node`, so a Node caller writes one extra import\n * and a handset can bundle this file at all.\n *\n * A default that only works on some platforms is worse than no default: it\n * fails at bundle time, far from the line that chose it.\n *\n * React Native passes an op-sqlite driver; see `src/db/op-sqlite-driver.ts` in\n * the `starkeep-apps` photos-mobile app for why that one emulates `prepare()`\n * rather than using op-sqlite's prepared statements.\n */\n driver: SqliteDriver;\n}\n\nexport interface SqliteDriver {\n open(path: string): RawDatabase;\n /**\n * Separate from the connection because `RawDatabase` deliberately does not\n * carry `close()`. Consumers of a connection have no business closing it —\n * only whoever opened it does, which is this adapter.\n */\n close(db: RawDatabase): void;\n}\n\n/**\n * How labels are spelled on this backend: the table is flat-named, SQLite\n * having no schemas. That is now the only difference — null ordering used to be\n * a second one, and stopped being with `value` NOT NULL. Everything else about\n * label SQL lives in `@starkeep/storage-adapter`.\n */\nconst AVAILABILITY = \"shared_object_availability\";\n\n/** The stored row shape, mapped back to the flat domain type at the boundary. */\ninterface AvailabilityRow {\n object_storage_key: string;\n state: string;\n tier: string | null;\n expected_latency_hours: number | null;\n ready_at_ms: number | null;\n restored_until_ms: number | null;\n observed_at_ms: number;\n}\n\nfunction rowToAvailability(row: AvailabilityRow): StoredAvailability {\n return {\n objectStorageKey: row.object_storage_key,\n state: row.state as StoredAvailability[\"state\"],\n tier: row.tier,\n expectedLatencyHours: row.expected_latency_hours,\n readyAtMs: row.ready_at_ms,\n restoredUntilMs: row.restored_until_ms,\n observedAtMs: row.observed_at_ms,\n };\n}\n\nconst LABELS: LabelDialect = {\n table: \"shared_record_labels\",\n};\n\nconst RECORDS = \"shared_records\";\n\nexport class SqliteDatabaseAdapter implements DatabaseAdapter {\n private database: RawDatabase | null = null;\n private readonly options: SqliteDatabaseAdapterOptions;\n private readonly driver: SqliteDriver;\n\n constructor(options: SqliteDatabaseAdapterOptions) {\n this.options = options;\n this.driver = options.driver;\n }\n\n async init(): Promise<void> {\n if (this.database) return;\n // Note what is *not* here: creating the parent directory. That used to be\n // an unconditional `mkdirSync`, which is Node's filesystem — a phone has no\n // such thing, and its database location is the driver's business rather\n // than a path this layer may create. \"How a connection comes into being\"\n // includes \"making sure there is somewhere to put it\", so both belong to\n // the driver together.\n this.database = this.driver.open(this.options.path);\n initializeLocalSchema(this.database);\n }\n\n async close(): Promise<void> {\n if (this.database) this.driver.close(this.database);\n this.database = null;\n }\n\n async healthCheck(): Promise<boolean> {\n if (!this.database) return false;\n try {\n this.database.prepare(kSql`SELECT 1`.compile(qb).sql).get();\n return true;\n } catch {\n return false;\n }\n }\n\n private getDatabase(): RawDatabase {\n if (!this.database) throw new StorageError(\"Database not initialized. Call init() first.\");\n return this.database;\n }\n\n /**\n * The raw SQLite connection, so sibling subsystems (the sync engine's change\n * log and state store, the resident set) can create side tables in the same\n * database file. Only valid after `init()`.\n *\n * Typed as {@link RawDatabase} rather than `DatabaseSync`: returning the\n * concrete Node type is what made a second driver impossible, since every\n * consumer was then nailed to `node:sqlite`, which React Native does not\n * have. `DatabaseSync` satisfies the narrower interface structurally, so\n * nothing about this connection changes — only what callers may reach for.\n */\n getRawDatabase(): RawDatabase {\n return this.getDatabase();\n }\n\n // The casts these three used to carry named `DatabaseSync[\"prepare\"]` to\n // borrow node:sqlite's parameter types. `RawStatement` declares `unknown[]`\n // directly, so they were already no-ops — and they were the last thing in\n // this file referring to a concrete driver.\n //\n // All three map their parameters through `toSqliteParam`, which is what makes\n // `row-values.ts`'s claim true — every bind on this connection, reads and\n // writes alike. It was true only of the query path until 2026-09-10, so a\n // declared `boolean` written through `putMetadata` reached the driver as a\n // JavaScript boolean and threw \"Provided value cannot be bound to SQLite\n // parameter\". Nothing had exercised it because no metadata column was a\n // boolean until `exif_present`.\n private runStmt(sql: string, ...params: unknown[]): void {\n this.getDatabase()\n .prepare(sql)\n .run(...params.map(toSqliteParam));\n }\n\n private getRow<T = SqliteRow>(sql: string, ...params: unknown[]): T | undefined {\n return this.getDatabase()\n .prepare(sql)\n .get(...params.map(toSqliteParam)) as T | undefined;\n }\n\n private allRows<T = SqliteRow>(sql: string, ...params: unknown[]): T[] {\n return this.getDatabase()\n .prepare(sql)\n .all(...params.map(toSqliteParam)) as T[];\n }\n\n async put(record: DataRecord): Promise<void> {\n const row = recordToRow(record);\n const updateColumns = Object.keys(row).filter((column) => column !== \"id\");\n const query = qb\n .insertInto(\"shared_records\")\n .values({ ...row })\n .onConflict((oc) =>\n oc\n .column(\"id\")\n .doUpdateSet((eb) =>\n Object.fromEntries(\n updateColumns.map((column) => [column, eb.ref(`excluded.${column}`)]),\n ),\n ),\n )\n .compile();\n this.runStmt(query.sql, ...query.parameters);\n }\n\n async get(id: StarkeepId): Promise<DataRecord | null> {\n const query = qb.selectFrom(\"shared_records\").selectAll().where(\"id\", \"=\", id).compile();\n const row = this.getRow<SqliteRow>(query.sql, ...query.parameters);\n return row ? rowToRecord(row) : null;\n }\n\n async delete(id: StarkeepId, hlc: HLCTimestamp): Promise<void> {\n const ts = serializeHLC(hlc);\n const query = qb\n .updateTable(\"shared_records\")\n // A tombstone frees its stand-in slot, the same rule `standInSlot`\n // applies on a full-row write.\n .set({ deleted_at: ts, updated_at: ts, node_id: hlc.nodeId, stand_in_slot: null })\n .where(\"id\", \"=\", id)\n .compile();\n this.runStmt(query.sql, ...query.parameters);\n }\n\n async getNodeWatermarks(): Promise<Record<string, HLCTimestamp>> {\n // Index-only on (node_id, updated_at). See `buildNodeWatermarks`.\n const watermarksQuery = buildNodeWatermarks(qb, RECORDS);\n const rows = this.allRows<{ node_id: string; max_updated_at: string }>(watermarksQuery.sql);\n const out: Record<string, HLCTimestamp> = {};\n for (const row of rows) {\n out[row.node_id] = deserializeHLC(row.max_updated_at);\n }\n return out;\n }\n\n async querySince(\n peerWatermarks: Record<string, HLCTimestamp>,\n limit: number,\n ): Promise<SincePage<DataRecord>> {\n const scans = planNodeScans(await this.getNodeWatermarks(), peerWatermarks);\n const { rows, hasMore, truncated } = await collectSince<SqliteRow>(\n scans,\n limit,\n async (scan, remaining) => {\n const compiled = buildScanSinceForNode(qb, RECORDS, scan, remaining);\n return this.allRows<SqliteRow>(compiled.sql, ...compiled.parameters);\n },\n (row) => deserializeHLC(row[\"updated_at\"] as string),\n );\n return { rows: rows.map(rowToRecord), hasMore, truncated };\n }\n\n async queryLabelsSince(\n peerWatermarks: Record<string, HLCTimestamp>,\n limit: number,\n ): Promise<SincePage<RecordLabel>> {\n const scans = planNodeScans(await this.getLabelNodeWatermarks(), peerWatermarks);\n const { rows, hasMore, truncated } = await collectSince<LabelRow>(\n scans,\n limit,\n async (scan, remaining) => {\n const compiled = buildScanSinceForNode(qb, LABELS.table, scan, remaining);\n return this.allRows<LabelRow>(compiled.sql, ...compiled.parameters);\n },\n (row) => deserializeHLC(row[\"updated_at\"] as string),\n );\n return { rows: rows.map(rowToLabel), hasMore, truncated };\n }\n\n async bucketDigest(prefixLength: number = DEFAULT_BUCKET_PREFIX_LENGTH): Promise<DigestBucket[]> {\n // Records and labels together: they are one channel and one coverage\n // watermark, so a digest over only half of it would report agreement while\n // a label was missing.\n const out: DigestBucket[] = [];\n for (const table of [RECORDS, LABELS.table]) {\n const compiled = buildBucketDigest(qb, table, prefixLength);\n out.push(\n ...toDigestBuckets(\n this.allRows<Record<string, unknown>>(compiled.sql, ...compiled.parameters),\n ),\n );\n }\n return mergeDigestBuckets(out);\n }\n\n async query(query: Query): Promise<QueryResult> {\n const { sql, params } = buildSelectQuery(query);\n const rows = this.allRows<SqliteRow & Record<string, unknown>>(sql, ...params);\n\n const limit = query.limit;\n const hasMore = limit ? rows.length > limit : false;\n const resultRows = hasMore ? rows.slice(0, limit) : rows;\n\n return {\n records: resultRows.map(rowToRecord),\n // Cut from the row itself, ordering values and all — see `nextCursorFrom`.\n // The page carries those values back under reserved aliases precisely so\n // this does not have to recompute what the database ordered on.\n nextCursor: hasMore ? nextCursorFrom(query, resultRows[resultRows.length - 1]) : null,\n hasMore,\n };\n }\n\n async countRecords(query: Query): Promise<number> {\n const { sql, params } = buildCountQuery(query);\n const row = this.getRow<{ total: number }>(sql, ...params);\n return row?.total ?? 0;\n }\n\n async countRecordsByType(query: Query): Promise<RecordTypeCount[]> {\n const { sql, params } = buildTypeCountsQuery(query);\n const rows = this.allRows<{\n type: string;\n count: number;\n latest_updated_at: string | null;\n }>(sql, ...params);\n return rows.map((row) => ({\n type: row.type,\n count: Number(row.count),\n latestUpdatedAt: row.latest_updated_at,\n }));\n }\n\n /**\n * See `DatabaseAdapter.queryShared`. Compiled by the same builder the\n * app-syncable plane uses, against the table the target names on this engine.\n */\n async queryShared(\n target: SharedQueryTarget,\n query: ParsedQuery,\n options: {\n readonly serverWhere?: readonly WhereClause[];\n readonly softDeleted?: SoftDeletedScope;\n } = {},\n ): Promise<ParsedQueryResult> {\n const schema = sharedQuerySchema(target);\n const table = sharedQueryTableName(target, \"sqlite\");\n const build = {\n serverWhere: options.serverWhere,\n excludeSoftDeleted: sharedQueryExcludesSoftDeleted(target),\n ...(options.softDeleted ? { softDeleted: options.softDeleted } : {}),\n };\n // Only the metadata tables declare one today (model3d's two flags), but\n // asking the schema rather than the target is what keeps a column added\n // later from reading back as 0 and 1 from this engine alone.\n const booleans = booleanColumnNames(schema.columns);\n\n if (query.mode === \"aggregate\") {\n const compiled = buildAppAggregateQuery(qb, table, query, SQLITE_APP_QUERY_DIALECT, build);\n return collectAggregatePage(query, fromSqliteRows(this.selectCompiled(compiled), booleans));\n }\n const compiled = buildAppRowQuery(qb, table, query, build);\n // Converted before the page is collected rather than after, so the page\n // token is cut from the same representation the rows carry.\n return collectRowPage(query, fromSqliteRows(this.selectCompiled(compiled), booleans));\n }\n\n /** Bind and run a compiled SELECT, adapting values SQLite cannot bind. */\n private selectCompiled(compiled: {\n sql: string;\n parameters: readonly unknown[];\n }): Record<string, unknown>[] {\n return this.allRows<Record<string, unknown>>(\n compiled.sql,\n ...compiled.parameters.map(toSqliteParam),\n );\n }\n\n async batch(operations: BatchOperation[]): Promise<void> {\n this.getDatabase().exec(\"BEGIN\");\n try {\n for (const operation of operations) {\n if (operation.type === \"put\") {\n await this.put(operation.record);\n } else {\n await this.delete(operation.id, operation.hlc);\n }\n }\n this.getDatabase().exec(\"COMMIT\");\n } catch (error) {\n this.getDatabase().exec(\"ROLLBACK\");\n throw error;\n }\n }\n\n async transaction<T>(callback: (transaction: Transaction) => Promise<T>): Promise<T> {\n this.getDatabase().exec(\"SAVEPOINT starkeep_tx\");\n try {\n const transaction: Transaction = {\n put: async (record) => this.put(record),\n get: async (id) => this.get(id),\n delete: async (id, hlc) => this.delete(id, hlc),\n query: async (query) => this.query(query),\n };\n const result = await callback(transaction);\n this.getDatabase().exec(\"RELEASE SAVEPOINT starkeep_tx\");\n return result;\n } catch (error) {\n this.getDatabase().exec(\"ROLLBACK TO SAVEPOINT starkeep_tx\");\n this.getDatabase().exec(\"RELEASE SAVEPOINT starkeep_tx\");\n throw new TransactionError(\"Transaction failed\", error);\n }\n }\n\n async putMetadata(recordType: string, row: MetadataRow): Promise<void> {\n const table = sqliteMetadataTableName(recordType);\n const values = metadataValues(recordType, row);\n const updateColumns = Object.keys(values).filter((c) => c !== \"record_id\");\n const query = qb\n .insertInto(table)\n .values(values)\n .onConflict((oc) =>\n updateColumns.length > 0\n ? oc\n .column(\"record_id\")\n .doUpdateSet((eb) =>\n Object.fromEntries(updateColumns.map((c) => [c, eb.ref(`excluded.${c}`)])),\n )\n : oc.column(\"record_id\").doNothing(),\n )\n .compile();\n this.runStmt(query.sql, ...query.parameters);\n }\n\n async getMetadata(typeId: string, recordId: StarkeepId): Promise<MetadataRow | null> {\n const table = sqliteMetadataTableName(typeId);\n const query = qb.selectFrom(table).selectAll().where(\"record_id\", \"=\", recordId).compile();\n const row = this.getRow<Record<string, unknown>>(query.sql, ...query.parameters);\n if (!row) return null;\n return columnsToMetadataRow(recordId, typeId, row);\n }\n\n async getMetadataByIds(\n typeId: string,\n recordIds: StarkeepId[],\n ): Promise<Map<StarkeepId, MetadataRow>> {\n const result = new Map<StarkeepId, MetadataRow>();\n if (recordIds.length === 0) return result;\n const table = sqliteMetadataTableName(typeId);\n const query = qb.selectFrom(table).selectAll().where(\"record_id\", \"in\", recordIds).compile();\n const rows = this.allRows<Record<string, unknown>>(query.sql, ...query.parameters);\n for (const row of rows) {\n const recordId = row[\"record_id\"] as StarkeepId;\n result.set(recordId, columnsToMetadataRow(recordId, typeId, row));\n }\n return result;\n }\n\n async deleteMetadata(typeId: string, recordId: StarkeepId): Promise<void> {\n const table = sqliteMetadataTableName(typeId);\n const query = qb.deleteFrom(table).where(\"record_id\", \"=\", recordId).compile();\n this.runStmt(query.sql, ...query.parameters);\n }\n\n async tombstoneMetadata(typeId: string, recordId: StarkeepId, hlc: HLCTimestamp): Promise<void> {\n this.setMetadataTombstone(typeId, recordId, serializeHLC(hlc));\n }\n\n async restoreMetadata(typeId: string, recordId: StarkeepId): Promise<void> {\n this.setMetadataTombstone(typeId, recordId, null);\n }\n\n private setMetadataTombstone(typeId: string, recordId: StarkeepId, value: string | null): void {\n const table = sqliteMetadataTableName(typeId);\n const query = qb\n .updateTable(table)\n .set({ [METADATA_DELETED_AT_COLUMN]: value })\n .where(\"record_id\", \"=\", recordId)\n .compile();\n this.runStmt(query.sql, ...query.parameters);\n }\n\n // ---- Cross-app record labels -------------------------------------------\n //\n // The SQL for all of these is built in `@starkeep/storage-adapter`, shared\n // with the DSQL adapter: same columns, same ON CONFLICT set, same cursor\n // predicate, same paging. Only the table name is this backend's business,\n // and it lives in LABELS above.\n\n async upsertLabels(labels: LabelUpsert[]): Promise<void> {\n if (labels.length === 0) return;\n const query = buildLabelUpsert(qb, LABELS, labels);\n this.runStmt(query.sql, ...query.parameters);\n }\n\n async retractLabels(retractions: LabelRetraction[]): Promise<void> {\n for (const r of retractions) {\n const query = buildLabelRetraction(qb, LABELS, r);\n this.runStmt(query.sql, ...query.parameters);\n }\n }\n\n async replaceLabelValues(replacements: LabelValueReplacement[]): Promise<void> {\n if (replacements.length === 0) return;\n // Tombstone-then-upsert per key, all in one transaction: a reader must never\n // see the moment where the old values are gone and the new ones are not yet\n // there, which for a single-valued key is the key appearing to be unset.\n this.getDatabase().exec(\"BEGIN\");\n try {\n for (const r of replacements) {\n const tombstone = buildLabelValueReplacementTombstone(qb, LABELS, r);\n this.runStmt(tombstone.sql, ...tombstone.parameters);\n if (r.values.length > 0) {\n const upsert = buildLabelUpsert(\n qb,\n LABELS,\n r.values.map((value) => ({\n recordId: r.recordId,\n appId: r.appId,\n key: r.key,\n value,\n recordType: r.recordType,\n hlc: r.hlc,\n })),\n );\n this.runStmt(upsert.sql, ...upsert.parameters);\n }\n }\n this.getDatabase().exec(\"COMMIT\");\n } catch (error) {\n this.getDatabase().exec(\"ROLLBACK\");\n throw error;\n }\n }\n\n async getLabelsByRecordIds(recordIds: StarkeepId[]): Promise<Map<StarkeepId, RecordLabel[]>> {\n if (recordIds.length === 0) return new Map();\n const query = buildLabelsByRecordIds(qb, LABELS, recordIds);\n return groupLabelsByRecordId(this.allRows<LabelRow>(query.sql, ...query.parameters));\n }\n\n /**\n * The reverse label read, run through the query grammar — see\n * `label-find.ts`. The grant rides in as `serverWhere` rather than as one of\n * the caller's own predicates, which is the separation every other shared\n * query draws.\n */\n async findByLabel(query: FindByLabelQuery): Promise<FindByLabelResult> {\n // `null` means the query cannot match anything — a caller with no readable\n // types — so there is nothing to ask the database.\n const plan = planFindByLabel(query);\n if (!plan) return emptyLabelPage();\n return labelPageFrom(\n await this.queryShared(LABEL_QUERY_TARGET, plan.query, {\n serverWhere: plan.serverWhere,\n }),\n );\n }\n\n // ---- Label sync ---------------------------------------------------------\n\n async putLabel(label: RecordLabel): Promise<void> {\n const query = buildLabelSnapshotUpsert(qb, LABELS, label);\n this.runStmt(query.sql, ...query.parameters);\n }\n\n async getLabel(\n recordId: StarkeepId,\n appId: string,\n key: string,\n value: string,\n ): Promise<RecordLabel | null> {\n const query = buildGetLabel(qb, LABELS, recordId, appId, key, value);\n const row = this.getRow<LabelRow>(query.sql, ...query.parameters);\n return row ? rowToLabel(row) : null;\n }\n\n async queryLabels(query: { limit?: number; cursor?: string }): Promise<{\n labels: RecordLabel[];\n nextCursor: string | null;\n hasMore: boolean;\n }> {\n const compiled = buildQueryLabels(qb, LABELS, query);\n const rows = this.allRows<LabelRow>(compiled.sql, ...compiled.parameters);\n return paginateLabelScan(rows, query.limit);\n }\n\n async getLabelNodeWatermarks(): Promise<Record<string, HLCTimestamp>> {\n const query = buildNodeWatermarks(qb, LABELS.table);\n const rows = this.allRows<{ node_id: string; max_updated_at: string }>(query.sql);\n const out: Record<string, HLCTimestamp> = {};\n for (const row of rows) out[row.node_id] = deserializeHLC(row.max_updated_at);\n return out;\n }\n\n // ---- Object availability ------------------------------------------------\n\n async getAvailability(objectStorageKeys: string[]): Promise<Map<string, StoredAvailability>> {\n const out = new Map<string, StoredAvailability>();\n if (objectStorageKeys.length === 0) return out;\n const compiled = qb\n .selectFrom(AVAILABILITY)\n .selectAll()\n .where(\"object_storage_key\", \"in\", objectStorageKeys)\n .compile();\n const rows = this.allRows<AvailabilityRow>(compiled.sql, ...compiled.parameters);\n for (const row of rows) out.set(row.object_storage_key, rowToAvailability(row));\n return out;\n }\n\n async putAvailability(row: StoredAvailability): Promise<void> {\n const compiled = qb\n .insertInto(AVAILABILITY)\n .values({\n object_storage_key: row.objectStorageKey,\n state: row.state,\n tier: row.tier,\n expected_latency_hours: row.expectedLatencyHours,\n ready_at_ms: row.readyAtMs,\n restored_until_ms: row.restoredUntilMs,\n observed_at_ms: row.observedAtMs,\n })\n .onConflict((oc) =>\n oc.column(\"object_storage_key\").doUpdateSet((eb) => ({\n state: eb.ref(\"excluded.state\"),\n tier: eb.ref(\"excluded.tier\"),\n expected_latency_hours: eb.ref(\"excluded.expected_latency_hours\"),\n ready_at_ms: eb.ref(\"excluded.ready_at_ms\"),\n restored_until_ms: eb.ref(\"excluded.restored_until_ms\"),\n observed_at_ms: eb.ref(\"excluded.observed_at_ms\"),\n })),\n )\n .compile();\n this.runStmt(compiled.sql, ...compiled.parameters);\n }\n\n async countRestoringObjects(): Promise<{ objectCount: number; bytes: number }> {\n // Joined to records for the byte total: availability is keyed by object,\n // and only the record row knows how big the object is.\n const compiled = qb\n .selectFrom(AVAILABILITY)\n .innerJoin(\n \"shared_records\",\n \"shared_records.object_storage_key\",\n `${AVAILABILITY}.object_storage_key`,\n )\n .select(({ fn }) => [\n fn.count<number>(`${AVAILABILITY}.object_storage_key`).as(\"object_count\"),\n fn.sum<number>(\"shared_records.size_bytes\").as(\"bytes\"),\n ])\n .where(`${AVAILABILITY}.state`, \"=\", kSql.lit(\"restoring\"))\n .compile();\n const row = this.getRow<{ object_count: number; bytes: number | null }>(\n compiled.sql,\n ...compiled.parameters,\n );\n return { objectCount: row?.object_count ?? 0, bytes: row?.bytes ?? 0 };\n }\n\n async tombstoneLabelsForRecord(recordId: StarkeepId, hlc: HLCTimestamp): Promise<void> {\n const query = buildTombstoneLabelsForRecord(qb, LABELS, recordId, hlc);\n this.runStmt(query.sql, ...query.parameters);\n }\n\n async restoreLabelsForRecord(\n recordId: StarkeepId,\n deletedAt: HLCTimestamp,\n hlc: HLCTimestamp,\n ): Promise<void> {\n const query = buildRestoreLabelsForRecord(qb, LABELS, recordId, deletedAt, hlc);\n this.runStmt(query.sql, ...query.parameters);\n }\n}\n\n/**\n * One stored metadata row, with SQLite's integers turned back into the booleans\n * the column declares.\n *\n * The read half of the boolean boundary, for the same reason as\n * `fromSqliteRows`: DSQL returns `true` and SQLite returns `1` for the same\n * logical row, and a metadata row rides the sync wire in whatever shape its\n * engine returned. Without this, `exif_present` would mean two things depending\n * on which node answered.\n */\nfunction columnsToMetadataRow(\n recordId: StarkeepId,\n typeId: string,\n columns: Record<string, unknown>,\n): MetadataRow {\n const category = typeCategory(typeId) ?? (typeId as Category);\n const booleans = booleanColumnNames(getCategory(category)?.metadataColumns);\n const row: MetadataRow = { recordId };\n for (const [key, value] of Object.entries(columns)) {\n // `deleted_at` is the server's, like the discriminant: a caller reading a\n // metadata row has no business seeing it, and nothing on the wire carries it.\n if (key === \"record_id\" || key === METADATA_DELETED_AT_COLUMN) continue;\n row[key] = booleans?.has(key) && typeof value === \"number\" ? value !== 0 : value;\n }\n return row;\n}\n\n/**\n * The values to write, with the grant discriminant derived from `recordType`.\n *\n * `recordType` is the record's own `<category>/<format>` id, not a bare\n * category, and a bare one is refused here rather than stored. A metadata row\n * labelled with the wrong discriminant is readable by the wrong app, so a\n * caller that had only a category has lost the thing this column exists to\n * carry and must go and read the record's type.\n *\n * Never taken from `row`: metadata rides the wire as a sync passenger, and a\n * peer supplying this column would be asserting who may read the row. See\n * METADATA_DISCRIMINANT_COLUMN.\n */\nfunction metadataValues(recordType: string, row: MetadataRow): Record<string, unknown> {\n if (!isKnownType(recordType)) {\n throw new StorageError(\n `putMetadata needs the record's own type, not \"${recordType}\": the ` +\n `${METADATA_DISCRIMINANT_COLUMN} column gates every read of this row`,\n );\n }\n const values: Record<string, unknown> = {\n record_id: row.recordId,\n [METADATA_DISCRIMINANT_COLUMN]: recordType,\n // Writing metadata asserts the row is live. Without this an app re-reporting\n // a restored record's dimensions would write into a row still carrying its\n // tombstone, and the one read that filters on the stamp would keep answering\n // nothing. Server-owned either way: a wire row carrying it is ignored below.\n [METADATA_DELETED_AT_COLUMN]: null,\n };\n for (const [key, value] of Object.entries(row)) {\n // `recordId` is spelled `record_id` above, and the discriminant is the\n // server's to set — a wire row carrying one is ignored, not honoured.\n if (\n key === \"recordId\" ||\n key === METADATA_DISCRIMINANT_COLUMN ||\n key === METADATA_DELETED_AT_COLUMN\n ) {\n continue;\n }\n values[key] = value;\n }\n return values;\n}\n","import type { DataRecord, MetadataRow, StarkeepId } from \"@starkeep/protocol-primitives\";\nimport {\n serializeHLC,\n deserializeHLC,\n createStarkeepId,\n isStandInRole,\n standInSlot,\n} from \"@starkeep/protocol-primitives\";\n\nexport interface SqliteRow {\n id: string;\n type: string;\n created_at: string;\n updated_at: string;\n /** Denormalized `updatedAt.nodeId`; must be rewritten with `updated_at`. */\n node_id: string;\n deleted_at: string | null;\n version: number;\n content_hash: string;\n object_storage_key: string;\n mime_type: string | null;\n size_bytes: number;\n original_filename: string | null;\n origin_app_id: string;\n parent_id: string | null;\n stand_in_role: string | null;\n fidelity: number | null;\n canonical_threshold: number | null;\n /** Null on a row written before the column existed, which reads as false. */\n self_canonical: number | null;\n /**\n * Derived from the three columns above and `deleted_at` on every write — see\n * `standInSlot`. Never read back into a record: it exists only so one\n * ordinary unique index can carry both stand-in uniqueness rules.\n */\n stand_in_slot: string | null;\n}\n\nexport function recordToRow(record: DataRecord): SqliteRow {\n return {\n id: record.id,\n type: record.type,\n created_at: serializeHLC(record.createdAt),\n updated_at: serializeHLC(record.updatedAt),\n node_id: record.updatedAt.nodeId,\n deleted_at: record.deletedAt ? serializeHLC(record.deletedAt) : null,\n version: record.version,\n content_hash: record.contentHash,\n object_storage_key: record.objectStorageKey,\n mime_type: record.mimeType,\n size_bytes: record.sizeBytes,\n original_filename: record.originalFilename,\n origin_app_id: record.originAppId,\n parent_id: record.parentId,\n stand_in_role: record.standInRole,\n fidelity: record.fidelity,\n canonical_threshold: record.canonicalThreshold,\n self_canonical: record.selfCanonical ? 1 : 0,\n stand_in_slot: standInSlot(record),\n };\n}\n\nexport function rowToRecord(row: SqliteRow): DataRecord {\n return {\n id: createStarkeepId(row.id),\n kind: \"data\",\n type: row.type,\n createdAt: deserializeHLC(row.created_at),\n updatedAt: deserializeHLC(row.updated_at),\n deletedAt: row.deleted_at ? deserializeHLC(row.deleted_at) : null,\n version: row.version,\n contentHash: row.content_hash,\n objectStorageKey: row.object_storage_key,\n mimeType: row.mime_type,\n sizeBytes: row.size_bytes,\n originalFilename: row.original_filename,\n originAppId: row.origin_app_id,\n parentId: row.parent_id ? createStarkeepId(row.parent_id) : null,\n standInRole: isStandInRole(row.stand_in_role) ? row.stand_in_role : null,\n // DSQL returns a bigint column as a string; the value is small, so a\n // Number is exact.\n fidelity: row.fidelity === null || row.fidelity === undefined ? null : Number(row.fidelity),\n canonicalThreshold:\n row.canonical_threshold === null || row.canonical_threshold === undefined\n ? null\n : Number(row.canonical_threshold),\n selfCanonical: row.self_canonical === 1,\n };\n}\n\n/**\n * Label rows are identical on both backends, so their row type and both\n * conversions live in `@starkeep/storage-adapter` — re-exported here for the\n * adapter that used to own them.\n */\nexport { rowToLabel, labelToRow, type LabelRow as SqliteLabelRow } from \"@starkeep/storage-adapter\";\n\n/**\n * Convert SQLite column-keyed row data into a MetadataRow keyed by recordId\n * plus camelCase or snake_case columns. We pass columns through as-is from\n * the DB so callers can address them however they prefer.\n */\nexport function metadataRowFromColumns(\n recordId: StarkeepId,\n columns: Record<string, unknown>,\n): MetadataRow {\n const row: MetadataRow = { recordId };\n for (const [key, value] of Object.entries(columns)) {\n if (key === \"record_id\") continue;\n row[key] = value;\n }\n return row;\n}\n","import type { Query } from \"@starkeep/storage-adapter\";\nimport {\n buildRecordCount,\n buildRecordSelect,\n buildRecordTypeCounts,\n type RecordDialect,\n} from \"@starkeep/storage-adapter\";\nimport { sqliteMetadataTableName } from \"@starkeep/protocol-primitives\";\nimport {\n DummyDriver,\n Kysely,\n SqliteAdapter,\n SqliteIntrospector,\n SqliteQueryCompiler,\n} from \"kysely\";\n\n// Single dynamic-schema Kysely instance used only to compile SQL — never\n// executes. The DummyDriver lets us reuse Kysely's compiler without pulling\n// in a real connection. `any` keeps it dialect-agnostic at the row level;\n// column names are validated against the live SQLite schema at runtime.\nexport type DB = Record<string, Record<string, unknown>>;\nexport const compiler = new Kysely<DB>({\n dialect: {\n createAdapter: () => new SqliteAdapter(),\n createDriver: () => new DummyDriver(),\n createIntrospector: (db) => new SqliteIntrospector(db),\n createQueryCompiler: () => new SqliteQueryCompiler(),\n },\n});\n\n/**\n * What SQLite calls the tables the shared record queries read.\n *\n * The queries themselves live in `@starkeep/storage-adapter`'s\n * `record-queries.ts`, for the reason stated there: this file and its DSQL twin\n * held two copies of one query and drifted in the ways that mattered.\n */\nconst DIALECT: RecordDialect = {\n records: \"shared_records\",\n labels: \"shared_record_labels\",\n metadataTable: sqliteMetadataTableName,\n};\n\nexport interface BuiltQuery {\n sql: string;\n params: unknown[];\n}\n\nexport function buildSelectQuery(query: Query): BuiltQuery {\n const compiled = buildRecordSelect(compiler, DIALECT, query);\n return { sql: compiled.sql, params: [...compiled.parameters] };\n}\n\nexport function buildCountQuery(query: Query): BuiltQuery {\n const compiled = buildRecordCount(compiler, DIALECT, query);\n return { sql: compiled.sql, params: [...compiled.parameters] };\n}\n\nexport function buildTypeCountsQuery(query: Query): BuiltQuery {\n const compiled = buildRecordTypeCounts(compiler, DIALECT, query);\n return { sql: compiled.sql, params: [...compiled.parameters] };\n}\n","import type { RawDatabase } from \"@starkeep/storage-adapter\";\nimport { sql } from \"kysely\";\nimport {\n CATEGORIES,\n sqliteMetadataDdl,\n metadataIndexDdls,\n hasMetadataTable,\n} from \"@starkeep/protocol-primitives\";\nimport { compiler as qb } from \"../query-builder.js\";\n\n/**\n * Local sqlite schema bootstrap.\n *\n * Layout follows desired-state-roles-and-permissions.md \"DSQL DDL ... Local\n * SQLite asymmetry\" section: prefix-named tables in one file instead of\n * separate schemas. Only tables that something in phase 1 actually reads or\n * writes are created here — promotion, metadata enrichment, and the janitor\n * land as separate workstreams with their own DDL.\n *\n * - shared_records — all shared data, all types (file-backed only)\n * - shared_record_<category>_metadata — per-category metadata rows (typed columns)\n * - shared_record_labels — cross-app assertions about shared records\n * - shared_access_grants — per-app, per-type permissions\n * - shared_app_label_keys — manifest-declared label keys, per app\n * - shared_app_registry — installed apps + HMAC secrets\n * - shared_app_install_steps — idempotent install/uninstall ledger\n *\n * No migration system: this is a fresh-start schema. The user removes\n * ~/.starkeep/data.db (or the local-data-server's STARKEEP_DIR is fresh)\n * before this code runs.\n */\n/**\n * Connection settings the query grammar's portability depends on.\n *\n * Separate from the schema DDL and exported because a connection can be opened\n * without the full local schema — the conformance harness creates one table and\n * nothing else — and a setting that the real server has and the conformance\n * suite does not is a setting whose divergence the suite cannot catch.\n *\n * `case_sensitive_like` is the whole list today. SQLite's LIKE folds ASCII case\n * by default and Postgres's does not, so `like: \"photo%\"` would otherwise match\n * `PHOTO123` locally and not in the cloud. DSQL uses the `C` collation only, so\n * with the fold turned off the two agree byte for byte. Turning it off also\n * lets SQLite use a btree index for an anchored pattern, which the fold rules\n * out.\n */\nexport function applyConnectionPragmas(db: RawDatabase): void {\n db.exec(\"PRAGMA case_sensitive_like = ON\");\n}\n\nfunction applyLocalSchemaDdl(db: RawDatabase): void {\n db.exec(\"PRAGMA journal_mode = WAL\");\n db.exec(\"PRAGMA foreign_keys = ON\");\n applyConnectionPragmas(db);\n\n // shared_records: node_id is denormalized from updated_at (its nodeId\n // component) on every write — it feeds the sync responder's per-node\n // coverage watermark via the (node_id, updated_at) index without scanning\n // the table. label is an advisory appId/purpose interest-filter marker\n // (e.g. photos/thumbnail); NULL = general interest. See DataRecord.label.\n db.exec(\n qb.schema\n .createTable(\"shared_records\")\n .ifNotExists()\n .addColumn(\"id\", \"text\", (c) => c.primaryKey())\n .addColumn(\"type\", \"text\", (c) => c.notNull())\n .addColumn(\"created_at\", \"text\", (c) => c.notNull())\n .addColumn(\"updated_at\", \"text\", (c) => c.notNull())\n .addColumn(\"node_id\", \"text\", (c) => c.notNull())\n .addColumn(\"deleted_at\", \"text\")\n .addColumn(\"version\", \"integer\", (c) => c.notNull().defaultTo(1))\n .addColumn(\"content_hash\", \"text\", (c) => c.notNull())\n .addColumn(\"object_storage_key\", \"text\", (c) => c.notNull())\n .addColumn(\"mime_type\", \"text\")\n .addColumn(\"size_bytes\", \"integer\", (c) => c.notNull())\n .addColumn(\"original_filename\", \"text\")\n .addColumn(\"origin_app_id\", \"text\", (c) => c.notNull())\n .addColumn(\"parent_id\", \"text\")\n // Stand-ins: a role, a reported fidelity, and the derived slot the unique\n // index below keys on. See `stand-ins/rules.ts` in protocol-primitives.\n .addColumn(\"stand_in_role\", \"text\", (c) =>\n c.check(sql`stand_in_role IN ('canonical', 'smaller')`),\n )\n .addColumn(\"fidelity\", \"integer\")\n // The threshold the platform judged an original by, and whether it\n // stands in for itself because no canonical encode could shrink it.\n // Platform-owned, like `fidelity` on an original.\n .addColumn(\"canonical_threshold\", \"integer\")\n .addColumn(\"self_canonical\", \"integer\")\n .addColumn(\"stand_in_slot\", \"text\")\n .compile().sql,\n );\n const sharedRecordsIndexes = [\n qb.schema\n .createIndex(\"idx_shared_records_type\")\n .ifNotExists()\n .on(\"shared_records\")\n .column(\"type\"),\n qb.schema\n .createIndex(\"idx_shared_records_node_watermark\")\n .ifNotExists()\n .on(\"shared_records\")\n .columns([\"node_id\", \"updated_at\"]),\n qb.schema\n .createIndex(\"idx_shared_records_origin_app\")\n .ifNotExists()\n .on(\"shared_records\")\n .column(\"origin_app_id\"),\n qb.schema\n .createIndex(\"idx_shared_records_parent_id\")\n .ifNotExists()\n .on(\"shared_records\")\n .column(\"parent_id\"),\n // Record-level dedup: \"is there already a live record for these bytes\n // under this parent?\", asked on **every** registration.\n //\n // The (filename, content_hash) unique index below cannot serve it — its\n // leading column is the filename, so a hash-only lookup would scan the\n // table once per write. Leading with content_hash is what makes the dedup\n // check affordable enough to be unconditional, and unconditional is what\n // makes \"one object key, one record\" an invariant rather than a hope.\n qb.schema\n .createIndex(\"idx_shared_records_content_hash\")\n .ifNotExists()\n .on(\"shared_records\")\n .columns([\"content_hash\", \"parent_id\", \"deleted_at\"]),\n ];\n for (const index of sharedRecordsIndexes) {\n db.exec(index.compile().sql);\n }\n\n // One live canonical stand-in per original, and one live stand-in per size.\n //\n // A plain column index rather than SQLite's partial index, so both engines\n // hold one index shape: DSQL rejects `WHERE` on CREATE INDEX, and the\n // serializers compute `stand_in_slot` — null on every record the rules do\n // not cover, including tombstones — so the partial predicate lives in the\n // column instead. NULL is distinct from NULL in a SQLite unique index, which\n // is exactly the reading wanted here: ordinary records never collide.\n db.exec(\n qb.schema\n .createIndex(\"uq_shared_records_stand_in_slot\")\n .ifNotExists()\n .unique()\n .on(\"shared_records\")\n .columns([\"parent_id\", \"stand_in_slot\"])\n .compile().sql,\n );\n\n // Duplicate-file prevention: (parent + filename + bytes) is unique among live\n // records. Tombstoned rows (deleted_at IS NOT NULL) are excluded so a\n // re-upload after delete is allowed.\n //\n // **This predicate is also the id rule.** `createDataRecord`\n // content-addresses a record's id from exactly these columns, so that two\n // nodes producing one file produce one row instead of colliding here. The two\n // are the same decision written in two languages: widen or narrow this index\n // and `identifiers/content-id.ts` has to move with it, or the class of record\n // that stops matching gets the sync wedge back. The DSQL index in\n // `admin-installer/src/dsql-schema-init.ts` is the third place, and says the\n // same thing.\n //\n // `parent_id` is in the key because the store cannot represent a shared\n // child: `parent_id` is one scalar column, so two originals whose derived\n // files are byte-identical under one name do not come to share a rendition —\n // the second registration overwrites the first record's parentage. Without\n // parentage in the key that overwrite is silent, and it needs no sync and no\n // carelessness to happen. See\n // `~/projects/starkeep/sync-duplicate-derivation-wedge-2026-08-29.md`.\n //\n // Both nullable columns are wrapped in `COALESCE`, which is why this is an\n // expression index rather than a column list. SQLite follows the standard and\n // treats NULL as distinct from NULL in a unique index, so naming `parent_id`\n // directly would silently stop constraining every top-level record — the\n // exact rows the constraint was originally written for. Coalescing to the\n // empty string makes a missing value equal to itself, which is what DSQL's\n // `NULLS NOT DISTINCT` does there and what `content-id.ts` does when it\n // hashes.\n //\n // Nothing drops the `uq_shared_records_filename_hash` this replaces: the\n // schema is fresh-start (see the note at the top of this file), so an\n // existing `data.db` is removed rather than migrated. A database carrying the\n // superseded index would keep enforcing the narrower rule and reject exactly\n // the derived children this key exists to separate.\n db.exec(\n qb.schema\n .createIndex(\"uq_shared_records_parent_filename_hash\")\n .ifNotExists()\n .unique()\n .on(\"shared_records\")\n .expression(sql`COALESCE(parent_id, ''), COALESCE(original_filename, ''), content_hash`)\n .where(sql.ref(\"deleted_at\"), \"is\", null)\n .compile().sql,\n );\n\n db.exec(\n qb.schema\n .createTable(\"shared_access_grants\")\n .ifNotExists()\n .addColumn(\"app_id\", \"text\", (c) => c.notNull())\n .addColumn(\"type_id\", \"text\", (c) => c.notNull())\n .addColumn(\"access\", \"text\", (c) => c.notNull().check(sql`access IN ('read', 'readwrite')`))\n .addColumn(\"metadata_write\", \"integer\", (c) => c.notNull().defaultTo(0))\n .addColumn(\"created_at\", \"text\", (c) => c.notNull().defaultTo(sql`(datetime('now'))`))\n .addPrimaryKeyConstraint(\"pk_shared_access_grants\", [\"app_id\", \"type_id\"] as never[])\n .compile().sql,\n );\n db.exec(\n qb.schema\n .createIndex(\"idx_shared_access_grants_app\")\n .ifNotExists()\n .on(\"shared_access_grants\")\n .column(\"app_id\")\n .compile().sql,\n );\n\n // shared_record_labels — cross-app assertions about shared records; the\n // local mirror of DSQL's shared.record_labels. See records/labels.ts in\n // protocol-primitives for what a label is and why app_id is a column rather\n // than a string prefix.\n db.exec(\n qb.schema\n .createTable(\"shared_record_labels\")\n .ifNotExists()\n .addColumn(\"record_id\", \"text\", (c) => c.notNull())\n .addColumn(\"app_id\", \"text\", (c) => c.notNull())\n .addColumn(\"key\", \"text\", (c) => c.notNull())\n // In the primary key, so a key is set-valued (faces=Alice and faces=Bob\n // are two rows), and therefore NOT NULL — a bare flag is \"\". See the\n // matching comment in dsql-schema-init.ts.\n .addColumn(\"value\", \"text\", (c) => c.notNull())\n // Denormalized from shared_records.type (immutable), so read gating\n // never joins back — on the reverse path that join is unbounded.\n .addColumn(\"record_type\", \"text\", (c) => c.notNull())\n .addColumn(\"created_at\", \"text\", (c) => c.notNull())\n .addColumn(\"updated_at\", \"text\", (c) => c.notNull())\n .addColumn(\"node_id\", \"text\", (c) => c.notNull())\n .addColumn(\"deleted_at\", \"text\")\n .addPrimaryKeyConstraint(\"pk_shared_record_labels\", [\n \"record_id\",\n \"app_id\",\n \"key\",\n \"value\",\n ] as never[])\n .compile().sql,\n );\n const sharedRecordLabelsIndexes = [\n // The reverse path. Column order mirrors DSQL's idx_record_labels_reverse\n // exactly — see the long comment there for why each column is where it is.\n // SQLite *does* support partial indexes, so `deleted_at` could have been a\n // WHERE clause here; it is a key column instead so the two backends have\n // one index shape between them and a query planned on one is planned the\n // same on the other.\n qb.schema\n .createIndex(\"idx_shared_record_labels_reverse\")\n .ifNotExists()\n .on(\"shared_record_labels\")\n .columns([\"app_id\", \"key\", \"deleted_at\", \"value\", \"record_id\"]),\n qb.schema\n .createIndex(\"idx_shared_record_labels_node_watermark\")\n .ifNotExists()\n .on(\"shared_record_labels\")\n .columns([\"node_id\", \"updated_at\"]),\n ];\n for (const index of sharedRecordLabelsIndexes) {\n db.exec(index.compile().sql);\n }\n\n // shared_object_availability — whether this node can serve an object's bytes\n // right now.\n //\n // Keyed by object key rather than record id: keys are content-addressed, so\n // two records legitimately share one object, and readability is a property of\n // the object. Per-record rows could disagree about one blob.\n //\n // Rows exist only for objects something has told us about; absence means the\n // default (instant). That is what \"maintained, not computed\" buys — a listing\n // costs one batched read instead of a HeadObject per record.\n db.exec(\n qb.schema\n .createTable(\"shared_object_availability\")\n .ifNotExists()\n .addColumn(\"object_storage_key\", \"text\", (c) => c.primaryKey())\n .addColumn(\"state\", \"text\", (c) => c.notNull())\n .addColumn(\"tier\", \"text\")\n .addColumn(\"expected_latency_hours\", \"integer\")\n .addColumn(\"ready_at_ms\", \"integer\")\n .addColumn(\"restored_until_ms\", \"integer\")\n .addColumn(\"observed_at_ms\", \"integer\", (c) => c.notNull())\n .compile().sql,\n );\n\n // shared_app_label_keys — manifest-declared label keys, written by the\n // installer and readable by every app. Cross-app readability is the point:\n // discoverability is why keys are declared in a manifest rather than counted\n // at runtime. Local mirror of DSQL's shared.app_label_keys.\n db.exec(\n qb.schema\n .createTable(\"shared_app_label_keys\")\n .ifNotExists()\n .addColumn(\"app_id\", \"text\", (c) => c.notNull())\n .addColumn(\"key\", \"text\", (c) => c.notNull())\n .addColumn(\"description\", \"text\")\n .addColumn(\"created_at\", \"text\", (c) => c.notNull().defaultTo(sql`(datetime('now'))`))\n .addPrimaryKeyConstraint(\"pk_shared_app_label_keys\", [\"app_id\", \"key\"] as never[])\n .compile().sql,\n );\n\n db.exec(\n qb.schema\n .createTable(\"shared_app_registry\")\n .ifNotExists()\n .addColumn(\"app_id\", \"text\", (c) => c.primaryKey())\n .addColumn(\"name\", \"text\", (c) => c.notNull())\n .addColumn(\"version\", \"text\", (c) => c.notNull())\n .addColumn(\"tier\", \"text\", (c) => c.notNull().defaultTo(\"app\"))\n .addColumn(\"manifest\", \"text\", (c) => c.notNull())\n .addColumn(\"status\", \"text\", (c) => c.notNull().defaultTo(\"installing\"))\n .addColumn(\"hmac_secret\", \"text\", (c) => c.notNull())\n .addColumn(\"installed_at\", \"text\", (c) => c.notNull().defaultTo(sql`(datetime('now'))`))\n .addColumn(\"updated_at\", \"text\", (c) => c.notNull().defaultTo(sql`(datetime('now'))`))\n .compile().sql,\n );\n\n db.exec(\n qb.schema\n .createTable(\"shared_app_install_steps\")\n .ifNotExists()\n .addColumn(\"app_id\", \"text\", (c) => c.notNull())\n .addColumn(\"operation\", \"text\", (c) =>\n c.notNull().check(sql`operation IN ('install', 'uninstall')`),\n )\n .addColumn(\"step\", \"text\", (c) => c.notNull())\n .addColumn(\"status\", \"text\", (c) =>\n c.notNull().check(sql`status IN ('pending', 'done', 'failed')`),\n )\n .addColumn(\"error\", \"text\")\n .addColumn(\"updated_at\", \"text\", (c) => c.notNull().defaultTo(sql`(datetime('now'))`))\n .addPrimaryKeyConstraint(\"pk_shared_app_install_steps\", [\n \"app_id\",\n \"operation\",\n \"step\",\n ] as never[])\n .compile().sql,\n );\n\n // App-specific syncable namespace registry. One row per installed app that\n // declared `infraRequirements.appSpecificSyncable`. Lists the tables the\n // installer materialized as `<app_id>_syncable_<name>` and whether the app\n // opted into the `apps/<app_id>/syncable/` file prefix. Read by the SDK to\n // gate row CRUD/file ops and by the sync engine to enumerate what to sync.\n db.exec(\n qb.schema\n .createTable(\"app_syncable_namespaces\")\n .ifNotExists()\n .addColumn(\"app_id\", \"text\", (c) => c.primaryKey())\n .addColumn(\"tables_json\", \"text\", (c) => c.notNull())\n .addColumn(\"files_enabled\", \"integer\", (c) => c.notNull().defaultTo(0))\n .addColumn(\"created_at\", \"text\", (c) => c.notNull().defaultTo(sql`(datetime('now'))`))\n .compile().sql,\n );\n\n // Per-category metadata tables on parity with DSQL. Generated from CATEGORIES\n // so adding a category or a column is a single edit in @starkeep/protocol-primitives's\n // core-types.ts. `other` has no metadata columns and gets no table.\n for (const c of CATEGORIES) {\n if (!hasMetadataTable(c.id)) continue;\n db.exec(sqliteMetadataDdl(c));\n // Same index as the DSQL side, so a predicate that seeks in the cloud\n // seeks locally too.\n for (const index of metadataIndexDdls(c, \"sqlite\")) db.exec(index.sql);\n }\n}\n\nexport function initializeLocalSchema(db: RawDatabase): void {\n try {\n applyLocalSchemaDdl(db);\n } catch (err) {\n // The DDL above is all `CREATE ... IF NOT EXISTS`, so it is a no-op against\n // an up-to-date DB and cannot fail on a fresh one. In practice the way it\n // DOES fail is a pre-existing DB written before a column was added: the\n // table already exists (so it is not recreated, and never gains the\n // column), and the first statement referencing the new column dies with a\n // bare \"no such column: x\". That message names the symptom, not the cause,\n // and the cause is the fresh-start contract in this file's header. Say so.\n throw new Error(\n `Local schema bootstrap failed: ${(err as Error).message}. This usually ` +\n `means the SQLite DB predates the current schema. There is no ` +\n `migration system by design — delete the DB ($STARKEEP_DIR/data.db, ` +\n `default ~/.starkeep/data.db) and it will be rebuilt on next start.`,\n { cause: err },\n );\n }\n}\n","/**\n * The `boolean` boundary on the SQLite side.\n *\n * SQLite stores a declared `boolean` as an integer, Postgres stores it as a\n * native boolean and returns one, and a row travels the sync wire exactly as\n * its engine returned it. Without a conversion at each engine's own boundary\n * the same logical row reads as `1` from the local server and `true` from the\n * cloud, and the wire form of a boolean would depend on which node happened to\n * send it. This module is what makes the JSON boolean the one app-facing and\n * on-the-wire form of the type.\n *\n * The Postgres counterpart is `pg-timestamps.ts` in `storage-aurora-dsql`,\n * which converts the two types *that* driver hands back in its own shape. Each\n * engine converts exactly what it would otherwise get wrong; neither converts\n * what the other does.\n */\n\n/** A column, as any table description in this system spells one. */\ninterface DeclaredColumn {\n readonly name: string;\n readonly type: string;\n}\n\n/**\n * The names of a table's declared `boolean` columns, or null when it has none.\n *\n * Null rather than an empty set so the caller can skip the row walk entirely,\n * which is most tables.\n */\nexport function booleanColumnNames(\n columns: readonly DeclaredColumn[] | null | undefined,\n): Set<string> | null {\n if (!columns) return null;\n const names = columns.filter((c) => c.type === \"boolean\").map((c) => c.name);\n return names.length > 0 ? new Set(names) : null;\n}\n\n/**\n * The read half of the boolean conversion: `0` and `1` back to `false` and\n * `true`.\n *\n * Applies to every row leaving this engine: query rows, aggregate group keys\n * (the parser forbids an aggregate output from colliding with a column name, so\n * matching by name is unambiguous), and rows bound for the wire.\n */\nexport function fromSqliteRows(\n rows: Record<string, unknown>[],\n booleanColumns: ReadonlySet<string> | null,\n): Record<string, unknown>[] {\n if (!booleanColumns || booleanColumns.size === 0) return rows;\n return rows.map((row) => {\n const out: Record<string, unknown> = { ...row };\n for (const name of booleanColumns) {\n const value = out[name];\n if (typeof value === \"number\") out[name] = value !== 0;\n }\n return out;\n });\n}\n\n/** SQLite's bindable parameter types. */\nexport type SqlParam = null | number | bigint | string | Uint8Array;\n\n/**\n * SQLite binds no booleans.\n *\n * A boolean column's value is normalized to a real boolean before it reaches\n * either engine — by the parser for a predicate, by `validateRow` for a written\n * row — so both engines are handed one thing, and this is where that one thing\n * becomes the integer SQLite stores. Postgres takes the boolean unchanged,\n * which is the whole reason the normalization happens upstream rather than here.\n *\n * Every bind on this connection goes through it, reads and writes alike. A\n * conversion applied to only half the traffic is the bug this replaced.\n */\nexport function toSqliteParam(value: unknown): SqlParam {\n if (typeof value === \"boolean\") return value ? 1 : 0;\n return value as SqlParam;\n}\n","import type { RawDatabase } from \"@starkeep/storage-adapter\";\nimport { compiler as qb } from \"../query-builder.js\";\nimport type {\n AppSyncableNamespace,\n AppSyncableTableInfo,\n AppSyncableNamespaceStore,\n} from \"@starkeep/shared-space-api\";\nimport { parseAppSyncableTables } from \"@starkeep/shared-space-api\";\n\nexport type { AppSyncableNamespace, AppSyncableTableInfo };\n\n// `<appId>_syncable_<table>` is what the manifest convention pins, but appIds\n// may contain dashes (e.g. \"cloud-data-server\") which aren't legal SQLite\n// identifiers. Normalize the same way as cloud-side PG roles.\nfunction normalizeAppId(appId: string): string {\n return appId.toLowerCase().replace(/-/g, \"_\");\n}\n\nexport function appSyncableTableName(appId: string, tableName: string): string {\n return `${normalizeAppId(appId)}_syncable_${tableName}`;\n}\n\nfunction rowToNamespace(r: {\n app_id: string;\n tables_json: string;\n files_enabled: number;\n}): AppSyncableNamespace {\n const tables = parseAppSyncableTables(r.app_id, r.tables_json);\n return {\n appId: r.app_id,\n tables,\n filesEnabled: r.files_enabled === 1,\n tableNames: tables.map((t) => t.name),\n };\n}\n\nexport function upsertAppSyncableNamespace(\n db: RawDatabase,\n appId: string,\n tables: AppSyncableTableInfo[],\n filesEnabled: boolean,\n): void {\n const query = qb\n .insertInto(\"app_syncable_namespaces\")\n .values({\n app_id: appId,\n tables_json: JSON.stringify(tables),\n files_enabled: filesEnabled ? 1 : 0,\n })\n .onConflict((oc) =>\n oc.column(\"app_id\").doUpdateSet((eb) => ({\n tables_json: eb.ref(\"excluded.tables_json\"),\n files_enabled: eb.ref(\"excluded.files_enabled\"),\n })),\n )\n .compile();\n db.prepare(query.sql).run(...(query.parameters as (string | number)[]));\n}\n\nexport function deleteAppSyncableNamespace(db: RawDatabase, appId: string): void {\n const query = qb.deleteFrom(\"app_syncable_namespaces\").where(\"app_id\", \"=\", appId).compile();\n db.prepare(query.sql).run(...(query.parameters as string[]));\n}\n\nexport function getAppSyncableNamespace(\n db: RawDatabase,\n appId: string,\n): AppSyncableNamespace | null {\n const query = qb\n .selectFrom(\"app_syncable_namespaces\")\n .select([\"app_id\", \"tables_json\", \"files_enabled\"])\n .where(\"app_id\", \"=\", appId)\n .compile();\n const row = db.prepare(query.sql).get(...(query.parameters as string[])) as\n | { app_id: string; tables_json: string; files_enabled: number }\n | undefined;\n if (!row) return null;\n return rowToNamespace(row);\n}\n\nexport function listAppSyncableNamespaces(db: RawDatabase): AppSyncableNamespace[] {\n const query = qb\n .selectFrom(\"app_syncable_namespaces\")\n .select([\"app_id\", \"tables_json\", \"files_enabled\"])\n .compile();\n const rows = db.prepare(query.sql).all() as Array<{\n app_id: string;\n tables_json: string;\n files_enabled: number;\n }>;\n return rows.map(rowToNamespace);\n}\n\n/**\n * Object-oriented wrapper over the free functions above — implements the\n * `AppSyncableNamespaceStore` interface required by `createAppSpecificFactory`\n * and the sync applier.\n */\nexport class SqliteAppSyncableNamespaceStore implements AppSyncableNamespaceStore {\n constructor(private readonly db: RawDatabase) {}\n\n get(appId: string): AppSyncableNamespace | null {\n return getAppSyncableNamespace(this.db, appId);\n }\n\n list(): AppSyncableNamespace[] {\n return listAppSyncableNamespaces(this.db);\n }\n}\n","import type { RawDatabase } from \"@starkeep/storage-adapter\";\nimport { sql, type CompiledQuery } from \"kysely\";\nimport type { HLCTimestamp } from \"@starkeep/protocol-primitives\";\nimport { serializeHLC, deserializeHLC } from \"@starkeep/protocol-primitives\";\nimport type {\n AppSyncableApplier,\n AppSyncableRowEntry,\n AppSyncableNamespaceStore,\n ScanCapableApplier,\n ScanSincePage,\n} from \"@starkeep/shared-space-api\";\nimport { requireWellFormedFileIndexRow } from \"@starkeep/shared-space-api\";\nimport {\n buildAppAggregateQuery,\n buildAppRowQuery,\n collectAggregatePage,\n collectRowPage,\n SQLITE_APP_QUERY_DIALECT,\n type BuildOptions,\n type ParsedQuery,\n type ParsedQueryResult,\n buildBucketDigest,\n buildNodeWatermarks,\n buildScanSinceForNode,\n collectSince,\n planNodeScans,\n requireKeyedWhere,\n rowToWireEntry,\n toDigestBuckets,\n DEFAULT_BUCKET_PREFIX_LENGTH,\n type DigestBucket,\n} from \"@starkeep/storage-adapter\";\nimport { compiler as qb } from \"../query-builder.js\";\nimport { appSyncableTableName } from \"./namespace.js\";\nimport { booleanColumnNames, fromSqliteRows, toSqliteParam } from \"../row-values.js\";\n\n// Both go through `toSqliteParam` for the reason the read path does: SQLite\n// binds no boolean, and a declared `boolean` column reaches here as one from\n// either writer — an app's own write, normalized by `validateRow`, or a peer's\n// row off the sync wire, which Postgres returns as a real boolean. The casts\n// these two used to carry admitted a boolean and left the driver to reject it.\nfunction runCompiled(db: RawDatabase, compiled: CompiledQuery): void {\n db.prepare(compiled.sql).run(...compiled.parameters.map(toSqliteParam));\n}\n\nfunction allCompiled<T>(db: RawDatabase, compiled: CompiledQuery): T[] {\n return db.prepare(compiled.sql).all(...compiled.parameters.map(toSqliteParam)) as T[];\n}\n\n/**\n * SQLite-backed implementation of `AppSyncableApplier`.\n *\n * All writes use the LWW (last-write-wins) rule based on the HLC-serialized\n * `updated_at` column: an incoming entry is only applied if its timestamp is\n * strictly greater than the row's current `updated_at`. This makes the applier\n * idempotent — replaying the same entry twice is a no-op.\n *\n * Delete is soft: the `deleted_at` column is set rather than removing the row\n * so that the inline-HLC pull path can propagate tombstones to other clients.\n */\nexport class SqliteAppSyncableApplier implements AppSyncableApplier, ScanCapableApplier {\n constructor(\n private readonly db: RawDatabase,\n private readonly namespace: AppSyncableNamespaceStore,\n ) {}\n\n apply(entry: AppSyncableRowEntry): void {\n const ns = this.namespace.get(entry.appId);\n if (!ns) {\n throw new Error(`SqliteAppSyncableApplier: app \"${entry.appId}\" not installed`);\n }\n const tableInfo = ns.tables.find((t) => t.name === entry.table);\n if (!tableInfo) {\n throw new Error(\n `SqliteAppSyncableApplier: table \"${entry.table}\" not declared for app \"${entry.appId}\"`,\n );\n }\n requireWellFormedFileIndexRow(entry);\n\n const fullName = appSyncableTableName(entry.appId, entry.table);\n const { pkColumns } = tableInfo;\n\n if (entry.op === \"insert\") {\n this.applyInsert(fullName, pkColumns, entry);\n } else if (entry.op === \"update\") {\n this.applyUpdate(fullName, pkColumns, entry);\n } else {\n this.applyDelete(fullName, pkColumns, entry);\n }\n }\n\n private applyInsert(fullName: string, pkColumns: string[], entry: AppSyncableRowEntry): void {\n const row = withNodeId(entry.row ?? {}, entry);\n const cols = Object.keys(row);\n if (cols.length === 0) return;\n\n const updateCols = cols.filter((c) => !pkColumns.includes(c));\n if (pkColumns.length === 0 || updateCols.length === 0) {\n // No PK declared (or nothing beyond it) — just insert, ignoring duplicates.\n runCompiled(\n this.db,\n qb\n .insertInto(fullName)\n .orIgnore()\n .values({ ...row })\n .compile(),\n );\n return;\n }\n\n // UPSERT with LWW: only overwrite if the incoming updated_at is newer.\n runCompiled(\n this.db,\n qb\n .insertInto(fullName)\n .values({ ...row })\n .onConflict((oc) =>\n oc\n .columns(pkColumns as never[])\n .doUpdateSet((eb) =>\n Object.fromEntries(updateCols.map((c) => [c, eb.ref(`excluded.${c}`)])),\n )\n .where(sql.ref(\"excluded.updated_at\"), \">\", sql.ref(`${fullName}.updated_at`)),\n )\n .compile(),\n );\n }\n\n private applyUpdate(\n fullName: string,\n pkColumns: readonly string[],\n entry: AppSyncableRowEntry,\n ): void {\n // node_id rides along whenever updated_at changes (it's derived from it).\n const rawPatch = entry.row ?? {};\n const patch = rawPatch[\"updated_at\"] ? withNodeId(rawPatch, entry) : rawPatch;\n const where = requireKeyedWhere(entry, \"update\", pkColumns);\n const patchCols = Object.keys(patch);\n const whereCols = Object.keys(where);\n if (patchCols.length === 0) return;\n\n // Only apply if the incoming updated_at is strictly newer (LWW).\n const incomingUpdatedAt = patch[\"updated_at\"] as string | undefined;\n let query = qb.updateTable(fullName).set({ ...patch });\n for (const c of whereCols) {\n query = query.where(c, \"=\", where[c]);\n }\n if (incomingUpdatedAt) {\n // `updated_at IS NULL OR updated_at < ?`, matching `applyDelete`. A bare\n // `<` is unknown against NULL, so a row with no position silently refused\n // every update while accepting every tombstone — the two halves of the\n // same LWW rule disagreeing about what \"older than everything\" means.\n // The column is NOT NULL wherever the installer created the table, which\n // is exactly why the inconsistency could sit here unnoticed.\n query = query.where((eb) =>\n eb.or([eb(\"updated_at\", \"is\", null), eb(\"updated_at\", \"<\", incomingUpdatedAt)]),\n );\n }\n runCompiled(this.db, query.compile());\n }\n\n private applyDelete(\n fullName: string,\n pkColumns: readonly string[],\n entry: AppSyncableRowEntry,\n ): void {\n const where = requireKeyedWhere(entry, \"delete\", pkColumns);\n const whereCols = Object.keys(where);\n // Soft-delete: set deleted_at and updated_at (and node_id with it).\n const incomingUpdatedAt = entry.row?.[\"updated_at\"] as string | undefined;\n const ts = incomingUpdatedAt ?? serializeHLC(entry.timestamp);\n\n // A tombstone that arrived over sync carries the whole row (see\n // `rowToWireEntry`), and it has to *land* even on a node that never held\n // the row it retracts.\n //\n // As an UPDATE alone it did not: the statement matched nothing and the\n // deletion evaporated. Both sides then held different numbers of rows for\n // the same author bucket — tombstones are counted, deliberately, because a\n // deletion is a row the peer must also hold — so `verify()` reported a\n // permanent hole, armed a repair, and the repair re-shipped the same\n // tombstone into the same nothing. Forever. The nodes that hit it are\n // exactly the ones repair exists for: one that joined after the delete, or\n // one that lost the row and is being filled back in.\n //\n // Upserting is safe precisely because the wire form carries every column,\n // so nothing has to be invented for a NOT NULL the app declared. A delete\n // issued locally through the API carries only its key and its timestamp,\n // and that one still goes through the UPDATE below — the row is here by\n // construction, and inventing a half-empty row for it would be wrong.\n const carriesFullRow =\n entry.row !== undefined &&\n pkColumns.length > 0 &&\n pkColumns.every((column) => entry.row?.[column] !== undefined);\n if (carriesFullRow) {\n const row = withNodeId({ ...entry.row, updated_at: ts, deleted_at: ts }, entry);\n const updateCols = Object.keys(row).filter((c) => !pkColumns.includes(c));\n runCompiled(\n this.db,\n qb\n .insertInto(fullName)\n .values({ ...row })\n .onConflict((oc) =>\n oc\n .columns(pkColumns as never[])\n .doUpdateSet((eb) =>\n Object.fromEntries(updateCols.map((c) => [c, eb.ref(`excluded.${c}`)])),\n )\n // The same LWW guard the UPDATE path carries, and for the same\n // reason: a replayed tombstone must not move a newer row back.\n .where(sql.ref(\"excluded.updated_at\"), \">\", sql.ref(`${fullName}.updated_at`)),\n )\n .compile(),\n );\n return;\n }\n\n let query = qb\n .updateTable(fullName)\n .set({ deleted_at: ts, updated_at: ts, node_id: nodeIdOf(ts, entry) });\n for (const c of whereCols) {\n query = query.where(c, \"=\", where[c]);\n }\n // LWW guard: tombstone only rows the incoming timestamp supersedes.\n query = query.where((eb) => eb.or([eb(\"updated_at\", \"is\", null), eb(\"updated_at\", \"<\", ts)]));\n runCompiled(this.db, query.compile());\n }\n\n /**\n * Whether this table exists in *this* database.\n *\n * Asked before the digest rather than inferred from a failed read, because\n * those are two different answers and only one of them is `[]`. An app that\n * is not installed here genuinely holds nothing; a table that is locked,\n * corrupt or unreadable holds an unknown number of rows, and reporting zero\n * for it is the loudest possible false alarm — every bucket in it reads as a\n * hole, in whichever direction the comparison runs.\n *\n * `sqlite_master` is the cheapest question that separates them, and asking it\n * cannot itself fail for a reason worth swallowing: a database whose schema\n * table will not read is not one whose app tables are merely absent.\n */\n private tableExists(fullName: string): boolean {\n const row = this.db\n .prepare(`SELECT name FROM sqlite_master WHERE type = 'table' AND name = ?`)\n .all(fullName);\n return row.length > 0;\n }\n\n /**\n * See `ScanCapableApplier.bucketDigest`. Missing table → `[]`; a table that\n * exists and will not read **throws**, so the caller's `supported: false`\n * path can do its job.\n *\n * This used to be `try { … } catch { return [] }`, which is the same mistake\n * `scanSince` made: `[]` is the wire value for \"this table holds nothing\", not\n * for \"I could not count it\". It made both engine-side \"could not count ⇒\n * supported: false\" guards unreachable on every production path, because no\n * real applier ever threw.\n */\n async bucketDigest(\n appId: string,\n table: string,\n prefixLength: number = DEFAULT_BUCKET_PREFIX_LENGTH,\n ): Promise<DigestBucket[]> {\n const fullName = appSyncableTableName(appId, table);\n if (!this.tableExists(fullName)) return [];\n const compiled = buildBucketDigest(qb, fullName, prefixLength);\n return toDigestBuckets(allCompiled<Record<string, unknown>>(this.db, compiled));\n }\n\n /**\n * See `ScanCapableApplier.getNodeWatermarks`. Missing table → `{}`; a table\n * that exists and will not read **throws**.\n *\n * The distinction matters more here than the `{}` return suggests, because\n * `scanSince` plans its authors from this map: an unreadable table that\n * answered `{}` produced no scans, and the scan then reported \"nothing owed,\n * every author complete\" — the exact silent-loss shape `scanSince`'s own catch\n * was written to prevent, reached one frame earlier.\n */\n async getNodeWatermarks(appId: string, table: string): Promise<Record<string, HLCTimestamp>> {\n const fullName = appSyncableTableName(appId, table);\n // Table might not exist yet (app not installed locally).\n if (!this.tableExists(fullName)) return {};\n const rows = allCompiled<{ node_id: string; max_updated_at: string }>(\n this.db,\n buildNodeWatermarks(qb, fullName),\n );\n const out: Record<string, HLCTimestamp> = {};\n for (const row of rows) {\n out[row.node_id] = deserializeHLC(row.max_updated_at);\n }\n return out;\n }\n\n /**\n * Pull-side synthesis: rows the peer hasn't seen, per author, seeking the\n * `(node_id, updated_at)` index rather than reading the table and filtering.\n * See `ScanCapableApplier.scanSince` for the contract and\n * `storage-adapter/src/database/since-queries.ts` for why it is a loop.\n */\n async scanSince(\n appId: string,\n table: string,\n peerWatermarks: Record<string, HLCTimestamp>,\n limit: number,\n ): Promise<ScanSincePage> {\n const fullName = appSyncableTableName(appId, table);\n // A missing table (app not installed locally) reads as \"nothing owed\"\n // rather than an error, the same fail-safe direction getNodeWatermarks\n // takes: understating only causes a re-ship. That case is settled *here*,\n // by getNodeWatermarks returning {} so no author is planned — which is why\n // nothing below needs a catch for it.\n const scans = planNodeScans(await this.getNodeWatermarks(appId, table), peerWatermarks);\n const pkColumns =\n this.namespace.get(appId)?.tables.find((t) => t.name === table)?.pkColumns ?? [];\n try {\n const { rows, hasMore, truncated } = await collectSince<Record<string, unknown>>(\n scans,\n limit,\n async (scan, remaining) => {\n const compiled = buildScanSinceForNode(qb, fullName, scan, remaining);\n return allCompiled<Record<string, unknown>>(this.db, compiled);\n },\n (row) => deserializeHLC(row[\"updated_at\"] as string),\n );\n return {\n // Converted before the row becomes a wire entry: what goes on the wire\n // is what the app sees, and a peer's applier binds a boolean it can.\n rows: fromSqliteRows(rows, this.booleanColumnsOf(appId, table))\n .map((row) => rowToWireEntry(appId, table, row, pkColumns, deserializeHLC))\n .filter((entry): entry is AppSyncableRowEntry => entry !== null),\n hasMore,\n truncated,\n };\n } catch (err) {\n // A read that failed part-way has enumerated *nothing it can vouch for*,\n // and `truncated: {}` is the wire value for the opposite — \"every author\n // complete, no ceiling\". Returning that lets the round ship rows whose\n // HLCs sit above the ones this scan never reached, which is the exact\n // silent-loss shape `round-cut.ts` exists to prevent.\n //\n // So every planned author gets a `null` ceiling: nothing is safe to ship\n // for any of them, and `hasMore` asks for the round to be retried.\n console.warn(\n `[app-syncable] scanSince failed for ${appId}.${table}: ${(err as Error).message}`,\n );\n const truncated: Record<string, HLCTimestamp | null> = {};\n for (const scan of scans) truncated[scan.nodeId] = null;\n return { rows: [], hasMore: true, truncated };\n }\n }\n\n /**\n * Run a parsed query. The read half of the app-data plane.\n *\n * Compiled by the shared builder rather than here, so the SQL this emits and\n * the SQL the DSQL applier emits are one piece of code — the two hand-written\n * read grammars this replaces had already drifted on their limit defaults\n * alone.\n */\n async runQuery(\n appId: string,\n table: string,\n query: ParsedQuery,\n options: BuildOptions = {},\n ): Promise<ParsedQueryResult> {\n const fullName = appSyncableTableName(appId, table);\n\n const booleanColumns = this.booleanColumnsOf(appId, table);\n\n if (query.mode === \"aggregate\") {\n const compiled = buildAppAggregateQuery(\n qb,\n fullName,\n query,\n SQLITE_APP_QUERY_DIALECT,\n options,\n );\n return collectAggregatePage(query, fromSqliteRows(this.selectRows(compiled), booleanColumns));\n }\n\n const compiled = buildAppRowQuery(qb, fullName, query, options);\n // `node:sqlite` has no streaming cursor, so the fetch budget is applied\n // over an array rather than over an iterator here. The row limit bounds what\n // that array can hold, and the response budget engages only on pathological\n // rows — so what is given up is that a page of 1 MiB text values is\n // materialized before being cut, on a server running on the operator's own\n // machine.\n // Converted before the page is collected rather than after, so the token\n // and the rows are computed from one representation.\n return collectRowPage(query, fromSqliteRows(this.selectRows(compiled), booleanColumns));\n }\n\n /** The names of a declared table's `boolean` columns, or null when it has none. */\n private booleanColumnsOf(appId: string, table: string): Set<string> | null {\n return booleanColumnNames(\n this.namespace.get(appId)?.tables.find((t) => t.name === table)?.columns,\n );\n }\n\n /** Bind and run a compiled SELECT, adapting values SQLite cannot bind. */\n private selectRows(compiled: CompiledQuery): Record<string, unknown>[] {\n return this.db.prepare(compiled.sql).all(...compiled.parameters.map(toSqliteParam)) as Record<\n string,\n unknown\n >[];\n }\n}\n\n/**\n * Return `row` with `node_id` set from its `updated_at` (falling back to the\n * entry timestamp). Writers can't be trusted to carry the column — locally\n * authored entries and older wire rows don't — so the applier derives it at\n * write time, keeping the NOT NULL invariant without touching every producer.\n */\nfunction withNodeId(\n row: Record<string, unknown>,\n entry: AppSyncableRowEntry,\n): Record<string, unknown> {\n return { ...row, node_id: nodeIdOf(row[\"updated_at\"], entry) };\n}\n\n/** nodeId from a serialized-HLC `updated_at`, or the entry timestamp's. */\nfunction nodeIdOf(updatedAt: unknown, entry: AppSyncableRowEntry): string {\n if (typeof updatedAt === \"string\") {\n try {\n return deserializeHLC(updatedAt).nodeId;\n } catch {\n // Not a serialized HLC — fall through to the entry timestamp.\n }\n }\n return entry.timestamp.nodeId;\n}\n\n// The wire-entry shape is shared with the DSQL applier — see\n// `storage-adapter/src/database/app-syncable-rows.ts`. It was duplicated here,\n// and both copies emitted keyless tombstones.\n","import type { RawDatabase } from \"@starkeep/storage-adapter\";\nimport { sql } from \"kysely\";\nimport {\n FILE_RECORDS_COLUMNS,\n FILE_RECORDS_TABLE,\n FILE_RECORDS_TABLE_INFO,\n appSyncableTableInfo,\n syncableIndexName,\n type AppSyncableTableInfo,\n type DeclaredColumn,\n} from \"@starkeep/shared-space-api\";\nimport { sqliteColumnType } from \"@starkeep/protocol-primitives\";\nimport { compiler as k } from \"../query-builder.js\";\nimport { appSyncableTableName, upsertAppSyncableNamespace } from \"./namespace.js\";\n\n/**\n * One syncable table as an app's manifest declares it: the structural shape of\n * admin-manifest's `SyncableTable`, so this package needs no manifest schema\n * and a phone can pass the block straight from the manifest JSON.\n */\nexport interface SyncableTableDeclaration {\n readonly name: string;\n readonly columns: readonly DeclaredColumn[];\n readonly indexes?: readonly { readonly columns: readonly string[] }[];\n}\n\n/** A manifest's `infraRequirements.appSpecificSyncable` block. */\nexport interface AppSyncableDeclaration {\n readonly tables: readonly SyncableTableDeclaration[];\n readonly files?: boolean;\n}\n\ninterface SyncableColumnDef {\n name: string;\n /** The emitted SQL type, from `sqliteColumnType`. */\n type: string;\n notNull: boolean;\n primaryKey: boolean;\n /**\n * True when the app declared this column `boolean`.\n *\n * `sqliteColumnType` maps `boolean` onto INTEGER, since SQLite has no\n * boolean type, and the physical type is all the rest of this shape needs.\n * The domain constraint does need the distinction, so it is carried\n * separately rather than recovered by guessing which integers are flags.\n */\n boolean?: boolean;\n}\n\n/**\n * Emits the CREATE TABLE / CREATE INDEX statements shared by manifest-declared\n * syncable tables and the reserved file-records table. updated_at, node_id\n * (denormalized from updated_at by the applier) and deleted_at are reserved by\n * the sync runtime for inline-HLC change tracking; they are appended\n * automatically and must not be declared in the manifest. (node_id, updated_at)\n * backs the responder's per-node coverage watermark query.\n */\nfunction createSyncableTable(\n db: RawDatabase,\n fullName: string,\n columns: SyncableColumnDef[],\n indexes: readonly { readonly columns: readonly string[] }[] = [],\n): void {\n let tb = k.schema.createTable(fullName).ifNotExists();\n for (const c of columns) {\n tb = tb.addColumn(c.name, sql.raw(c.type), (col) => {\n const withNull = c.notNull || c.primaryKey ? col.notNull() : col;\n // A declared `boolean` is physically an INTEGER here, so nothing but this\n // holds it to 0 and 1. The platform's own write path already checks the\n // value, but the sync-apply path does not: a wire row goes straight to the\n // applier, so a peer running different code can put anything in the\n // column. DSQL needs no equivalent — its native `boolean` *is* the domain\n // — and DSQL could not gain one later anyway, since it rejects\n // `ALTER TABLE ADD CONSTRAINT` (probed 2026-09-10).\n return c.boolean ? withNull.check(sql`${sql.ref(c.name)} in (0, 1)`) : withNull;\n });\n }\n tb = tb\n .addColumn(\"updated_at\", \"text\", (col) => col.notNull())\n .addColumn(\"node_id\", \"text\", (col) => col.notNull())\n .addColumn(\"deleted_at\", \"text\");\n // `syncableTableSchema` refuses a table with no primary key\n // (`admin-manifest/src/schema.ts`), so this branch is now unreachable through\n // any manifest-driven install. It stays because a table created without a\n // constraint is *silently* wrong rather than loudly wrong: the applier's\n // UPSERT would have nothing to conflict on, so every replay of a wire entry —\n // a repair round, a re-ship after a lost response, a watermark reset —\n // inserts the row again, and a tombstone could never name the row it retracts.\n const pks = columns.filter((c) => c.primaryKey).map((c) => c.name);\n if (pks.length > 0) {\n tb = tb.addPrimaryKeyConstraint(`pk_${fullName}`, pks as never[]);\n }\n db.exec(tb.compile().sql);\n db.exec(\n k.schema\n .createIndex(`idx_${fullName}_updated_at`)\n .ifNotExists()\n .on(fullName)\n .column(\"updated_at\")\n .compile().sql,\n );\n db.exec(\n k.schema\n .createIndex(`idx_${fullName}_node_watermark`)\n .ifNotExists()\n .on(fullName)\n .columns([\"node_id\", \"updated_at\"])\n .compile().sql,\n );\n // App-declared indexes. The query grammar makes an expensive question cheap\n // to ask; these are what make it cheap to answer, and without a matching one\n // a new filter or a grouped count is a full scan.\n //\n // Named the same way the DSQL side names them, so the two backends carry the\n // same index under the same name and a reader comparing them is comparing\n // like with like.\n for (const index of indexes) {\n db.exec(\n k.schema\n .createIndex(syncableIndexName(fullName, [...index.columns]))\n .ifNotExists()\n .on(fullName)\n .columns([...index.columns])\n .compile().sql,\n );\n }\n}\n\nexport function createAppSyncableTables(\n db: RawDatabase,\n appId: string,\n tables: readonly SyncableTableDeclaration[],\n): void {\n for (const table of tables) {\n createSyncableTable(\n db,\n appSyncableTableName(appId, table.name),\n table.columns.map((c) => ({\n name: c.name,\n type: sqliteColumnType(c.type),\n notNull: Boolean(c.notNull),\n primaryKey: Boolean(c.primaryKey),\n boolean: c.type === \"boolean\",\n })),\n table.indexes,\n );\n }\n}\n\n/**\n * Create the framework-owned `_starkeep_sync_records` table for an app that\n * opted into `filesEnabled`. Same column shape as the manifest-declared\n * syncable tables (plus the standard updated_at/deleted_at HLC columns) so\n * the LWW applier can treat it uniformly.\n */\nexport function createReservedFileRecordsTable(db: RawDatabase, appId: string): void {\n createSyncableTable(\n db,\n appSyncableTableName(appId, FILE_RECORDS_TABLE),\n // Through the one mapping, like `createAppSyncableTables` above. This was a\n // hand-written ternary whose Postgres twin in `dsql-ddl.ts` answered\n // `bigint` where this one answered `integer`, for one declared type.\n FILE_RECORDS_COLUMNS.map((c) => ({\n name: c.name,\n type: sqliteColumnType(c.type),\n notNull: Boolean(c.notNull),\n primaryKey: Boolean(c.primaryKey),\n })),\n );\n}\n\n/**\n * The namespace registry's description of an app's tables: the declared ones,\n * plus the reserved file-records table when files are enabled. Derived from\n * the declaration rather than read back from SQLite, because a declared type\n * is not recoverable from a physical column, and it runs in the data server,\n * which never sees a manifest.\n */\nexport function appSyncableNamespaceTables(\n syncable: AppSyncableDeclaration,\n): AppSyncableTableInfo[] {\n const declared = syncable.tables.map((t) => appSyncableTableInfo(t.name, t.columns));\n return syncable.files ? [...declared, FILE_RECORDS_TABLE_INFO] : declared;\n}\n\n/**\n * Create an app's syncable tables and register its namespace, from its\n * manifest's `appSpecificSyncable` block. Idempotent, so a node may run it on\n * every start.\n *\n * The desktop's local installer runs the same two halves as separate ledger\n * steps; a node that holds an app's private data without installing the app,\n * as Photos Mobile does, calls this once at bring-up. Both therefore create\n * identical tables.\n */\nexport function registerAppSyncableNamespace(\n db: RawDatabase,\n appId: string,\n syncable: AppSyncableDeclaration,\n): void {\n createAppSyncableTables(db, appId, syncable.tables);\n if (syncable.files) createReservedFileRecordsTable(db, appId);\n upsertAppSyncableNamespace(\n db,\n appId,\n appSyncableNamespaceTables(syncable),\n syncable.files === true,\n );\n}\n","/**\n * Which user a node's library belongs to, and the database half of binding it.\n *\n * One node serves one cloud user. Every object key carries its owner's segment\n * (`shared/<userId>/...`, `apps/<appId>/<userId>/syncable/...`), and a library\n * no cloud has bound yet writes under `LOCAL_USER_SEGMENT`. The first time the\n * node signs in, the ID token's `sub` names the user, and binding renames the\n * `local` segment to that user's id before the first sync:\n * on disk, which each host does its own way, and in every stored key, which\n * this file does for every host. After that, a cloud that names a different\n * user stops sync rather than mixing two users' data.\n *\n * ## The order a host binds in\n *\n * 1. {@link checkLibraryBindable}, which refuses a library bound elsewhere.\n * 2. Move the files under `local` to the user's segment.\n * 3. {@link commitLibraryBinding}, which rewrites the stored keys and stores\n * the user last, in one transaction.\n *\n * A crash part-way leaves the library unbound, so the next start runs the\n * pass again. Every step is idempotent: a file move merges into one already\n * made, and the key rewrites match only keys that still carry `local`.\n *\n * ## The sweep\n *\n * The pass also runs for a library already bound to the same user. A write\n * that built its key under `local` before the pass and landed after it is\n * moved and rewritten by the next pass.\n *\n * See `~/projects/starkeep/plan-multi-user-roles-2026-10-16.md`, step 4.9.\n */\n\nimport { sql } from \"kysely\";\nimport type { RawDatabase } from \"@starkeep/storage-adapter\";\nimport { LOCAL_USER_SEGMENT, USER_SEGMENT_PATTERN } from \"@starkeep/protocol-primitives\";\nimport { compiler as qb } from \"./query-builder.js\";\n\nconst OWNER_TABLE = \"library_owner\";\n\nfunction ensureOwnerTable(db: RawDatabase): void {\n db.exec(\n qb.schema\n .createTable(OWNER_TABLE)\n .ifNotExists()\n .addColumn(\"id\", \"integer\", (c) => c.primaryKey())\n .addColumn(\"user_id\", \"text\", (c) => c.notNull())\n .compile().sql,\n );\n}\n\n/** The user this library is bound to, or null while unbound. */\nexport function boundUserId(db: RawDatabase): string | null {\n ensureOwnerTable(db);\n const row = db\n .prepare(\n qb.selectFrom(OWNER_TABLE).select(\"user_id\").where(\"id\", \"=\", sql.lit(0)).compile().sql,\n )\n .get() as { user_id: string } | undefined;\n return row?.user_id ?? null;\n}\n\n/** The segment this library writes keys under: its bound user, or `local`. */\nexport function libraryUserSegment(db: RawDatabase): string {\n return boundUserId(db) ?? LOCAL_USER_SEGMENT;\n}\n\n/** A column that can hold a `local` key. */\nexport interface LibraryKeyColumn {\n readonly table: string;\n readonly column: string;\n /** Whether the column is the table's primary key, so a rewrite can collide. */\n readonly primaryKey: boolean;\n}\n\n/**\n * The key columns every SQLite node has: records, availability, the resident\n * set, and each app's file index, which stores the full key as its row id.\n * Only the tables this database holds.\n */\nexport function libraryKeyColumns(db: RawDatabase): LibraryKeyColumn[] {\n return coreKeyColumns(db).filter(({ table }) => tableExists(db, table));\n}\n\nfunction coreKeyColumns(db: RawDatabase): LibraryKeyColumn[] {\n const columns: LibraryKeyColumn[] = [\n { table: \"shared_records\", column: \"object_storage_key\", primaryKey: false },\n { table: \"shared_object_availability\", column: \"object_storage_key\", primaryKey: true },\n { table: \"resident_keys\", column: \"object_storage_key\", primaryKey: true },\n { table: \"resident_keys\", column: \"record_id\", primaryKey: false },\n ];\n const tables = db\n .prepare(\n qb.selectFrom(\"sqlite_master\").select(\"name\").where(\"type\", \"=\", sql.lit(\"table\")).compile()\n .sql,\n )\n .all() as Array<{ name: string }>;\n for (const { name } of tables) {\n if (name.endsWith(\"__starkeep_sync_records\")) {\n columns.push(\n { table: name, column: \"id\", primaryKey: true },\n { table: name, column: \"object_storage_key\", primaryKey: false },\n );\n }\n }\n return columns;\n}\n\nfunction tableExists(db: RawDatabase, table: string): boolean {\n return (\n db\n .prepare(\n qb\n .selectFrom(\"sqlite_master\")\n .select(\"name\")\n .where(\"type\", \"=\", sql.lit(\"table\"))\n .where(\"name\", \"=\", sql.lit(table))\n .compile().sql,\n )\n .get() !== undefined\n );\n}\n\n/**\n * The two key namespaces, each as the pattern a `local` key matches and the\n * same key under `userId`.\n */\nfunction namespaces(column: string, userId: string) {\n return [\n {\n local: sql.lit(`shared/${LOCAL_USER_SEGMENT}/%`),\n // Keeps the slash after `local`, so `shared/local/x` becomes `shared/<userId>/x`.\n rebound: sql<string>`'shared/' || ${sql.lit(userId)} || substr(${sql.ref(column)}, ${sql.lit(`shared/${LOCAL_USER_SEGMENT}`.length + 1)})`,\n },\n // apps/<appId>/local/syncable/... — the app id is the segment before `local`.\n {\n local: sql.lit(`apps/%/${LOCAL_USER_SEGMENT}/syncable/%`),\n rebound: sql<string>`replace(${sql.ref(column)}, ${sql.lit(`/${LOCAL_USER_SEGMENT}/syncable/`)}, ${sql.lit(`/${userId}/syncable/`)})`,\n },\n ];\n}\n\n/**\n * Rewrite one key column from the `local` segment to `userId`, in both key\n * namespaces. Keys without the `local` segment are untouched. In a primary-key\n * column, a `local` row whose rewritten key already exists is a duplicate a\n * sweep found, and is dropped: the same key names the same object.\n */\nfunction rebindColumn(\n db: RawDatabase,\n { table, column, primaryKey }: LibraryKeyColumn,\n userId: string,\n): number {\n let changed = 0;\n for (const { local, rebound } of namespaces(column, userId)) {\n if (primaryKey) {\n const duplicates = qb\n .deleteFrom(table)\n .where(sql.ref(column), \"like\", local)\n .where(\n sql<boolean>`${rebound} in (${qb.selectFrom(table).select(sql.ref(column).as(\"k\"))})`,\n )\n .compile();\n db.prepare(duplicates.sql).run(...duplicates.parameters);\n }\n const update = qb\n .updateTable(table)\n .set({ [column]: rebound })\n .where(sql.ref(column), \"like\", local)\n .compile();\n const result = db.prepare(update.sql).run(...update.parameters) as {\n changes?: number | bigint;\n };\n changed += Number(result.changes ?? 0);\n }\n return changed;\n}\n\n/** The cloud names a different user than the one this library belongs to. */\nexport class LibraryBoundElsewhereError extends Error {\n constructor(\n readonly boundTo: string,\n readonly cloudSays: string,\n ) {\n super(\n `This library belongs to user ${boundTo}, but the cloud says this device syncs for user ${cloudSays}. ` +\n `Sync stays off so the two libraries do not mix.`,\n );\n this.name = \"LibraryBoundElsewhereError\";\n }\n}\n\n/**\n * Refuse to bind the library to `userId` when it cannot be: the id is not a\n * user segment, or the library belongs to someone else. Runs before a host\n * moves any file.\n */\nexport function checkLibraryBindable(db: RawDatabase, userId: string): void {\n if (!USER_SEGMENT_PATTERN.test(userId) || userId === LOCAL_USER_SEGMENT) {\n throw new Error(`cannot bind the library to ${JSON.stringify(userId)}`);\n }\n const current = boundUserId(db);\n if (current !== null && current !== userId) throw new LibraryBoundElsewhereError(current, userId);\n}\n\n/**\n * Rewrite every stored key from `local` to `userId`, then store the user, in\n * one transaction. A host passes the key columns of its own tables in\n * `extraKeyColumns`. Returns how many keys changed.\n */\nexport function commitLibraryBinding(\n db: RawDatabase,\n userId: string,\n extraKeyColumns: readonly LibraryKeyColumn[] = [],\n): number {\n checkLibraryBindable(db, userId);\n const columns = [...coreKeyColumns(db), ...extraKeyColumns].filter(({ table }) =>\n tableExists(db, table),\n );\n let rewritten = 0;\n db.exec(\"BEGIN\");\n try {\n for (const column of columns) rewritten += rebindColumn(db, column, userId);\n db.prepare(\n qb\n .insertInto(OWNER_TABLE)\n .values({ id: sql.lit(0), user_id: sql.raw(\"?\") })\n .onConflict((oc) =>\n oc.column(\"id\").doUpdateSet((eb) => ({ user_id: eb.ref(\"excluded.user_id\") })),\n )\n .compile().sql,\n ).run(userId);\n db.exec(\"COMMIT\");\n } catch (err) {\n db.exec(\"ROLLBACK\");\n throw err;\n }\n return rewritten;\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;;;ACCA,IAAAA,0BAA+B;AAS/B,IAAAC,8BASO;AAeP,IAAAD,0BA4CO;AACP,IAAAE,iBAA4B;;;AC9E5B,iCAMO;AAwFP,6BAAwE;AAzDjE,SAAS,YAAY,QAA+B;AACzD,SAAO;AAAA,IACL,IAAI,OAAO;AAAA,IACX,MAAM,OAAO;AAAA,IACb,gBAAY,yCAAa,OAAO,SAAS;AAAA,IACzC,gBAAY,yCAAa,OAAO,SAAS;AAAA,IACzC,SAAS,OAAO,UAAU;AAAA,IAC1B,YAAY,OAAO,gBAAY,yCAAa,OAAO,SAAS,IAAI;AAAA,IAChE,SAAS,OAAO;AAAA,IAChB,cAAc,OAAO;AAAA,IACrB,oBAAoB,OAAO;AAAA,IAC3B,WAAW,OAAO;AAAA,IAClB,YAAY,OAAO;AAAA,IACnB,mBAAmB,OAAO;AAAA,IAC1B,eAAe,OAAO;AAAA,IACtB,WAAW,OAAO;AAAA,IAClB,eAAe,OAA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AAE,IAAI,MAAM;AACZ,OAAG,KAAK,QAAQ;AAAA,EAClB,SAAS,KAAK;AACZ,OAAG,KAAK,UAAU;AAClB,UAAM;AAAA,EACR;AACA,SAAO;AACT;","names":["import_storage_adapter","import_protocol_primitives","import_kysely","import_storage_adapter","import_protocol_primitives","import_kysely","import_protocol_primitives","kSql","sql","compiled","import_kysely","import_protocol_primitives","import_shared_space_api","import_storage_adapter","compiled","import_kysely","import_shared_space_api","import_protocol_primitives","import_kysely","import_protocol_primitives"]}