@pgxsinkit/client 0.1.31 → 0.1.36

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.
Files changed (85) hide show
  1. package/README.md +11 -0
  2. package/dist/convergence.d.ts +76 -0
  3. package/dist/convergence.d.ts.map +1 -0
  4. package/dist/debug.d.ts +34 -0
  5. package/dist/debug.d.ts.map +1 -0
  6. package/dist/index.d.ts +421 -7
  7. package/dist/index.d.ts.map +1 -1
  8. package/dist/index.js +7214 -2234
  9. package/dist/index.js.map +74 -44
  10. package/dist/lazy-guard.d.ts +58 -0
  11. package/dist/lazy-guard.d.ts.map +1 -0
  12. package/dist/local-store.d.ts +56 -0
  13. package/dist/local-store.d.ts.map +1 -0
  14. package/dist/local-tables.d.ts +707 -0
  15. package/dist/local-tables.d.ts.map +1 -0
  16. package/dist/mutation-state.d.ts +62 -0
  17. package/dist/mutation-state.d.ts.map +1 -0
  18. package/dist/mutation.d.ts +117 -4
  19. package/dist/mutation.d.ts.map +1 -1
  20. package/dist/schema.d.ts +49 -0
  21. package/dist/schema.d.ts.map +1 -1
  22. package/dist/shape-sync.d.ts +180 -0
  23. package/dist/shape-sync.d.ts.map +1 -0
  24. package/dist/sync/apply.d.ts +51 -0
  25. package/dist/sync/apply.d.ts.map +1 -0
  26. package/dist/sync/copy.d.ts +43 -0
  27. package/dist/sync/copy.d.ts.map +1 -0
  28. package/dist/sync/drizzle-executor.d.ts +5 -0
  29. package/dist/sync/drizzle-executor.d.ts.map +1 -0
  30. package/dist/sync/index.d.ts +32 -0
  31. package/dist/sync/index.d.ts.map +1 -0
  32. package/dist/sync/metadata-tables.d.ts +131 -0
  33. package/dist/sync/metadata-tables.d.ts.map +1 -0
  34. package/dist/sync/nudge.d.ts +49 -0
  35. package/dist/sync/nudge.d.ts.map +1 -0
  36. package/dist/sync/shape-inbox.d.ts +215 -0
  37. package/dist/sync/shape-inbox.d.ts.map +1 -0
  38. package/dist/sync/subscription-state.d.ts +39 -0
  39. package/dist/sync/subscription-state.d.ts.map +1 -0
  40. package/dist/sync/tags.d.ts +130 -0
  41. package/dist/sync/tags.d.ts.map +1 -0
  42. package/dist/sync/types.d.ts +118 -0
  43. package/dist/sync/types.d.ts.map +1 -0
  44. package/dist/sync-auth.d.ts +53 -0
  45. package/dist/sync-auth.d.ts.map +1 -0
  46. package/dist/worker/attach-sync-client.d.ts +75 -0
  47. package/dist/worker/attach-sync-client.d.ts.map +1 -0
  48. package/dist/worker/define-sync-worker.d.ts +75 -0
  49. package/dist/worker/define-sync-worker.d.ts.map +1 -0
  50. package/dist/worker/live-diff.d.ts +44 -0
  51. package/dist/worker/live-diff.d.ts.map +1 -0
  52. package/dist/worker/protocol.d.ts +260 -0
  53. package/dist/worker/protocol.d.ts.map +1 -0
  54. package/dist/worker/token-cache.d.ts +26 -0
  55. package/dist/worker/token-cache.d.ts.map +1 -0
  56. package/oxlint-plugin.js +143 -0
  57. package/package.json +19 -7
  58. package/skills/core/SKILL.md +197 -0
  59. package/skills/operating/SKILL.md +243 -0
  60. package/src/convergence.ts +197 -0
  61. package/src/debug.ts +151 -0
  62. package/src/index.ts +1104 -44
  63. package/src/lazy-guard.ts +121 -0
  64. package/src/local-store.ts +193 -0
  65. package/src/local-tables.ts +546 -0
  66. package/src/mutation-state.ts +90 -0
  67. package/src/mutation.ts +1868 -562
  68. package/src/schema.ts +352 -27
  69. package/src/shape-sync.ts +477 -0
  70. package/src/sync/apply.ts +530 -0
  71. package/src/sync/copy.ts +206 -0
  72. package/src/sync/drizzle-executor.ts +48 -0
  73. package/src/sync/index.ts +1076 -0
  74. package/src/sync/metadata-tables.ts +67 -0
  75. package/src/sync/nudge.ts +110 -0
  76. package/src/sync/shape-inbox.ts +566 -0
  77. package/src/sync/subscription-state.ts +135 -0
  78. package/src/sync/tags.ts +365 -0
  79. package/src/sync/types.ts +132 -0
  80. package/src/sync-auth.ts +117 -0
  81. package/src/worker/attach-sync-client.ts +558 -0
  82. package/src/worker/define-sync-worker.ts +596 -0
  83. package/src/worker/live-diff.ts +140 -0
  84. package/src/worker/protocol.ts +325 -0
  85. package/src/worker/token-cache.ts +84 -0
package/src/index.ts CHANGED
@@ -1,10 +1,11 @@
1
- import { PGlite, type PGliteInterfaceExtensions } from "@electric-sql/pglite";
1
+ import { PGlite, type Results } from "@electric-sql/pglite";
2
2
  import { live, type PGliteWithLive } from "@electric-sql/pglite/live";
3
3
  import type { PgliteDatabase } from "drizzle-orm/pglite";
4
4
  import { drizzle } from "drizzle-orm/pglite";
5
5
  import { defineRelations } from "drizzle-orm/relations";
6
6
 
7
7
  import type {
8
+ MutationAck,
8
9
  MutationDiagnostics,
9
10
  RegistryRelations,
10
11
  RegistryTables,
@@ -16,31 +17,306 @@ import type {
16
17
  SyncTableName,
17
18
  SyncTableRegistry,
18
19
  SyncTableUpdateInput,
20
+ WriteMode,
19
21
  } from "@pgxsinkit/contracts";
20
22
  import { getSyncRegistrySchema } from "@pgxsinkit/contracts";
21
- import { createElectricExtension, startConfiguredSync } from "@pgxsinkit/sync-engine";
22
23
 
23
- import { createMutationRuntime, type MutationBatchItem, type MutationDetail, type MutationKind } from "./mutation";
24
- import { generateLocalSchemaSql } from "./schema";
24
+ import { type ConvergenceDriver, type ConvergenceTrigger, createConvergenceDriver } from "./convergence";
25
+ import { syncDebug, timeAsync } from "./debug";
26
+ import { assertLazyRefsActivated, buildLazyGuardIndex, findReferencedLazyKeysInSql } from "./lazy-guard";
27
+ import {
28
+ type LocalStoreVersionEvent,
29
+ clearLazyGroupActivation,
30
+ readActivatedLazyGroups,
31
+ reconcileLocalStoreVersion,
32
+ writeLazyGroupActivation,
33
+ } from "./local-store";
34
+ import {
35
+ createMutationRuntime,
36
+ type MutationBatchItem,
37
+ type MutationDetail,
38
+ type MutationKind,
39
+ type WriteUnit,
40
+ } from "./mutation";
41
+ import { buildDesyncTableSql, buildDropReadCacheSql, buildWipeLocalStoreSql, generateLocalSchemaSql } from "./schema";
42
+ import { startConfiguredSync } from "./shape-sync";
43
+ import { createSyncEngine, type SyncEngine } from "./sync";
44
+ import { buildShapeHeaders } from "./sync-auth";
25
45
 
26
46
  export { generateLocalSchemaSql };
47
+ export {
48
+ type ConvergenceClient,
49
+ type ConvergenceDriver,
50
+ type ConvergenceDriverOptions,
51
+ type ConvergenceTrigger,
52
+ createBrowserConvergenceTrigger,
53
+ createConvergenceDriver,
54
+ createIntervalConvergenceTrigger,
55
+ } from "./convergence";
56
+ export { instrumentShapeFetch, setSyncDebugSink, syncDebug, timeAsync } from "./debug";
57
+ export {
58
+ type AttachedSyncClient,
59
+ attachSyncClient,
60
+ type AttachSyncClientOptions,
61
+ provisionSyncWorker,
62
+ } from "./worker/attach-sync-client";
63
+ export { defineSyncWorker, type DefineSyncWorkerOptions, type SyncWorkerHost } from "./worker/define-sync-worker";
64
+ export {
65
+ computeLiveDiff,
66
+ type LiveDiffState,
67
+ LiveRowsMaterializer,
68
+ rowKey,
69
+ seedLiveDiffState,
70
+ } from "./worker/live-diff";
71
+ export { createWorkerTokenCache, type WorkerTokenCache } from "./worker/token-cache";
72
+ export {
73
+ type AttachAckPayload,
74
+ type AttachPayload,
75
+ type AuthTokenSnapshot,
76
+ BRIDGE_CHANNEL,
77
+ BRIDGE_PROTOCOL_VERSION,
78
+ type BridgeCodec,
79
+ type BridgeEnvelope,
80
+ type BridgeEvent,
81
+ type BridgeMessageType,
82
+ type BridgePort,
83
+ encodeEnvelope,
84
+ identityCodec,
85
+ isBridgeEnvelope,
86
+ type LiveDiffPayload,
87
+ type LiveInitialPayload,
88
+ postBridgeMessage,
89
+ type ProvisionAckPayload,
90
+ type ProvisionPayload,
91
+ type RpcOp,
92
+ type RpcPayload,
93
+ type RpcResultPayload,
94
+ type SetOnlinePayload,
95
+ type SubscribePayload,
96
+ type TokenRequestPayload,
97
+ type TokenResponsePayload,
98
+ type WakePayload,
99
+ } from "./worker/protocol";
100
+ export {
101
+ assertLazyRefsActivated,
102
+ buildLazyGuardIndex,
103
+ findReferencedLazyKeysInSql,
104
+ type LazyGuardIndex,
105
+ LazyRelationNotActivatedError,
106
+ } from "./lazy-guard";
107
+ export {
108
+ getJournalTable,
109
+ getLocalMetaTable,
110
+ getOverlayTable,
111
+ getReadModelView,
112
+ getSyncedLocalTable,
113
+ getSyncStateView,
114
+ type JournalTable,
115
+ type LocalMetaTable,
116
+ type OverlayTable,
117
+ type ReadModelView,
118
+ type SyncStateView,
119
+ } from "./local-tables";
120
+ export type { LocalStoreVersionEvent };
27
121
 
28
- export type ClientPGlite = PGliteWithLive &
29
- PGliteInterfaceExtensions<{ electric: ReturnType<typeof createElectricExtension> }>;
122
+ // The store carries PGlite's own `live` extension (a genuine create-time extension) plus the pgxsinkit
123
+ // sync engine's namespace, attached post-create by `createSyncClient` as the `electric` property (ADR-0032
124
+ // S1) — no longer a create-time extension. The `electric` part is derived from `createSyncEngine`'s real
125
+ // return so the type follows the attached object.
126
+ export type ClientPGlite = PGliteWithLive & { electric: SyncEngine["namespace"] };
127
+
128
+ /**
129
+ * The pre-warmed PGlite boot assets (the WASM modules + filesystem bundle), consumed by
130
+ * {@link createClientPGlite} / {@link CreateSyncClientOptions.pgliteBootAssets}. The host fetches +
131
+ * compiles these on an earlier screen and hands the promise in, so `PGlite.create` skips its own lazy
132
+ * asset load — see the field's JSDoc for the accelerator geometry.
133
+ */
134
+ export interface PgliteBootAssets {
135
+ pgliteWasmModule?: WebAssembly.Module;
136
+ initdbWasmModule?: WebAssembly.Module;
137
+ fsBundle?: Blob;
138
+ }
139
+
140
+ /**
141
+ * Create the raw local PGlite store the sync client runs on — the SAME `PGlite.create` call
142
+ * {@link createSyncClient} makes internally (the `electric` + `live` extensions, pre-warmed boot-asset
143
+ * consumption, and the `boot pglite.create` rail stamp), extracted so exactly one implementation exists
144
+ * and a host can create the store EAGERLY on an earlier screen. Hand the returned (still-pending)
145
+ * instance to {@link CreateSyncClientOptions.precreatedPglite}: the client then owns schema exec, prepare
146
+ * hooks, journal recovery and store-version reconcile, exactly as its own `dataDir` path does.
147
+ *
148
+ * The instance is deliberately **schemaless** — the registry-derived local schema is role/registry
149
+ * dependent, so it is applied post-create by `createSyncClient`. The eager create buys only the expensive
150
+ * initdb (+ IDBFS open), which is the dominant cold-boot cost once the WASM is pre-warmed.
151
+ *
152
+ * `bootAssets` is the pre-warmed WASM/fs bundle (see {@link CreateSyncClientOptions.pgliteBootAssets}); a
153
+ * rejected warm is caught to `undefined`, so PGlite falls back to loading its own assets — never a failure.
154
+ */
155
+ export async function createClientPGlite(
156
+ dataDir: string,
157
+ options?: { bootAssets?: Promise<PgliteBootAssets> },
158
+ ): Promise<ClientPGlite> {
159
+ // Stamp only the storage scheme (e.g. "idb:" / "memory:"), never the full path — the path can carry an
160
+ // identity-specific store name, and the boot rail stays monotonic-and-scheme only.
161
+ const dataDirScheme = dataDir.slice(0, dataDir.indexOf(":") + 1);
162
+ // Resolve any pre-warmed boot assets BEFORE (and outside) the `boot pglite.create` stamp: the
163
+ // fetch+compile was kicked off on an earlier screen, so this await just retrieves the already-settled
164
+ // result and the stamp measures the create itself. A rejected warm is caught to `undefined` so a failed
165
+ // pre-warm silently falls back to PGlite's own asset loading rather than failing the boot.
166
+ const bootAssets = options?.bootAssets ? await options.bootAssets.catch(() => undefined) : undefined;
167
+ return (await timeAsync(
168
+ "boot pglite.create",
169
+ () =>
170
+ // Only PGlite's own `live` extension is a create-time extension; the pgxsinkit sync engine is NOT
171
+ // (ADR-0032 S1) — it is a plain module `createSyncClient` attaches post-create as `pg.electric`. So
172
+ // a store minted here is deliberately ENGINE-LESS by construction: a spare/pre-warmed store (e.g.
173
+ // the board's login-screen mint) carries no engine, no shape streams, and no Electric connections
174
+ // until it is claimed and handed to `createSyncClient`. The `as ClientPGlite` cast reflects that the
175
+ // `electric` namespace is provisioned later, exactly as the registry-derived schema is.
176
+ PGlite.create(dataDir, {
177
+ ...(bootAssets ?? {}),
178
+ extensions: {
179
+ live,
180
+ },
181
+ }),
182
+ { dataDir: dataDirScheme },
183
+ // `as unknown as` because the raw store is deliberately engine-less here (only `live` is a create-time
184
+ // extension); `createSyncClient` provisions the `electric` namespace post-create (ADR-0032 S1).
185
+ )) as unknown as ClientPGlite;
186
+ }
30
187
 
31
188
  export interface CreateSyncClientOptions<TRegistry extends SyncTableRegistry> {
32
189
  registry: TRegistry;
33
190
  electricUrl: string;
34
191
  writeUrl: string;
35
192
  getAuthToken?: () => Promise<string | undefined>;
193
+ /**
194
+ * Static headers added to **every** read-shape and write request, alongside the per-request
195
+ * `Authorization` (which always wins). The toolkit is agnostic about deployment-gateway
196
+ * credentials, so this is the seam for them — e.g. a Supabase Cloud `apikey` header the platform
197
+ * function gateway expects. Sent even when no `getAuthToken` is supplied.
198
+ */
199
+ requestHeaders?: Record<string, string>;
200
+ /**
201
+ * Extra static headers sent on the **write** path only (the mutation-flush POST), merged over
202
+ * {@link requestHeaders} (`{...requestHeaders, ...writeRequestHeaders}`). Read/shape requests never
203
+ * see these. The seam exists because the two ingress points have opposite geometry: the write
204
+ * function is DB-bound, so pinning it to the database's region (e.g. an `x-region` header) keeps its
205
+ * chatty function→DB protocol on a ~1ms loop; the read proxy's upstream is a globally-distributed
206
+ * CDN (Electric Cloud), so pinning reads away from the caller pays intercontinental round trips per
207
+ * catch-up hop. Put region/DB-affinity headers here; keep gateway credentials the reads also need
208
+ * (e.g. `apikey`) in the shared {@link requestHeaders}.
209
+ */
210
+ writeRequestHeaders?: Record<string, string>;
36
211
  syncEnabled?: boolean;
37
212
  dataDir?: string;
213
+ /**
214
+ * Pre-warmed PGlite boot assets (the WASM modules + filesystem bundle), awaited and passed straight
215
+ * into `PGlite.create`. The intent is to hide PGlite's ~2.5s cold `boot pglite.create` cost —
216
+ * dominated by the WASM fetch+compile — behind user think-time: the host starts fetching/compiling
217
+ * these on an earlier screen (e.g. the login/identity picker) and hands the still-pending promise
218
+ * here, so by the time a store is opened the assets are already resolved and `PGlite.create` skips
219
+ * its own lazy asset load. Ignored when {@link pgliteInstance} is supplied (the caller owns that
220
+ * instance's boot). A rejected/failed warm is caught to `undefined` and never fails the boot — PGlite
221
+ * falls back to loading its own assets, so this is a pure best-effort accelerator.
222
+ */
223
+ pgliteBootAssets?: Promise<PgliteBootAssets>;
38
224
  resetSubscriptionKeys?: string[];
39
225
  prepareLocalDbBeforeSchema?: (pglite: ClientPGlite) => Promise<void>;
40
226
  prepareLocalDb?: (pglite: ClientPGlite) => Promise<void>;
41
227
  onStatusChange?: (status: SyncRuntimeStatus) => void;
42
228
  onTableInitialSync?: (tableKey: string) => void;
229
+ /**
230
+ * A fully-provisioned PGlite instance the CALLER owns end-to-end. The client runs NONE of its
231
+ * post-create boot steps against it — no schema exec, prepare hooks, or store-version reconcile
232
+ * (journal recovery still runs, as it does on every path). Use it only when the caller has already
233
+ * applied the registry schema itself. Contrast the three PGlite-provenance seams:
234
+ * - {@link dataDir} (default) — the client creates the store AND runs every post-create step.
235
+ * - {@link precreatedPglite} — the caller creates the raw store (via {@link createClientPGlite}), but
236
+ * the client still runs every post-create step (schema/prepare/reconcile), exactly as `dataDir` does.
237
+ * - `pgliteInstance` — the caller creates AND provisions the store; the client runs none of them.
238
+ *
239
+ * Mutually exclusive with {@link precreatedPglite} (supplying both throws).
240
+ */
43
241
  pgliteInstance?: ClientPGlite;
242
+ /**
243
+ * A raw PGlite instance the caller created EAGERLY (via {@link createClientPGlite}) — typically on an
244
+ * earlier screen, to hide the ~1.9s cold `initdb`/IDBFS open behind user think-time — but for which the
245
+ * client still owns EVERYTHING else: schema exec, prepare hooks, journal recovery, and store-version
246
+ * reconcile all run exactly as on the {@link dataDir} path. This is the difference from
247
+ * {@link pgliteInstance} (which skips schema/prepare/reconcile because the caller owns them); see that
248
+ * option's JSDoc for the three-way distinction.
249
+ *
250
+ * The promise form lets the still-pending eager create be handed straight in. Precedence/validation:
251
+ * - Supplying both this and {@link pgliteInstance} throws — they claim different ownership.
252
+ * - {@link dataDir} is used ONLY as the fallback store id if this promise REJECTS: a failed eager
253
+ * create is caught, logged on the boot rail, and the normal `dataDir` create path runs instead (also
254
+ * consuming {@link pgliteBootAssets} if provided). The pattern is a pure accelerator, never a boot
255
+ * dependency.
256
+ */
257
+ precreatedPglite?: Promise<ClientPGlite>;
258
+ /**
259
+ * PROVABLY-fresh store hint (ADR-0032 S4 / backlog-0003): the caller guarantees this store is brand-new
260
+ * and schemaless — no prior schema, no synced rows, no persisted subscription state. When set (and sync
261
+ * is enabled, and the client owns schema exec — i.e. not the {@link pgliteInstance} path), the shape
262
+ * catch-up is started BEFORE the local boot phases (schema exec, journal recovery, store-version
263
+ * reconcile) and buffered in memory, with commits gated until those phases finish — so the network
264
+ * catch-up overlaps them instead of running strictly after. On a far-from-database caller this collapses
265
+ * boot from `local-phases + catch-up` toward `max(local-phases, catch-up)`.
266
+ *
267
+ * MUST be set only when freshness is proven, never derived by probing — a claimed schemaless spare (the
268
+ * board's claim path knows: a claimed spare is always fresh; a mapped/returning store never is). A wrong
269
+ * `true` on a warm store would start the streams from offset 0 and skip the subscription-state read,
270
+ * re-snapshotting instead of resuming. Absent/false → the exact sequential path (the default, correct for
271
+ * every warm store).
272
+ */
273
+ freshStore?: boolean;
274
+ /**
275
+ * Hard cap on send attempts before a still-failing mutation is quarantined
276
+ * (ADR-0005 congestion policy). Defaults to the library's built-in cap.
277
+ */
278
+ maxMutationAttempts?: number;
279
+ /**
280
+ * Invoked when mutations are quarantined (permanently rejected by the server, terminal). The library
281
+ * surfaces them here rather than silently dropping or retry-looping (ADR-0006). Surface, then either
282
+ * re-author + resubmit or roll back via {@link SyncClient.discardQuarantined} — which clears the kept
283
+ * overlay + quarantined journal rows so the entity accepts new mutations again.
284
+ */
285
+ onQuarantine?: (quarantined: MutationDetail[]) => void | Promise<void>;
286
+ /**
287
+ * Invoked when mutations are `conflicted` — a stale write the server declined under the
288
+ * `reject-if-stale` Conflict policy (ADR-0015). The optimistic Overlay is kept, so the app shows a
289
+ * resolution/diff UI and resolves each as a new write (`mutate.update`) or `discardConflict`s it.
290
+ */
291
+ onConflict?: (conflicted: MutationDetail[]) => void | Promise<void>;
292
+ /**
293
+ * Invoked when a pessimistic write-unit is `rejected` (ADR-0022) — a business decline from the
294
+ * authoritative endpoint (capacity/quota/uniqueness). The inverse of `onConflict`: the optimistic Overlay
295
+ * was auto-discarded for the whole unit, so the app surfaces the typed reason rather than a resolve UI.
296
+ */
297
+ onReject?: (rejected: MutationDetail[]) => void | Promise<void>;
298
+ /**
299
+ * Invoked on boot when the registry fingerprint differs from the one the local store was
300
+ * provisioned under (ADR-0006). `rebuilt` = the read cache was dropped and rebuilt at the
301
+ * new shape; `deferred` = un-flushed/quarantined writes are still owed, so the rebuild is
302
+ * postponed (and retried on a later boot) rather than dropping owed data.
303
+ */
304
+ onSchemaChange?: (event: LocalStoreVersionEvent) => void | Promise<void>;
305
+ /**
306
+ * Opt-in convergence driver (ADR-0005). Supply a {@link ConvergenceTrigger} (e.g.
307
+ * `createBrowserConvergenceTrigger()`) and the client drives `flush`/`reconcile`/`retryFailed`
308
+ * on the trigger's schedule, started once sync is ready and stopped on `stop()`/`destroy()`.
309
+ * Omit it for fully-manual convergence (the mechanism primitives stay public either way).
310
+ */
311
+ autoSync?: ConvergenceTrigger;
312
+ /** Invoked after each automatic convergence pass with its error, or `null` on success (only when `autoSync` is set). */
313
+ onConvergencePass?: (error: unknown) => void;
314
+ /**
315
+ * Invoked when a read-path sync commit fails after exhausting its retries (ADR-0009 decision 5).
316
+ * The runtime enters the `degraded` phase and holds the read cache at the last applied commit
317
+ * instead of silently diverging from the server; recovery is a later commit or a restart/refetch.
318
+ */
319
+ onSyncError?: (error: Error) => void;
44
320
  }
45
321
 
46
322
  export interface SyncClientTableHandle<TRegistry extends SyncTableRegistry, TKey extends SyncTableName<TRegistry>> {
@@ -51,6 +327,114 @@ export interface SyncClientTableHandle<TRegistry extends SyncTableRegistry, TKey
51
327
  delete: (entityKey: Record<string, string>) => Promise<void>;
52
328
  }
53
329
 
330
+ /**
331
+ * A table handle inside a {@link SyncClient.transaction} block (ADR-0022 §2). It *collects* mutations into
332
+ * the open write-unit rather than enqueuing each immediately; the whole set is enqueued atomically when the
333
+ * block's callback returns. The calls are synchronous (collection only) — no per-call await needed.
334
+ */
335
+ export interface SyncTransactionTableHandle<
336
+ TRegistry extends SyncTableRegistry,
337
+ TKey extends SyncTableName<TRegistry>,
338
+ > {
339
+ create: (input: SyncTableCreateInput<TRegistry, TKey>) => void;
340
+ update: (entityKey: Record<string, string>, patch: SyncTableUpdateInput<TRegistry, TKey>) => void;
341
+ delete: (entityKey: Record<string, string>) => void;
342
+ /**
343
+ * An **update-by-key with no local base row** (ADR-0022 addendum). Ordinary `update` requires the entity
344
+ * to be present in the actor's local read model (it seeds the optimistic overlay and captures the base
345
+ * server version); `updateBlind` skips that presence check and writes NO overlay — nothing appears in the
346
+ * read model. Use it when the write target is deliberately EXCLUDED from your read shape (a write-only
347
+ * flow, or an anonymity-scoped moderation write whose row streams only to a different projection), so there
348
+ * is no local row to update and nothing to show optimistically.
349
+ *
350
+ * **Pessimistic-only.** The /unit expander is authoritative for the outcome, so a blind write is meaningful
351
+ * only inside a `transaction({ mode: "pessimistic" })` block (or over a statically-pessimistic table). An
352
+ * optimistic-routed blind write has nothing to converge and THROWS at enqueue.
353
+ *
354
+ * The acked journal row **retires without a synced echo** (no visible row ever converges for it), so it does
355
+ * not linger — unlike the seed-a-phantom-row workaround this replaces, whose acked row + overlay lingered
356
+ * forever behind the echo barrier. A `conflicted` blind write stays dischargeable via `discardConflict`; a
357
+ * `rejected` one is surfaced via `onReject`, both with no overlay to clean up.
358
+ */
359
+ updateBlind: (entityKey: Record<string, string>, patch: SyncTableUpdateInput<TRegistry, TKey>) => void;
360
+ }
361
+
362
+ /** The handle passed to a {@link SyncClient.transaction} callback: collecting table handles for the unit. */
363
+ export interface SyncTransaction<TRegistry extends SyncTableRegistry> {
364
+ tables: { [TKey in SyncTableName<TRegistry>]: SyncTransactionTableHandle<TRegistry, TKey> };
365
+ }
366
+
367
+ /**
368
+ * The result of a {@link SyncClient.transaction}. A `pessimistic` block carries the authoritative server
369
+ * `acks` (each `acked` / `conflicted` / `rejected`); an `optimistic` block enqueues atomically and flushes
370
+ * in the background, so its `acks` are empty.
371
+ */
372
+ export interface SyncTransactionResult {
373
+ acks: MutationAck[];
374
+ }
375
+
376
+ /** Minimal shape of a Drizzle select builder: inspectable via `.toSQL()` and awaitable for its rows. */
377
+ export interface DrizzleQueryBuilder<TRows extends readonly unknown[]> extends PromiseLike<TRows> {
378
+ toSQL(): { sql: string; params: unknown[] };
379
+ }
380
+
381
+ /**
382
+ * The builder callback for a guarded read (ADR-0021): it receives the client and returns a Drizzle
383
+ * select builder. Reach relations through `c.views` / `c.drizzle` / a directly-imported synced table.
384
+ */
385
+ export type GuardedQueryFn<TRegistry extends SyncTableRegistry, TRows extends readonly unknown[]> = (
386
+ client: SyncClient<TRegistry>,
387
+ ) => DrizzleQueryBuilder<TRows>;
388
+
389
+ /**
390
+ * A guarded query whose builder MAY embed a raw `sql` template fragment (ADR-0021). A raw fragment can
391
+ * name a lazy relation as a bare/unquoted identifier the compiled-SQL scan cannot see, so declare those
392
+ * relations in `use` — they are activated and awaited before the query runs. Pure-Drizzle reads need no
393
+ * `use` (the scan detects every relation): pass the builder callback directly to `client.query`.
394
+ */
395
+ export interface GuardedRawQuerySpec<TRegistry extends SyncTableRegistry, TRows extends readonly unknown[]> {
396
+ use?: readonly SyncTableName<TRegistry>[];
397
+ build: GuardedQueryFn<TRegistry, TRows>;
398
+ }
399
+
400
+ /**
401
+ * Inputs to the read-path safety seam {@link SyncClient.prepareQuery}. The lazy relations a query reads
402
+ * are detected by scanning the compiled `sql` (union with the optional explicit `use`), then activated.
403
+ * Shared by the live React hooks and the non-live facade.
404
+ */
405
+ export interface PrepareQueryInput<TRegistry extends SyncTableRegistry> {
406
+ /** The compiled (parameterised) Drizzle SQL the query will run — the scan's ground-truth target. */
407
+ sql: string;
408
+ /** Lazy relations to also activate, beyond those scanned from `sql` — a pre-activation hint, not required. */
409
+ use?: readonly SyncTableName<TRegistry>[];
410
+ }
411
+
412
+ /**
413
+ * The narrow live-rows seam (ADR-0032 S2 §4) both client modes implement so the `@pgxsinkit/react` hooks
414
+ * work against either. Input for a reactive subscription: the compiled SQL + params (from a Drizzle
415
+ * builder's `.toSQL()` or a raw string) and the result's `pkColumns` (drives worker-side diff keying;
416
+ * omit for a keyless query). The in-process client runs it directly over `pglite.live`; the worker-attached
417
+ * client runs the live query in the worker and streams DIFFs across the bridge.
418
+ */
419
+ export interface SubscribeLiveRowsInput {
420
+ sql: string;
421
+ params: readonly unknown[];
422
+ /** The result's PK columns — the diff-keying identity across the bridge (§4). Omit for a keyless query. */
423
+ pkColumns?: readonly string[];
424
+ /**
425
+ * Lazy relations (ADR-0021) to activate before the query runs — forwarded to the worker so it can
426
+ * `prepareQuery` before registering the live query (the tab's own `prepareQuery` is a no-op against the
427
+ * worker bridge). Ignored by the in-process client, whose `prepareQuery` already ran on the tab.
428
+ */
429
+ use?: readonly string[];
430
+ }
431
+
432
+ /** A handle to a live-rows subscription: the initial ordered snapshot plus an idempotent unsubscribe. */
433
+ export interface LiveRowsSubscription<TRow> {
434
+ initialRows: TRow[];
435
+ unsubscribe: () => void;
436
+ }
437
+
54
438
  export interface SyncClient<TRegistry extends SyncTableRegistry> {
55
439
  drizzle: PgliteDatabase<RegistryRelations<TRegistry>>;
56
440
  pglite: ClientPGlite;
@@ -62,7 +446,18 @@ export interface SyncClient<TRegistry extends SyncTableRegistry> {
62
446
  status: SyncRuntimeStatus;
63
447
  start: () => Promise<void>;
64
448
  stop: () => Promise<void>;
65
- destroy: () => Promise<void>;
449
+ /**
450
+ * Wipe the entire local store (synced cache + overlay + journal) and close the handle
451
+ * (ADR-0005). Refuses if mutations are still owed to the server unless `force` is set, so
452
+ * it never silently drops un-flushed writes. Distinct from `stop()`, which only halts sync.
453
+ */
454
+ destroy: (options?: { force?: boolean }) => Promise<void>;
455
+ /**
456
+ * Drop and rebuild the reconstructible synced read cache, preserving the overlay and
457
+ * mutation journal (ADR-0006). The next sync refills it. Use to recover from a corrupt or
458
+ * stale read cache without losing un-flushed writes.
459
+ */
460
+ dropReadCache: () => Promise<void>;
66
461
  flush: (table?: SyncTableName<TRegistry>) => Promise<void>;
67
462
  reconcile: (table?: SyncTableName<TRegistry>) => Promise<void>;
68
463
  retryFailed: (table?: SyncTableName<TRegistry>) => Promise<void>;
@@ -81,11 +476,168 @@ export interface SyncClient<TRegistry extends SyncTableRegistry> {
81
476
  delete: <TKey extends SyncTableName<TRegistry>>(table: TKey, entityKey: Record<string, string>) => Promise<void>;
82
477
  batch: (items: ReadonlyArray<MutationBatchItem<TRegistry>>) => Promise<void>;
83
478
  };
479
+ /**
480
+ * Discard a `conflicted` entity (ADR-0015): clear its conflicted journal entry and kept optimistic
481
+ * Overlay, so the Read model falls back to the synced (server) value. Use when the user abandons a
482
+ * stale edit instead of resolving it as a new write.
483
+ */
484
+ discardConflict: <TKey extends SyncTableName<TRegistry>>(
485
+ table: TKey,
486
+ entityKey: Record<string, string>,
487
+ ) => Promise<void>;
488
+ /**
489
+ * Discard a `quarantined` entity (ADR-0006): clear its quarantined journal entry and kept optimistic
490
+ * Overlay, so the Read model falls back to the synced (server) value. The rollback path for a write
491
+ * the server permanently rejected — e.g. an RLS policy denial (42501) routed to quarantine. After the
492
+ * discard the phantom optimistic row is gone and the entity accepts new mutations again (no longer
493
+ * blocked behind the quarantined head). Symmetric to {@link SyncClient.discardConflict}; the overlay
494
+ * is kept when another still-owed write depends on it. No-op for an entity with no quarantined entry.
495
+ */
496
+ discardQuarantined: <TKey extends SyncTableName<TRegistry>>(
497
+ table: TKey,
498
+ entityKey: Record<string, string>,
499
+ ) => Promise<void>;
84
500
  diagnostics: (table?: SyncTableName<TRegistry>) => Promise<{ mutation: MutationDiagnostics }>;
501
+ /**
502
+ * The INSPECTION read surface (debug pages, REPLs, ad-hoc counts) — identical on the in-process and
503
+ * worker-attached client (on the latter the statement runs in the worker). The statement runs raw
504
+ * against the local store: it BYPASSES the mutation journal and optimistic overlay, and any write it
505
+ * issues stays local and will NOT converge. For app data reads prefer the live-rows hooks /
506
+ * {@link subscribeLiveRows} (or the guarded {@link query} family); reach for this only to look at the
507
+ * store, not to read app state or mutate it.
508
+ */
509
+ rawQuery: (sql: string, params?: unknown[], options?: RawQueryOptions) => Promise<Results>;
510
+ /** {@link rawQuery} for multi-statement SQL, returning one {@link Results} per statement. */
511
+ rawExec: (sql: string, options?: RawQueryOptions) => Promise<Results[]>;
512
+ /**
513
+ * Run a one-shot (non-live) typed **pure-Drizzle** query with the lazy-relation safety net (ADR-0021).
514
+ * Pass the builder callback directly — pgxsinkit scans the compiled SQL and activates + awaits every
515
+ * lazy relation it reads (FROM, JOIN, subquery, WHERE) before it runs, and the tripwire rejects any
516
+ * lazy relation the SQL still references but that is not active, so the result is never silently
517
+ * empty/stale. The guaranteed-safe alternative to a bare `client.drizzle` read. If the builder embeds
518
+ * a raw `sql` template fragment, use {@link queryRaw} and declare the lazy relations in `use`.
519
+ */
520
+ query: <TRows extends readonly unknown[]>(build: GuardedQueryFn<TRegistry, TRows>) => Promise<TRows>;
521
+ /** {@link query} returning the first row, or null when empty. */
522
+ queryRow: <TRows extends readonly unknown[]>(
523
+ build: GuardedQueryFn<TRegistry, TRows>,
524
+ ) => Promise<TRows[number] | null>;
525
+ /**
526
+ * {@link query} for a builder that embeds a raw `sql` template fragment (ADR-0021). The compiled-SQL
527
+ * scan can miss a lazy relation named as a bare/unquoted identifier inside raw SQL, so declare those
528
+ * in `use` — they are activated and awaited before the query runs. Pure-Drizzle reads should use
529
+ * {@link query} instead (no `use` needed).
530
+ */
531
+ queryRaw: <TRows extends readonly unknown[]>(spec: GuardedRawQuerySpec<TRegistry, TRows>) => Promise<TRows>;
532
+ /** {@link queryRaw} returning the first row, or null when empty. */
533
+ queryRawRow: <TRows extends readonly unknown[]>(
534
+ spec: GuardedRawQuerySpec<TRegistry, TRows>,
535
+ ) => Promise<TRows[number] | null>;
536
+ /**
537
+ * Activate one or more lazy relations (ADR-0021): open their consistency-group subscription if held
538
+ * out of the eager boot, resolving once their initial sync completes. Idempotent — eager or
539
+ * already-started relations resolve immediately. Use to pre-activate before a raw/`client.drizzle`
540
+ * read, or as the manual escape hatch the tripwire points to.
541
+ */
542
+ ensureSynced: (keys: readonly SyncTableName<TRegistry>[]) => Promise<void>;
543
+ /**
544
+ * Whether a relation's group has started and hydrated (ADR-0021). False for a still-dormant `lazy`
545
+ * relation; true for eager relations once boot completes (and always when sync is disabled).
546
+ */
547
+ isSynced: (key: SyncTableName<TRegistry>) => boolean;
548
+ /**
549
+ * Revert a `lazy` relation to dormant (ADR-0021 §2) — the inverse of on-demand activation: stop its
550
+ * consistency group's stream, clear any persisted `lazy + persistent` activation (so the next boot
551
+ * holds it dormant again), and clean-truncate its local read cache. A later reference re-activates it
552
+ * from scratch. Refuses when the relation is `eager` (always-on, would immediately re-sync) or owes
553
+ * the server unsettled writes (the truncate would drop them — flush or discard first). The reclaim
554
+ * primitive a host wires to navigation/idle for a rarely-opened lazy view; for an `ephemeral`
555
+ * relation, idle-eviction is otherwise automatic at session end.
556
+ */
557
+ desync: (key: SyncTableName<TRegistry>) => Promise<void>;
558
+ /**
559
+ * The read-path safety seam (ADR-0021): scan the compiled `sql` for the lazy relations it reads
560
+ * (∪ the optional `use`), activate them, and await their initial sync — so a lazy relation
561
+ * auto-activates on *any* reference (FROM, JOIN, subquery, WHERE). Resolves once it is safe to run the
562
+ * query; a backstop throws {@link LazyRelationNotActivatedError} only if a referenced relation could
563
+ * not be activated. Exposed for the React live hooks (which own their query build); `query`/`queryRow`
564
+ * are the higher-level non-live wrappers. Raw, non-Drizzle SQL is out of scope — pass `use`, or
565
+ * `ensureSynced` first.
566
+ */
567
+ prepareQuery: (input: PrepareQueryInput<TRegistry>) => Promise<void>;
568
+ /**
569
+ * Author an atomic write-**unit** (ADR-0022 §2). The callback receives collecting table handles; every
570
+ * mutation it issues is tagged into one unit and enqueued atomically when the callback returns.
571
+ *
572
+ * - `mode: "pessimistic"` — **server-authoritative**: the unit flush-routes to the authoritative endpoint
573
+ * and this call resolves only once the server has decided. The result's `acks` carry each member's
574
+ * outcome — `acked`, `conflicted` (overlay kept, ADR-0015), or `rejected` (overlay auto-discarded for
575
+ * the whole unit, surfaced via `onReject`, ADR-0022 §4). Throws on transport failure (overlay kept). A
576
+ * pessimistic block may also issue {@link SyncTransactionTableHandle.updateBlind} — an update-by-key with
577
+ * no local base row and no overlay, for a write target excluded from the actor's read shape.
578
+ * - `mode: "optimistic"` — an atomic batch enqueue that flushes in the background (empty `acks`).
579
+ */
580
+ transaction: (
581
+ options: { mode: WriteMode },
582
+ run: (tx: SyncTransaction<TRegistry>) => void | Promise<void>,
583
+ ) => Promise<SyncTransactionResult>;
584
+ /**
585
+ * Per-group readiness (ADR-0032 decision 6): a promise resolving the moment the given table's
586
+ * consistency group is up-to-date. Resolves immediately for an already-ready (or sync-disabled)
587
+ * group; stays pending for a still-dormant `lazy` relation until it is activated and caught up. The
588
+ * opt-in progressive-paint signal beside the all-eager-groups `ready` gate. `status.groups` carries the
589
+ * same readiness as a synchronous snapshot.
590
+ */
591
+ groupReady: (table: SyncTableName<TRegistry>) => Promise<void>;
592
+ /**
593
+ * The live-rows seam (ADR-0032 S2 §4): register a reactive query and receive its initial ordered
594
+ * snapshot plus subsequent updates via `onRows`. The React live hooks consume THIS (not `pglite.live`
595
+ * directly), so they run unchanged against both the in-process client (which implements it over
596
+ * `pglite.live`) and the worker-attached client (which implements it over the bridge). Prefer the
597
+ * higher-level `@pgxsinkit/react` hooks; this is the lower-level primitive they build on.
598
+ */
599
+ subscribeLiveRows: <TRow extends Record<string, unknown> = Record<string, unknown>>(
600
+ input: SubscribeLiveRowsInput,
601
+ onRows: (rows: TRow[]) => void,
602
+ ) => Promise<LiveRowsSubscription<TRow>>;
85
603
  }
86
604
 
87
605
  export type { MutationBatchItem, MutationDetail, MutationDiagnostics, MutationKind };
88
606
 
607
+ /**
608
+ * The structured-clone-safe subset of PGlite's `QueryOptions` the inspection surface carries. Kept
609
+ * narrow ON PURPOSE: on a worker-attached client the options object crosses the bridge via
610
+ * `postMessage`, so function-valued options (`parsers`, `serializers`, `onNotice`) can never be part
611
+ * of this contract. `rowMode: "array"` is what `@electric-sql/pglite-repl` asks for on every exec.
612
+ */
613
+ export interface RawQueryOptions {
614
+ rowMode?: "object" | "array";
615
+ }
616
+
617
+ /** The `{ query, exec }` duck `@electric-sql/pglite-repl` drives, backed by a client's inspection surface. */
618
+ export interface ReplInspectionSurface {
619
+ query: (sql: string, params?: unknown[], options?: RawQueryOptions) => Promise<Results>;
620
+ exec: (sql: string, options?: RawQueryOptions) => Promise<Results[]>;
621
+ }
622
+
623
+ /**
624
+ * Shape a {@link SyncClient}'s inspection surface (`rawQuery`/`rawExec`) as the `{ query, exec }` duck
625
+ * `@electric-sql/pglite-repl` needs. Identical on the in-process and worker-attached client — on the latter
626
+ * each statement routes through the worker bridge, so the REPL works even though `client.pglite` is
627
+ * unavailable. Cast the result at the `<Repl pg={...}>` prop (the REPL types the prop as a full `PGlite`).
628
+ * The surface is registry-independent, so it accepts any client's `rawQuery`/`rawExec` pair.
629
+ */
630
+ export function replAdapter(
631
+ client: Pick<SyncClient<SyncTableRegistry>, "rawQuery" | "rawExec">,
632
+ ): ReplInspectionSurface {
633
+ return {
634
+ // Thread the options through UNMODIFIED — the REPL execs with `{ rowMode: "array" }` and renders
635
+ // each row with `row.map`, so dropping the options here breaks every REPL statement.
636
+ query: (sql, params, options) => client.rawQuery(sql, params, options),
637
+ exec: (sql, options) => client.rawExec(sql, options),
638
+ };
639
+ }
640
+
89
641
  export async function createSyncClient<const TRegistry extends SyncTableRegistry>(
90
642
  options: CreateSyncClientOptions<TRegistry>,
91
643
  ): Promise<SyncClient<TRegistry>> {
@@ -99,75 +651,464 @@ export async function createSyncClient<const TRegistry extends SyncTableRegistry
99
651
  resolveReady = resolve;
100
652
  });
101
653
 
654
+ if (options.pgliteInstance && options.precreatedPglite) {
655
+ throw new Error(
656
+ "createSyncClient: pass at most one of `pgliteInstance` or `precreatedPglite` — they claim different ownership of the post-create boot steps (schema exec, prepare hooks, store-version reconcile).",
657
+ );
658
+ }
659
+
660
+ // Bind the boot-asset option once for the two create paths (fresh `dataDir`, and the `precreatedPglite`
661
+ // reject-fallback), so both consume the same pre-warm.
662
+ const createBootAssets = options.pgliteBootAssets ? { bootAssets: options.pgliteBootAssets } : undefined;
663
+ const fallbackDataDir = options.dataDir ?? "idb://pgxsinkit-overlay-v1";
664
+
102
665
  let pglite: ClientPGlite;
103
666
  if (options.pgliteInstance) {
667
+ // The caller created AND provisioned this store; the client runs NONE of the post-create boot steps
668
+ // (schema/prepare/reconcile) — see the `pgliteInstance` JSDoc.
104
669
  pglite = options.pgliteInstance;
105
- // Assume schema is already applied by caller
670
+ } else if (options.precreatedPglite) {
671
+ // The caller created the raw store eagerly via `createClientPGlite`; the client still owns every
672
+ // post-create step below. A REJECTED eager create must never fail the boot: fall back to the normal
673
+ // `dataDir` create here, so the pattern stays a pure accelerator.
674
+ pglite = await options.precreatedPglite.catch((error: unknown) => {
675
+ syncDebug("boot precreated pglite rejected — falling back to dataDir create", {
676
+ error: error instanceof Error ? error.message : String(error),
677
+ });
678
+ return createClientPGlite(fallbackDataDir, createBootAssets);
679
+ });
106
680
  } else {
107
- pglite = (await PGlite.create(options.dataDir ?? "idb://pgxsinkit-overlay-v1", {
108
- extensions: {
109
- electric: createElectricExtension(),
110
- live,
111
- },
112
- })) as ClientPGlite;
681
+ pglite = await createClientPGlite(fallbackDataDir, createBootAssets);
682
+ }
683
+
684
+ // Attach the sync engine explicitly, over the already-created instance, on ALL three provenance paths
685
+ // (pgliteInstance, precreatedPglite, dataDir) — ADR-0032 S1. The engine is no longer a create-time
686
+ // extension, so the raw store (a `createClientPGlite` mint, or a caller's own instance) carries no
687
+ // `electric` namespace until this point; the property assignment gives `ClientPGlite` its exact former
688
+ // structural shape (live + electric) so every `pglite.electric.…` call site is unchanged. It is attached
689
+ // BEFORE the schema/prepare steps below so a `prepareLocalDb` hook sees the same `.electric` it did when
690
+ // the extension provided it at create time. `engine.close` (the former extension close hook — abort every
691
+ // shape stream) is kept private to this client and run explicitly by `stop`/`destroy` at the same moment
692
+ // `pglite.close()` used to trigger it.
693
+ const engine: SyncEngine = await createSyncEngine(pglite);
694
+ (pglite as { electric: SyncEngine["namespace"] }).electric = engine.namespace;
695
+
696
+ const syncEnabled = options.syncEnabled ?? true;
697
+ // Whether the read path's first initial sync has completed, so a recovery from `auth-needed` returns to
698
+ // the right steady-state phase (`ready` if already caught up, else `syncing`).
699
+ let initialSyncCompleted = false;
700
+ // Why the runtime is `degraded` (#4). A read-stream error degraded clears on the next successful batch; a
701
+ // commit-failure degraded is sticky (a fetch can succeed while applies still fail), so a bare
702
+ // `onSyncActivity` must not clear it.
703
+ let degradedReason: "stream" | "commit" | null = null;
704
+
705
+ // ─── Fresh-store prefetch overlap (ADR-0032 S4 / backlog-0003) ─────────────────────────────────────
706
+ // On a PROVABLY-FRESH store (the caller's `freshStore` hint — a claimed schemaless spare) the shape
707
+ // catch-up needs none of the local boot phases, so start it NOW and gate its commits on `dbReady`, which
708
+ // we resolve once schema exec + journal recovery + store-version reconcile complete. The network then
709
+ // overlaps those phases instead of running strictly after them. Gated to the schema-owning paths (the
710
+ // `pgliteInstance` path runs no schema step, so it has nothing to hide); warm stores keep the exact
711
+ // sequential path. See the `freshStore` option's JSDoc for who sets the hint (the board's claim path).
712
+ const overlapPrefetch = syncEnabled && options.freshStore === true && !options.pgliteInstance;
713
+ let openDbGate: () => void = () => {};
714
+ const dbReady = overlapPrefetch
715
+ ? new Promise<void>((resolve) => {
716
+ openDbGate = resolve;
717
+ })
718
+ : null;
113
719
 
720
+ // The sync-start options, built once and used by BOTH the overlap early-start and the sequential start —
721
+ // the only per-call difference is the promoted-lazy set (empty on a fresh store) and the overlap gate.
722
+ const buildStartOptions = (promotedGroups: ReadonlySet<string>): Parameters<typeof startConfiguredSync>[1] => ({
723
+ syncConfig: buildSyncConfigFromRegistry(options.registry, options.electricUrl),
724
+ registry: options.registry,
725
+ promotedGroups,
726
+ ...(dbReady ? { dbReady } : {}),
727
+ // Persist a durable lazy group's activation on first on-demand start, so the next boot promotes it.
728
+ onLazyActivated: (groupKey) => {
729
+ void writeLazyGroupActivation(pglite, options.registry, groupKey);
730
+ },
731
+ // The read path resolves the token per request (ADR-0013), not frozen at boot — so a long-lived session
732
+ // never wedges on JWT expiry. Read and write share one token lifecycle.
733
+ ...(options.getAuthToken || options.requestHeaders
734
+ ? {
735
+ shapeHeaders: buildShapeHeaders({
736
+ ...(options.getAuthToken ? { getAuthToken: options.getAuthToken } : {}),
737
+ ...(options.requestHeaders ? { requestHeaders: options.requestHeaders } : {}),
738
+ }),
739
+ }
740
+ : {}),
741
+ ...(options.onTableInitialSync ? { onTableInitialSync: options.onTableInitialSync } : {}),
742
+ // Per-group readiness (ADR-0032 decision 6): mirror each group's catch-up into `status.groups` and
743
+ // re-emit, so an app can drive progressive per-group paint off `status` (and `client.groupReady`).
744
+ onGroupReady: (groupKey) => {
745
+ status.groups = { ...(status.groups ?? {}), [groupKey]: true };
746
+ options.onStatusChange?.(status);
747
+ },
748
+ onInitialSync: () => {
749
+ initialSyncCompleted = true;
750
+ status.phase = "ready";
751
+ options.onStatusChange?.(status);
752
+ // Boot complete: the first initial sync landed and `ready` is about to resolve. One monotonic stamp
753
+ // closes the boot rail opened by `boot pglite.create` (the stamp itself is the number).
754
+ syncDebug("boot client ready");
755
+ resolveReady();
756
+ },
757
+ onSyncError: (error) => {
758
+ // A sync commit exhausted its retries (ADR-0009 decision 5): go degraded and surface it, rather than
759
+ // letting the read cache silently diverge from the server. Sticky (see below).
760
+ status.phase = "degraded";
761
+ degradedReason = "commit";
762
+ status.lastError = error.message;
763
+ options.onStatusChange?.(status);
764
+ options.onSyncError?.(error);
765
+ },
766
+ // #4: a terminal/transient NON-auth read-stream error → `degraded`, so the runtime never keeps reporting
767
+ // healthy while the read stream has stalled. Does not override the more-actionable `auth-needed`, nor a
768
+ // commit-failure degraded. Cleared on the next successful batch below.
769
+ onReadStreamError: (error) => {
770
+ // Never mask the more-actionable auth-needed, nor a sticky commit-failure degraded (its lastError is
771
+ // the more serious signal — a stream blip must not overwrite it).
772
+ if (status.phase === "auth-needed") return;
773
+ if (status.phase === "degraded" && degradedReason === "commit") return;
774
+ // Enter, or refresh, a stream-degraded status. Refreshing keeps `lastError` pointing at the most
775
+ // recent stream fault (and re-emits) rather than freezing on the first one, so a stream that fails one
776
+ // way then another reports the current cause (observability).
777
+ status.phase = "degraded";
778
+ degradedReason = "stream";
779
+ status.lastError = error.message;
780
+ options.onStatusChange?.(status);
781
+ },
782
+ // Clear a recoverable status (auth-needed, or a read-stream degraded) the moment a batch is delivered
783
+ // again. A commit-failure degraded is NOT cleared here — a fetch can succeed while applies keep failing,
784
+ // so only `onSyncError` clearing (a clean commit) would lift it.
785
+ onSyncActivity: () => {
786
+ if (status.phase === "auth-needed" || (status.phase === "degraded" && degradedReason === "stream")) {
787
+ degradedReason = null;
788
+ status.phase = initialSyncCompleted ? "ready" : "syncing";
789
+ options.onStatusChange?.(status);
790
+ }
791
+ },
792
+ // ADR-0013 Phase 3: surface a persistent read-path auth failure as a distinct `auth-needed` status (the
793
+ // app prompts re-login) while the stream keeps retrying for a fresh token. Only wired when a token
794
+ // provider exists — without one there is no auth lifecycle to track.
795
+ ...(options.getAuthToken
796
+ ? {
797
+ onAuthError: () => {
798
+ if (status.phase !== "auth-needed") {
799
+ status.phase = "auth-needed";
800
+ options.onStatusChange?.(status);
801
+ }
802
+ },
803
+ }
804
+ : {}),
805
+ });
806
+
807
+ // Overlap: kick the shape streams off BEFORE schema exec (they buffer catch-up into the memory inbox,
808
+ // commits gated on `dbReady`). A fresh store has no persisted lazy activations and no subscriptions to
809
+ // reset, so both DB reads the sequential path makes first are skipped here.
810
+ let earlySync: ReturnType<typeof startConfiguredSync> | null = null;
811
+ if (overlapPrefetch) {
812
+ status.isRunning = true;
813
+ status.phase = "syncing";
814
+ options.onStatusChange?.(status);
815
+ earlySync = startConfiguredSync(
816
+ pglite as unknown as Parameters<typeof startConfiguredSync>[0],
817
+ buildStartOptions(new Set()),
818
+ );
819
+ }
820
+
821
+ if (!options.pgliteInstance) {
114
822
  if (options.prepareLocalDbBeforeSchema) {
115
- await options.prepareLocalDbBeforeSchema(pglite);
823
+ const prepareBeforeSchema = options.prepareLocalDbBeforeSchema;
824
+ await timeAsync("boot prepare(before-schema)", () => prepareBeforeSchema(pglite));
116
825
  }
117
826
 
118
827
  const schemaSql = generateLocalSchemaSql(options.registry);
119
- await pglite.exec(schemaSql);
828
+ await timeAsync("boot local schema", () => pglite.exec(schemaSql));
120
829
 
121
830
  if (options.prepareLocalDb) {
122
- await options.prepareLocalDb(pglite);
831
+ const prepareLocalDb = options.prepareLocalDb;
832
+ await timeAsync("boot prepare(local-db)", () => prepareLocalDb(pglite));
123
833
  }
124
834
  }
125
835
 
836
+ // The write path's headers are the shared base plus the write-only overrides (region/DB-affinity):
837
+ // `{...requestHeaders, ...writeRequestHeaders}`. The read/shape path keeps `requestHeaders` alone
838
+ // (below), so `writeRequestHeaders` never reach reads — the two ingress points pin independently.
839
+ const writePathHeaders =
840
+ options.requestHeaders || options.writeRequestHeaders
841
+ ? { ...(options.requestHeaders ?? {}), ...(options.writeRequestHeaders ?? {}) }
842
+ : undefined;
843
+
844
+ const mutationRuntime = createMutationRuntime({
845
+ db: pglite,
846
+ registry: options.registry,
847
+ writeUrl: options.writeUrl,
848
+ ...(options.getAuthToken ? { getAuthToken: options.getAuthToken } : {}),
849
+ ...(writePathHeaders ? { requestHeaders: writePathHeaders } : {}),
850
+ ...(options.maxMutationAttempts != null ? { maxMutationAttempts: options.maxMutationAttempts } : {}),
851
+ ...(options.onQuarantine ? { onQuarantine: options.onQuarantine } : {}),
852
+ ...(options.onConflict ? { onConflict: options.onConflict } : {}),
853
+ ...(options.onReject ? { onReject: options.onReject } : {}),
854
+ });
855
+
856
+ // Reclaim any in-flight mutations interrupted by a previous shutdown (ADR-0005), then
857
+ // reconcile the local store against the current registry fingerprint before sync starts
858
+ // (ADR-0006). Skipped when the caller supplies their own pglite (they own its schema).
859
+ await timeAsync("boot journal recovery", () => mutationRuntime.recoverSending());
860
+
861
+ let versionEvent: LocalStoreVersionEvent | null = null;
862
+
863
+ if (!options.pgliteInstance) {
864
+ versionEvent = await timeAsync("boot store-version reconcile", () =>
865
+ reconcileLocalStoreVersion({
866
+ db: pglite,
867
+ registry: options.registry,
868
+ runtime: mutationRuntime,
869
+ ...(options.onSchemaChange ? { onSchemaChange: options.onSchemaChange } : {}),
870
+ }),
871
+ );
872
+ }
873
+
126
874
  const drizzleDb = createDrizzleDatabase(pglite, buildSchema(options.registry));
875
+ // Static index of the registry's lazy relations (ADR-0021), driving the read-path safety net.
876
+ const lazyGuardIndex = buildLazyGuardIndex(options.registry);
127
877
 
128
- const syncEnabled = options.syncEnabled ?? true;
129
878
  let sync: Awaited<ReturnType<typeof startConfiguredSync>> | null = null;
879
+ let convergenceDriver: ConvergenceDriver | null = null;
130
880
 
131
881
  status.isRunning = true;
132
882
 
883
+ // Open the overlap commit gate now the local store is ready (schema exec + journal recovery + reconcile
884
+ // done): the catch-up the streams prefetched during those phases now drains in one commit train. A no-op
885
+ // on the sequential path (`openDbGate` is the empty default there).
886
+ openDbGate();
887
+
133
888
  if (syncEnabled) {
134
- await resetSubscriptionsIfRequested(pglite, options.resetSubscriptionKeys);
889
+ if (earlySync) {
890
+ // Overlap path: the shape streams have been prefetching since before schema exec; adopt the handle
891
+ // (it resolves as soon as the streams are subscribed — catch-up drains via the gate just lifted, and
892
+ // `onInitialSync` still gates `ready` on a fully-consistent first paint).
893
+ sync = await earlySync;
894
+ } else {
895
+ // Sequential path (warm store / no fresh hint): the exact pre-S4 ordering — reset any rebuilt
896
+ // subscriptions, promote durable lazy groups, then start (catch-up strictly after the local phases).
897
+ // After a read-cache rebuild the Electric subscription bookkeeping is stale (it would believe the
898
+ // dropped shapes are still caught up and never backfill), so reset every shape subscription to force a
899
+ // fresh re-stream (ADR-0006).
900
+ const resetKeys =
901
+ versionEvent?.status === "rebuilt"
902
+ ? [...(options.resetSubscriptionKeys ?? []), ...allGroupSubscriptionKeys(options.registry)]
903
+ : options.resetSubscriptionKeys;
904
+ await resetSubscriptionsIfRequested(pglite, resetKeys);
135
905
 
136
- status.phase = "syncing";
137
- options.onStatusChange?.(status);
906
+ status.phase = "syncing";
907
+ options.onStatusChange?.(status);
138
908
 
139
- const syncAuthToken = options.getAuthToken ? await options.getAuthToken() : undefined;
909
+ // Promote any `lazy + persistent` group activated on a previous boot back into the eager set
910
+ // (ADR-0021 §2); the sync engine does no DB read of its own.
911
+ const promotedGroups = await readActivatedLazyGroups(pglite, options.registry);
140
912
 
141
- sync = await startConfiguredSync(pglite as unknown as Parameters<typeof startConfiguredSync>[0], {
142
- syncConfig: buildSyncConfigFromRegistry(options.registry, options.electricUrl),
143
- ...(syncAuthToken ? { shapeHeaders: { Authorization: `Bearer ${syncAuthToken}` } } : {}),
144
- ...(options.onTableInitialSync ? { onTableInitialSync: options.onTableInitialSync } : {}),
145
- onInitialSync: () => {
146
- status.phase = "ready";
147
- options.onStatusChange?.(status);
148
- resolveReady();
149
- },
150
- });
913
+ sync = await timeAsync("boot sync start", () =>
914
+ startConfiguredSync(
915
+ pglite as unknown as Parameters<typeof startConfiguredSync>[0],
916
+ buildStartOptions(promotedGroups),
917
+ ),
918
+ );
919
+ }
151
920
  } else {
152
921
  status.phase = "ready";
153
922
  options.onStatusChange?.(status);
154
923
  resolveReady();
155
924
  }
156
925
 
157
- const mutationRuntime = createMutationRuntime({
158
- db: pglite,
159
- registry: options.registry,
160
- writeUrl: options.writeUrl,
161
- ...(options.getAuthToken ? { getAuthToken: options.getAuthToken } : {}),
162
- });
926
+ if (options.autoSync) {
927
+ convergenceDriver = createConvergenceDriver({
928
+ client: {
929
+ flush: () => mutationRuntime.flush(),
930
+ reconcile: () => mutationRuntime.reconcile(),
931
+ },
932
+ trigger: options.autoSync,
933
+ ...(options.onConvergencePass ? { onPass: options.onConvergencePass } : {}),
934
+ });
163
935
 
164
- await mutationRuntime.recoverSending();
936
+ // Start driving convergence once the initial sync is ready, so a pass never races the
937
+ // first shape load. stop()/destroy() halt it.
938
+ void ready.then(() => convergenceDriver?.start());
939
+ }
165
940
 
941
+ // Event-driven convergence: the moment a mutation is enqueued, ask the driver to run a pass so the
942
+ // write flushes immediately rather than waiting for the trigger's next interval tick. This is what
943
+ // lets the interval be a rare fallback (and so run far less often). No-op when `autoSync` is off — the
944
+ // caller drives `flush`/`reconcile` itself.
945
+ const requestConvergence = () => convergenceDriver?.requestPass();
166
946
  const mutate: SyncClient<TRegistry>["mutate"] = {
167
- create: (table, input) => mutationRuntime.create(table, input),
168
- update: (table, entityKey, patch) => mutationRuntime.update(table, entityKey, patch),
169
- delete: (table, entityKey) => mutationRuntime.delete(table, entityKey),
170
- batch: (items) => mutationRuntime.batch(items),
947
+ create: async (table, input) => {
948
+ await mutationRuntime.create(table, input);
949
+ requestConvergence();
950
+ },
951
+ update: async (table, entityKey, patch) => {
952
+ await mutationRuntime.update(table, entityKey, patch);
953
+ requestConvergence();
954
+ },
955
+ delete: async (table, entityKey) => {
956
+ await mutationRuntime.delete(table, entityKey);
957
+ requestConvergence();
958
+ },
959
+ batch: async (items) => {
960
+ await mutationRuntime.batch(items);
961
+ requestConvergence();
962
+ },
963
+ };
964
+
965
+ // ─── Lazy-relation activation + the declared-safe query facade (ADR-0021) ──────────────────────
966
+ const ensureSynced: SyncClient<TRegistry>["ensureSynced"] = async (keys) => {
967
+ const activeSync = sync;
968
+ if (activeSync == null || keys.length === 0) return;
969
+ const groupKeys = new Set<string>();
970
+ for (const key of keys) {
971
+ const groupKey = activeSync.groupKeyForTable(key);
972
+ if (groupKey != null) groupKeys.add(groupKey);
973
+ }
974
+ await Promise.all([...groupKeys].map((groupKey) => activeSync.ensureGroupStarted(groupKey)));
975
+ };
976
+
977
+ const isSynced: SyncClient<TRegistry>["isSynced"] = (key) => {
978
+ const activeSync = sync;
979
+ // Sync disabled → local-only: reads hit whatever is in the local store, so nothing is "dormant".
980
+ if (activeSync == null) return true;
981
+ return activeSync.isTableStarted(key);
982
+ };
983
+
984
+ const desync: SyncClient<TRegistry>["desync"] = async (key) => {
985
+ const entry = options.registry[key];
986
+ if (entry == null) throw new Error(`desync: unknown table ${String(key)}`);
987
+ if (entry.subscription !== "lazy") {
988
+ throw new Error(
989
+ `desync('${String(key)}') refused: only a lazy relation can be desynced — an eager relation is always-on and would immediately re-sync.`,
990
+ );
991
+ }
992
+
993
+ // ADR-0021 §2/§4: desync operates on the whole consistency GROUP — a group is one subscription / one
994
+ // transaction frontier, so reverting one member to dormant reverts them all. Gather the group's tables
995
+ // (a table with no `consistencyGroup` is its own singleton group).
996
+ const targetGroup = entry.consistencyGroup;
997
+ const groupTableKeys = (
998
+ targetGroup == null
999
+ ? [key]
1000
+ : (Object.keys(options.registry) as SyncTableName<TRegistry>[]).filter(
1001
+ (candidate) => options.registry[candidate]!.consistencyGroup === targetGroup,
1002
+ )
1003
+ ) as SyncTableName<TRegistry>[];
1004
+
1005
+ // Refuse if ANY writable member owes the server unsent/unsettled writes: the truncate clears the
1006
+ // journal, so dropping un-acked local intent would be silent data loss. Flush (or discard) those first.
1007
+ let owed = 0;
1008
+ for (const member of groupTableKeys) {
1009
+ if (options.registry[member]!.mode === "readonly") continue;
1010
+ const stats = await mutationRuntime.readMutationStats(member);
1011
+ owed +=
1012
+ stats.pendingCount + stats.sendingCount + stats.failedCount + stats.quarantinedCount + stats.conflictedCount;
1013
+ }
1014
+ if (owed > 0) {
1015
+ throw new Error(
1016
+ `desync('${String(key)}') refused: ${owed} unsettled mutation(s) in the group's local journal. Flush or discard them first.`,
1017
+ );
1018
+ }
1019
+
1020
+ const activeSync = sync;
1021
+ // The group key IS the Electric subscription key (`consistencyGroup ?? shapeKey`); fall back to the
1022
+ // registry derivation when sync is disabled.
1023
+ const groupKey = activeSync?.groupKeyForTable(key) ?? entry.consistencyGroup ?? entry.shape?.shapeKey;
1024
+ // Stop the stream BEFORE truncating so a live shape can't re-populate the rows we just cleared, and
1025
+ // revert the durable promotion (a no-op for ephemeral, which never persisted a flag) so the next boot
1026
+ // holds the relation dormant again.
1027
+ if (activeSync != null && groupKey != null) activeSync.stopGroup(groupKey);
1028
+ if (groupKey != null) await clearLazyGroupActivation(pglite, options.registry, groupKey);
1029
+ // CRITICAL: delete the group's persisted Electric subscription so a later re-activation re-streams the
1030
+ // shape from scratch. Without this it would resume from the old cursor and never re-send the rows we
1031
+ // truncate below — leaving the relation permanently missing its pre-desync data.
1032
+ if (groupKey != null) await resetSubscriptionsIfRequested(pglite, [groupKey]);
1033
+ // Clean-truncate every member's local cluster.
1034
+ for (const member of groupTableKeys) {
1035
+ await pglite.exec(buildDesyncTableSql(options.registry, member as string));
1036
+ }
1037
+ };
1038
+
1039
+ const transaction: SyncClient<TRegistry>["transaction"] = async ({ mode }, run) => {
1040
+ // The block's table handles only COLLECT mutations; the whole set is enqueued atomically as one unit.
1041
+ const collected: MutationBatchItem<TRegistry>[] = [];
1042
+ const txTables = Object.fromEntries(
1043
+ Object.keys(options.registry).map((tableKey) => [
1044
+ tableKey,
1045
+ {
1046
+ create: (input: unknown) => {
1047
+ collected.push({ table: tableKey, kind: "create", input } as MutationBatchItem<TRegistry>);
1048
+ },
1049
+ update: (entityKey: Record<string, string>, patch: unknown) => {
1050
+ collected.push({ table: tableKey, kind: "update", entityKey, patch } as MutationBatchItem<TRegistry>);
1051
+ },
1052
+ updateBlind: (entityKey: Record<string, string>, patch: unknown) => {
1053
+ collected.push({
1054
+ table: tableKey,
1055
+ kind: "update",
1056
+ entityKey,
1057
+ patch,
1058
+ blind: true,
1059
+ } as MutationBatchItem<TRegistry>);
1060
+ },
1061
+ delete: (entityKey: Record<string, string>) => {
1062
+ collected.push({ table: tableKey, kind: "delete", entityKey } as MutationBatchItem<TRegistry>);
1063
+ },
1064
+ },
1065
+ ]),
1066
+ ) as SyncTransaction<TRegistry>["tables"];
1067
+
1068
+ await run({ tables: txTables });
1069
+
1070
+ if (collected.length === 0) {
1071
+ return { acks: [] };
1072
+ }
1073
+
1074
+ const unit: WriteUnit = { id: globalThis.crypto.randomUUID(), mode };
1075
+ await mutationRuntime.batch(collected, unit);
1076
+
1077
+ if (mode === "optimistic") {
1078
+ // An atomic batch enqueue; the background convergence loop flushes it (no foreground answer).
1079
+ void mutationRuntime.flush();
1080
+ return { acks: [] };
1081
+ }
1082
+
1083
+ // Pessimistic: flush-route this unit to the authoritative endpoint and await the per-mutation result.
1084
+ return await mutationRuntime.flushUnit(unit.id);
1085
+ };
1086
+
1087
+ const prepareQuery: SyncClient<TRegistry>["prepareQuery"] = async ({ sql, use }) => {
1088
+ // Scan the compiled SQL for the lazy relations it reads (∪ the explicit `use`) and activate them.
1089
+ // The compiled SQL is ground truth and Drizzle quotes every relation, so any reference — FROM, JOIN,
1090
+ // subquery, WHERE — is caught; over-matching is bounded and harmless (one spurious persistent
1091
+ // subscription at worst, never a wrong result). Detection and activation are one step (ADR-0021).
1092
+ const toActivate = new Set<string>(use ?? []);
1093
+ for (const key of findReferencedLazyKeysInSql(sql, lazyGuardIndex)) toActivate.add(key);
1094
+ await ensureSynced([...toActivate] as SyncTableName<TRegistry>[]);
1095
+ // Backstop: if a referenced lazy relation is somehow still not active (a failed start, or no group),
1096
+ // throw rather than let the query read empty/stale. In the normal path everything scanned was just
1097
+ // activated, so this passes.
1098
+ assertLazyRefsActivated({
1099
+ sql,
1100
+ index: lazyGuardIndex,
1101
+ isActive: (key) => isSynced(key as SyncTableName<TRegistry>),
1102
+ });
1103
+ };
1104
+
1105
+ const runGuardedQuery = async <TRows extends readonly unknown[]>(
1106
+ build: GuardedQueryFn<TRegistry, TRows>,
1107
+ use?: readonly SyncTableName<TRegistry>[],
1108
+ ): Promise<TRows> => {
1109
+ const builder = build(client);
1110
+ await prepareQuery({ sql: builder.toSQL().sql, ...(use ? { use } : {}) });
1111
+ return builder;
171
1112
  };
172
1113
 
173
1114
  const client: SyncClient<TRegistry> = {
@@ -194,31 +1135,123 @@ export async function createSyncClient<const TRegistry extends SyncTableRegistry
194
1135
  await ready;
195
1136
  },
196
1137
  stop: async () => {
1138
+ // Await any in-flight convergence pass before closing PGlite, so a pass never queries a
1139
+ // closed handle.
1140
+ await convergenceDriver?.stop();
197
1141
  sync?.unsubscribe();
198
1142
  status.isRunning = false;
199
1143
  options.onStatusChange?.(status);
1144
+ // Tear the engine down (abort every shape stream) immediately before closing the DB — the exact
1145
+ // point PGlite's own close used to invoke the former extension's close hook (ADR-0032 S1). Order
1146
+ // preserved: convergence stop → sync unsubscribe → status → engine close → pglite close.
1147
+ await engine.close();
200
1148
  await pglite.close();
201
1149
  },
202
- destroy: async () => {
1150
+ destroy: async (destroyOptions) => {
1151
+ if (!destroyOptions?.force) {
1152
+ const stats = await mutationRuntime.readMutationStats();
1153
+ const owed =
1154
+ stats.pendingCount + stats.sendingCount + stats.failedCount + stats.quarantinedCount + stats.conflictedCount;
1155
+
1156
+ if (owed > 0) {
1157
+ throw new Error(
1158
+ `destroy() refused: ${owed} mutation(s) still owed to the server. Flush them first or call destroy({ force: true }).`,
1159
+ );
1160
+ }
1161
+ }
1162
+
1163
+ // Drain any in-flight convergence pass before wiping, so a pass never writes into a store
1164
+ // being torn down underneath it.
1165
+ await convergenceDriver?.stop();
203
1166
  sync?.unsubscribe();
204
1167
  status.isRunning = false;
205
1168
  options.onStatusChange?.(status);
1169
+ await pglite.exec(buildWipeLocalStoreSql(options.registry));
1170
+ // Same teardown ordering as `stop`: abort the engine's streams before closing the DB, the moment
1171
+ // the former extension close hook fired during `pglite.close()` (ADR-0032 S1).
1172
+ await engine.close();
206
1173
  await pglite.close();
207
1174
  },
1175
+ dropReadCache: async () => {
1176
+ await pglite.exec(buildDropReadCacheSql(options.registry));
1177
+ await pglite.exec(generateLocalSchemaSql(options.registry));
1178
+ // Reset the Electric subscriptions so the rebuilt synced tables re-stream from scratch
1179
+ // rather than the bookkeeping believing they are already caught up (ADR-0006).
1180
+ await resetSubscriptionsIfRequested(pglite, allGroupSubscriptionKeys(options.registry));
1181
+ },
208
1182
  flush: (table) => mutationRuntime.flush(table),
209
1183
  reconcile: (table) => mutationRuntime.reconcile(table),
210
1184
  retryFailed: (table) => mutationRuntime.retryFailed(table),
211
1185
  recoverSending: (table) => mutationRuntime.recoverSending(table),
212
1186
  readMutationDetails: (table) => mutationRuntime.readMutationDetails(table),
213
1187
  mutate,
1188
+ discardConflict: (table, entityKey) => mutationRuntime.discardConflict(table, entityKey),
1189
+ discardQuarantined: (table, entityKey) => mutationRuntime.discardQuarantined(table, entityKey),
214
1190
  diagnostics: async (table) => ({
215
1191
  mutation: await mutationRuntime.readMutationStats(table),
216
1192
  }),
1193
+ // Inspection surface (see the interface doc): straight through to the underlying store, no journal /
1194
+ // overlay involvement. The worker facade runs the identical call inside the worker's own client.
1195
+ rawQuery: (sql, params, options) => pglite.query(sql, params as unknown[] | undefined, options),
1196
+ rawExec: (sql, options) => pglite.exec(sql, options),
1197
+ query: (build) => runGuardedQuery(build),
1198
+ queryRow: async (build) => {
1199
+ const rows = await runGuardedQuery(build);
1200
+ return rows[0] ?? null;
1201
+ },
1202
+ queryRaw: (spec) => runGuardedQuery(spec.build, spec.use),
1203
+ queryRawRow: async (spec) => {
1204
+ const rows = await runGuardedQuery(spec.build, spec.use);
1205
+ return rows[0] ?? null;
1206
+ },
1207
+ ensureSynced,
1208
+ isSynced,
1209
+ desync,
1210
+ prepareQuery,
1211
+ transaction,
1212
+ groupReady: async (table) => {
1213
+ const activeSync = sync;
1214
+ // Sync disabled → local-only: every relation is trivially "ready" (nothing to await).
1215
+ if (activeSync == null) return;
1216
+ const groupKey = activeSync.groupKeyForTable(table as string);
1217
+ if (groupKey == null) return;
1218
+ await activeSync.groupReady(groupKey);
1219
+ },
1220
+ // The live-rows seam over PGlite's own `live` extension (ADR-0032 S2 §4) — the EXACT call the React
1221
+ // hooks made inline before the seam existed (`pglite.live.query` → `initialResults.rows` + `subscribe`),
1222
+ // so the in-process path is unchanged. `pkColumns` is unused here: PGlite's live query already diffs
1223
+ // incrementally against its own materialized state; the column set only matters for the worker bridge.
1224
+ subscribeLiveRows: async ({ sql, params }, onRows) => {
1225
+ const registered = await pglite.live.query<Record<string, unknown>>(sql, params as unknown[]);
1226
+ const listener = (results: { rows: Record<string, unknown>[] }) => {
1227
+ onRows(results.rows as never);
1228
+ };
1229
+ registered.subscribe(listener);
1230
+ return {
1231
+ initialRows: registered.initialResults.rows as never,
1232
+ unsubscribe: () => {
1233
+ void registered.unsubscribe(listener);
1234
+ },
1235
+ };
1236
+ },
217
1237
  };
218
1238
 
219
1239
  return client;
220
1240
  }
221
1241
 
1242
+ /**
1243
+ * Every persisted subscription key declared by the registry — one per consistency group (ADR-0009
1244
+ * decision 2), not per table. Grouped tables share a subscription-state row keyed by their group;
1245
+ * ungrouped tables are singleton groups keyed by their own `shapeKey`. Deduped, since several tables
1246
+ * collapse onto one group key.
1247
+ */
1248
+ function allGroupSubscriptionKeys<TRegistry extends SyncTableRegistry>(registry: TRegistry): string[] {
1249
+ const keys = Object.values(registry)
1250
+ .filter((entry) => typeof entry.shape?.shapeKey === "string" && entry.shape.shapeKey.length > 0)
1251
+ .map((entry) => entry.consistencyGroup ?? entry.shape!.shapeKey);
1252
+ return [...new Set(keys)];
1253
+ }
1254
+
222
1255
  async function resetSubscriptionsIfRequested(pglite: ClientPGlite, keys: string[] | undefined) {
223
1256
  if (!keys || keys.length === 0) {
224
1257
  return;
@@ -260,6 +1293,23 @@ function buildViews<TRegistry extends SyncTableRegistry>(registry: TRegistry) {
260
1293
  ) as RegistryViews<TRegistry>;
261
1294
  }
262
1295
 
1296
+ /**
1297
+ * The tab-side READ handles a worker-attached client exposes (ADR-0032 S2): a build-only Drizzle instance
1298
+ * plus the registry views. On the attach client, Drizzle is used only to COMPILE queries to SQL
1299
+ * (`.toSQL()`) on the tab — execution happens in the worker via the live-rows bridge / RPC — so it is
1300
+ * constructed over a stub client that is never invoked (`construct` stores the client without calling it).
1301
+ * The same builders `createSyncClient` uses, so a query built on either client compiles identically.
1302
+ */
1303
+ export function buildRegistryReadHandles<TRegistry extends SyncTableRegistry>(
1304
+ registry: TRegistry,
1305
+ ): { drizzle: PgliteDatabase<RegistryRelations<TRegistry>>; views: RegistryViews<TRegistry> } {
1306
+ const stubClient = {} as ClientPGlite;
1307
+ return {
1308
+ drizzle: createDrizzleDatabase(stubClient, buildSchema(registry)),
1309
+ views: buildViews(registry),
1310
+ };
1311
+ }
1312
+
263
1313
  function buildSyncConfigFromRegistry<TRegistry extends SyncTableRegistry>(
264
1314
  registry: TRegistry,
265
1315
  electricUrl: string,
@@ -280,6 +1330,16 @@ function buildSyncTableInput(entry: SyncTableEntry, tableKey: string) {
280
1330
  primaryKey: entry.primaryKey,
281
1331
  ...(entry.shape !== undefined ? { shape: entry.shape } : {}),
282
1332
  clientProjection,
1333
+ // The read-path apply ladder (strategy + json casts) is resolved by the engine directly from the
1334
+ // registry entry via `resolveApplyTarget` (ADR-0029 D1/D2) — `deriveSyncColumnTypes` /
1335
+ // `classifyTableApplyStrategy` on the model, never carried through this config surface.
1336
+ // Carry the consistency group (ADR-0009 decision 2) so the sync starter buckets grouped tables
1337
+ // onto one MultiShapeStream; absent → singleton group.
1338
+ ...(entry.consistencyGroup ? { consistencyGroup: entry.consistencyGroup } : {}),
1339
+ // Carry the lifecycle axes (ADR-0021) so the sync starter can hold lazy groups out of the eager
1340
+ // boot set and provision ephemeral clusters as TEMP; absent → eager/persistent (today's path).
1341
+ ...(entry.subscription ? { subscription: entry.subscription } : {}),
1342
+ ...(entry.retention ? { retention: entry.retention } : {}),
283
1343
  };
284
1344
  }
285
1345