@starkeep/storage-sqlite 0.3.0 → 0.4.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.js CHANGED
@@ -1,7 +1,4 @@
1
1
  // src/adapter.ts
2
- import { DatabaseSync } from "sqlite";
3
- import { mkdirSync, existsSync } from "fs";
4
- import { dirname } from "path";
5
2
  import { serializeHLC as serializeHLC2, deserializeHLC as deserializeHLC2, sqliteMetadataTableName } from "@starkeep/protocol-primitives";
6
3
  import {
7
4
  StorageError,
@@ -107,6 +104,16 @@ function buildSelectQuery(query) {
107
104
  qb = applyFilter(qb, filter);
108
105
  }
109
106
  }
107
+ if (query.excludeLabel) {
108
+ const { appId, key } = query.excludeLabel;
109
+ qb = qb.where(
110
+ (eb) => eb.not(
111
+ eb.exists(
112
+ eb.selectFrom("shared_record_labels").select("record_id").whereRef("shared_record_labels.record_id", "=", "shared_records.id").where("app_id", "=", appId).where("key", "=", key).where("deleted_at", "is", null)
113
+ )
114
+ )
115
+ );
116
+ }
110
117
  if (query.cursor) {
111
118
  qb = qb.where("id", ">", query.cursor);
112
119
  }
@@ -165,6 +172,15 @@ function applyLocalSchemaDdl(db) {
165
172
  compiler.schema.createIndex("idx_shared_records_node_watermark").ifNotExists().on("shared_records").columns(["node_id", "updated_at"]),
166
173
  compiler.schema.createIndex("idx_shared_records_origin_app").ifNotExists().on("shared_records").column("origin_app_id"),
167
174
  compiler.schema.createIndex("idx_shared_records_parent_id").ifNotExists().on("shared_records").column("parent_id"),
175
+ // Record-level dedup: "is there already a live record for these bytes
176
+ // under this parent?", asked on **every** registration.
177
+ //
178
+ // The (filename, content_hash) unique index below cannot serve it — its
179
+ // leading column is the filename, so a hash-only lookup would scan the
180
+ // table once per write. Leading with content_hash is what makes the dedup
181
+ // check affordable enough to be unconditional, and unconditional is what
182
+ // makes "one object key, one record" an invariant rather than a hope.
183
+ compiler.schema.createIndex("idx_shared_records_content_hash").ifNotExists().on("shared_records").columns(["content_hash", "parent_id", "deleted_at"]),
168
184
  // Duplicate-file prevention: (filename + bytes) is unique among live
169
185
  // records. Tombstoned rows (deleted_at IS NOT NULL) are excluded so a
170
186
  // re-upload after delete is allowed. Records with NULL filename are not
@@ -201,6 +217,9 @@ function applyLocalSchemaDdl(db) {
201
217
  for (const index of sharedRecordLabelsIndexes) {
202
218
  db.exec(index.compile().sql);
203
219
  }
220
+ db.exec(
221
+ compiler.schema.createTable("shared_object_availability").ifNotExists().addColumn("object_storage_key", "text", (c) => c.primaryKey()).addColumn("state", "text", (c) => c.notNull()).addColumn("tier", "text").addColumn("expected_latency_hours", "integer").addColumn("ready_at_ms", "integer").addColumn("restored_until_ms", "integer").addColumn("observed_at_ms", "integer", (c) => c.notNull()).compile().sql
222
+ );
204
223
  db.exec(
205
224
  compiler.schema.createTable("shared_app_label_keys").ifNotExists().addColumn("app_id", "text", (c) => c.notNull()).addColumn("key", "text", (c) => c.notNull()).addColumn("description", "text").addColumn("created_at", "text", (c) => c.notNull().defaultTo(sql`(datetime('now'))`)).addPrimaryKeyConstraint("pk_shared_app_label_keys", ["app_id", "key"]).compile().sql
206
225
  );
@@ -242,28 +261,36 @@ function initializeLocalSchema(db) {
242
261
  }
243
262
 
244
263
  // src/adapter.ts
264
+ var AVAILABILITY = "shared_object_availability";
265
+ function rowToAvailability(row) {
266
+ return {
267
+ objectStorageKey: row.object_storage_key,
268
+ state: row.state,
269
+ tier: row.tier,
270
+ expectedLatencyHours: row.expected_latency_hours,
271
+ readyAtMs: row.ready_at_ms,
272
+ restoredUntilMs: row.restored_until_ms,
273
+ observedAtMs: row.observed_at_ms
274
+ };
275
+ }
245
276
  var LABELS = {
246
277
  table: "shared_record_labels"
247
278
  };
248
279
  var SqliteDatabaseAdapter = class {
249
280
  database = null;
250
281
  options;
282
+ driver;
251
283
  constructor(options) {
252
284
  this.options = options;
285
+ this.driver = options.driver;
253
286
  }
254
287
  async init() {
255
288
  if (this.database) return;
256
- if (this.options.path !== ":memory:") {
257
- const dir = dirname(this.options.path);
258
- if (!existsSync(dir)) {
259
- mkdirSync(dir, { recursive: true });
260
- }
261
- }
262
- this.database = new DatabaseSync(this.options.path);
289
+ this.database = this.driver.open(this.options.path);
263
290
  initializeLocalSchema(this.database);
264
291
  }
265
292
  async close() {
266
- this.database?.close();
293
+ if (this.database) this.driver.close(this.database);
267
294
  this.database = null;
268
295
  }
269
296
  async healthCheck() {
@@ -280,25 +307,31 @@ var SqliteDatabaseAdapter = class {
280
307
  return this.database;
281
308
  }
282
309
  /**
283
- * Returns the raw SQLite connection so sibling subsystems (e.g. the sync
284
- * engine's change log + state store) can create side tables in the same
285
- * database file. Callers must only use this after `init()`.
310
+ * The raw SQLite connection, so sibling subsystems (the sync engine's change
311
+ * log and state store, the resident set) can create side tables in the same
312
+ * database file. Only valid after `init()`.
313
+ *
314
+ * Typed as {@link RawDatabase} rather than `DatabaseSync`: returning the
315
+ * concrete Node type is what made a second driver impossible, since every
316
+ * consumer was then nailed to `node:sqlite`, which React Native does not
317
+ * have. `DatabaseSync` satisfies the narrower interface structurally, so
318
+ * nothing about this connection changes — only what callers may reach for.
286
319
  */
287
320
  getRawDatabase() {
288
321
  return this.getDatabase();
289
322
  }
323
+ // The casts these three used to carry named `DatabaseSync["prepare"]` to
324
+ // borrow node:sqlite's parameter types. `RawStatement` declares `unknown[]`
325
+ // directly, so they were already no-ops — and they were the last thing in
326
+ // this file referring to a concrete driver.
290
327
  runStmt(sql3, ...params) {
291
328
  this.getDatabase().prepare(sql3).run(...params);
292
329
  }
293
330
  getRow(sql3, ...params) {
294
- return this.getDatabase().prepare(sql3).get(
295
- ...params
296
- );
331
+ return this.getDatabase().prepare(sql3).get(...params);
297
332
  }
298
333
  allRows(sql3, ...params) {
299
- return this.getDatabase().prepare(sql3).all(
300
- ...params
301
- );
334
+ return this.getDatabase().prepare(sql3).all(...params);
302
335
  }
303
336
  async put(record) {
304
337
  const row = recordToRow(record);
@@ -497,6 +530,47 @@ var SqliteDatabaseAdapter = class {
497
530
  for (const row of rows) out[row.node_id] = deserializeHLC2(row.max_updated_at);
498
531
  return out;
499
532
  }
533
+ // ---- Object availability ------------------------------------------------
534
+ async getAvailability(objectStorageKeys) {
535
+ const out = /* @__PURE__ */ new Map();
536
+ if (objectStorageKeys.length === 0) return out;
537
+ const compiled = compiler.selectFrom(AVAILABILITY).selectAll().where("object_storage_key", "in", objectStorageKeys).compile();
538
+ const rows = this.allRows(compiled.sql, ...compiled.parameters);
539
+ for (const row of rows) out.set(row.object_storage_key, rowToAvailability(row));
540
+ return out;
541
+ }
542
+ async putAvailability(row) {
543
+ const compiled = compiler.insertInto(AVAILABILITY).values({
544
+ object_storage_key: row.objectStorageKey,
545
+ state: row.state,
546
+ tier: row.tier,
547
+ expected_latency_hours: row.expectedLatencyHours,
548
+ ready_at_ms: row.readyAtMs,
549
+ restored_until_ms: row.restoredUntilMs,
550
+ observed_at_ms: row.observedAtMs
551
+ }).onConflict(
552
+ (oc) => oc.column("object_storage_key").doUpdateSet((eb) => ({
553
+ state: eb.ref("excluded.state"),
554
+ tier: eb.ref("excluded.tier"),
555
+ expected_latency_hours: eb.ref("excluded.expected_latency_hours"),
556
+ ready_at_ms: eb.ref("excluded.ready_at_ms"),
557
+ restored_until_ms: eb.ref("excluded.restored_until_ms"),
558
+ observed_at_ms: eb.ref("excluded.observed_at_ms")
559
+ }))
560
+ ).compile();
561
+ this.runStmt(compiled.sql, ...compiled.parameters);
562
+ }
563
+ async countRestoringObjects() {
564
+ const compiled = compiler.selectFrom(AVAILABILITY).innerJoin("shared_records", "shared_records.object_storage_key", `${AVAILABILITY}.object_storage_key`).select(({ fn }) => [
565
+ fn.count(`${AVAILABILITY}.object_storage_key`).as("object_count"),
566
+ fn.sum("shared_records.size_bytes").as("bytes")
567
+ ]).where(`${AVAILABILITY}.state`, "=", kSql.lit("restoring")).compile();
568
+ const row = this.getRow(
569
+ compiled.sql,
570
+ ...compiled.parameters
571
+ );
572
+ return { objectCount: row?.object_count ?? 0, bytes: row?.bytes ?? 0 };
573
+ }
500
574
  async tombstoneLabelsForRecord(recordId, hlc) {
501
575
  const query = buildTombstoneLabelsForRecord(compiler, LABELS, recordId, hlc);
502
576
  this.runStmt(query.sql, ...query.parameters);
package/dist/index.js.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"sources":["../src/adapter.ts","../src/serialization.ts","../src/query-builder.ts","../src/schema/bootstrap.ts","../src/app-syncable/namespace.ts","../src/app-syncable/apply.ts"],"sourcesContent":["import { DatabaseSync } from \"node:sqlite\";\nimport { mkdirSync, existsSync } from \"node:fs\";\nimport { dirname } from \"node:path\";\nimport type {\n DataRecord,\n HLCTimestamp,\n MetadataRow,\n RecordLabel,\n StarkeepId,\n} from \"@starkeep/protocol-primitives\";\nimport { serializeHLC, deserializeHLC, sqliteMetadataTableName } 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} from \"@starkeep/storage-adapter\";\nimport {\n StorageError,\n TransactionError,\n buildFindByLabel,\n buildGetLabel,\n buildLabelNodeWatermarks,\n buildLabelRetraction,\n buildLabelValueReplacementTombstone,\n buildLabelSnapshotUpsert,\n buildLabelUpsert,\n buildLabelsByRecordIds,\n buildQueryLabels,\n buildTombstoneLabelsForRecord,\n groupLabelsByRecordId,\n paginateFindByLabel,\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 { buildSelectQuery, compiler as qb } from \"./query-builder.js\";\nimport { initializeLocalSchema } from \"./schema/bootstrap.js\";\n\nexport interface SqliteDatabaseAdapterOptions {\n path: string | \":memory:\";\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 LABELS: LabelDialect = {\n table: \"shared_record_labels\",\n};\n\nexport class SqliteDatabaseAdapter implements DatabaseAdapter {\n private database: DatabaseSync | null = null;\n private readonly options: SqliteDatabaseAdapterOptions;\n\n constructor(options: SqliteDatabaseAdapterOptions) {\n this.options = options;\n }\n\n async init(): Promise<void> {\n if (this.database) return;\n if (this.options.path !== \":memory:\") {\n const dir = dirname(this.options.path);\n if (!existsSync(dir)) {\n mkdirSync(dir, { recursive: true });\n }\n }\n this.database = new DatabaseSync(this.options.path);\n initializeLocalSchema(this.database);\n }\n\n async close(): Promise<void> {\n this.database?.close();\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(): DatabaseSync {\n if (!this.database) throw new StorageError(\"Database not initialized. Call init() first.\");\n return this.database;\n }\n\n /**\n * Returns the raw SQLite connection so sibling subsystems (e.g. the sync\n * engine's change log + state store) can create side tables in the same\n * database file. Callers must only use this after `init()`.\n */\n getRawDatabase(): DatabaseSync {\n return this.getDatabase();\n }\n\n private runStmt(sql: string, ...params: unknown[]): void {\n this.getDatabase().prepare(sql).run(...(params as Parameters<ReturnType<DatabaseSync[\"prepare\"]>[\"run\"]>));\n }\n\n private getRow<T = SqliteRow>(sql: string, ...params: unknown[]): T | undefined {\n return this.getDatabase().prepare(sql).get(\n ...(params as Parameters<ReturnType<DatabaseSync[\"prepare\"]>[\"get\"]>),\n ) as unknown as T | undefined;\n }\n\n private allRows<T = SqliteRow>(sql: string, ...params: unknown[]): T[] {\n return this.getDatabase().prepare(sql).all(\n ...(params as Parameters<ReturnType<DatabaseSync[\"prepare\"]>[\"all\"]>),\n ) as unknown 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.column(\"id\").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 .set({ deleted_at: ts, updated_at: ts, node_id: hlc.nodeId })\n .where(\"id\", \"=\", id)\n .compile();\n this.runStmt(query.sql, ...query.parameters);\n }\n\n async getNodeWatermarks(): Promise<Record<string, HLCTimestamp>> {\n // Within one node_id group, updated_at is fixed-width hex up to the\n // nodeId suffix, so lexicographic MAX equals HLC MAX. The\n // (node_id, updated_at) index makes this an index-only scan.\n const watermarksQuery = qb\n .selectFrom(\"shared_records\")\n .select(({ fn }) => [\"node_id\", fn.max(\"updated_at\").as(\"max_updated_at\")])\n .groupBy(\"node_id\")\n .compile();\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 query(query: Query): Promise<QueryResult> {\n const { sql, params } = buildSelectQuery(query);\n const rows = this.allRows<SqliteRow>(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 nextCursor: hasMore ? resultRows[resultRows.length - 1].id : null,\n hasMore,\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(typeId: string, row: MetadataRow): Promise<void> {\n const table = sqliteMetadataTableName(typeId);\n const values: Record<string, unknown> = { record_id: row.recordId };\n for (const [key, value] of Object.entries(row)) {\n if (key === \"recordId\") continue;\n values[key] = value;\n }\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.column(\"record_id\").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, 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, 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 // ---- 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(\n recordIds: StarkeepId[],\n ): Promise<Map<StarkeepId, RecordLabel[]>> {\n if (recordIds.length === 0) return new Map();\n const query = buildLabelsByRecordIds(qb, LABELS, recordIds);\n return groupLabelsByRecordId(\n this.allRows<LabelRow>(query.sql, ...query.parameters),\n );\n }\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 compiled = buildFindByLabel(qb, LABELS, query);\n if (!compiled) return { labels: [], nextCursor: null, hasMore: false };\n const rows = this.allRows<LabelRow>(compiled.sql, ...compiled.parameters);\n return paginateFindByLabel(rows, query.limit);\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 = buildLabelNodeWatermarks(qb, LABELS);\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 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\nfunction columnsToMetadataRow(\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 {\n DataRecord,\n MetadataRow,\n StarkeepId,\n} from \"@starkeep/protocol-primitives\";\nimport { serializeHLC, deserializeHLC, createStarkeepId } 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}\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 };\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 };\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 DummyDriver,\n Kysely,\n SqliteAdapter,\n SqliteIntrospector,\n SqliteQueryCompiler,\n type ExpressionBuilder,\n type SelectQueryBuilder,\n} from \"kysely\";\n\n// External (camelCase) → column name (snake_case). Unknown fields pass through.\nconst FIELD_MAP: Record<string, string> = {\n id: \"id\",\n type: \"type\",\n createdAt: \"created_at\",\n updatedAt: \"updated_at\",\n deletedAt: \"deleted_at\",\n version: \"version\",\n contentHash: \"content_hash\",\n objectStorageKey: \"object_storage_key\",\n mimeType: \"mime_type\",\n sizeBytes: \"size_bytes\",\n originAppId: \"origin_app_id\",\n parentId: \"parent_id\",\n originalFilename: \"original_filename\",\n};\n\nfunction mapField(field: string): string {\n return FIELD_MAP[field] ?? field;\n}\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\nexport interface BuiltQuery {\n sql: string;\n params: unknown[];\n}\n\nexport function buildSelectQuery(query: Query): BuiltQuery {\n type Qb = SelectQueryBuilder<DB, \"shared_records\", unknown>;\n let qb = compiler.selectFrom(\"shared_records\").selectAll() as Qb;\n\n if (query.type) {\n qb = qb.where(\"type\", \"=\", query.type);\n }\n\n if (query.filters) {\n for (const filter of query.filters) {\n qb = applyFilter(qb, filter);\n }\n }\n\n if (query.cursor) {\n qb = qb.where(\"id\", \">\", query.cursor);\n }\n\n if (query.sort && query.sort.length > 0) {\n for (const s of query.sort) {\n qb = qb.orderBy(mapField(s.field), s.direction === \"desc\" ? \"desc\" : \"asc\");\n }\n } else {\n qb = qb.orderBy(\"id\", \"asc\");\n }\n\n if (query.limit) {\n qb = qb.limit(query.limit + 1); // +1 to detect hasMore\n }\n\n const compiled = qb.compile();\n return { sql: compiled.sql, params: [...compiled.parameters] };\n}\n\nfunction applyFilter<Qb extends SelectQueryBuilder<DB, \"shared_records\", unknown>>(\n qb: Qb,\n filter: { field: string; operator: string; value?: unknown },\n): Qb {\n const col = mapField(filter.field);\n switch (filter.operator) {\n case \"eq\": return qb.where(col, \"=\", filter.value) as Qb;\n case \"neq\": return qb.where(col, \"!=\", filter.value) as Qb;\n case \"gt\": return qb.where(col, \">\", filter.value) as Qb;\n case \"gte\": return qb.where(col, \">=\", filter.value) as Qb;\n case \"lt\": return qb.where(col, \"<\", filter.value) as Qb;\n case \"lte\": return qb.where(col, \"<=\", filter.value) as Qb;\n case \"in\": return qb.where(col, \"in\", filter.value as unknown[]) as Qb;\n case \"like\": return qb.where(col, \"like\", `%${filter.value}%`) as Qb;\n case \"isNull\":\n return qb.where((eb: ExpressionBuilder<DB, \"shared_records\">) => eb(col, \"is\", null)) as Qb;\n case \"isNotNull\":\n return qb.where((eb: ExpressionBuilder<DB, \"shared_records\">) => eb(col, \"is not\", null)) as Qb;\n default: return qb;\n }\n}\n","import type { DatabaseSync } from \"node:sqlite\";\nimport { sql } from \"kysely\";\nimport { CATEGORIES, sqliteMetadataDdl } 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 */\nfunction applyLocalSchemaDdl(db: DatabaseSync): void {\n db.exec(\"PRAGMA journal_mode = WAL\");\n db.exec(\"PRAGMA foreign_keys = ON\");\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 .compile().sql,\n );\n const sharedRecordsIndexes = [\n qb.schema.createIndex(\"idx_shared_records_type\").ifNotExists().on(\"shared_records\").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 // Duplicate-file prevention: (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. Records with NULL filename are not\n // constrained — the rule requires both filename and content to match.\n qb.schema\n .createIndex(\"uq_shared_records_filename_hash\")\n .ifNotExists()\n .unique()\n .on(\"shared_records\")\n .columns([\"original_filename\", \"content_hash\"])\n .where(sql.ref(\"deleted_at\"), \"is\", null)\n .where(sql.ref(\"original_filename\"), \"is not\", null),\n ];\n for (const index of sharedRecordsIndexes) {\n db.exec(index.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_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 (c.id === \"other\") continue;\n db.exec(sqliteMetadataDdl(c));\n }\n}\n\nexport function initializeLocalSchema(db: DatabaseSync): 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","import type { DatabaseSync } from \"node:sqlite\";\nimport { compiler as qb } from \"../query-builder.js\";\nimport type {\n AppSyncableNamespace,\n AppSyncableTableInfo,\n AppSyncableNamespaceStore,\n} 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: AppSyncableTableInfo[] = JSON.parse(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: DatabaseSync,\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: DatabaseSync, 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: DatabaseSync,\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\n .prepare(query.sql)\n .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: DatabaseSync): AppSyncableNamespace[] {\n const query = qb\n .selectFrom(\"app_syncable_namespaces\")\n .select([\"app_id\", \"tables_json\", \"files_enabled\"])\n .compile();\n const rows = db\n .prepare(query.sql)\n .all() as Array<{ app_id: string; tables_json: string; files_enabled: number }>;\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: DatabaseSync) {}\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 { DatabaseSync } from \"node:sqlite\";\nimport { sql, type CompiledQuery } from \"kysely\";\nimport type { HLCTimestamp } from \"@starkeep/protocol-primitives\";\nimport { serializeHLC, deserializeHLC } from \"@starkeep/protocol-primitives\";\nimport type { AppSyncableApplier, AppSyncableRowEntry, AppSyncableNamespaceStore, ScanCapableApplier, ScanSinceOptions, ScanSincePage } from \"@starkeep/shared-space-api\";\nimport { compiler as qb } from \"../query-builder.js\";\nimport { appSyncableTableName } from \"./namespace.js\";\n\ntype SqlParam = null | number | bigint | string | Uint8Array;\n\nfunction runCompiled(db: DatabaseSync, compiled: CompiledQuery): void {\n db.prepare(compiled.sql).run(...(compiled.parameters as SqlParam[]));\n}\n\nfunction allCompiled<T>(db: DatabaseSync, compiled: CompiledQuery): T[] {\n return db.prepare(compiled.sql).all(...(compiled.parameters as SqlParam[])) 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\n implements AppSyncableApplier, ScanCapableApplier\n{\n constructor(\n private readonly db: DatabaseSync,\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(\n `SqliteAppSyncableApplier: app \"${entry.appId}\" not installed`,\n );\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, entry);\n } else {\n this.applyDelete(fullName, entry);\n }\n }\n\n private applyInsert(\n fullName: string,\n pkColumns: string[],\n entry: AppSyncableRowEntry,\n ): 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.insertInto(fullName).orIgnore().values({ ...row }).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(fullName: string, entry: AppSyncableRowEntry): 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 = entry.where ?? {};\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 query = query.where(\"updated_at\", \"<\", incomingUpdatedAt);\n }\n runCompiled(this.db, query.compile());\n }\n\n private applyDelete(fullName: string, entry: AppSyncableRowEntry): void {\n const where = entry.where ?? {};\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 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) =>\n eb.or([eb(\"updated_at\", \"is\", null), eb(\"updated_at\", \"<\", ts)]),\n );\n runCompiled(this.db, query.compile());\n }\n\n /** See `ScanCapableApplier.getNodeWatermarks`. Missing table → `{}`. */\n async getNodeWatermarks(\n appId: string,\n table: string,\n ): Promise<Record<string, HLCTimestamp>> {\n const fullName = appSyncableTableName(appId, table);\n let rows: { node_id: string; max_updated_at: string }[];\n try {\n rows = allCompiled<{ node_id: string; max_updated_at: string }>(\n this.db,\n qb\n .selectFrom(fullName)\n .select(({ fn }) => [\"node_id\", fn.max(\"updated_at\").as(\"max_updated_at\")])\n .groupBy(\"node_id\")\n .compile(),\n );\n } catch {\n // Table might not exist yet (app not installed locally).\n return {};\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: return rows updated after `sinceHlcStr` (or `cursor`\n * if higher) in HLC order, paginated. `updated_at` is a serialized HLC\n * whose lexicographic order matches HLC order (fixed-width hex), and each\n * row's HLC is unique per node, so it doubles as the cursor — no separate\n * tiebreaker column is needed.\n */\n async scanSince(\n appId: string,\n table: string,\n sinceHlcStr: string,\n options?: ScanSinceOptions,\n ): Promise<ScanSincePage> {\n const fullName = appSyncableTableName(appId, table);\n const floor =\n options?.cursor !== undefined && options.cursor > sinceHlcStr\n ? options.cursor\n : sinceHlcStr;\n const limit = options?.limit;\n let rows: Record<string, unknown>[];\n try {\n let query = qb\n .selectFrom(fullName)\n .selectAll()\n .where(\"updated_at\", \">\", floor)\n .orderBy(\"updated_at\", \"asc\");\n if (limit !== undefined) {\n query = query.limit(limit + 1);\n }\n rows = allCompiled<Record<string, unknown>>(this.db, query.compile());\n } catch {\n // Table might not exist yet (app not installed locally).\n return { rows: [], nextCursor: null, hasMore: false };\n }\n const hasMore = limit !== undefined && rows.length > limit;\n const pageRows = hasMore ? rows.slice(0, limit) : rows;\n const entries = pageRows.map((row) => rowToEntry(appId, table, row));\n const nextCursor =\n hasMore && pageRows.length > 0\n ? (pageRows[pageRows.length - 1]![\"updated_at\"] as string)\n : null;\n return { rows: entries, nextCursor, hasMore };\n }\n\n /** Support read path from the factory's queryRows. */\n queryRows(\n appId: string,\n table: string,\n where?: Record<string, unknown>,\n ): Record<string, unknown>[] {\n const fullName = appSyncableTableName(appId, table);\n const whereCols = where ? Object.keys(where) : [];\n // Filter out soft-deleted rows by default.\n let query = qb.selectFrom(fullName).selectAll().where(\"deleted_at\", \"is\", null);\n for (const c of whereCols) {\n query = query.where(c, \"=\", where![c]);\n }\n return allCompiled<Record<string, unknown>>(this.db, query.compile());\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\nfunction rowToEntry(\n appId: string,\n table: string,\n row: Record<string, unknown>,\n): AppSyncableRowEntry {\n const updatedAtStr = row[\"updated_at\"] as string;\n const deletedAtStr = row[\"deleted_at\"] as string | null | undefined;\n const timestamp = deserializeHLC(updatedAtStr);\n\n // For wire propagation we emit op=\"insert\" (upsert) for live rows so the\n // receiver creates the row if it doesn't exist yet. op=\"update\" only\n // targets existing rows and would silently drop new rows during initial\n // sync. Tombstones still ride the soft-delete path.\n if (deletedAtStr) {\n return { timestamp, appId, table, op: \"delete\", row };\n }\n return { timestamp, appId, table, op: \"insert\", row };\n}\n"],"mappings":";AAAA,SAAS,oBAAoB;AAC7B,SAAS,WAAW,kBAAkB;AACtC,SAAS,eAAe;AAQxB,SAAS,gBAAAA,eAAc,kBAAAC,iBAAgB,+BAA+B;AAatE;AAAA,EACE;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EAC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el","sql","serializeHLC","deserializeHLC","sql","serializeHLC","deserializeHLC"]}
1
+ {"version":3,"sources":["../src/adapter.ts","../src/serialization.ts","../src/query-builder.ts","../src/schema/bootstrap.ts","../src/app-syncable/namespace.ts","../src/app-syncable/apply.ts"],"sourcesContent":["import type { RawDatabase } from \"@starkeep/storage-adapter\";\nimport type {\n DataRecord,\n HLCTimestamp,\n MetadataRow,\n RecordLabel,\n StarkeepId,\n} from \"@starkeep/protocol-primitives\";\nimport { serializeHLC, deserializeHLC, sqliteMetadataTableName } 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} from \"@starkeep/storage-adapter\";\nimport {\n StorageError,\n TransactionError,\n buildFindByLabel,\n buildGetLabel,\n buildLabelNodeWatermarks,\n buildLabelRetraction,\n buildLabelValueReplacementTombstone,\n buildLabelSnapshotUpsert,\n buildLabelUpsert,\n buildLabelsByRecordIds,\n buildQueryLabels,\n buildTombstoneLabelsForRecord,\n groupLabelsByRecordId,\n paginateFindByLabel,\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 { buildSelectQuery, compiler as qb } from \"./query-builder.js\";\nimport { initializeLocalSchema } from \"./schema/bootstrap.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\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 private runStmt(sql: string, ...params: unknown[]): void {\n this.getDatabase().prepare(sql).run(...params);\n }\n\n private getRow<T = SqliteRow>(sql: string, ...params: unknown[]): T | undefined {\n return this.getDatabase().prepare(sql).get(...params) as T | undefined;\n }\n\n private allRows<T = SqliteRow>(sql: string, ...params: unknown[]): T[] {\n return this.getDatabase().prepare(sql).all(...params) 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.column(\"id\").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 .set({ deleted_at: ts, updated_at: ts, node_id: hlc.nodeId })\n .where(\"id\", \"=\", id)\n .compile();\n this.runStmt(query.sql, ...query.parameters);\n }\n\n async getNodeWatermarks(): Promise<Record<string, HLCTimestamp>> {\n // Within one node_id group, updated_at is fixed-width hex up to the\n // nodeId suffix, so lexicographic MAX equals HLC MAX. The\n // (node_id, updated_at) index makes this an index-only scan.\n const watermarksQuery = qb\n .selectFrom(\"shared_records\")\n .select(({ fn }) => [\"node_id\", fn.max(\"updated_at\").as(\"max_updated_at\")])\n .groupBy(\"node_id\")\n .compile();\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 query(query: Query): Promise<QueryResult> {\n const { sql, params } = buildSelectQuery(query);\n const rows = this.allRows<SqliteRow>(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 nextCursor: hasMore ? resultRows[resultRows.length - 1].id : null,\n hasMore,\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(typeId: string, row: MetadataRow): Promise<void> {\n const table = sqliteMetadataTableName(typeId);\n const values: Record<string, unknown> = { record_id: row.recordId };\n for (const [key, value] of Object.entries(row)) {\n if (key === \"recordId\") continue;\n values[key] = value;\n }\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.column(\"record_id\").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, 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, 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 // ---- 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(\n recordIds: StarkeepId[],\n ): Promise<Map<StarkeepId, RecordLabel[]>> {\n if (recordIds.length === 0) return new Map();\n const query = buildLabelsByRecordIds(qb, LABELS, recordIds);\n return groupLabelsByRecordId(\n this.allRows<LabelRow>(query.sql, ...query.parameters),\n );\n }\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 compiled = buildFindByLabel(qb, LABELS, query);\n if (!compiled) return { labels: [], nextCursor: null, hasMore: false };\n const rows = this.allRows<LabelRow>(compiled.sql, ...compiled.parameters);\n return paginateFindByLabel(rows, query.limit);\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 = buildLabelNodeWatermarks(qb, LABELS);\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(\"shared_records\", \"shared_records.object_storage_key\", `${AVAILABILITY}.object_storage_key`)\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\nfunction columnsToMetadataRow(\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 {\n DataRecord,\n MetadataRow,\n StarkeepId,\n} from \"@starkeep/protocol-primitives\";\nimport { serializeHLC, deserializeHLC, createStarkeepId } 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}\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 };\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 };\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 DummyDriver,\n Kysely,\n SqliteAdapter,\n SqliteIntrospector,\n SqliteQueryCompiler,\n type ExpressionBuilder,\n type SelectQueryBuilder,\n} from \"kysely\";\n\n// External (camelCase) → column name (snake_case). Unknown fields pass through.\nconst FIELD_MAP: Record<string, string> = {\n id: \"id\",\n type: \"type\",\n createdAt: \"created_at\",\n updatedAt: \"updated_at\",\n deletedAt: \"deleted_at\",\n version: \"version\",\n contentHash: \"content_hash\",\n objectStorageKey: \"object_storage_key\",\n mimeType: \"mime_type\",\n sizeBytes: \"size_bytes\",\n originAppId: \"origin_app_id\",\n parentId: \"parent_id\",\n originalFilename: \"original_filename\",\n};\n\nfunction mapField(field: string): string {\n return FIELD_MAP[field] ?? field;\n}\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\nexport interface BuiltQuery {\n sql: string;\n params: unknown[];\n}\n\nexport function buildSelectQuery(query: Query): BuiltQuery {\n type Qb = SelectQueryBuilder<DB, \"shared_records\", unknown>;\n let qb = compiler.selectFrom(\"shared_records\").selectAll() as Qb;\n\n if (query.type) {\n qb = qb.where(\"type\", \"=\", query.type);\n }\n\n if (query.filters) {\n for (const filter of query.filters) {\n qb = applyFilter(qb, filter);\n }\n }\n\n if (query.excludeLabel) {\n // NOT EXISTS rather than a LEFT JOIN … IS NULL: a record can carry several\n // values of one key, and a join would multiply its row before the null\n // test, so the record would come back once per *other* label it holds.\n // The tombstone check is not optional — a retracted rendition label means\n // the record is no longer a rendition, and treating the dead row as live\n // would permanently hide it from the grid.\n const { appId, key } = query.excludeLabel;\n qb = qb.where((eb: ExpressionBuilder<DB, \"shared_records\">) =>\n eb.not(\n eb.exists(\n eb\n .selectFrom(\"shared_record_labels\")\n .select(\"record_id\")\n .whereRef(\"shared_record_labels.record_id\", \"=\", \"shared_records.id\")\n .where(\"app_id\", \"=\", appId)\n .where(\"key\", \"=\", key)\n .where(\"deleted_at\", \"is\", null),\n ),\n ),\n ) as Qb;\n }\n\n if (query.cursor) {\n qb = qb.where(\"id\", \">\", query.cursor);\n }\n\n if (query.sort && query.sort.length > 0) {\n for (const s of query.sort) {\n qb = qb.orderBy(mapField(s.field), s.direction === \"desc\" ? \"desc\" : \"asc\");\n }\n } else {\n qb = qb.orderBy(\"id\", \"asc\");\n }\n\n if (query.limit) {\n qb = qb.limit(query.limit + 1); // +1 to detect hasMore\n }\n\n const compiled = qb.compile();\n return { sql: compiled.sql, params: [...compiled.parameters] };\n}\n\nfunction applyFilter<Qb extends SelectQueryBuilder<DB, \"shared_records\", unknown>>(\n qb: Qb,\n filter: { field: string; operator: string; value?: unknown },\n): Qb {\n const col = mapField(filter.field);\n switch (filter.operator) {\n case \"eq\": return qb.where(col, \"=\", filter.value) as Qb;\n case \"neq\": return qb.where(col, \"!=\", filter.value) as Qb;\n case \"gt\": return qb.where(col, \">\", filter.value) as Qb;\n case \"gte\": return qb.where(col, \">=\", filter.value) as Qb;\n case \"lt\": return qb.where(col, \"<\", filter.value) as Qb;\n case \"lte\": return qb.where(col, \"<=\", filter.value) as Qb;\n case \"in\": return qb.where(col, \"in\", filter.value as unknown[]) as Qb;\n case \"like\": return qb.where(col, \"like\", `%${filter.value}%`) as Qb;\n case \"isNull\":\n return qb.where((eb: ExpressionBuilder<DB, \"shared_records\">) => eb(col, \"is\", null)) as Qb;\n case \"isNotNull\":\n return qb.where((eb: ExpressionBuilder<DB, \"shared_records\">) => eb(col, \"is not\", null)) as Qb;\n default: return qb;\n }\n}\n","import type { RawDatabase } from \"@starkeep/storage-adapter\";\nimport { sql } from \"kysely\";\nimport { CATEGORIES, sqliteMetadataDdl } 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 */\nfunction applyLocalSchemaDdl(db: RawDatabase): void {\n db.exec(\"PRAGMA journal_mode = WAL\");\n db.exec(\"PRAGMA foreign_keys = ON\");\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 .compile().sql,\n );\n const sharedRecordsIndexes = [\n qb.schema.createIndex(\"idx_shared_records_type\").ifNotExists().on(\"shared_records\").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 // Duplicate-file prevention: (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. Records with NULL filename are not\n // constrained — the rule requires both filename and content to match.\n qb.schema\n .createIndex(\"uq_shared_records_filename_hash\")\n .ifNotExists()\n .unique()\n .on(\"shared_records\")\n .columns([\"original_filename\", \"content_hash\"])\n .where(sql.ref(\"deleted_at\"), \"is\", null)\n .where(sql.ref(\"original_filename\"), \"is not\", null),\n ];\n for (const index of sharedRecordsIndexes) {\n db.exec(index.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 (c.id === \"other\") continue;\n db.exec(sqliteMetadataDdl(c));\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","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\";\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: AppSyncableTableInfo[] = JSON.parse(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\n .prepare(query.sql)\n .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\n .prepare(query.sql)\n .all() as Array<{ app_id: string; tables_json: string; files_enabled: number }>;\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 { AppSyncableApplier, AppSyncableRowEntry, AppSyncableNamespaceStore, ScanCapableApplier, ScanSinceOptions, ScanSincePage } from \"@starkeep/shared-space-api\";\nimport { compiler as qb } from \"../query-builder.js\";\nimport { appSyncableTableName } from \"./namespace.js\";\n\ntype SqlParam = null | number | bigint | string | Uint8Array;\n\nfunction runCompiled(db: RawDatabase, compiled: CompiledQuery): void {\n db.prepare(compiled.sql).run(...(compiled.parameters as SqlParam[]));\n}\n\nfunction allCompiled<T>(db: RawDatabase, compiled: CompiledQuery): T[] {\n return db.prepare(compiled.sql).all(...(compiled.parameters as SqlParam[])) 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\n implements AppSyncableApplier, ScanCapableApplier\n{\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(\n `SqliteAppSyncableApplier: app \"${entry.appId}\" not installed`,\n );\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, entry);\n } else {\n this.applyDelete(fullName, entry);\n }\n }\n\n private applyInsert(\n fullName: string,\n pkColumns: string[],\n entry: AppSyncableRowEntry,\n ): 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.insertInto(fullName).orIgnore().values({ ...row }).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(fullName: string, entry: AppSyncableRowEntry): 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 = entry.where ?? {};\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 query = query.where(\"updated_at\", \"<\", incomingUpdatedAt);\n }\n runCompiled(this.db, query.compile());\n }\n\n private applyDelete(fullName: string, entry: AppSyncableRowEntry): void {\n const where = entry.where ?? {};\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 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) =>\n eb.or([eb(\"updated_at\", \"is\", null), eb(\"updated_at\", \"<\", ts)]),\n );\n runCompiled(this.db, query.compile());\n }\n\n /** See `ScanCapableApplier.getNodeWatermarks`. Missing table → `{}`. */\n async getNodeWatermarks(\n appId: string,\n table: string,\n ): Promise<Record<string, HLCTimestamp>> {\n const fullName = appSyncableTableName(appId, table);\n let rows: { node_id: string; max_updated_at: string }[];\n try {\n rows = allCompiled<{ node_id: string; max_updated_at: string }>(\n this.db,\n qb\n .selectFrom(fullName)\n .select(({ fn }) => [\"node_id\", fn.max(\"updated_at\").as(\"max_updated_at\")])\n .groupBy(\"node_id\")\n .compile(),\n );\n } catch {\n // Table might not exist yet (app not installed locally).\n return {};\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: return rows updated after `sinceHlcStr` (or `cursor`\n * if higher) in HLC order, paginated. `updated_at` is a serialized HLC\n * whose lexicographic order matches HLC order (fixed-width hex), and each\n * row's HLC is unique per node, so it doubles as the cursor — no separate\n * tiebreaker column is needed.\n */\n async scanSince(\n appId: string,\n table: string,\n sinceHlcStr: string,\n options?: ScanSinceOptions,\n ): Promise<ScanSincePage> {\n const fullName = appSyncableTableName(appId, table);\n const floor =\n options?.cursor !== undefined && options.cursor > sinceHlcStr\n ? options.cursor\n : sinceHlcStr;\n const limit = options?.limit;\n let rows: Record<string, unknown>[];\n try {\n let query = qb\n .selectFrom(fullName)\n .selectAll()\n .where(\"updated_at\", \">\", floor)\n .orderBy(\"updated_at\", \"asc\");\n if (limit !== undefined) {\n query = query.limit(limit + 1);\n }\n rows = allCompiled<Record<string, unknown>>(this.db, query.compile());\n } catch {\n // Table might not exist yet (app not installed locally).\n return { rows: [], nextCursor: null, hasMore: false };\n }\n const hasMore = limit !== undefined && rows.length > limit;\n const pageRows = hasMore ? rows.slice(0, limit) : rows;\n const entries = pageRows.map((row) => rowToEntry(appId, table, row));\n const nextCursor =\n hasMore && pageRows.length > 0\n ? (pageRows[pageRows.length - 1]![\"updated_at\"] as string)\n : null;\n return { rows: entries, nextCursor, hasMore };\n }\n\n /** Support read path from the factory's queryRows. */\n queryRows(\n appId: string,\n table: string,\n where?: Record<string, unknown>,\n ): Record<string, unknown>[] {\n const fullName = appSyncableTableName(appId, table);\n const whereCols = where ? Object.keys(where) : [];\n // Filter out soft-deleted rows by default.\n let query = qb.selectFrom(fullName).selectAll().where(\"deleted_at\", \"is\", null);\n for (const c of whereCols) {\n query = query.where(c, \"=\", where![c]);\n }\n return allCompiled<Record<string, unknown>>(this.db, query.compile());\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\nfunction rowToEntry(\n appId: string,\n table: string,\n row: Record<string, unknown>,\n): AppSyncableRowEntry {\n const updatedAtStr = row[\"updated_at\"] as string;\n const deletedAtStr = row[\"deleted_at\"] as string | null | undefined;\n const timestamp = deserializeHLC(updatedAtStr);\n\n // For wire propagation we emit op=\"insert\" (upsert) for live rows so the\n // receiver creates the row if it doesn't exist yet. op=\"update\" only\n // targets existing rows and would silently drop new rows during initial\n // sync. Tombstones still ride the soft-delete path.\n if (deletedAtStr) {\n return { timestamp, appId, table, op: \"delete\", row };\n }\n return { timestamp, appId, table, op: \"insert\", row };\n}\n"],"mappings":";AAQA,SAAS,gBAAAA,eAAc,kBAAAC,iBAAgB,+BAA+B;AActE;AAAA,EACE;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA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AAI;AAAA,EACtD;AACA,SAAO,EAAE,WAAW,OAAO,OAAO,IAAI,UAAU,IAAI;AACtD;","names":["serializeHLC","deserializeHLC","rowToLabel","sql","serializeHLC","deserializeHLC","rowToLabel","sql","serializeHLC","deserializeHLC","sql","serializeHLC","deserializeHLC"]}
@@ -0,0 +1,45 @@
1
+ "use strict";
2
+ var __defProp = Object.defineProperty;
3
+ var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
4
+ var __getOwnPropNames = Object.getOwnPropertyNames;
5
+ var __hasOwnProp = Object.prototype.hasOwnProperty;
6
+ var __export = (target, all) => {
7
+ for (var name in all)
8
+ __defProp(target, name, { get: all[name], enumerable: true });
9
+ };
10
+ var __copyProps = (to, from, except, desc) => {
11
+ if (from && typeof from === "object" || typeof from === "function") {
12
+ for (let key of __getOwnPropNames(from))
13
+ if (!__hasOwnProp.call(to, key) && key !== except)
14
+ __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
15
+ }
16
+ return to;
17
+ };
18
+ var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
19
+
20
+ // src/node-entry.ts
21
+ var node_entry_exports = {};
22
+ __export(node_entry_exports, {
23
+ nodeSqliteDriver: () => nodeSqliteDriver
24
+ });
25
+ module.exports = __toCommonJS(node_entry_exports);
26
+
27
+ // src/node-driver.ts
28
+ var import_node_sqlite = require("node:sqlite");
29
+ var import_node_fs = require("node:fs");
30
+ var import_node_path = require("node:path");
31
+ var nodeSqliteDriver = {
32
+ open: (path) => {
33
+ if (path !== ":memory:") {
34
+ const dir = (0, import_node_path.dirname)(path);
35
+ if (!(0, import_node_fs.existsSync)(dir)) (0, import_node_fs.mkdirSync)(dir, { recursive: true });
36
+ }
37
+ return new import_node_sqlite.DatabaseSync(path);
38
+ },
39
+ close: (db) => db.close()
40
+ };
41
+ // Annotate the CommonJS export names for ESM import in node:
42
+ 0 && (module.exports = {
43
+ nodeSqliteDriver
44
+ });
45
+ //# sourceMappingURL=node-entry.cjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/node-entry.ts","../src/node-driver.ts"],"sourcesContent":["/**\n * `@starkeep/storage-sqlite/node` — the Node-only entry point.\n *\n * Everything portable stays on the main entry. This one exists solely so that\n * importing the Node driver is an explicit act, and so the main entry can be\n * bundled for React Native without `node:sqlite` in its import graph.\n */\n\nexport { nodeSqliteDriver } from \"./node-driver.js\";\n","/**\n * The Node driver, and the only file in this package that names `node:sqlite`.\n *\n * ## Why it is not in the barrel\n *\n * A static `import { DatabaseSync } from \"node:sqlite\"` at module scope does not\n * merely fail on React Native — it makes the whole package unbundleable there.\n * Metro resolves the import graph eagerly, so the specifier has to resolve even\n * when nothing calls the thing behind it. Injecting an op-sqlite driver does not\n * help: by the time the adapter is constructed, the barrel has already dragged\n * `node:sqlite` in.\n *\n * That is the same failure `@starkeep/storage-adapter` had with `node:crypto`\n * for its content hashing, and the resolution is the same in spirit: the shared\n * entry point stays portable, and the platform-specific implementation is\n * something a Node caller opts into. The difference is that a SHA-256 has a\n * portable default and a SQLite connection does not, so this cannot be a default\n * at all — hence `driver` being a required option rather than one with a\n * fallback that only works on half the platforms.\n *\n * Import it from `@starkeep/storage-sqlite/node`. The main entry has no `node:`\n * imports and is safe to bundle for a handset.\n */\n\nimport type { RawDatabase } from \"@starkeep/storage-adapter\";\nimport { DatabaseSync } from \"node:sqlite\";\nimport { mkdirSync, existsSync } from \"node:fs\";\nimport { dirname } from \"node:path\";\nimport type { SqliteDriver } from \"./adapter.js\";\n\n/** Node's built-in SQLite. The default everywhere except React Native. */\nexport const nodeSqliteDriver: SqliteDriver = {\n open: (path) => {\n // Node's SQLite will not create a missing parent directory, so this driver\n // must. op-sqlite manages its own location and does not want this done for\n // it — which is why it lives here rather than in the adapter.\n if (path !== \":memory:\") {\n const dir = dirname(path);\n if (!existsSync(dir)) mkdirSync(dir, { recursive: true });\n }\n return new DatabaseSync(path);\n },\n close: (db) => (db as unknown as DatabaseSync).close(),\n};\n"],"mappings":";;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;;;ACyBA,yBAA6B;AAC7B,qBAAsC;AACtC,uBAAwB;AAIjB,IAAM,mBAAiC;AAAA,EAC5C,MAAM,CAAC,SAAS;AAId,QAAI,SAAS,YAAY;AACvB,YAAM,UAAM,0BAAQ,IAAI;AACxB,UAAI,KAAC,2BAAW,GAAG,EAAG,+BAAU,KAAK,EAAE,WAAW,KAAK,CAAC;AAAA,IAC1D;AACA,WAAO,IAAI,gCAAa,IAAI;AAAA,EAC9B;AAAA,EACA,OAAO,CAAC,OAAQ,GAA+B,MAAM;AACvD;","names":[]}