@pgxsinkit/client 0.1.53 → 0.2.1

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 +22 -0
  2. package/dist/adoption.d.ts +118 -0
  3. package/dist/adoption.d.ts.map +1 -0
  4. package/dist/boot-report.d.ts +54 -15
  5. package/dist/boot-report.d.ts.map +1 -1
  6. package/dist/convergence.d.ts +2 -1
  7. package/dist/convergence.d.ts.map +1 -1
  8. package/dist/export-store.d.ts +1 -1
  9. package/dist/export-store.d.ts.map +1 -1
  10. package/dist/index.d.ts +286 -51
  11. package/dist/index.d.ts.map +1 -1
  12. package/dist/index.js +4795 -1519
  13. package/dist/index.js.map +34 -24
  14. package/dist/live-rows-sql.d.ts +1 -1
  15. package/dist/local-store.d.ts +16 -31
  16. package/dist/local-store.d.ts.map +1 -1
  17. package/dist/local-tables.d.ts +4 -4
  18. package/dist/mutation.d.ts +18 -15
  19. package/dist/mutation.d.ts.map +1 -1
  20. package/dist/opfs-effects.d.ts +51 -0
  21. package/dist/opfs-effects.d.ts.map +1 -0
  22. package/dist/placement-probe.d.ts +75 -0
  23. package/dist/placement-probe.d.ts.map +1 -0
  24. package/dist/schema.d.ts +11 -16
  25. package/dist/schema.d.ts.map +1 -1
  26. package/dist/store-boot.d.ts +77 -0
  27. package/dist/store-boot.d.ts.map +1 -0
  28. package/dist/store-lifecycle.d.ts +153 -0
  29. package/dist/store-lifecycle.d.ts.map +1 -0
  30. package/dist/store-meta.d.ts +190 -0
  31. package/dist/store-meta.d.ts.map +1 -0
  32. package/dist/store-path.d.ts +77 -7
  33. package/dist/store-path.d.ts.map +1 -1
  34. package/dist/sync/apply.d.ts.map +1 -1
  35. package/dist/sync/shape-inbox.d.ts +1 -1
  36. package/dist/sync/types.d.ts +3 -3
  37. package/dist/testing.js.map +3 -3
  38. package/dist/worker/attach-sync-client.d.ts +300 -16
  39. package/dist/worker/attach-sync-client.d.ts.map +1 -1
  40. package/dist/worker/define-sync-worker.d.ts +164 -23
  41. package/dist/worker/define-sync-worker.d.ts.map +1 -1
  42. package/dist/worker/election-coordinator.d.ts +95 -0
  43. package/dist/worker/election-coordinator.d.ts.map +1 -0
  44. package/dist/worker/engine-control.d.ts +266 -0
  45. package/dist/worker/engine-control.d.ts.map +1 -0
  46. package/dist/worker/engine-router.d.ts +75 -0
  47. package/dist/worker/engine-router.d.ts.map +1 -0
  48. package/dist/worker/live-query-manager.d.ts.map +1 -1
  49. package/dist/worker/protocol.d.ts +47 -31
  50. package/dist/worker/protocol.d.ts.map +1 -1
  51. package/dist/worker/sw-placement.d.ts +37 -0
  52. package/dist/worker/sw-placement.d.ts.map +1 -0
  53. package/package.json +4 -3
  54. package/skills/core/SKILL.md +15 -12
  55. package/skills/operating/SKILL.md +142 -46
  56. package/src/adoption.ts +275 -0
  57. package/src/boot-report.ts +70 -17
  58. package/src/convergence.ts +2 -1
  59. package/src/export-store.ts +1 -1
  60. package/src/index.ts +1157 -115
  61. package/src/live-rows-sql.ts +1 -1
  62. package/src/local-store.ts +18 -40
  63. package/src/local-tables.ts +2 -2
  64. package/src/mutation.ts +115 -53
  65. package/src/mutations-api.ts +3 -3
  66. package/src/opfs-effects.ts +160 -0
  67. package/src/placement-probe.ts +168 -0
  68. package/src/schema.ts +17 -22
  69. package/src/store-boot.ts +343 -0
  70. package/src/store-lifecycle.ts +227 -0
  71. package/src/store-meta.ts +459 -0
  72. package/src/store-path.ts +197 -22
  73. package/src/sync/apply.ts +63 -63
  74. package/src/sync/index.ts +2 -2
  75. package/src/sync/shape-inbox.ts +1 -1
  76. package/src/sync/types.ts +3 -3
  77. package/src/testing.ts +2 -2
  78. package/src/worker/attach-sync-client.ts +1753 -102
  79. package/src/worker/define-sync-worker.ts +1034 -71
  80. package/src/worker/election-coordinator.ts +462 -0
  81. package/src/worker/engine-control.ts +379 -0
  82. package/src/worker/engine-router.ts +355 -0
  83. package/src/worker/live-query-manager.ts +4 -1
  84. package/src/worker/protocol.ts +46 -16
  85. package/src/worker/sw-placement.ts +64 -0
@@ -18,10 +18,12 @@ import type { Results } from "@electric-sql/pglite";
18
18
  import type {
19
19
  MutationDiagnostics,
20
20
  SyncRuntimeStatus,
21
+ SyncStorageDeclaration,
21
22
  SyncTableName,
22
23
  SyncTableRegistry,
23
24
  WriteMode,
24
25
  } from "@pgxsinkit/contracts";
26
+ import { StorageDeclarationRefusedError } from "@pgxsinkit/contracts";
25
27
 
26
28
  import type { BootReport } from "../boot-report";
27
29
  import type { DataExportOptions, DataExportResult } from "../export-data";
@@ -42,7 +44,40 @@ import {
42
44
  type SyncTransactionResult,
43
45
  } from "../index";
44
46
  import type { LocalStoreVersionEvent } from "../local-store";
47
+ import { createOpfsEffects, type OpfsEffectsDeps } from "../opfs-effects";
48
+ import { type DestructionEffects, runDestruction } from "../store-lifecycle";
49
+ import { deleteStoreMetaRecord, type StoreMetaDeps, writeStoreMetaRecord } from "../store-meta";
50
+ import { storeIndexedDbDatabaseName } from "../store-path";
45
51
  import { readTestStoreMarker } from "../store-path";
52
+ import {
53
+ CONTROL_PORT_DELIVERY_KEY,
54
+ DECLARATION_KEY,
55
+ DECLARATION_REFUSED_KEY,
56
+ type DeclarationRefusedWire,
57
+ DESTROY_QUERY_KEY,
58
+ DESTROY_VERDICT_KEY,
59
+ PLACEMENT_RESULT_KEY,
60
+ type PlacementQueryResult,
61
+ PLACEMENT_QUERY_KEY,
62
+ } from "./define-sync-worker";
63
+ import {
64
+ type CoordinatorDeps,
65
+ createElectionCoordinator,
66
+ type ElectionCoordinator,
67
+ type SwBridgePort,
68
+ } from "./election-coordinator";
69
+ import {
70
+ type EngineControlMessage,
71
+ engineIdentityEquals,
72
+ type EngineIdentity,
73
+ EngineRelocatedError,
74
+ engineRelocatedFromWire,
75
+ executionLimitMismatchFromWire,
76
+ type ExecutionLimitConfig,
77
+ isStaleIdentity,
78
+ readControlEnvelope,
79
+ wrapControlEnvelope,
80
+ } from "./engine-control";
46
81
  import { LiveRowsMaterializer } from "./live-diff";
47
82
  import {
48
83
  type AttachAckPayload,
@@ -55,6 +90,7 @@ import {
55
90
  type ExportArtefactWire,
56
91
  type GuardedQueryWireArgs,
57
92
  identityCodec,
93
+ type BridgeErrorWire,
58
94
  isBridgeEnvelope,
59
95
  type LiveDiffPayload,
60
96
  type LiveHydratedPayload,
@@ -71,14 +107,439 @@ import {
71
107
  interface WorkerLike {
72
108
  port?: BridgePort;
73
109
  postMessage?: (message: unknown, transfer?: BridgeTransferable[]) => void;
74
- addEventListener?: (type: "message", listener: (event: { data: unknown }) => void) => void;
75
- removeEventListener?: (type: "message", listener: (event: { data: unknown }) => void) => void;
110
+ addEventListener?: (
111
+ type: "message" | "error",
112
+ listener: (event: { data?: unknown; message?: unknown }) => void,
113
+ ) => void;
114
+ removeEventListener?: (
115
+ type: "message" | "error",
116
+ listener: (event: { data?: unknown; message?: unknown }) => void,
117
+ ) => void;
118
+ terminate?: () => void;
119
+ }
120
+
121
+ /**
122
+ * The elected engine worker handle the election coordinator drives (ADR-0049 D5, step 8): `terminate()` (a
123
+ * deliberate teardown / respawn), `onError` (a reported worker death → immediate respawn), and
124
+ * `deliverControlPort` (post the engine end of the announce control channel — `{ [CONTROL_PORT_DELIVERY_KEY]:
125
+ * true }` with the port transferred — so the elected worker's step-9 control plane starts on it). The consumer
126
+ * supplies a factory that constructs their own `defineSyncWorker` entry as a dedicated `Worker`; wrap it with
127
+ * {@link wrapEngineWorker}.
128
+ */
129
+ export interface ElectedEngineWorker {
130
+ terminate(): void;
131
+ onError(listener: (message: string) => void): void;
132
+ deliverControlPort(port: unknown): void;
133
+ }
134
+
135
+ /**
136
+ * Wrap a dedicated `Worker` (a consumer's `defineSyncWorker` engine entry) into the {@link ElectedEngineWorker}
137
+ * the coordinator drives (ADR-0049 step 10b). `deliverControlPort` posts `{ [CONTROL_PORT_DELIVERY_KEY]: true }`
138
+ * on the worker's implicit port with the control-channel end TRANSFERRED — exactly the delivery message the
139
+ * step-9 engine control plane listens for. `onError` subscribes to the worker's `error` event; `terminate`
140
+ * forwards to `worker.terminate()`.
141
+ */
142
+ /**
143
+ * The default {@link AttachSyncClientOptions.awaitOwnershipRelease} — a documented NO-OP (ADR-0049 step 11b
144
+ * follow-up 1). The OPFS-repacked VFS enforces single-owner access with EXCLUSIVE OPFS sync-access handles
145
+ * (`StoreOwnedError`), not a Web Lock, so there is no ownership lock to await from here without importing the
146
+ * VFS. The bounded wait for the dead worker's agent to release the handle lives entirely in the SUCCESSOR'S OPEN
147
+ * PATH: the respawned engine's `createOpfsRepacked` open retries on the owned-store contention error until it
148
+ * clears (the `openWithBoundedRetries` wrapper) — the fault-matrix "successor open retries on contention" row.
149
+ * So the coordinator can respawn immediately after a deliberate terminate; its VFS open is the real gate.
150
+ */
151
+ export function resolvedOwnershipRelease(): Promise<void> {
152
+ return Promise.resolve();
153
+ }
154
+
155
+ export function wrapEngineWorker(worker: WorkerLike): ElectedEngineWorker {
156
+ const post = (message: unknown, transfer: BridgeTransferable[]): void => {
157
+ if (worker.postMessage) worker.postMessage(message, transfer);
158
+ else worker.port?.postMessage(message, transfer);
159
+ };
160
+ return {
161
+ terminate: () => worker.terminate?.(),
162
+ onError: (listener) => {
163
+ worker.addEventListener?.("error", (event) => {
164
+ const message = (event as { message?: unknown }).message;
165
+ listener(typeof message === "string" ? message : "elected engine worker error");
166
+ });
167
+ },
168
+ deliverControlPort: (port) => post({ [CONTROL_PORT_DELIVERY_KEY]: true }, [port as BridgeTransferable]),
169
+ };
170
+ }
171
+
172
+ /**
173
+ * `destroy()` on an attached facade REFUSES when other tabs still hold the store (ADR-0049 D8, plan fault row
174
+ * "`destroy()` with peers attached → refused with a typed error — close peers first"). The SharedWorker — the
175
+ * only role that knows the attached-tab count — answers a peer-count query; more than one attached tab (this
176
+ * one plus at least one other) raises this. `peers` is the total attached-tab count, this tab included.
177
+ */
178
+ export class StoreDestroyRefusedError extends Error {
179
+ readonly peers: number;
180
+ constructor(peers: number) {
181
+ super(
182
+ `[pgxsinkit] destroy() refused: ${Math.max(0, peers - 1)} other tab(s) are still attached to this store. ` +
183
+ "Close the peer tabs first, then destroy — the store is shared and destroying it under a live peer would " +
184
+ "strand that tab's engine.",
185
+ );
186
+ this.name = "StoreDestroyRefusedError";
187
+ this.peers = peers;
188
+ }
189
+ }
190
+
191
+ /**
192
+ * Attach WIRING failure (ADR-0049 D1/D5): the SharedWorker requires election (a router-only, handle-denied home)
193
+ * but the elected engine worker CANNOT be constructed — neither a `createEngineWorker` override was supplied NOR is
194
+ * the SharedWorker's own script URL derivable (a plain scope that cannot report `self.location.href`, or a
195
+ * non-module entry). Capability absence FALLS BACK (idbfs); a wiring failure ERRORS — the capability was present and
196
+ * the configuration was wrong, and silently downgrading storage would hide the defect. `[pgxsinkit]`-prefixed like
197
+ * the repo's other typed errors so a consumer can `instanceof`-branch it.
198
+ */
199
+ export class ElectedEngineUnconstructibleError extends Error {
200
+ constructor(detail: string) {
201
+ super(
202
+ `[pgxsinkit] cannot attach: this SharedWorker is router-only (election required) but the elected engine ` +
203
+ `worker cannot be constructed — ${detail}. Pass a \`createEngineWorker\` override for entries that cannot ` +
204
+ `be reconstructed from their URL as a module worker (classic-script / blob: / data: / CSP-constrained), ` +
205
+ `or use a SharedWorker whose script URL is derivable (ADR-0049 D5). This is a wiring defect, not a ` +
206
+ `capability fallback — the platform can hold sync-access handles here.`,
207
+ );
208
+ this.name = "ElectedEngineUnconstructibleError";
209
+ }
210
+ }
211
+
212
+ /** The minimal `indexedDB.deleteDatabase` surface (no DOM lib) — mirrors `store-boot.ts`'s idb delete seam. */
213
+ interface IdbDeleteSurface {
214
+ deleteDatabase(name: string): {
215
+ error?: unknown;
216
+ onsuccess: (() => void) | null;
217
+ onerror: (() => void) | null;
218
+ onblocked?: (() => void) | null;
219
+ };
220
+ }
221
+
222
+ /** Resolve the `deleteDatabase` surface: injected meta deps first (tests), else structural off `globalThis`. */
223
+ function resolveIdbDeleteSurface(meta?: StoreMetaDeps): IdbDeleteSurface | undefined {
224
+ if (meta != null && "indexedDB" in meta) return meta.indexedDB as unknown as IdbDeleteSurface | undefined;
225
+ return (globalThis as { indexedDB?: IdbDeleteSurface }).indexedDB;
226
+ }
227
+
228
+ /** Delete-if-present the store's PGlite idb database; only `onsuccess` proves completion. */
229
+ function deleteStoreIdbDatabase(storePath: string, meta?: StoreMetaDeps): Promise<void> {
230
+ const idb = resolveIdbDeleteSurface(meta);
231
+ if (idb?.deleteDatabase == null) return Promise.resolve();
232
+ const name = storeIndexedDbDatabaseName(storePath);
233
+ return new Promise<void>((resolve, reject) => {
234
+ let settled = false;
235
+ let timeout: ReturnType<typeof setTimeout> | undefined;
236
+ const finish = (error?: unknown) => {
237
+ if (settled) return;
238
+ settled = true;
239
+ if (timeout !== undefined) clearTimeout(timeout);
240
+ if (error === undefined) resolve();
241
+ else reject(error);
242
+ };
243
+ let request: {
244
+ error?: unknown;
245
+ onsuccess: (() => void) | null;
246
+ onerror: (() => void) | null;
247
+ onblocked?: (() => void) | null;
248
+ };
249
+ try {
250
+ request = idb.deleteDatabase(name);
251
+ } catch (error) {
252
+ finish(error);
253
+ return;
254
+ }
255
+ request.onsuccess = () => finish();
256
+ request.onerror = () => finish(request.error ?? new Error(`indexedDB deletion failed for ${name}`));
257
+ request.onblocked = () => undefined;
258
+ timeout = setTimeout(() => finish(new Error(`indexedDB deletion timed out while blocked for ${name}`)), 5_000);
259
+ });
260
+ }
261
+
262
+ /**
263
+ * Build the REAL {@link DestructionEffects} for a store — the OPFS commitment sentinel + store directory
264
+ * (`opfs-effects.ts`), the meta record (`store-meta.ts`), and the PGlite idb database. The destruction machine is
265
+ * backend-agnostic (`store-lifecycle.ts`): `deleteBackendStore` delete-if-presents BOTH the OPFS directory and
266
+ * the idb database, so it works whichever backend the store used. Injectable IO (`opfs`/`meta`) so the wiring is
267
+ * unit-testable with fakes.
268
+ */
269
+ export function createStoreDestructionEffects(
270
+ storePath: string,
271
+ deps?: { opfs?: OpfsEffectsDeps; meta?: StoreMetaDeps },
272
+ ): DestructionEffects {
273
+ const opfs = createOpfsEffects(storePath, deps?.opfs);
274
+ const meta = deps?.meta;
275
+ return {
276
+ setPhase: (phase) => writeStoreMetaRecord(storePath, { phase, updatedAt: Date.now() }, meta),
277
+ deleteSentinel: () => opfs.deleteSentinel(),
278
+ deleteBackendStore: async () => {
279
+ await opfs.deleteStoreDirectory();
280
+ await deleteStoreIdbDatabase(storePath, meta);
281
+ },
282
+ deleteMetaRecord: () => deleteStoreMetaRecord(storePath, meta),
283
+ };
284
+ }
285
+
286
+ /**
287
+ * Destroy every local artifact of a store BY PATH (ADR-0050 stage 2; the public face of the ADR-0049 D8
288
+ * destruction machinery): the OPFS store directory, the commitment sentinel, the meta record, AND the idb
289
+ * database — backend-agnostic (delete-if-present on both backends), with the bounded VFS-ownership-lag retry.
290
+ *
291
+ * **Precondition: the store is NOT running.** This is the companion to {@link SyncClient.destroy} (the
292
+ * supervised destroy of an ATTACHED store — peer-checked, teardown-acknowledged): reach for
293
+ * `destroyStoreArtifacts` for a store nobody is attached to — an obsolete path a preference change left
294
+ * behind, a wipe of known store paths. Called on a path a live engine still holds, the backend delete throws
295
+ * an ownership error after the bounded retry — loud, and safely RE-RUNNABLE: the destruction sequence is
296
+ * idempotent and phase-recorded (a store whose meta record says `deleting` is refused for boot), so a re-run
297
+ * completes it. No liveness probe is attempted here — it could not be race-free, and the ownership error
298
+ * already fails hard; callers keep failed paths on their own retry list (e.g. the board's Obsolete stores).
299
+ */
300
+ export function destroyStoreArtifacts(storePath: string, opts?: StoreDestructionRetryOptions): Promise<void> {
301
+ return runStoreDestruction(createStoreDestructionEffects(storePath), opts);
302
+ }
303
+
304
+ /** Options for {@link quiesceStoreWorker} (ADR-0050). */
305
+ export interface StoreWorkerQuiesceOptions {
306
+ /** The ADR-0050 storage declaration to post on the port. Omit (or `{}`) to state NO opinion — always
307
+ * compatible with whatever declaration the live worker already bound, so it can never be refused. Passing a
308
+ * concrete declaration risks a `StorageDeclarationRefusedError` if it disagrees with the bound one. */
309
+ storage?: SyncStorageDeclaration;
310
+ /** Bound on the whole handshake (declaration → placement reply → teardown ack). Default 6000ms. On timeout
311
+ * the returned promise REJECTS — the caller keeps the path on its retry list; it is NOT proof of teardown. */
312
+ timeoutMs?: number;
313
+ /** Injectable timers (tests); defaults to real `setTimeout`/`clearTimeout`. */
314
+ timers?: AttachClientTimers;
315
+ }
316
+
317
+ /** The outcome of {@link quiesceStoreWorker}. */
318
+ export interface StoreWorkerQuiesceOutcome {
319
+ /** The store's engine home as reported by its placement reply. */
320
+ engineHome: PlacementQueryResult["engineHome"];
321
+ /** True iff an SW-direct engine was torn down here (its host closed, releasing the backend connection).
322
+ * `false` for an `elected-worker` home — there is no in-SharedWorker engine to close from this router-only
323
+ * connection; the elected dedicated engine dies with its owning tab (the browser terminates it on document
324
+ * teardown), releasing its store, so no active teardown is needed before a path-addressed destroy. */
325
+ toreDown: boolean;
326
+ }
327
+
328
+ /**
329
+ * Quiesce the SharedWorker HOSTING a store, by path, so its backend connection is released BEFORE a
330
+ * {@link destroyStoreArtifacts} on the same path (ADR-0050). The gap it closes: the board's workers are
331
+ * `extendedLifetime`, so a store's SharedWorker OUTLIVES the document that spawned it — and the idbfs backend
332
+ * holds its IndexedDB connection open for the engine's whole life. So after a reload, an idbfs store's worker
333
+ * is still alive and still holding the connection; `deleteDatabase` blocks and `destroyStoreArtifacts` fails,
334
+ * boot after boot, until the browser eventually reaps the worker. OPFS releases its handles when idle, so it
335
+ * never had this problem — this is the idbfs (SW-direct) fix.
336
+ *
337
+ * `worker` is a factory (or instance), exactly like {@link attachSyncClient}'s `worker` — the caller constructs
338
+ * `new SharedWorker(url, { name: storePath })`, so the library stays DOM-free. Connecting by that name reaches
339
+ * the LIVE worker (if any) or spawns a fresh one; either way the sequence is: post the declaration, query
340
+ * placement, and — for a `shared-worker` home — send `engine-teardown` and await its reserved ack, which the
341
+ * host posts only after `closeHost()` has stopped the engine and released the backend connection (it then
342
+ * closes its own scope). An `elected-worker` home resolves immediately with `toreDown: false` (see the field).
343
+ *
344
+ * Idempotent and safe on an already-dead store: a fresh spawn boots no engine, and its teardown closes an empty
345
+ * host. Compose it as `await quiesceStoreWorker(f).catch(() => {}); await destroyStoreArtifacts(path)` — a
346
+ * quiesce failure (timeout) must NOT abort the destroy, whose own ownership-lag handling reports honestly and
347
+ * leaves the path re-runnable.
348
+ */
349
+ export function quiesceStoreWorker(
350
+ worker: (() => WorkerLike) | WorkerLike,
351
+ opts?: StoreWorkerQuiesceOptions,
352
+ ): Promise<StoreWorkerQuiesceOutcome> {
353
+ const timers: AttachClientTimers = opts?.timers ?? {
354
+ setTimeout: (fn, ms) => setTimeout(fn, ms),
355
+ clearTimeout: (handle) => clearTimeout(handle as ReturnType<typeof setTimeout>),
356
+ };
357
+ const timeoutMs = opts?.timeoutMs ?? 6000;
358
+ const port = resolvePort({ worker });
359
+ return new Promise<StoreWorkerQuiesceOutcome>((resolve, reject) => {
360
+ let settled = false;
361
+ let teardownIdentity: EngineIdentity | undefined;
362
+ const finish = (run: () => void): void => {
363
+ if (settled) return;
364
+ settled = true;
365
+ timers.clearTimeout(timeout);
366
+ port.removeEventListener("message", listener);
367
+ run();
368
+ };
369
+ const timeout = timers.setTimeout(
370
+ () => finish(() => reject(new Error(`[pgxsinkit] quiesceStoreWorker timed out after ${timeoutMs}ms`))),
371
+ timeoutMs,
372
+ );
373
+ const listener = (event: { data: unknown }): void => {
374
+ const placement = readPlacementResult(event.data);
375
+ if (placement !== undefined) {
376
+ if (placement.engineHome !== "shared-worker") {
377
+ finish(() => resolve({ engineHome: placement.engineHome, toreDown: false }));
378
+ return;
379
+ }
380
+ // SW-direct: ask the in-scope host to quiesce+close, then await its reserved teardown ack (pingId -1),
381
+ // which proves the engine stopped and the backend connection was released (define-sync-worker).
382
+ teardownIdentity = { swInstanceId: placement.swInstanceId, generation: 0 };
383
+ port.postMessage(wrapControlEnvelope({ type: "engine-teardown", identity: teardownIdentity }));
384
+ return;
385
+ }
386
+ const refusal = readDeclarationRefusal(event.data);
387
+ if (refusal !== undefined) {
388
+ finish(() => reject(new StorageDeclarationRefusedError(refusal.message)));
389
+ return;
390
+ }
391
+ const control = readControlEnvelope(event.data);
392
+ if (
393
+ control?.type === "control-ack" &&
394
+ control.pingId === -1 &&
395
+ teardownIdentity !== undefined &&
396
+ control.identity?.swInstanceId === teardownIdentity.swInstanceId
397
+ ) {
398
+ if (control.error) {
399
+ finish(() => reject(new Error(`[pgxsinkit] store-worker teardown failed: ${control.error?.message}`)));
400
+ } else {
401
+ finish(() => resolve({ engineHome: "shared-worker", toreDown: true }));
402
+ }
403
+ }
404
+ };
405
+ port.addEventListener("message", listener);
406
+ port.start?.();
407
+ // Declaration FIRST (ADR-0050), then the placement query. If the worker's placement is still pending (a
408
+ // fresh spawn), the queued-traffic path redelivers the follow-up teardown after routing (ADR-0050 W1).
409
+ port.postMessage({ [DECLARATION_KEY]: opts?.storage ?? {} });
410
+ port.postMessage({ [PLACEMENT_QUERY_KEY]: true });
411
+ });
412
+ }
413
+
414
+ /** The bounded ownership-retry options for {@link runStoreDestruction} (the VFS-lock-lag guard, D8/fault row). */
415
+ export interface StoreDestructionRetryOptions {
416
+ /** Max retries of `deleteBackendStore` on an ownership-lock-lag error before giving up (default 5). */
417
+ maxOwnershipRetries?: number;
418
+ /** Classify an error as VFS-ownership-lock lag (retryable). Default: OPFS `NoModificationAllowedError`-class. */
419
+ isOwnershipError?: (error: unknown) => boolean;
420
+ /** Between-retries delay; defaults to a real timer. Injected in tests. */
421
+ delay?: (ms: number) => Promise<void>;
422
+ /** The between-retries delay (ms); default 50. */
423
+ retryDelayMs?: number;
424
+ }
425
+
426
+ /** Default ownership-lag classifier: OPFS raises `NoModificationAllowedError`/`InvalidStateError` while a sync-access handle is open. */
427
+ function defaultIsOwnershipError(error: unknown): boolean {
428
+ const name = (error as { name?: string } | null)?.name;
429
+ if (name === "NoModificationAllowedError" || name === "InvalidStateError") return true;
430
+ const message = (error as { message?: unknown } | null)?.message;
431
+ const text = (typeof message === "string" ? message : "").toLowerCase();
432
+ return text.includes("owned") || text.includes("ownership") || text.includes("locked") || text.includes("in use");
433
+ }
434
+
435
+ /**
436
+ * Run the destructive lifecycle (ADR-0049 D8) with a BOUNDED ownership-lock-lag retry around the backend-store
437
+ * delete. The engine was just detached, so its VFS ownership lock may not have cleared yet — the fault row
438
+ * "VFS ownership-lock release lag → successor retries until clear, bounded" applies to destroy too. The other
439
+ * steps (set `deleting`, delete sentinel, delete the meta record) are idempotent and not retried here. Shared by
440
+ * the attached-facade supervisor (this module) and the in-process `destroy()` (index.ts).
441
+ */
442
+ export async function runStoreDestruction(
443
+ effects: DestructionEffects,
444
+ opts?: StoreDestructionRetryOptions,
445
+ ): Promise<void> {
446
+ const maxRetries = opts?.maxOwnershipRetries ?? 5;
447
+ const isOwnershipError = opts?.isOwnershipError ?? defaultIsOwnershipError;
448
+ const delay = opts?.delay ?? ((ms: number) => new Promise<void>((resolve) => setTimeout(resolve, ms)));
449
+ const retryDelayMs = opts?.retryDelayMs ?? 50;
450
+ const guarded: DestructionEffects = {
451
+ setPhase: (phase) => effects.setPhase(phase),
452
+ deleteSentinel: () => effects.deleteSentinel(),
453
+ deleteMetaRecord: () => effects.deleteMetaRecord(),
454
+ deleteBackendStore: async () => {
455
+ for (let attempt = 0; ; attempt += 1) {
456
+ try {
457
+ await effects.deleteBackendStore();
458
+ return;
459
+ } catch (error) {
460
+ if (attempt >= maxRetries || !isOwnershipError(error)) throw error;
461
+ await delay(retryDelayMs);
462
+ }
463
+ }
464
+ },
465
+ };
466
+ await runDestruction(guarded);
76
467
  }
77
468
 
469
+ /** Narrow a raw SharedWorker placement reply (`{ [PLACEMENT_RESULT_KEY]: … }`), or `undefined` for foreign traffic. */
470
+ function readPlacementResult(data: unknown): PlacementQueryResult | undefined {
471
+ if (typeof data !== "object" || data === null) return undefined;
472
+ const result = (data as { [PLACEMENT_RESULT_KEY]?: unknown })[PLACEMENT_RESULT_KEY];
473
+ if (typeof result !== "object" || result === null) return undefined;
474
+ return result as PlacementQueryResult;
475
+ }
476
+
477
+ /** Narrow a raw SharedWorker destroy peer-count verdict (`{ [DESTROY_VERDICT_KEY]: { peers } }`), or `undefined`. */
478
+ function readDestroyVerdict(data: unknown): number | undefined {
479
+ if (typeof data !== "object" || data === null) return undefined;
480
+ const verdict = (data as { [DESTROY_VERDICT_KEY]?: unknown })[DESTROY_VERDICT_KEY];
481
+ if (typeof verdict !== "object" || verdict === null) return undefined;
482
+ const peers = (verdict as { peers?: unknown }).peers;
483
+ return typeof peers === "number" ? peers : undefined;
484
+ }
485
+
486
+ /** Narrow a raw storage-declaration refusal (`{ [DECLARATION_REFUSED_KEY]: { message, name } }`), or `undefined`. */
487
+ function readDeclarationRefusal(data: unknown): DeclarationRefusedWire | undefined {
488
+ if (typeof data !== "object" || data === null) return undefined;
489
+ const refusal = (data as { [DECLARATION_REFUSED_KEY]?: unknown })[DECLARATION_REFUSED_KEY];
490
+ if (typeof refusal !== "object" || refusal === null) return undefined;
491
+ const message = (refusal as { message?: unknown }).message;
492
+ return typeof message === "string" ? (refusal as unknown as DeclarationRefusedWire) : undefined;
493
+ }
494
+
495
+ /**
496
+ * The `setTimeout`/`clearTimeout` pair the handoff-queue deadline and the bridge-silence reconnect schedule on
497
+ * (ADR-0049 step 7) — injectable for deterministic tests, exactly the discipline `engine-router.ts` follows so
498
+ * the whole placement seam is unit-testable with no real timers.
499
+ */
500
+ export interface AttachClientTimers {
501
+ setTimeout(fn: () => void, ms: number): unknown;
502
+ clearTimeout(handle: unknown): void;
503
+ }
504
+
505
+ /**
506
+ * The RPC ops that MUTATE the store/journal or push to the server — the ones whose lost response after a
507
+ * relocation is `outcome: "unknown"` (a journal update may already exist, there is no dedup key; ADR-0049 D10,
508
+ * invariant 5). Everything NOT in this set is a READ (or an idempotent activation) that is safe to repeat, so it
509
+ * settles `outcome: "not-dispatched"`. `ensureSynced` is deliberately a read here: activation is additive and
510
+ * idempotent (starting an already-active group is a no-op), so repeating it can never double-apply. The
511
+ * `export*` ops read the store into an artefact (no mutation) and are likewise safe to repeat.
512
+ */
513
+ const MUTATION_RPC_OPS: ReadonlySet<RpcOp> = new Set<RpcOp>([
514
+ "create",
515
+ "update",
516
+ "delete",
517
+ "batch",
518
+ "transaction",
519
+ "flush",
520
+ "reconcile",
521
+ "retryFailed",
522
+ "recoverSending",
523
+ "discardConflict",
524
+ "discardQuarantined",
525
+ "desync",
526
+ "discardEphemeral",
527
+ // `rawExec` is WRITE-CAPABLE (its docstring: any write it issues stays local and will NOT converge), so a
528
+ // dispatched rawExec with a lost response is `"unknown"` — retrying could double-apply a local write.
529
+ "rawExec",
530
+ ]);
531
+
78
532
  export interface AttachSyncClientOptions<TRegistry extends SyncTableRegistry> {
79
533
  registry: TRegistry;
80
- /** A native `Worker` or `SharedWorker` (or anything port-shaped). Provide this OR {@link port}. */
81
- worker?: WorkerLike;
534
+ /**
535
+ * The worker input — PRIMARILY a FACTORY `() => SharedWorker` (ADR-0049 D5). A `SharedWorker` object cannot be
536
+ * reconstructed from itself, so the factory is what makes SharedWorker-death recovery (the keepalive
537
+ * reconstruction, and the {@link bridgeSilenceMs} bridge-silence reconnect) a GUARANTEE rather than an option:
538
+ * both re-invoke it for a fresh SharedWorker. A bare instance (a native `Worker`/`SharedWorker`, or anything
539
+ * port-shaped) is ALSO accepted for tests and exotic hosts — reconstruction is then structurally unavailable
540
+ * (diagnostics say so). Provide this OR {@link port}.
541
+ */
542
+ worker?: (() => WorkerLike) | WorkerLike;
82
543
  /** A raw transport port (a `MessageChannel` port in tests, a `SharedWorker.port` in a browser). */
83
544
  port?: BridgePort;
84
545
  /**
@@ -112,11 +573,27 @@ export interface AttachSyncClientOptions<TRegistry extends SyncTableRegistry> {
112
573
  * Restore the worker's store from a backup on attach (ADR-0035 decision 6) — the worker-mode `restoreFrom`.
113
574
  * A `File`/`Blob` as produced by {@link SyncClient.exportStore}; the facade decomposes it into a transferred
114
575
  * `ArrayBuffer` + name/mime ({@link RestoreArtefactWire}) and the worker recomposes it for `createSyncClient`.
115
- * Restore rides the FIRST (boot) attach: passing it when the worker's engine has ALREADY booted rejects the
116
- * attach with a typed error (you cannot restore into a running store). The restored engine boots offline and
117
- * its recovered journal is quarantined, exactly as in-process — see `restoreFrom` on `createSyncClient`.
576
+ * Restore rides the one handshake that reaches the ENGINE HOME: a restore-bearing attach awaits the
577
+ * placement reply, then carries the artifact on the SW-port handshake when the in-scope host is the engine
578
+ * (SW-direct / declared-idbfs) or on the first per-tab PIPE handshake when the engine is elected — the
579
+ * router-only SharedWorker is payload-blind, so a restore posted there would be dropped and destroyed.
580
+ * Passing it when the engine has ALREADY booted rejects the attach with a typed error
581
+ * (`RestoreIntoRunningStoreError` by name — you cannot restore into a running store). The restored engine
582
+ * boots offline and its recovered journal is quarantined, exactly as in-process — see `restoreFrom` on
583
+ * `createSyncClient`.
118
584
  */
119
585
  restoreFrom?: File | Blob;
586
+ /**
587
+ * The tab's WIRE storage declaration for this store (ADR-0050) — posted as the declaration message on the
588
+ * worker port BEFORE the placement query (so `backend: "idbfs"` can skip the probe), and carried on the
589
+ * provision/attach payloads so the engine binds it (durability included). Omit (or `{}`) for "no opinion":
590
+ * a registry-attached static declaration, else the capability defaults, decide. A registry-attached
591
+ * declaration is AUTHORITATIVE — an explicit field here that disagrees with it (or with the declaration
592
+ * another tab already bound) is a typed refusal (`StorageDeclarationRefusedError`), never silently
593
+ * overridden: a store's declaration is immutable, and a preference change mints a fresh store under a
594
+ * fresh path instead.
595
+ */
596
+ storage?: SyncStorageDeclaration;
120
597
  codec?: BridgeCodec;
121
598
  onStatusChange?: (status: SyncRuntimeStatus) => void;
122
599
  onConflict?: (details: MutationDetail[]) => void;
@@ -130,6 +607,87 @@ export interface AttachSyncClientOptions<TRegistry extends SyncTableRegistry> {
130
607
  * attaches AFTER the boot never receives the push — it reads the report via {@link SyncClient.bootReport}.
131
608
  */
132
609
  onBootReport?: (report: BootReport) => void;
610
+ /**
611
+ * The bridge-silence deadline (ms) for non-leader reconnection (ADR-0049 D5). DISABLED when undefined (the
612
+ * default); the election coordinator (step 8) sets it. When set: a pending op left with NO bridge traffic
613
+ * since it was posted, past this deadline, triggers ONE reconnect attempt via the {@link worker} FACTORY (if the
614
+ * input is a factory) — construct a fresh SharedWorker, resolve its port, re-attach, flush the queue,
615
+ * re-subscribe. With a bare-instance input reconstruction is structurally unavailable, so no reconnect is armed.
616
+ * Scheduled on {@link timers}.
617
+ */
618
+ bridgeSilenceMs?: number;
619
+ /**
620
+ * The bounded handoff queue (ADR-0049 invariant 9). While the handoff window is open — after a relocation
621
+ * notice, before the replacement pipe's handshake completes — new data-path ops are QUEUED, not posted.
622
+ * `cap` overflow or `deadlineMs` expiry fails queued ops with `EngineRelocatedError("not-dispatched")` (they
623
+ * never left the tab, so they are safe to retry). Defaults: `cap` 256, `deadlineMs` 15000. The deadline is
624
+ * scheduled on {@link timers}.
625
+ */
626
+ handoffQueue?: { cap?: number; deadlineMs?: number };
627
+ /**
628
+ * Injectable timers for the handoff-queue deadline and the bridge-silence reconnect (ADR-0049 step 7) — the
629
+ * same deterministic-test seam `engine-router.ts` exposes. Defaults to `globalThis.setTimeout`/`clearTimeout`.
630
+ */
631
+ timers?: AttachClientTimers;
632
+ /**
633
+ * The elected engine worker OVERRIDE (ADR-0049 D5). In `elected-worker` placement (a router-only SharedWorker)
634
+ * the tab's election coordinator spawns the real engine as a dedicated `Worker`. NORMALLY NO WIRING IS NEEDED:
635
+ * the worker entry is dual-scope (one file serves both homes), the SharedWorker reports its own script URL in the
636
+ * placement reply, and the winning tab constructs the engine as `new Worker(swScriptUrl, { type: "module" })`
637
+ * itself. Supply this override ONLY for entries that cannot be reconstructed from their URL as a module worker
638
+ * (classic-script workers, `blob:`/`data:` URLs, CSP constraints); wrap the constructed worker with
639
+ * {@link wrapEngineWorker}. When election is required but NEITHER a derivable URL NOR this override is available,
640
+ * attach fails with the typed {@link ElectedEngineUnconstructibleError} — never a silent no-engine attach.
641
+ */
642
+ createEngineWorker?: () => ElectedEngineWorker;
643
+ /**
644
+ * The opt-in engine-construction EXECUTION LIMIT (ADR-0049 D5) as this tab carries it — every tab attaching to a
645
+ * store MUST carry the SAME value the worker was constructed with (`ExecutionLimitMismatchError` on a mismatch).
646
+ * DISABLED by default (`undefined` / absent `maxDispatchMs`) — no finite worst-case query duration exists, so
647
+ * enabling the limit (which converts slow to terminated by policy) is a deliberate consumer choice. When
648
+ * `maxDispatchMs` is set AND this tab is on an elected per-tab pipe, a dispatched RPC still outstanding past the
649
+ * limit is reported to the router as an `overdue-dispatch` (the router then probes the engine's control channel;
650
+ * a WASM-blocked engine cannot answer → the leader retires + respawns it). ELECTED PLACEMENT ONLY — on SW-direct
651
+ * the option is rejected as unsupported during attach rather than silently ignored.
652
+ */
653
+ executionLimit?: ExecutionLimitConfig;
654
+ /**
655
+ * The leader-keepalive ping cadence (ms) the election coordinator uses (ADR-0049 step 8). Default 20000. The
656
+ * keepalive is the ONE standing timer that detects SharedWorker death (unanswered pings) → reconstruct via the
657
+ * {@link worker} factory + re-announce the still-live engine. Lower it to detect SW death faster.
658
+ */
659
+ keepaliveIntervalMs?: number;
660
+ /** Consecutive unanswered keepalive pings before SharedWorker reconstruction (ADR-0049 step 8). Default 2. */
661
+ keepaliveMissThreshold?: number;
662
+ /**
663
+ * Await the VFS ownership release after a deliberate engine termination (ADR-0049 step 8). Defaults to the
664
+ * documented no-op {@link resolvedOwnershipRelease} — the HONEST MINIMUM (step 11b follow-up 1): the
665
+ * OPFS-repacked VFS enforces ownership with EXCLUSIVE OPFS sync-access handles (`StoreOwnedError` /
666
+ * `STORE_OWNED`), NOT a Web Lock, so there is no lock name to `navigator.locks.request(..., { ifAvailable })`
667
+ * against here. The bounded wait therefore lives in the SUCCESSOR'S OPEN PATH: the respawned elected engine
668
+ * worker's own `createOpfsRepacked` open throws the owned-store contention error and is retried with backoff
669
+ * (the `openWithBoundedRetries` wrapper in `createClientPGlite`) until the dead worker's agent releases the
670
+ * handle — exactly the fault-matrix row "VFS ownership-lock release lag → successor open retries on contention
671
+ * until clear, bounded, then boot failure". Supply a custom async wait only to inject a real probe (tests do).
672
+ */
673
+ awaitOwnershipRelease?: () => Promise<void>;
674
+ /**
675
+ * @internal test seam (ADR-0049 step 10b): override the election coordinator's IO — the Web Locks surface and
676
+ * the page-lifecycle subscription. Production reads `navigator.locks` structurally and subscribes to real
677
+ * `pagehide`/`pageshow`. Injected so the election wiring is unit-testable with a fake locks (no real
678
+ * `navigator.locks` under Bun).
679
+ */
680
+ electionIo?: {
681
+ locks?: CoordinatorDeps["locks"];
682
+ pageLifecycle?: CoordinatorDeps["pageLifecycle"];
683
+ };
684
+ /**
685
+ * @internal test seam (ADR-0049 step 10b): override the destruction effects the ATTACHED `destroy()` runs
686
+ * after it detaches. Production builds real OPFS + meta-record + idb effects from the store path
687
+ * ({@link createStoreDestructionEffects}); injected so the supervised-destroy path is unit-testable with fake
688
+ * effects (effect-order assertions, ownership-lock-lag retry).
689
+ */
690
+ createDestructionEffects?: (storePath: string) => DestructionEffects;
133
691
  }
134
692
 
135
693
  /**
@@ -149,21 +707,278 @@ export type AttachedSyncClient<TRegistry extends SyncTableRegistry> = SyncClient
149
707
  setOnline: (online: boolean) => void;
150
708
  };
151
709
 
710
+ /**
711
+ * The IO a shared election coordinator is built from (ADR-0049 step 8) — the subset both {@link attachSyncClient}
712
+ * and the elected {@link provisionSyncWorker} pass so ONE coordinator serves a tab's whole (provision + attach)
713
+ * lifecycle per store (invariant 2 — never self-queued). A module-level builder (not a per-call closure) so both
714
+ * entry points construct the identical coordinator.
715
+ */
716
+ interface ElectedCoordinatorParams {
717
+ storePath: string;
718
+ /** The SW control port the coordinator posts announce/keepalive on (the FIRST creator's connection). */
719
+ controlPort: BridgePort;
720
+ createEngineWorker: () => ElectedEngineWorker;
721
+ /** The SharedWorker reconstruction factory (ADR-0049 D5) — drives the keepalive SW-death recovery. Absent for a
722
+ bare-instance input, where reconstruction is structurally unavailable. */
723
+ swFactory?: () => WorkerLike;
724
+ /** The tab's wire storage declaration (ADR-0050) — posted FIRST on every reconstructed SW port, before the
725
+ coordinator's announce/keepalive traffic, so a fresh bootstrap binds and routes instead of refusing. */
726
+ storage?: SyncStorageDeclaration;
727
+ electionIo?: AttachSyncClientOptions<SyncTableRegistry>["electionIo"];
728
+ awaitOwnershipRelease?: () => Promise<void>;
729
+ timers: AttachClientTimers;
730
+ pageLifecycle?: CoordinatorDeps["pageLifecycle"];
731
+ keepaliveIntervalMs?: number;
732
+ keepaliveMissThreshold?: number;
733
+ }
734
+
735
+ /**
736
+ * Build the tab's election coordinator over a SW control port. The spawn adapter mints the announce control
737
+ * channel and delivers its ENGINE end to the freshly-spawned worker; `createControlChannel` yields the SAME
738
+ * channel so `announce` transfers the ROUTER end to the SharedWorker; a re-announce WITHOUT a respawn (keepalive
739
+ * SW reconstruction) re-delivers a fresh engine-end to the retained live engine (step 11b follow-up 2).
740
+ */
741
+ function buildElectedCoordinator(params: ElectedCoordinatorParams): ElectionCoordinator {
742
+ const factory = params.createEngineWorker;
743
+ let pendingChannel: MessageChannel | undefined;
744
+ let liveEngine: ElectedEngineWorker | undefined;
745
+ const locks = params.electionIo?.locks ??
746
+ (globalThis as { navigator?: { locks?: CoordinatorDeps["locks"] } }).navigator?.locks ?? {
747
+ request: () => Promise.resolve(),
748
+ };
749
+ const deps: CoordinatorDeps = {
750
+ locks,
751
+ spawnEngineWorker: () => {
752
+ const engine = factory();
753
+ liveEngine = engine;
754
+ const channel = new MessageChannel();
755
+ pendingChannel = channel;
756
+ engine.deliverControlPort(channel.port2);
757
+ return { terminate: () => engine.terminate(), onError: (listener) => engine.onError(listener) };
758
+ },
759
+ createControlChannel: () => {
760
+ if (pendingChannel !== undefined) {
761
+ const channel = pendingChannel;
762
+ pendingChannel = undefined;
763
+ return { port1: channel.port1, port2: channel.port2 };
764
+ }
765
+ const channel = new MessageChannel();
766
+ liveEngine?.deliverControlPort(channel.port2);
767
+ return { port1: channel.port1, port2: channel.port2 };
768
+ },
769
+ swPort: params.controlPort as unknown as SwBridgePort,
770
+ ...(params.swFactory
771
+ ? {
772
+ reconstructSw: () => {
773
+ const port = resolvePort({ worker: params.swFactory! });
774
+ // ADR-0050: the reconstructed SharedWorker is a fresh bootstrap — declare before the coordinator's
775
+ // announce rides this port, or the bootstrap refuses/queues nothing and recovery hangs.
776
+ port.postMessage({ [DECLARATION_KEY]: params.storage ?? {} });
777
+ return port as unknown as SwBridgePort;
778
+ },
779
+ }
780
+ : {}),
781
+ awaitOwnershipRelease: params.awaitOwnershipRelease ?? resolvedOwnershipRelease,
782
+ timers: params.timers,
783
+ ...(params.pageLifecycle ? { pageLifecycle: params.pageLifecycle } : {}),
784
+ };
785
+ return createElectionCoordinator(deps, {
786
+ storePath: params.storePath,
787
+ ...(params.keepaliveIntervalMs != null ? { keepaliveIntervalMs: params.keepaliveIntervalMs } : {}),
788
+ ...(params.keepaliveMissThreshold != null ? { keepaliveMissThreshold: params.keepaliveMissThreshold } : {}),
789
+ });
790
+ }
791
+
792
+ /**
793
+ * Per-store SHARED election coordinators (ADR-0049 step 8 — "one coordinator per tab per store; provision and
794
+ * attach share it"). Populated ONLY by an elected {@link provisionSyncWorker}; a later {@link attachSyncClient}
795
+ * on the SAME store (same page realm) ADOPTS it (`claimForAttach` — no second lock request, no second engine,
796
+ * invariant 2). Empty when no provision ran, so attach-only flows never touch it (no shared coordinator to adopt). Keyed
797
+ * by store path; ref-counted so it clears once every provision claim + adopting attach has released.
798
+ */
799
+ const sharedCoordinators = new Map<
800
+ string,
801
+ {
802
+ coordinator: ElectionCoordinator;
803
+ refs: number;
804
+ /** Release the provision claim and cancel its expiry after an explicit construction-identity retirement. */
805
+ releaseProvision?: () => void;
806
+ /**
807
+ * The provision's live engine pipe, held for HANDOVER (ADR-0049 step 8). The router mints exactly ONE proxy
808
+ * pipe per SW connection; when provision and attach share one port (the documented ordered-messages contract,
809
+ * e.g. the board), that pipe is delivered during provisioning — so the adopting attach must receive THIS pipe
810
+ * rather than wait for a `connect-port` that will never be re-sent. Cleared on take; closed if never taken.
811
+ */
812
+ provisionPipe?: { pipe: BridgePort; identity: EngineIdentity };
813
+ }
814
+ >();
815
+
816
+ /** Adopt an existing per-store coordinator (incrementing its ref), or register a freshly-built one. */
817
+ function adoptOrRegisterCoordinator(storePath: string, build: () => ElectionCoordinator): ElectionCoordinator {
818
+ let entry = sharedCoordinators.get(storePath);
819
+ if (entry === undefined) {
820
+ entry = { coordinator: build(), refs: 0 };
821
+ sharedCoordinators.set(storePath, entry);
822
+ }
823
+ entry.refs += 1;
824
+ return entry.coordinator;
825
+ }
826
+
827
+ /** Look up an already-registered per-store coordinator WITHOUT registering one (attach's adopt-if-present probe). */
828
+ function lookupSharedCoordinator(storePath: string): ElectionCoordinator | undefined {
829
+ return sharedCoordinators.get(storePath)?.coordinator;
830
+ }
831
+
832
+ /** Increment the ref of an already-registered coordinator (an adopting attach); no-op if none is registered. */
833
+ function retainSharedCoordinator(storePath: string): void {
834
+ const entry = sharedCoordinators.get(storePath);
835
+ if (entry !== undefined) entry.refs += 1;
836
+ }
837
+
838
+ /** Release one ref; the entry clears at zero so a later provision/attach starts a fresh coordinator. */
839
+ function releaseSharedCoordinator(storePath: string): void {
840
+ const entry = sharedCoordinators.get(storePath);
841
+ if (entry === undefined) return;
842
+ entry.refs -= 1;
843
+ if (entry.refs <= 0) {
844
+ entry.provisionPipe?.pipe.close?.();
845
+ sharedCoordinators.delete(storePath);
846
+ }
847
+ }
848
+
849
+ /** Stash the provision's engine pipe for the adopting attach's handover; no-op when no entry is registered. */
850
+ function stashProvisionPipe(storePath: string, pipe: BridgePort, identity: EngineIdentity): void {
851
+ const entry = sharedCoordinators.get(storePath);
852
+ if (entry !== undefined) entry.provisionPipe = { pipe, identity };
853
+ }
854
+
855
+ /** Take (and clear) the stashed provision pipe — exactly one adopting attach may consume it. */
856
+ function takeProvisionPipe(storePath: string): { pipe: BridgePort; identity: EngineIdentity } | undefined {
857
+ const entry = sharedCoordinators.get(storePath);
858
+ const stashed = entry?.provisionPipe;
859
+ if (entry !== undefined) delete entry.provisionPipe;
860
+ return stashed;
861
+ }
862
+
863
+ /** Record the provision claim's explicit release companion on its shared coordinator entry. */
864
+ function setProvisionRelease(storePath: string, release: () => void): void {
865
+ const entry = sharedCoordinators.get(storePath);
866
+ if (entry !== undefined) entry.releaseProvision = release;
867
+ }
868
+
152
869
  export async function attachSyncClient<const TRegistry extends SyncTableRegistry>(
153
870
  options: AttachSyncClientOptions<TRegistry>,
154
871
  ): Promise<AttachedSyncClient<TRegistry>> {
155
872
  const codec = options.codec ?? identityCodec;
156
873
  const port = resolvePort(options);
874
+ // The SharedWorker reconstruction factory (ADR-0049 D5), or undefined for a bare-instance/port input. Drives the
875
+ // bridge-silence reconnect and the coordinator's keepalive SW-reconstruction; both re-invoke it for a fresh
876
+ // SharedWorker. Absent → reconstruction is structurally unavailable and those recovery paths are simply not armed.
877
+ const workerFactory = workerFactoryOf(options.worker);
878
+
879
+ // ─── ADR-0049 placement seams (data-port indirection, handoff window, reconnect) ──────────────────
880
+ // `controlPort` permanently carries the `{ pgx0049 }` control plane (relocation notices + `connect-port`);
881
+ // `dataPort` starts AS the control port (SW-direct / declared-idbfs / no-pgx0049: the data path never leaves the SW port) and SWAPS to a
882
+ // transferred pipe on `connect-port`. Every data-path send goes through `currentDataPort()` so the pending
883
+ // maps stay in place across a swap (invariant 6 — one direct pipe per tab; the router never sees payloads).
884
+ let controlPort: BridgePort = port;
885
+ let dataPort: BridgePort = port;
886
+ const currentDataPort = (): BridgePort => dataPort;
887
+ const timers: AttachClientTimers = options.timers ?? {
888
+ setTimeout: (fn, ms) => globalThis.setTimeout(fn, ms),
889
+ clearTimeout: (handle) => globalThis.clearTimeout(handle as ReturnType<typeof globalThis.setTimeout>),
890
+ };
891
+ // The current engine identity (invariant 7 — the pair), set on each accepted `connect-port`; `hasPipe` marks
892
+ // that the data path has left the control port. The handoff window (`windowOpen`) queues new ops.
893
+ let currentEngineIdentity: EngineIdentity | undefined;
894
+ let hasPipe = false;
895
+ let windowOpen = false;
896
+ // Bounded handoff queue (invariant 9): thunks deferred while the window is open, each carrying a `reject` so
897
+ // cap-overflow / deadline-expiry can fail the caller with `EngineRelocatedError("not-dispatched")`.
898
+ const handoffQueue: Array<{ dispatch: () => void; reject: (error: Error) => void }> = [];
899
+ const queueCap = options.handoffQueue?.cap ?? 256;
900
+ const queueDeadlineMs = options.handoffQueue?.deadlineMs ?? 15000;
901
+ let queueDeadlineHandle: unknown;
902
+ // Bridge-silence reconnect (D5): armed on each dispatch when `bridgeSilenceMs` + a factory are set; ONE
903
+ // attempt. `bridgeSeenSinceArm` distinguishes a live-but-slow engine from true silence.
904
+ let silenceHandle: unknown;
905
+ let bridgeSeenSinceArm = false;
906
+ let reconnecting = false;
907
+ // ─── ADR-0049 election + supervised-destroy state ─────────────────────────────────────────────────
908
+ // The tab's election coordinator (created lazily on a router-only `electionRequired` placement reply — the
909
+ // elected engine factory is the `createEngineWorker` override or the URL-derived default) + its released-on-detach
910
+ // claim; and the pending destroy peer-count verdict resolver (the SharedWorker answers a `{ [DESTROY_QUERY_KEY] }`
911
+ // query with the attached-tab count).
912
+ let electionCoordinator: ElectionCoordinator | undefined;
913
+ let releaseElectionClaim: (() => void) | undefined;
914
+ let destroyVerdictResolver: ((peers: number) => void) | undefined;
915
+ let placementResult: PlacementQueryResult | undefined;
916
+ let swTeardownAckResolver: ((error?: BridgeErrorWire) => void) | undefined;
917
+ let swTeardownIdentity: EngineIdentity | undefined;
918
+ // Set to the store path when this attach ADOPTED a shared (provision-registered) coordinator — so detach
919
+ // releases the shared ref (ref-counted registry cleanup). Undefined when this tab built its own coordinator.
920
+ let adoptedSharedCoordinatorStore: string | undefined;
921
+ // The placement decision is single-shot: once we act on the first `electionRequired` reply we ignore any repeat.
922
+ let placementDecided = false;
923
+ // Settles when the FIRST placement reply arrives (the bootstrap meta listener answers the query in BOTH SW
924
+ // modes) — or REJECTS typed when the worker refuses this tab's storage declaration (ADR-0050), which arrives
925
+ // in place of the placement reply. Every boot awaits it before the first handshake — see the send site.
926
+ let resolvePlacementKnown: (() => void) | undefined;
927
+ let rejectPlacementKnown: ((error: Error) => void) | undefined;
928
+ const placementKnown = new Promise<void>((resolve, reject) => {
929
+ resolvePlacementKnown = resolve;
930
+ rejectPlacementKnown = reject;
931
+ });
932
+ // A refusal may land after a detach already settled the boot path — never an unhandled rejection.
933
+ void placementKnown.catch(() => undefined);
934
+ // The restore artifact rides EXACTLY ONE handshake — its ArrayBuffer detaches on first post, so a resend
935
+ // would carry an empty buffer. Set the moment a handshake actually carries it (see `runAttachHandshake`).
936
+ let restoreConsumed = false;
937
+
938
+ // ─── ADR-0049 first-attach gate (placement-query-FIRST ordering — elected-mode ack routing) ───────
939
+ // `attachSyncClient` no longer gates on the SW-port attach ack: a router-only SharedWorker (elected-worker home)
940
+ // is payload-blind and DROPS the bridge `attach`, so that ack would never come there. Instead the attach resolves
941
+ // when the FIRST attach ack lands from EITHER home — the in-scope SW engine (SW-direct / declared-idbfs / no-SW
942
+ // baseline) OR the elected engine over the per-tab pipe (`onConnectPort`, after election delivers `connect-port`).
943
+ // It REJECTS on a boot-failure ack, on detach, or — when election is required but the engine worker cannot be
944
+ // constructed — with the typed {@link ElectedEngineUnconstructibleError} (a WIRING failure, never a hang). With a
945
+ // constructible engine, the coordinator's own election spawns it and delivers the pipe, so no attach deadline exists.
946
+ let firstAttachSettled = false;
947
+ let resolveFirstAttach!: () => void;
948
+ let rejectFirstAttach!: (error: Error) => void;
949
+ const firstAttachReady = new Promise<void>((resolve, reject) => {
950
+ resolveFirstAttach = resolve;
951
+ rejectFirstAttach = reject;
952
+ });
953
+ void firstAttachReady.catch(() => undefined);
954
+ const settleFirstAttach = (): void => {
955
+ if (firstAttachSettled) return;
956
+ firstAttachSettled = true;
957
+ resolveFirstAttach();
958
+ };
959
+ const failFirstAttach = (error: Error): void => {
960
+ if (firstAttachSettled) return;
961
+ firstAttachSettled = true;
962
+ rejectFirstAttach(error);
963
+ };
157
964
 
158
965
  // ─── Correlation + subscription bookkeeping ──────────────────────────────────────────────────────
159
966
  let nextId = 0;
160
967
  const newId = (prefix: string) => `${prefix}-${++nextId}`;
161
- const rpcPending = new Map<string, { resolve: (value: unknown) => void; reject: (error: Error) => void }>();
968
+ // `kind` (ADR-0049 invariant 5): a lost response on a MUTATION settles `outcome: "unknown"`, on a READ
969
+ // `outcome: "not-dispatched"` (safe to repeat). Stamped at every `rpc` call site from {@link MUTATION_RPC_OPS}.
970
+ const rpcPending = new Map<
971
+ string,
972
+ { resolve: (value: unknown) => void; reject: (error: Error) => void; kind: "read" | "mutation" }
973
+ >();
162
974
  const initialPending = new Map<
163
975
  string,
164
976
  { resolve: (payload: LiveInitialPayload) => void; reject: (error: Error) => void }
165
977
  >();
166
978
  const diffHandlers = new Map<string, (diff: Omit<LiveDiffPayload, "queryId">) => void>();
979
+ // Live subscriptions that have completed their initial snapshot (keyed by queryId) — re-issued through the
980
+ // same subscribe machinery on a pipe swap so live queries re-establish (invariant 5; ADR-0041 re-attach).
981
+ const activeSubscriptions = new Map<string, { resubscribe: () => void }>();
167
982
  // Resolvers for per-subscription `hydrated` promises, keyed by queryId. The worker posts
168
983
  // `live-hydrated` on the same port as the diff stream, strictly after the catch-up rows — so
169
984
  // resolution here guarantees the rows have already been applied by the materializer.
@@ -192,11 +1007,11 @@ export async function attachSyncClient<const TRegistry extends SyncTableRegistry
192
1007
  // ─── Auth: push at attach + on notifyAuthChanged, answer pull-requests ────────────────────────────
193
1008
  const pushToken = async () => {
194
1009
  const token = options.getToken ? await options.getToken() : null;
195
- postBridgeMessage(port, codec, "token-push", token);
1010
+ postBridgeMessage(currentDataPort(), codec, "token-push", token);
196
1011
  };
197
1012
  const answerPull = async (requestId: string) => {
198
1013
  const token = options.getToken ? await options.getToken() : null;
199
- postBridgeMessage(port, codec, "token-response", { requestId, token });
1014
+ postBridgeMessage(currentDataPort(), codec, "token-response", { requestId, token });
200
1015
  };
201
1016
 
202
1017
  // ─── Inbound message routing ─────────────────────────────────────────────────────────────────────
@@ -289,6 +1104,9 @@ export async function attachSyncClient<const TRegistry extends SyncTableRegistry
289
1104
 
290
1105
  const listener = (message: { data: unknown }) => {
291
1106
  if (!isBridgeEnvelope(message.data)) return;
1107
+ // Any bridge traffic on the data port proves the engine is answering — clears the bridge-silence suspicion
1108
+ // (ADR-0049 D5), so a live-but-slow engine is never mistaken for a dead SharedWorker.
1109
+ bridgeSeenSinceArm = true;
292
1110
  const envelope = message.data;
293
1111
  const payload = codec.decode(envelope.payload);
294
1112
  switch (envelope.type) {
@@ -300,7 +1118,13 @@ export async function attachSyncClient<const TRegistry extends SyncTableRegistry
300
1118
  // fold any downstream milestones/failures the tail already crossed (a late attach). `engineReady`
301
1119
  // covers a LATE attach whose engine already fired its monotonic `ready` before this ack (FIX 3).
302
1120
  if (ack.error) {
303
- attachAckReject?.(rebuildError(ack.error));
1121
+ const settle = pendingAttachAck;
1122
+ pendingAttachAck = null;
1123
+ const bootError = rebuildError(ack.error);
1124
+ settle?.reject(bootError);
1125
+ // A boot-failure ack on the FIRST attach (SW-direct) fails `attachSyncClient` (invariant: never hand out
1126
+ // a client whose engine failed to boot); a no-op once the first attach already settled (a re-attack ack).
1127
+ failFirstAttach(bootError);
304
1128
  } else {
305
1129
  if (ack.engineReady) markReady();
306
1130
  resolveLocalReadReady();
@@ -310,7 +1134,12 @@ export async function attachSyncClient<const TRegistry extends SyncTableRegistry
310
1134
  if (ack.writeReadyError) failWriteReady(rebuildError(ack.writeReadyError));
311
1135
  if (ack.bootSettled) settleBootSettled();
312
1136
  if (ack.bootSettledError) failBootSettled(rebuildError(ack.bootSettledError));
313
- attachAckResolve?.(ack);
1137
+ const settle = pendingAttachAck;
1138
+ pendingAttachAck = null;
1139
+ settle?.resolve(ack);
1140
+ // The first attach ack from EITHER home (SW-direct engine, or the elected engine over the pipe) resolves
1141
+ // `attachSyncClient`. Idempotent — a re-attach ack (pipe swap / reconnect) is a no-op here.
1142
+ settleFirstAttach();
314
1143
  }
315
1144
  break;
316
1145
  }
@@ -324,8 +1153,9 @@ export async function attachSyncClient<const TRegistry extends SyncTableRegistry
324
1153
  const pending = rpcPending.get(id);
325
1154
  if (pending) {
326
1155
  rpcPending.delete(id);
1156
+ clearOverdue(id);
327
1157
  if (result.ok) pending.resolve(result.value);
328
- else pending.reject(rebuildError(result.error));
1158
+ else pending.reject(rebuildRpcError(result.error));
329
1159
  break;
330
1160
  }
331
1161
  // A failed `subscribe` is reported as an `rpc-result` correlated by the subscribe's envelope id
@@ -334,7 +1164,7 @@ export async function attachSyncClient<const TRegistry extends SyncTableRegistry
334
1164
  const initial = initialPending.get(id);
335
1165
  if (initial && !result.ok) {
336
1166
  initialPending.delete(id);
337
- initial.reject(rebuildError(result.error));
1167
+ initial.reject(rebuildRpcError(result.error));
338
1168
  }
339
1169
  break;
340
1170
  }
@@ -368,28 +1198,462 @@ export async function attachSyncClient<const TRegistry extends SyncTableRegistry
368
1198
  break;
369
1199
  }
370
1200
  };
371
- port.addEventListener("message", listener);
372
- port.start?.();
1201
+ // ─── ADR-0049 control-plane listener (the `{ pgx0049 }` envelope) ─────────────────────────────────
1202
+ // Lives on the CONTROL port for this tab's whole lifetime. It reacts to exactly the placement messages: a
1203
+ // `connect-port` (with a transferred pipe) swaps the data path; a `leader-granted`/`engine-retiring` notice
1204
+ // opens the handoff window. Foreign traffic (data-path bridge envelopes, anything else) is untouched — the
1205
+ // control plane is INERT until pgx0049 traffic arrives, so a plain SW-port attach is pure data-path passthrough.
1206
+ const controlListener = (event: { data: unknown; ports?: readonly BridgePort[] }) => {
1207
+ // ADR-0049 step 10b: the SharedWorker's RAW placement reply + destroy peer-count verdict (distinct envelope
1208
+ // keys, NOT `pgx0049` control messages). Handle those first, then fall through to the control envelope.
1209
+ const placementResult = readPlacementResult(event.data);
1210
+ if (placementResult !== undefined) {
1211
+ onPlacementResult(placementResult);
1212
+ return;
1213
+ }
1214
+ // ADR-0050: the worker refused this tab's storage declaration (explicit conflict with the bound/static
1215
+ // declaration, or engine-bound traffic before the declaration). It arrives IN PLACE of the placement
1216
+ // reply, so fail the boot typed and loudly — never a hang, never a silently different storage mode.
1217
+ const declarationRefusal = readDeclarationRefusal(event.data);
1218
+ if (declarationRefusal !== undefined) {
1219
+ const refusal = new StorageDeclarationRefusedError(declarationRefusal.message);
1220
+ rejectPlacementKnown?.(refusal);
1221
+ failFirstAttach(refusal);
1222
+ return;
1223
+ }
1224
+ const destroyPeers = readDestroyVerdict(event.data);
1225
+ if (destroyPeers !== undefined) {
1226
+ destroyVerdictResolver?.(destroyPeers);
1227
+ return;
1228
+ }
1229
+ const control = readControlEnvelope(event.data);
1230
+ if (control === undefined) return;
1231
+ switch (control.type) {
1232
+ case "connect-port":
1233
+ void onConnectPort(control.identity, event.ports?.[0]);
1234
+ break;
1235
+ case "control-ack":
1236
+ if (
1237
+ control.pingId === -1 &&
1238
+ swTeardownIdentity !== undefined &&
1239
+ engineIdentityEquals(control.identity, swTeardownIdentity)
1240
+ ) {
1241
+ swTeardownAckResolver?.(control.error);
1242
+ }
1243
+ break;
1244
+ case "leader-granted":
1245
+ case "engine-retiring":
1246
+ onRelocationNotice(control);
1247
+ break;
1248
+ default:
1249
+ break;
1250
+ }
1251
+ };
1252
+
1253
+ // The bridge listener starts on the data port (initially === the control port); the control listener stays on
1254
+ // the control port. In the no-pgx0049 case both sit on the one `port` and coexist (each ignores the other's
1255
+ // traffic), so the data path is unchanged.
1256
+ dataPort.addEventListener("message", listener);
1257
+ dataPort.start?.();
1258
+ controlPort.addEventListener("message", controlListener);
1259
+ controlPort.start?.();
1260
+
1261
+ // ─── Data-port swap + handoff-queue + reconnect machinery (ADR-0049) ──────────────────────────────
1262
+ /** Move the bridge listener onto `next`; close the previous pipe when replacing one (never the control port). */
1263
+ const swapDataPort = (next: BridgePort, closePrev: boolean): void => {
1264
+ const prev = dataPort;
1265
+ if (prev === next) return;
1266
+ next.addEventListener("message", listener);
1267
+ next.start?.();
1268
+ prev.removeEventListener("message", listener);
1269
+ // The control port keeps carrying `{ pgx0049 }` and MUST NOT be closed on the first swap; a replaced pipe is
1270
+ // dead and IS closed (invariant 5 — old-pipe pendings settled, the pipe closed, never replayed).
1271
+ if (closePrev && prev !== controlPort) prev.close?.();
1272
+ dataPort = next;
1273
+ };
1274
+
1275
+ /**
1276
+ * Settle EVERY in-flight pending op by outcome (ADR-0049 invariant 5) — used on a relocation notice, a pipe
1277
+ * replacement, and a reconnect. A MUTATION whose response is lost is `"unknown"` (its journal update may
1278
+ * exist; inspect/reconcile, never auto-retry); a dispatched READ is `"not-dispatched"` — the name means
1279
+ * "safe to retry" (a read cannot double-apply; ADR-0049 D10: "dispatched reads are safe to repeat — caller
1280
+ * policy"). Live-query initial pendings are reads → `"not-dispatched"`; `hydrated` promises are doneness
1281
+ * signals with no reject path, so they RESOLVE (the file's existing convention on teardown), and re-subscribe
1282
+ * re-hydrates. Nothing is ever auto-retried here.
1283
+ */
1284
+ const settleInFlight = (): void => {
1285
+ for (const [id, pending] of rpcPending) {
1286
+ rpcPending.delete(id);
1287
+ clearOverdue(id);
1288
+ pending.reject(new EngineRelocatedError(pending.kind === "mutation" ? "unknown" : "not-dispatched"));
1289
+ }
1290
+ for (const [id, pending] of initialPending) {
1291
+ initialPending.delete(id);
1292
+ pending.reject(new EngineRelocatedError("not-dispatched"));
1293
+ }
1294
+ for (const resolve of hydratedPending.values()) resolve();
1295
+ hydratedPending.clear();
1296
+ };
1297
+
1298
+ const clearQueueDeadline = (): void => {
1299
+ if (queueDeadlineHandle !== undefined) {
1300
+ timers.clearTimeout(queueDeadlineHandle);
1301
+ queueDeadlineHandle = undefined;
1302
+ }
1303
+ };
1304
+ const armQueueDeadline = (): void => {
1305
+ if (queueDeadlineHandle !== undefined) return;
1306
+ queueDeadlineHandle = timers.setTimeout(() => {
1307
+ queueDeadlineHandle = undefined;
1308
+ // The window outlived the deadline — the queued work never left the tab, so fail it "not-dispatched".
1309
+ const items = handoffQueue.splice(0);
1310
+ for (const item of items) item.reject(new EngineRelocatedError("not-dispatched"));
1311
+ }, queueDeadlineMs);
1312
+ };
1313
+ /** Enqueue a deferred data-path op while the window is open; cap overflow fails it "not-dispatched" at once. */
1314
+ const enqueue = (dispatch: () => void, reject: (error: Error) => void): void => {
1315
+ if (handoffQueue.length >= queueCap) {
1316
+ reject(new EngineRelocatedError("not-dispatched"));
1317
+ return;
1318
+ }
1319
+ handoffQueue.push({ dispatch, reject });
1320
+ armQueueDeadline();
1321
+ };
1322
+ /** Flush the queue in order after a successful re-attach; clears the deadline. */
1323
+ const flushQueue = (): void => {
1324
+ clearQueueDeadline();
1325
+ const items = handoffQueue.splice(0);
1326
+ for (const item of items) item.dispatch();
1327
+ };
1328
+
1329
+ const resubscribeAll = (): void => {
1330
+ for (const sub of activeSubscriptions.values()) sub.resubscribe();
1331
+ };
1332
+
1333
+ /** A relocation notice opens the handoff window: settle in-flight per invariant 5, then QUEUE new calls. */
1334
+ function onRelocationNotice(control: EngineControlMessage): void {
1335
+ if (detached) return;
1336
+ // `engine-retiring` is identity-tagged: ignore a STALE one (a superseded engine) once we have an identity;
1337
+ // `leader-granted` is untagged and always applies (it precedes any engine).
1338
+ if (
1339
+ control.type === "engine-retiring" &&
1340
+ currentEngineIdentity !== undefined &&
1341
+ isStaleIdentity(currentEngineIdentity, control.identity)
1342
+ ) {
1343
+ return;
1344
+ }
1345
+ if (windowOpen) return;
1346
+ windowOpen = true;
1347
+ settleInFlight();
1348
+ armQueueDeadline();
1349
+ }
1350
+
1351
+ /**
1352
+ * A `connect-port` delivers a transferred pipe (invariant 6). The FIRST one swaps the data path off the
1353
+ * control port and re-attaches over the pipe. A SUBSEQUENT one under a NEWER identity is a pipe REPLACEMENT
1354
+ * (a new SharedWorker handing fresh pipes): settle old-pipe in-flight, close the old pipe, swap, re-attach,
1355
+ * flush the queue, and re-subscribe every live query.
1356
+ */
1357
+ async function onConnectPort(identity: EngineIdentity, pipe: BridgePort | undefined): Promise<void> {
1358
+ if (detached || pipe === undefined) return;
1359
+ // A duplicate for the SAME identity we already piped is a no-op (never re-pipe the same engine).
1360
+ if (currentEngineIdentity !== undefined && engineIdentityEquals(currentEngineIdentity, identity)) return;
1361
+ const replacing = hasPipe;
1362
+ // Hold the window open across the swap+handshake so calls issued mid-flight queue rather than race.
1363
+ windowOpen = true;
1364
+ if (replacing) settleInFlight();
1365
+ currentEngineIdentity = identity;
1366
+ swapDataPort(pipe, replacing);
1367
+ hasPipe = true;
1368
+ try {
1369
+ // `includeRestore: true` — in elected mode THIS is the engine's boot attach, so the restore artifact
1370
+ // (withheld from the router-dropped SW-port handshake) rides here, over the direct tab↔engine pipe.
1371
+ // The `restoreConsumed` guard makes it first-carry-only: a pipe REPLACEMENT re-attach never re-sends.
1372
+ await runAttachHandshake(pipe, true);
1373
+ } catch {
1374
+ // A failed re-attach leaves the window open; a later notice / connect-port can retry. Never auto-retried.
1375
+ return;
1376
+ }
1377
+ windowOpen = false;
1378
+ flushQueue();
1379
+ resubscribeAll();
1380
+ }
1381
+
1382
+ /** Arm the bridge-silence timer after a dispatch (D5) — only when a deadline AND a SharedWorker factory exist. */
1383
+ const armSilence = (): void => {
1384
+ if (options.bridgeSilenceMs === undefined || workerFactory === undefined) return;
1385
+ if (silenceHandle !== undefined || detached) return;
1386
+ bridgeSeenSinceArm = false;
1387
+ silenceHandle = timers.setTimeout(() => {
1388
+ silenceHandle = undefined;
1389
+ if (detached) return;
1390
+ // A pending op survived the deadline with NO bridge traffic since it was posted → the transport looks
1391
+ // dead. Reconnect ONCE. If traffic WAS seen but ops are still pending, re-arm (a slow-but-live engine).
1392
+ if (!bridgeSeenSinceArm && rpcPending.size > 0) void reconnect();
1393
+ else if (rpcPending.size > 0) armSilence();
1394
+ }, options.bridgeSilenceMs);
1395
+ };
1396
+
1397
+ /**
1398
+ * ONE bridge-silence reconnect attempt (ADR-0049 D5): construct a fresh SharedWorker via the worker FACTORY, move
1399
+ * both listeners to its port, settle the presumed-dead transport's in-flight per invariant 5, re-run the attach
1400
+ * handshake, then flush + re-subscribe. With a bare-instance input (no factory) this is unreachable — reconstruction
1401
+ * is structurally unavailable. Never more than one concurrent attempt.
1402
+ */
1403
+ async function reconnect(): Promise<void> {
1404
+ if (reconnecting || detached || workerFactory === undefined) return;
1405
+ reconnecting = true;
1406
+ let newPort: BridgePort;
1407
+ try {
1408
+ newPort = resolvePort({ worker: workerFactory });
1409
+ } catch {
1410
+ reconnecting = false;
1411
+ return;
1412
+ }
1413
+ settleInFlight();
1414
+ dataPort.removeEventListener("message", listener);
1415
+ controlPort.removeEventListener("message", controlListener);
1416
+ controlPort = newPort;
1417
+ dataPort = newPort;
1418
+ hasPipe = false;
1419
+ currentEngineIdentity = undefined;
1420
+ windowOpen = true;
1421
+ newPort.addEventListener("message", listener);
1422
+ newPort.addEventListener("message", controlListener);
1423
+ newPort.start?.();
1424
+ // ADR-0050: the reconstructed SharedWorker may be a FRESH bootstrap whose placement is still pending —
1425
+ // every port must declare before any engine-bound message. The declaration precedes the attach on the same
1426
+ // port, and the bootstrap queues the attach until placement resolves (no placement round-trip needed here).
1427
+ newPort.postMessage({ [DECLARATION_KEY]: options.storage ?? {} });
1428
+ try {
1429
+ await runAttachHandshake(newPort, false);
1430
+ } catch {
1431
+ reconnecting = false;
1432
+ return;
1433
+ }
1434
+ windowOpen = false;
1435
+ flushQueue();
1436
+ resubscribeAll();
1437
+ reconnecting = false;
1438
+ }
1439
+
1440
+ // ─── ADR-0049 election wiring + supervised destroy ────────────────────────────────────────────────
1441
+ /** The store PATH this tab owns — the identity every store-IO surface (OPFS namespaces, meta record, idb db, leader lock) derives from. */
1442
+ const resolveDestroyStorePath = (): string => options.storePath ?? options.storeId ?? "pgxsinkit-overlay-v1";
1443
+ // The elected engine worker factory for THIS attach (ADR-0049 D5): the `createEngineWorker` OVERRIDE, else the
1444
+ // default derived from the SharedWorker's reported script URL (`new Worker(url, { type: "module" })`). Resolved on
1445
+ // the `electionRequired` reply; `undefined` means neither is available — a WIRING failure, not a fallback.
1446
+ let electedEngineFactory: (() => ElectedEngineWorker) | undefined;
1447
+
1448
+ /**
1449
+ * The SharedWorker reported the engine home. In `elected-worker` (router-only) mode this tab must elect its own
1450
+ * engine: resolve the engine factory (the `createEngineWorker` override, else the URL-derived default), build the
1451
+ * coordinator (once), and take one attach claim. When NEITHER a derivable URL NOR an override is available the
1452
+ * engine is genuinely unconstructible on a handle-denied home — a WIRING failure, so the attach fails with the
1453
+ * typed {@link ElectedEngineUnconstructibleError} (never a silent no-engine attach). `shared-worker` (SW-direct /
1454
+ * declared-idbfs) needs no election.
1455
+ */
1456
+ function onPlacementResult(result: PlacementQueryResult): void {
1457
+ if (detached || placementDecided) return;
1458
+ placementDecided = true;
1459
+ placementResult = result;
1460
+ resolvePlacementKnown?.();
1461
+ // SW-direct / declared-idbfs (or a non-placement transport that never replies): the SW-port attach ack gates the flow.
1462
+ if (!result.electionRequired) return;
1463
+ // Elected-worker (router-only): resolve the engine factory. Auto-derivation from the reported script URL is the
1464
+ // default (dual-scope entry); the `createEngineWorker` override wins where an entry is not URL-reconstructible.
1465
+ electedEngineFactory = options.createEngineWorker ?? deriveEngineWorkerFactory(result.swScriptUrl);
1466
+ if (electedEngineFactory === undefined) {
1467
+ // The capability is PRESENT (this home requires election) but the engine cannot be constructed — a wiring
1468
+ // defect. Fail the attach typed; never a silent no-engine attach and never a storage downgrade (ADR-0049 D1).
1469
+ failFirstAttach(
1470
+ new ElectedEngineUnconstructibleError(
1471
+ result.swScriptUrl === undefined
1472
+ ? "the SharedWorker reported no derivable script URL and no `createEngineWorker` override was supplied"
1473
+ : "no `Worker` constructor is available in this scope to derive the module engine and no override was supplied",
1474
+ ),
1475
+ );
1476
+ return;
1477
+ }
1478
+ // ADOPT an existing PROVISION grant for this store if one is registered (ADR-0049 step 8, fault row
1479
+ // "provision then attach, same tab → attach adopts the provision grant; never self-queued"): reuse the same
1480
+ // coordinator + its already-granted lock + already-spawned engine — `claimForAttach` adds NO second lock
1481
+ // request and spawns NO second engine (invariant 2). The router pipes this tab's OWN connection to that engine
1482
+ // and the boot adopts the provisioned store (no double initdb). Absent → build this tab's own coordinator.
1483
+ const storePath = resolveDestroyStorePath();
1484
+ const adopted = lookupSharedCoordinator(storePath);
1485
+ if (adopted !== undefined) {
1486
+ retainSharedCoordinator(storePath);
1487
+ adoptedSharedCoordinatorStore = storePath;
1488
+ electionCoordinator = adopted;
1489
+ } else {
1490
+ electionCoordinator = buildElectionCoordinator();
1491
+ }
1492
+ releaseElectionClaim = electionCoordinator.claimForAttach();
1493
+ // Provision-pipe HANDOVER (ADR-0049 step 8): when this attach shares its SW port with the provision that
1494
+ // registered the adopted coordinator, the router's one-and-only pipe for this connection was already
1495
+ // delivered during provisioning — feed it into the normal connect-port path instead of waiting for a
1496
+ // re-send that never comes. On a fresh (non-shared) port the stash is empty and the router's ordinary
1497
+ // late-joiner `connect-port` drives the handshake as usual.
1498
+ if (adopted !== undefined) {
1499
+ const stashed = takeProvisionPipe(storePath);
1500
+ if (stashed !== undefined) void onConnectPort(stashed.identity, stashed.pipe);
1501
+ }
1502
+ }
1503
+
1504
+ /**
1505
+ * SW-direct stores are owned by the in-scope host, not an elected coordinator. Ask that host to quiesce and
1506
+ * close, then await its reserved teardown ack before detaching this tab and deleting the store. A timeout is
1507
+ * deliberately not treated as proof of worker death: destruction still runs and its bounded ownership retry
1508
+ * reports an honest failure while the durable `deleting` phase remains recoverable.
1509
+ */
1510
+ const awaitSharedHostTeardown = async (): Promise<void> => {
1511
+ const placement = placementResult;
1512
+ if (placement?.engineHome !== "shared-worker") return;
1513
+ const identity: EngineIdentity = { swInstanceId: placement.swInstanceId, generation: 0 };
1514
+ await new Promise<void>((resolve, reject) => {
1515
+ let settled = false;
1516
+ const timeout = timers.setTimeout(() => {
1517
+ if (settled) return;
1518
+ settled = true;
1519
+ swTeardownAckResolver = undefined;
1520
+ swTeardownIdentity = undefined;
1521
+ resolve();
1522
+ }, 5_000);
1523
+ swTeardownIdentity = identity;
1524
+ swTeardownAckResolver = (error) => {
1525
+ if (settled) return;
1526
+ settled = true;
1527
+ timers.clearTimeout(timeout);
1528
+ swTeardownAckResolver = undefined;
1529
+ swTeardownIdentity = undefined;
1530
+ if (error) reject(new Error(`[pgxsinkit] SW-direct host teardown failed: ${error.message}`));
1531
+ else resolve();
1532
+ };
1533
+ controlPort.postMessage(wrapControlEnvelope({ type: "engine-teardown", identity }));
1534
+ });
1535
+ };
1536
+
1537
+ /**
1538
+ * Construct the tab's election coordinator over the SW control port. The spawn adapter creates the announce
1539
+ * control channel and delivers its ENGINE end (`port2`) to the freshly-spawned worker (fixing step-8's
1540
+ * "port2 went nowhere"); `createControlChannel` then returns the SAME channel so the coordinator's `announce`
1541
+ * transfers the ROUTER end (`port1`) to the SharedWorker. `navigator.locks` is read structurally (injectable
1542
+ * for tests); the page-lifecycle subscription is the real `pagehide`/`pageshow` (also injectable).
1543
+ */
1544
+ function buildElectionCoordinator(): ElectionCoordinator {
1545
+ return buildElectedCoordinator({
1546
+ storePath: resolveDestroyStorePath(),
1547
+ controlPort,
1548
+ createEngineWorker: electedEngineFactory!,
1549
+ ...(workerFactory ? { swFactory: workerFactory } : {}),
1550
+ ...(options.storage ? { storage: options.storage } : {}),
1551
+ ...(options.electionIo ? { electionIo: options.electionIo } : {}),
1552
+ ...(options.awaitOwnershipRelease ? { awaitOwnershipRelease: options.awaitOwnershipRelease } : {}),
1553
+ timers,
1554
+ ...(pageLifecycle ? { pageLifecycle } : {}),
1555
+ ...(options.keepaliveIntervalMs != null ? { keepaliveIntervalMs: options.keepaliveIntervalMs } : {}),
1556
+ ...(options.keepaliveMissThreshold != null ? { keepaliveMissThreshold: options.keepaliveMissThreshold } : {}),
1557
+ });
1558
+ }
1559
+
1560
+ /** Ask the SharedWorker how many tabs are attached (this one included) — the destroy peer-refusal gate. */
1561
+ const queryDestroyPeers = (): Promise<number> =>
1562
+ new Promise<number>((resolve, reject) => {
1563
+ const timeout = timers.setTimeout(() => {
1564
+ destroyVerdictResolver = undefined;
1565
+ reject(new Error("[pgxsinkit] destroy() timed out waiting for the SharedWorker peer-count verdict."));
1566
+ }, options.handoffQueue?.deadlineMs ?? 15000);
1567
+ destroyVerdictResolver = (peers) => {
1568
+ timers.clearTimeout(timeout);
1569
+ destroyVerdictResolver = undefined;
1570
+ resolve(peers);
1571
+ };
1572
+ controlPort.postMessage({ [DESTROY_QUERY_KEY]: true });
1573
+ });
1574
+
1575
+ // ─── ADR-0049 D5: execution-limit OVERDUE-DISPATCH reporting (tab side) ────────────────────────────
1576
+ // When `executionLimit.maxDispatchMs` is set and this tab holds a per-tab pipe (elected engine), a dispatched
1577
+ // RPC still pending past the limit is reported ONCE to the router as an identity-tagged `overdue-dispatch`. The
1578
+ // router then probes the engine control channel; a WASM-blocked engine cannot answer on its event loop, so the
1579
+ // router (past its probe threshold) fans `engine-retiring` and the leader terminates + respawns it. The router
1580
+ // NEVER treats slow-below-threshold as death (a long query under the limit runs to completion). Per-id timers,
1581
+ // cleared on settlement; reported on the CONTROL port (where the router listens), stamped with the current
1582
+ // engine identity so the router discards a stale report. SW-direct has no pipe/identity, so it never arms.
1583
+ const overdueMs = options.executionLimit?.maxDispatchMs;
1584
+ const overdueTimers = new Map<string, unknown>();
1585
+ const clearOverdue = (id: string): void => {
1586
+ const handle = overdueTimers.get(id);
1587
+ if (handle !== undefined) {
1588
+ timers.clearTimeout(handle);
1589
+ overdueTimers.delete(id);
1590
+ }
1591
+ };
1592
+ const clearAllOverdue = (): void => {
1593
+ for (const handle of overdueTimers.values()) timers.clearTimeout(handle);
1594
+ overdueTimers.clear();
1595
+ };
1596
+ const armOverdue = (id: string): void => {
1597
+ if (overdueMs === undefined) return;
1598
+ overdueTimers.set(
1599
+ id,
1600
+ timers.setTimeout(() => {
1601
+ overdueTimers.delete(id);
1602
+ // Report only while the op is genuinely still outstanding on a live pipe (we know the engine identity).
1603
+ if (detached || !rpcPending.has(id) || currentEngineIdentity === undefined) return;
1604
+ controlPort.postMessage(
1605
+ wrapControlEnvelope({
1606
+ type: "overdue-dispatch",
1607
+ identity: currentEngineIdentity,
1608
+ elapsedMs: overdueMs,
1609
+ }),
1610
+ );
1611
+ }, overdueMs),
1612
+ );
1613
+ };
373
1614
 
374
1615
  // ─── RPC helper ──────────────────────────────────────────────────────────────────────────────────
375
1616
  const rpc = <T>(op: RpcOp, args: unknown[]): Promise<T> => {
376
1617
  // A detached client has no live port listener, so a worker reply could never resolve this — reject at
377
1618
  // once rather than register a forever-pending waiter (ADR-0040 P2).
378
1619
  if (detached) return Promise.reject(detachError());
379
- const id = newId("rpc");
1620
+ const kind: "read" | "mutation" = MUTATION_RPC_OPS.has(op) ? "mutation" : "read";
380
1621
  return new Promise<T>((resolve, reject) => {
381
- rpcPending.set(id, { resolve: resolve as (value: unknown) => void, reject });
382
- postBridgeMessage(port, codec, "rpc", { op, args }, id);
1622
+ const dispatch = () => {
1623
+ const id = newId("rpc");
1624
+ rpcPending.set(id, { resolve: resolve as (value: unknown) => void, reject, kind });
1625
+ postBridgeMessage(currentDataPort(), codec, "rpc", { op, args }, id);
1626
+ armSilence();
1627
+ armOverdue(id);
1628
+ };
1629
+ // While the handoff window is open, QUEUE rather than post (invariant 9); otherwise dispatch immediately.
1630
+ if (windowOpen) enqueue(dispatch, reject);
1631
+ else dispatch();
383
1632
  });
384
1633
  };
385
1634
 
386
1635
  // ─── Attach handshake ────────────────────────────────────────────────────────────────────────────
387
- let attachAckResolve: ((ack: AttachAckPayload) => void) | null = null;
388
- let attachAckReject: ((error: Error) => void) | null = null;
389
- const attachAck = new Promise<AttachAckPayload>((resolve, reject) => {
390
- attachAckResolve = resolve;
391
- attachAckReject = reject;
392
- });
1636
+ // Re-entrant (ADR-0049): the SAME handshake runs for the FIRST attach and for every re-attach (pipe swap,
1637
+ // reconnect). `pendingAttachAck` holds whichever handshake is currently awaiting its `attach-ack`; the bridge
1638
+ // listener settles it. `runAttachHandshake` posts `attach` over a target port and awaits the ack.
1639
+ let pendingAttachAck: { resolve: (ack: AttachAckPayload) => void; reject: (error: Error) => void } | null = null;
1640
+ const runAttachHandshake = (target: BridgePort, includeRestore: boolean): Promise<AttachAckPayload> =>
1641
+ new Promise<AttachAckPayload>((resolve, reject) => {
1642
+ // The restore artifact rides at most ONE handshake ever (`restoreConsumed`): posting transfers (detaches)
1643
+ // its ArrayBuffer, so any later handshake would carry an empty husk. The caller chooses the target that
1644
+ // actually reaches the engine home; this guard makes a second carry structurally impossible.
1645
+ const carryRestore = includeRestore && restoreWire !== undefined && !restoreConsumed;
1646
+ if (carryRestore) restoreConsumed = true;
1647
+ pendingAttachAck = { resolve, reject };
1648
+ postBridgeMessage(
1649
+ target,
1650
+ codec,
1651
+ "attach",
1652
+ buildAttachPayload(carryRestore),
1653
+ undefined,
1654
+ carryRestore && restoreWire ? [restoreWire.buffer] : undefined,
1655
+ );
1656
+ });
393
1657
 
394
1658
  // ADR-0041 stage 2 — staged boot readiness on the worker-attached client. The `attach-ack` fires AT the
395
1659
  // engine's `localReadReady` (the Option B contract), so this client resolves `attachSyncClient` there and
@@ -460,17 +1724,26 @@ export async function attachSyncClient<const TRegistry extends SyncTableRegistry
460
1724
  if (detached) return;
461
1725
  detached = true;
462
1726
  status.isRunning = false;
463
- // Detach THIS tab; the worker engine keeps running for other tabs (ADR-0032 decision 2).
464
- for (const queryId of diffHandlers.keys()) postBridgeMessage(port, codec, "unsubscribe", { queryId });
1727
+ // Detach THIS tab; the worker engine keeps running for other tabs (ADR-0032 decision 2). Sent on the
1728
+ // CURRENT data port (ADR-0049: the pipe once swapped, else the control port).
1729
+ for (const queryId of diffHandlers.keys()) postBridgeMessage(currentDataPort(), codec, "unsubscribe", { queryId });
465
1730
  diffHandlers.clear();
466
- postBridgeMessage(port, codec, "detach", null);
1731
+ activeSubscriptions.clear();
1732
+ postBridgeMessage(currentDataPort(), codec, "detach", null);
1733
+ // ADR-0049 D8: tell the SharedWorker ROUTER this tab is gone, on the CONTROL port — the `detach` above rode
1734
+ // the per-tab PIPE, which the router never sees, so its `tabCount` (the destroy peer-refusal input) would
1735
+ // otherwise never fall. A `pgx0049` control envelope (the router stays payload-blind); harmless on a
1736
+ // non-placement transport (ignored) and when the control port IS the data port (SW-direct).
1737
+ controlPort.postMessage(wrapControlEnvelope({ type: "tab-detach" }));
467
1738
  // Settle every tab-side promise now the port listener is about to go (ADR-0040 P2) — otherwise an
468
1739
  // operation still awaiting a worker reply hangs forever. RPCs and initial subscribes promise DATA, so
469
1740
  // REJECT them (fabricating a value is worse than a clear failure); hydration and group-ready waiters are
470
1741
  // DONENESS signals, so RESOLVE them (their awaiters are void-chained hook code that should settle, not
471
1742
  // throw). The attach-ack is rejected too so a detach DURING boot rejects `attachSyncClient` (a no-op once
472
1743
  // it has already settled).
473
- attachAckReject?.(detachError());
1744
+ const settleAttachAck = pendingAttachAck;
1745
+ pendingAttachAck = null;
1746
+ settleAttachAck?.reject(detachError());
474
1747
  // ADR-0041 (FIX A): reject EVERY still-pending readiness STAGE with ONE typed `ClientDisposedError`, so
475
1748
  // `instanceof ClientDisposedError` behaves identically in worker and in-process mode (the class doc + the
476
1749
  // in-process client already promise the typed error on disposal). `detachError()` stays for RPC/subscription
@@ -478,6 +1751,10 @@ export async function attachSyncClient<const TRegistry extends SyncTableRegistry
478
1751
  // `localReadReady` is left as-is: pre-ack it never resolved (the attach itself rejected); post-ack it already
479
1752
  // resolved. The `milestone-error` path is untouched — that is a genuine engine failure, not disposal.
480
1753
  const disposedError = new ClientDisposedError();
1754
+ // ADR-0049: a detach BEFORE the first attach ack settles fails `attachSyncClient` (a detach-during-boot rejects
1755
+ // the attach rather than leaving it pending) — with the SAME "client detached" error the pre-firstAttachReady
1756
+ // handshake rejection used, preserving the ADR-0040 P2 contract (idempotent once the attach already resolved).
1757
+ failFirstAttach(detachError());
481
1758
  failWriteReady(disposedError);
482
1759
  failBootSettled(disposedError);
483
1760
  // The attached `ready` had NO reject path — a detach BEFORE initial sync would otherwise leave
@@ -488,20 +1765,41 @@ export async function attachSyncClient<const TRegistry extends SyncTableRegistry
488
1765
  }
489
1766
  for (const pending of rpcPending.values()) pending.reject(detachError());
490
1767
  rpcPending.clear();
1768
+ clearAllOverdue();
491
1769
  for (const pending of initialPending.values()) pending.reject(detachError());
492
1770
  initialPending.clear();
493
1771
  for (const resolve of hydratedPending.values()) resolve();
494
1772
  hydratedPending.clear();
495
1773
  for (const waiters of groupWaiters.values()) for (const resolve of waiters) resolve();
496
1774
  groupWaiters.clear();
1775
+ // ADR-0049: queued handoff ops settle with the detach error (rule 5), and the placement timers are cleared.
1776
+ const queued = handoffQueue.splice(0);
1777
+ for (const item of queued) item.reject(detachError());
1778
+ clearQueueDeadline();
1779
+ // ADR-0049 step 10b: release this tab's leader-lock claim (invariant 2 — one claim per attachment, released
1780
+ // on detach). Idempotent; a no-op when this tab never elected (SW-direct / no factory).
1781
+ releaseElectionClaim?.();
1782
+ releaseElectionClaim = undefined;
1783
+ // Release this tab's ref on an ADOPTED shared coordinator (ref-counted registry cleanup); no-op otherwise.
1784
+ if (adoptedSharedCoordinatorStore !== undefined) {
1785
+ releaseSharedCoordinator(adoptedSharedCoordinatorStore);
1786
+ adoptedSharedCoordinatorStore = undefined;
1787
+ }
1788
+ if (silenceHandle !== undefined) {
1789
+ timers.clearTimeout(silenceHandle);
1790
+ silenceHandle = undefined;
1791
+ }
497
1792
  if (pagehideListener) pageWindow?.removeEventListener("pagehide", pagehideListener);
498
- port.removeEventListener("message", listener);
499
- port.close?.();
1793
+ // Tear down BOTH listeners: the bridge listener on the data port, the control listener on the control port.
1794
+ dataPort.removeEventListener("message", listener);
1795
+ controlPort.removeEventListener("message", controlListener);
1796
+ dataPort.close?.();
1797
+ if (controlPort !== dataPort) controlPort.close?.();
500
1798
  };
501
1799
  // Structural window guard — this file compiles without the DOM lib (it also runs under tests/workers).
502
1800
  interface PageLifecycleWindowLike {
503
- addEventListener(type: "pagehide", handler: (event: { persisted: boolean }) => void): void;
504
- removeEventListener(type: "pagehide", handler: (event: { persisted: boolean }) => void): void;
1801
+ addEventListener(type: "pagehide" | "pageshow", handler: (event: { persisted: boolean }) => void): void;
1802
+ removeEventListener(type: "pagehide" | "pageshow", handler: (event: { persisted: boolean }) => void): void;
505
1803
  }
506
1804
  const pageWindow = (globalThis as { window?: PageLifecycleWindowLike }).window;
507
1805
  const pagehideListener = pageWindow
@@ -510,6 +1808,17 @@ export async function attachSyncClient<const TRegistry extends SyncTableRegistry
510
1808
  }
511
1809
  : undefined;
512
1810
  if (pagehideListener) pageWindow?.addEventListener("pagehide", pagehideListener);
1811
+ // ADR-0049 step 10b: the real page-lifecycle subscription the election coordinator's BFCache hooks use
1812
+ // (`pagehide.persisted` → release authority + retire; `pageshow` → re-queue + re-attach). Structural window
1813
+ // check, exactly like the detach `pagehide` above; injectable (`electionIo.pageLifecycle`) for tests.
1814
+ const pageLifecycle: CoordinatorDeps["pageLifecycle"] =
1815
+ options.electionIo?.pageLifecycle ??
1816
+ (pageWindow
1817
+ ? {
1818
+ onPageHide: (listener) => pageWindow.addEventListener("pagehide", (event) => listener(event.persisted)),
1819
+ onPageShow: (listener) => pageWindow.addEventListener("pageshow", () => listener()),
1820
+ }
1821
+ : undefined);
513
1822
 
514
1823
  const initialToken = options.getToken ? await options.getToken() : null;
515
1824
  // The testing memory-backend override travels as an explicit wire field, not the symbol marker — a symbol
@@ -525,30 +1834,78 @@ export async function attachSyncClient<const TRegistry extends SyncTableRegistry
525
1834
  mimeType: options.restoreFrom.type || "application/octet-stream",
526
1835
  }
527
1836
  : undefined;
528
- const attachPayload: AttachPayload = {
529
- token: initialToken,
530
- ...(options.storeId ? { storeId: options.storeId } : {}),
531
- ...(options.storePath ? { storePath: options.storePath } : {}),
532
- ...(memoryOverride ? { testStoreBackend: "memory" as const } : {}),
533
- ...(restoreWire ? { restore: restoreWire } : {}),
534
- ...(options.syncEnabled != null || options.role != null || options.freshStore != null
535
- ? {
536
- config: {
537
- ...(options.syncEnabled != null ? { syncEnabled: options.syncEnabled } : {}),
538
- ...(options.role != null ? { role: options.role } : {}),
539
- ...(options.freshStore != null ? { freshStore: options.freshStore } : {}),
540
- },
541
- }
542
- : {}),
543
- };
544
- postBridgeMessage(port, codec, "attach", attachPayload, undefined, restoreWire ? [restoreWire.buffer] : undefined);
1837
+ // The attach payload builder — reused by the FIRST attach and every re-attach (pipe swap / reconnect). Restore
1838
+ // rides ONLY the one handshake that reaches the engine home (SW port in SW-direct, first pipe attach when
1839
+ // elected — see the send sites); `runAttachHandshake`'s `restoreConsumed` guard makes any later carry
1840
+ // structurally impossible (the buffer is transferred/detached, and you cannot restore into a running store).
1841
+ function buildAttachPayload(includeRestore: boolean): AttachPayload {
1842
+ return {
1843
+ token: initialToken,
1844
+ ...(options.storeId ? { storeId: options.storeId } : {}),
1845
+ ...(options.storePath ? { storePath: options.storePath } : {}),
1846
+ // ADR-0050: the wire storage declaration also rides the attach payload, so the ENGINE binds it
1847
+ // (durability included) wherever it runs — the pre-placement declaration message only steers placement.
1848
+ ...(options.storage ? { storage: options.storage } : {}),
1849
+ ...(memoryOverride ? { testStoreBackend: "memory" as const } : {}),
1850
+ ...(options.executionLimit ? { executionLimit: options.executionLimit } : {}),
1851
+ ...(includeRestore && restoreWire ? { restore: restoreWire } : {}),
1852
+ ...(options.syncEnabled != null || options.role != null || options.freshStore != null
1853
+ ? {
1854
+ config: {
1855
+ ...(options.syncEnabled != null ? { syncEnabled: options.syncEnabled } : {}),
1856
+ ...(options.role != null ? { role: options.role } : {}),
1857
+ ...(options.freshStore != null ? { freshStore: options.freshStore } : {}),
1858
+ },
1859
+ }
1860
+ : {}),
1861
+ };
1862
+ }
1863
+ // ─── ADR-0050 declaration-FIRST, then placement-query, then handshake ─────────────────────────────
1864
+ // Post the storage DECLARATION MESSAGE first — always, even empty (`{}` = "no opinion") — because a
1865
+ // registry-silent worker DEFERS its placement decision until the first declaration arrives (`backend:
1866
+ // "idbfs"` must skip the probe, so the declaration must precede the decision). Then the placement query
1867
+ // (ADR-0049): a router-only SharedWorker (elected-worker home) is payload-blind and DROPS the bridge
1868
+ // `attach`, so an SW-port ack could never gate the flow — but the bootstrap meta listener answers the
1869
+ // placement query in BOTH SW modes, so this reliably drives election. In SW-direct / declared-idbfs (and
1870
+ // the no-placement / plain-port case) the reply is `electionRequired: false` (or absent) and the SW-port
1871
+ // attach below acks normally — a plain in-scope host attach.
1872
+ controlPort.postMessage({ [DECLARATION_KEY]: options.storage ?? {} });
1873
+ controlPort.postMessage({ [PLACEMENT_QUERY_KEY]: true });
1874
+ // EVERY boot awaits the placement reply before the first handshake (ADR-0050). The worker only installs the
1875
+ // engine listener on this port once placement resolves and the port's declaration is accepted, so an attach
1876
+ // posted earlier would be refused as a protocol violation — and the reply's slot is also where a storage
1877
+ // DECLARATION REFUSAL arrives (typed boot failure instead of a reply). This costs no real latency: the old
1878
+ // fire-and-forget attach queued browser-side behind the very same placement decision. Restore-bearing boots
1879
+ // additionally depend on this ordering for artifact routing: the restore's ArrayBuffer detaches on first
1880
+ // post, and in elected mode the router-only SharedWorker silently DROPS bridge `attach` envelopes — so the
1881
+ // restore is carried on the SW-port handshake only when the in-scope host IS the engine (SW-direct /
1882
+ // declared-idbfs), and on the first per-tab PIPE handshake (`onConnectPort`) when the engine is elected.
545
1883
  try {
546
- await attachAck;
1884
+ await placementKnown;
547
1885
  } catch (error) {
548
- // The worker's engine boot failed (ADR-0032 FIX 1) OR a terminal pagehide rejected the ack mid-boot
549
- // (ADR-0040 P2): run the full detach so BOTH the message listener AND the pagehide listener are removed
550
- // (no port/window handler leaks), then let the error propagate out of `attachSyncClient`. Idempotent, so
551
- // a pagehide that already detached makes this a cheap no-op.
1886
+ // A typed declaration refusal (never a plain transport error): run the full detach so both listeners and
1887
+ // the pagehide handler are removed, then propagate — the boot fails loudly with the refusal.
1888
+ detachFromWorker();
1889
+ throw error;
1890
+ }
1891
+ // Send the tab's attach handshake — placement is KNOWN here (awaited above). SW-direct / plain / no-reply:
1892
+ // the current data port reaches the in-scope engine, which acks it (restore included). Elected
1893
+ // (`electionRequired`): the engine-reaching handshake is the per-tab PIPE one (`onConnectPort`, or the
1894
+ // adoption handover of a stashed provision pipe); the SW-port post below is the router-dropped
1895
+ // fire-and-forget (payload-blind — never taught to answer bridge envelopes), kept so `firstAttachReady` can
1896
+ // settle off whichever port answers first. The ONE case that must not post is elected mode with the data
1897
+ // path ALREADY swapped onto an adopted pipe — there the post would reach the live engine as a DUPLICATE
1898
+ // attach (a second boot) instead of being dropped.
1899
+ const handshakePort = currentDataPort();
1900
+ if (placementResult?.electionRequired !== true || handshakePort === controlPort) {
1901
+ void runAttachHandshake(handshakePort, placementResult?.electionRequired !== true).catch(() => undefined);
1902
+ }
1903
+ try {
1904
+ await firstAttachReady;
1905
+ } catch (error) {
1906
+ // The engine boot failed (ADR-0032 FIX 1), a terminal pagehide rejected the ack mid-boot (ADR-0040 P2), or a
1907
+ // degraded election never delivered a pipe: run the full detach so BOTH listeners AND the pagehide handler are
1908
+ // removed (no leaks), then propagate. Idempotent — a pagehide that already detached makes this a cheap no-op.
552
1909
  detachFromWorker();
553
1910
  throw error;
554
1911
  }
@@ -563,31 +1920,36 @@ export async function attachSyncClient<const TRegistry extends SyncTableRegistry
563
1920
  // than register a forever-pending initial waiter (ADR-0040 P2).
564
1921
  if (detached) throw detachError();
565
1922
  const queryId = newId("live");
566
- const id = newId("sub");
567
1923
  const materializer = new LiveRowsMaterializer<TRow>(input.pkColumns);
568
1924
  diffHandlers.set(queryId, (diff) => {
569
1925
  onRows(materializer.apply(diff));
570
1926
  });
1927
+ // The subscribe payload — reused by the initial subscribe AND by the ADR-0049 re-subscribe on a pipe swap.
1928
+ const subscribePayload = {
1929
+ queryId,
1930
+ sql: input.sql,
1931
+ params: [...input.params],
1932
+ ...(input.fields ? { fields: [...input.fields] } : {}),
1933
+ ...(input.pkColumns ? { pkColumns: [...input.pkColumns] } : {}),
1934
+ ...(input.use ? { use: [...input.use] } : {}),
1935
+ // Per-subscription keep-alive hint (ADR-0040 decision 4) forwarded to the worker's manager.
1936
+ ...(input.keepAliveMs != null ? { keepAliveMs: input.keepAliveMs } : {}),
1937
+ };
571
1938
  let initial: LiveInitialPayload;
572
1939
  try {
573
1940
  initial = await new Promise<LiveInitialPayload>((resolve, reject) => {
1941
+ const id = newId("sub");
574
1942
  initialPending.set(id, { resolve, reject });
575
- postBridgeMessage(
576
- port,
577
- codec,
578
- "subscribe",
579
- {
580
- queryId,
581
- sql: input.sql,
582
- params: [...input.params],
583
- ...(input.fields ? { fields: [...input.fields] } : {}),
584
- ...(input.pkColumns ? { pkColumns: [...input.pkColumns] } : {}),
585
- ...(input.use ? { use: [...input.use] } : {}),
586
- // Per-subscription keep-alive hint (ADR-0040 decision 4) forwarded to the worker's manager.
587
- ...(input.keepAliveMs != null ? { keepAliveMs: input.keepAliveMs } : {}),
588
- },
589
- id,
590
- );
1943
+ // While the handoff window is open, QUEUE the subscribe (invariant 9); otherwise post at once.
1944
+ const dispatch = () => postBridgeMessage(currentDataPort(), codec, "subscribe", subscribePayload, id);
1945
+ if (windowOpen) {
1946
+ enqueue(dispatch, (error) => {
1947
+ initialPending.delete(id);
1948
+ reject(error);
1949
+ });
1950
+ } else {
1951
+ dispatch();
1952
+ }
591
1953
  });
592
1954
  } catch (error) {
593
1955
  // The worker rejected the subscribe (invalid SQL, etc.); the initial-payload waiter rejected via the
@@ -596,6 +1958,21 @@ export async function attachSyncClient<const TRegistry extends SyncTableRegistry
596
1958
  throw error;
597
1959
  }
598
1960
  const initialRows = materializer.seed(initial.rows as TRow[]);
1961
+ // Register the live query for ADR-0049 re-subscribe: on a pipe swap, re-issue the SAME subscribe (same
1962
+ // queryId → diffs still route to the same materializer/handler) and re-seed the materializer off the fresh
1963
+ // snapshot. This is the re-attach re-establishment of live queries (ADR-0041 staged readiness); its
1964
+ // multi-tab integration coverage is step 12. A rejected re-subscribe leaves the existing rows in place.
1965
+ const resubscribe = () => {
1966
+ const rid = newId("sub");
1967
+ initialPending.set(rid, {
1968
+ resolve: (fresh) => {
1969
+ onRows(materializer.seed(fresh.rows as TRow[]));
1970
+ },
1971
+ reject: () => undefined,
1972
+ });
1973
+ postBridgeMessage(currentDataPort(), codec, "subscribe", subscribePayload, rid);
1974
+ };
1975
+ activeSubscriptions.set(queryId, { resubscribe });
599
1976
  // Pending groups present → build the `hydrated` promise the worker settles via `live-hydrated` (posted
600
1977
  // after the catch-up rows on the same port — rows-before-signal). A missing/empty `hydratingTables`
601
1978
  // means every referenced group (eager OR lazy) was already ready (steady state) or sync is disabled:
@@ -611,9 +1988,10 @@ export async function attachSyncClient<const TRegistry extends SyncTableRegistry
611
1988
  initialRows,
612
1989
  unsubscribe: () => {
613
1990
  diffHandlers.delete(queryId);
1991
+ activeSubscriptions.delete(queryId);
614
1992
  hydratedPending.get(queryId)?.();
615
1993
  hydratedPending.delete(queryId);
616
- postBridgeMessage(port, codec, "unsubscribe", { queryId });
1994
+ postBridgeMessage(currentDataPort(), codec, "unsubscribe", { queryId });
617
1995
  },
618
1996
  // The lazy relations the worker's guard activated for this query (observability). `hydrated` — driven
619
1997
  // by `hydratingTables`, not this — resolves once every pending group's caught-up rows are delivered.
@@ -709,10 +2087,56 @@ export async function attachSyncClient<const TRegistry extends SyncTableRegistry
709
2087
  start: async () => {
710
2088
  await ready;
711
2089
  },
2090
+ // The tab facade holds no local engine — its "activity" is the worker bridge. Synchronously detaching it
2091
+ // (idempotent, no await) IS the tab-side halt: it stops posting/subscribing on the pipe and settles every
2092
+ // pending promise, the analogue of aborting the in-process engine's streams. `stop()` does the same.
2093
+ haltActivity: () => {
2094
+ detachFromWorker();
2095
+ },
712
2096
  stop: async () => {
713
2097
  detachFromWorker();
714
2098
  },
715
- destroy: notSupported("client.destroy"),
2099
+ // ADR-0049 step 10b — SUPERVISED destroy from the attached facade. The SUPERVISOR is the TAB context, which
2100
+ // survives engine shutdown BY CONSTRUCTION: it detaches the engine, then runs the destructive lifecycle
2101
+ // itself (the tab has full OPFS/IndexedDB access). Ordering, per the plan's D8 fault rows:
2102
+ // 1. PEER REFUSAL FIRST — the SharedWorker alone knows the attached-tab count; more than one tab attached
2103
+ // (this one + a peer) → `StoreDestroyRefusedError` (close peers first). Runs BEFORE detach + any effect.
2104
+ // 2. REFUSE-IF-OWED (unless `force`) — a cheap journal read via the `diagnostics` RPC while still attached
2105
+ // (one round-trip; the honest minimum — the tab has no local journal). `force` skips it.
2106
+ // 3. DETACH, then run the destruction (set `deleting` → delete sentinel → delete backend store → delete
2107
+ // meta record) with a bounded ownership-lock-lag retry on the backend delete (the just-detached engine's
2108
+ // VFS ownership lock may lag). The initiating call resolves from the tab supervisor (invariant 13).
2109
+ destroy: async (destroyOptions) => {
2110
+ if (detached) throw detachError();
2111
+ const peers = await queryDestroyPeers();
2112
+ if (peers > 1) throw new StoreDestroyRefusedError(peers);
2113
+ if (!destroyOptions?.force) {
2114
+ const { mutation } = await client.diagnostics();
2115
+ const owed =
2116
+ mutation.pendingCount +
2117
+ mutation.sendingCount +
2118
+ mutation.failedCount +
2119
+ mutation.quarantinedCount +
2120
+ mutation.conflictedCount;
2121
+ if (owed > 0) {
2122
+ throw new Error(
2123
+ `destroy() refused: ${owed} mutation(s) still owed to the server. Flush them first or call destroy({ force: true }).`,
2124
+ );
2125
+ }
2126
+ }
2127
+ const storePath = resolveDestroyStorePath();
2128
+ // ADR-0049 D8 ordering (elected placement): RETIRE this tab's own elected engine and AWAIT its teardown —
2129
+ // the point its EXCLUSIVE OPFS sync-access handle is provably released — BEFORE deleting. The engine is a
2130
+ // dedicated Worker torn down ASYNCHRONOUSLY via the coordinator's retirement handshake; without this
2131
+ // barrier `deleteBackendStore` raced that release and failed `NoModificationAllowedError`. Run it while the
2132
+ // control channel is still up (before detach closes the SW port). A no-op when this tab holds no engine.
2133
+ if (electionCoordinator !== undefined) await electionCoordinator.retireEngine();
2134
+ else await awaitSharedHostTeardown();
2135
+ // Detach the engine FIRST — the supervisor is this tab, which outlives the engine. Idempotent.
2136
+ detachFromWorker();
2137
+ const effects = options.createDestructionEffects?.(storePath) ?? createStoreDestructionEffects(storePath);
2138
+ await runStoreDestruction(effects);
2139
+ },
716
2140
  dropReadCache: notSupported("client.dropReadCache"),
717
2141
  flush: (table) => rpc<void>("flush", [table]),
718
2142
  reconcile: (table) => rpc<void>("reconcile", [table]),
@@ -887,7 +2311,7 @@ export async function attachSyncClient<const TRegistry extends SyncTableRegistry
887
2311
  void pushToken();
888
2312
  },
889
2313
  setOnline: (online: boolean) => {
890
- postBridgeMessage(port, codec, "set-online", { online });
2314
+ postBridgeMessage(currentDataPort(), codec, "set-online", { online });
891
2315
  },
892
2316
  };
893
2317
 
@@ -906,44 +2330,222 @@ export async function attachSyncClient<const TRegistry extends SyncTableRegistry
906
2330
  return client;
907
2331
  }
908
2332
 
2333
+ /** {@link provisionSyncWorker} options — attach's transport/store/factory seams, plus the provision expiry. */
2334
+ export type ProvisionSyncWorkerOptions<TRegistry extends SyncTableRegistry> = Pick<
2335
+ AttachSyncClientOptions<TRegistry>,
2336
+ | "worker"
2337
+ | "port"
2338
+ | "storeId"
2339
+ | "storePath"
2340
+ | "storage"
2341
+ | "codec"
2342
+ | "createEngineWorker"
2343
+ | "electionIo"
2344
+ | "awaitOwnershipRelease"
2345
+ | "timers"
2346
+ > & {
2347
+ /**
2348
+ * How long (ms) the elected-mode provision claim (and its shared-coordinator ref) is held before an abandoned
2349
+ * warmed provision auto-retires (ADR-0049 step 8, "abandoned warmed provision → claim expiry"). Default 60000.
2350
+ * A later {@link attachSyncClient} on the same store ADOPTS the grant within this window (adding its own claim,
2351
+ * so the engine outlives the expiry). Inert on SW-direct.
2352
+ */
2353
+ provisionExpiryMs?: number;
2354
+ };
2355
+
909
2356
  /**
910
- * Pre-spawn a worker's store WITHOUT attaching (ADR-0032 decision 5). Sent at the board's login screen
911
- * against a freshly-named spare `SharedWorker`: the worker runs PGlite `create`/initdb only and holds the
912
- * raw store idle until the real {@link attachSyncClient} claim adopts it. Resolves when the worker acks the
913
- * provision (its initdb settled); rejects only if the worker reports the create failed — the caller treats
914
- * either outcome as best-effort, since attach falls back to a fresh create regardless.
2357
+ * Pre-spawn a worker's store WITHOUT attaching (ADR-0032 decision 5). Sent at the board's login screen against a
2358
+ * freshly-named spare `SharedWorker`: the worker runs PGlite `create`/initdb only and holds the raw store idle
2359
+ * until the real {@link attachSyncClient} claim adopts it. Resolves when the worker acks the provision (its initdb
2360
+ * settled); rejects only if the worker reports the create failed — the caller treats either outcome as best-effort,
2361
+ * since attach falls back to a fresh create regardless.
2362
+ *
2363
+ * Routed through the SAME placement-query-first flow as {@link attachSyncClient} (ADR-0049 step 8): a SW-direct
2364
+ * (or declared-idbfs) SharedWorker takes the `provision` bridge envelope on the SW port; a
2365
+ * router-only (`electionRequired`) SharedWorker DROPS bridge envelopes, so provision drives the election
2366
+ * coordinator's PROVISION CLAIM (expiry-bounded) and delivers the `provision` over the elected engine's per-tab
2367
+ * PIPE. The coordinator is REGISTERED per store so a later attach on the same tab ADOPTS the grant — no second
2368
+ * lock, no second engine, no double initdb (invariant 2). Elected mode REQUIRES a {@link createEngineWorker}
2369
+ * factory (mirroring attach); its absence is a clear rejection, never a hang.
915
2370
  */
916
- export function provisionSyncWorker<TRegistry extends SyncTableRegistry>(
917
- options: Pick<AttachSyncClientOptions<TRegistry>, "worker" | "port" | "storeId" | "storePath" | "codec">,
2371
+ export function provisionSyncWorker<const TRegistry extends SyncTableRegistry>(
2372
+ options: ProvisionSyncWorkerOptions<TRegistry>,
918
2373
  ): Promise<void> {
919
2374
  const codec = options.codec ?? identityCodec;
920
2375
  const port = resolvePort(options);
921
- // The testing memory-backend override travels as an explicit wire field (a symbol does not survive
922
- // structured clone, ADR-0036) — read it off the spread helper's options and forward it to the worker.
2376
+ const timers: AttachClientTimers = options.timers ?? {
2377
+ setTimeout: (fn, ms) => globalThis.setTimeout(fn, ms),
2378
+ clearTimeout: (handle) => globalThis.clearTimeout(handle as ReturnType<typeof globalThis.setTimeout>),
2379
+ };
2380
+ const storePath = options.storePath ?? options.storeId ?? "pgxsinkit-overlay-v1";
2381
+ // The testing memory-backend override travels as an explicit wire field (a symbol does not survive structured
2382
+ // clone, ADR-0036) — read it off the spread helper's options and forward it to the worker.
923
2383
  const memoryOverride = readTestStoreMarker(options) === "memory";
924
- return new Promise<void>((resolve, reject) => {
925
- const listener = (message: { data: unknown }) => {
926
- if (!isBridgeEnvelope(message.data)) return;
927
- if (message.data.type !== "provision-ack") return;
928
- port.removeEventListener("message", listener);
929
- const ack = codec.decode(message.data.payload) as ProvisionAckPayload;
930
- if (ack.ok) resolve();
931
- else reject(new Error(ack.error?.message ?? "worker provision failed"));
2384
+ const provisionPayload = {
2385
+ ...(options.storeId ? { storeId: options.storeId } : {}),
2386
+ ...(options.storePath ? { storePath: options.storePath } : {}),
2387
+ // ADR-0050: the wire storage declaration rides the provision payload too, so the mint's durability comes
2388
+ // from the store's bound declaration wherever the engine runs.
2389
+ ...(options.storage ? { storage: options.storage } : {}),
2390
+ ...(memoryOverride ? { testStoreBackend: "memory" as const } : {}),
2391
+ };
2392
+ const pageLifecycle = readDefaultPageLifecycle();
2393
+
2394
+ const provision = new Promise<void>((resolve, reject) => {
2395
+ let settled = false;
2396
+ const ackRemovers: Array<() => void> = [];
2397
+ const controlListener = (event: { data: unknown; ports?: readonly BridgePort[] }): void => {
2398
+ const placement = readPlacementResult(event.data);
2399
+ if (placement !== undefined) {
2400
+ onPlacement(placement);
2401
+ return;
2402
+ }
2403
+ // ADR-0050: the worker refused this provision's storage declaration — it arrives in place of the
2404
+ // placement reply, so the provision fails typed and loudly (never a hang, never a silent mode).
2405
+ const declarationRefusal = readDeclarationRefusal(event.data);
2406
+ if (declarationRefusal !== undefined) {
2407
+ settle(() => reject(new StorageDeclarationRefusedError(declarationRefusal.message)));
2408
+ return;
2409
+ }
2410
+ const control = readControlEnvelope(event.data);
2411
+ if (control?.type === "connect-port") onProvisionPipe(event.ports?.[0], control.identity);
932
2412
  };
933
- port.addEventListener("message", listener);
2413
+ const settle = (fn: () => void): void => {
2414
+ if (settled) return;
2415
+ settled = true;
2416
+ port.removeEventListener("message", controlListener);
2417
+ for (const remove of ackRemovers) remove();
2418
+ fn();
2419
+ };
2420
+
2421
+ // Await `provision-ack` on whichever port carries it: the SW port (SW-direct) or the elected engine's pipe.
2422
+ // In elected mode the SW-port `provision` is dropped by the router, so its ack never comes — the pipe's does.
2423
+ const awaitAckOn = (ackPort: BridgePort): void => {
2424
+ const ackListener = (message: { data: unknown }): void => {
2425
+ if (!isBridgeEnvelope(message.data) || message.data.type !== "provision-ack") return;
2426
+ const ack = codec.decode(message.data.payload) as ProvisionAckPayload;
2427
+ settle(() => (ack.ok ? resolve() : reject(new Error(ack.error?.message ?? "worker provision failed"))));
2428
+ };
2429
+ ackPort.addEventListener("message", ackListener);
2430
+ ackPort.start?.();
2431
+ ackRemovers.push(() => ackPort.removeEventListener("message", ackListener));
2432
+ };
2433
+ const postProvisionOn = (target: BridgePort): void => {
2434
+ awaitAckOn(target);
2435
+ postBridgeMessage(target, codec, "provision", provisionPayload);
2436
+ };
2437
+
2438
+ let placementDecided = false;
2439
+ let piped = false;
2440
+ const onProvisionPipe = (pipe: BridgePort | undefined, identity: EngineIdentity): void => {
2441
+ if (piped || pipe === undefined) return;
2442
+ piped = true;
2443
+ // The router piped this provision connection to the elected engine — deliver the `provision` over the pipe,
2444
+ // and STASH the pipe on the shared coordinator entry: the router mints one pipe per SW connection, so when a
2445
+ // later attach adopts this grant on the SAME port (the board's ordered-messages contract) it must receive
2446
+ // THIS pipe by handover — no second `connect-port` will ever arrive for an already-piped tab.
2447
+ stashProvisionPipe(storePath, pipe, identity);
2448
+ postProvisionOn(pipe);
2449
+ };
2450
+
2451
+ const onPlacement = (result: PlacementQueryResult): void => {
2452
+ if (placementDecided) return;
2453
+ placementDecided = true;
2454
+ // SW-direct (or a plain host, which answers the placement query itself): the worker installs the engine
2455
+ // listener on this port only once placement resolves and the declaration is accepted (ADR-0050), so the
2456
+ // `provision` is posted NOW — on the reply — never fire-and-forget before it.
2457
+ if (!result.electionRequired) {
2458
+ postProvisionOn(port);
2459
+ return;
2460
+ }
2461
+ // Elected (router-only): the SW drops the `provision` bridge envelope, so ELECT and provision over the pipe.
2462
+ // Resolve the engine factory exactly as attach does — the `createEngineWorker` override, else the default
2463
+ // derived from the SharedWorker's reported script URL (dual-scope entry). Neither available → a WIRING failure.
2464
+ const engineFactory = options.createEngineWorker ?? deriveEngineWorkerFactory(result.swScriptUrl);
2465
+ if (engineFactory === undefined) {
2466
+ settle(() =>
2467
+ reject(
2468
+ new ElectedEngineUnconstructibleError(
2469
+ result.swScriptUrl === undefined
2470
+ ? "provisionSyncWorker: the SharedWorker reported no derivable script URL and no `createEngineWorker` override was supplied"
2471
+ : "provisionSyncWorker: no `Worker` constructor is available in this scope to derive the module engine and no override was supplied",
2472
+ ),
2473
+ ),
2474
+ );
2475
+ return;
2476
+ }
2477
+ const provisionSwFactory = workerFactoryOf(options.worker);
2478
+ const coordinator = adoptOrRegisterCoordinator(storePath, () =>
2479
+ buildElectedCoordinator({
2480
+ storePath,
2481
+ controlPort: port,
2482
+ createEngineWorker: engineFactory,
2483
+ ...(provisionSwFactory ? { swFactory: provisionSwFactory } : {}),
2484
+ ...(options.storage ? { storage: options.storage } : {}),
2485
+ ...(options.electionIo ? { electionIo: options.electionIo } : {}),
2486
+ ...(options.awaitOwnershipRelease ? { awaitOwnershipRelease: options.awaitOwnershipRelease } : {}),
2487
+ timers,
2488
+ ...(pageLifecycle ? { pageLifecycle } : {}),
2489
+ }),
2490
+ );
2491
+ // The PROVISION CLAIM elects → the coordinator spawns the engine + announces; the router pipes this
2492
+ // connection (→ `onProvisionPipe`). Bound by expiry: an abandoned warmed provision auto-retires (its claim
2493
+ // AND its shared-coordinator ref release together), so a store nobody adopts never pins the leader lock.
2494
+ const releaseProvisionClaim = coordinator.claimForProvision();
2495
+ const expiryMs = options.provisionExpiryMs ?? 60_000;
2496
+ let released = false;
2497
+ const expiryHandle = timers.setTimeout(() => {
2498
+ if (released) return;
2499
+ released = true;
2500
+ const entry = sharedCoordinators.get(storePath);
2501
+ if (entry?.releaseProvision === releaseProvision) delete entry.releaseProvision;
2502
+ releaseProvisionClaim();
2503
+ releaseSharedCoordinator(storePath);
2504
+ }, expiryMs);
2505
+ const releaseProvision = (): void => {
2506
+ if (released) return;
2507
+ released = true;
2508
+ timers.clearTimeout(expiryHandle);
2509
+ releaseProvisionClaim();
2510
+ };
2511
+ setProvisionRelease(storePath, releaseProvision);
2512
+ };
2513
+
2514
+ port.addEventListener("message", controlListener);
934
2515
  port.start?.();
935
- postBridgeMessage(port, codec, "provision", {
936
- ...(options.storeId ? { storeId: options.storeId } : {}),
937
- ...(options.storePath ? { storePath: options.storePath } : {}),
938
- ...(memoryOverride ? { testStoreBackend: "memory" as const } : {}),
939
- });
2516
+ // Declaration-FIRST, then placement query (ADR-0050, mirroring attach): the declaration message unblocks a
2517
+ // registry-silent worker's deferred placement decision, and the query is answered in BOTH SW modes by the
2518
+ // bootstrap meta listener. The `provision` itself is posted ON the placement reply (`onPlacement`): SW-direct
2519
+ // takes it on this port; a router-only SW would drop it, so elected mode delivers it over the pipe instead.
2520
+ port.postMessage({ [DECLARATION_KEY]: options.storage ?? {} });
2521
+ port.postMessage({ [PLACEMENT_QUERY_KEY]: true });
940
2522
  });
2523
+ return provision;
941
2524
  }
942
2525
 
943
- /** Resolve the transport port from the options: an explicit port, a SharedWorker's `.port`, or a Worker itself. */
944
- function resolvePort(options: { port?: BridgePort; worker?: WorkerLike }): BridgePort {
2526
+ /** Resolve the default page-lifecycle subscription off `globalThis.window` (structural, no DOM lib) — for the
2527
+ elected provision coordinator's BFCache hooks; `undefined` in a non-window scope. Mirrors the attach client. */
2528
+ function readDefaultPageLifecycle(): CoordinatorDeps["pageLifecycle"] {
2529
+ interface PageLifecycleWindowLike {
2530
+ addEventListener(type: "pagehide" | "pageshow", handler: (event: { persisted: boolean }) => void): void;
2531
+ }
2532
+ const pageWindow = (globalThis as { window?: PageLifecycleWindowLike }).window;
2533
+ if (!pageWindow) return undefined;
2534
+ return {
2535
+ onPageHide: (listener) => pageWindow.addEventListener("pagehide", (event) => listener(event.persisted)),
2536
+ onPageShow: (listener) => pageWindow.addEventListener("pageshow", () => listener()),
2537
+ };
2538
+ }
2539
+
2540
+ /**
2541
+ * Resolve the transport port from the options: an explicit port, or a worker input (ADR-0049 D5) that is EITHER a
2542
+ * FACTORY `() => WorkerLike` (invoked here for a fresh instance — the reconnect/reconstruct callers pass the factory
2543
+ * so each call yields a new SharedWorker) OR a bare instance. From the instance: a SharedWorker's `.port`, or a
2544
+ * Worker itself (which IS the port).
2545
+ */
2546
+ function resolvePort(options: { port?: BridgePort; worker?: (() => WorkerLike) | WorkerLike }): BridgePort {
945
2547
  if (options.port) return options.port;
946
- const worker = options.worker;
2548
+ const worker = typeof options.worker === "function" ? (options.worker as () => WorkerLike)() : options.worker;
947
2549
  if (!worker) throw new Error("attachSyncClient: provide a `worker` or a `port`.");
948
2550
  if (worker.port) return worker.port;
949
2551
  if (worker.postMessage && worker.addEventListener && worker.removeEventListener) {
@@ -952,11 +2554,60 @@ function resolvePort(options: { port?: BridgePort; worker?: WorkerLike }): Bridg
952
2554
  throw new Error("attachSyncClient: the provided `worker` is neither a Worker nor a SharedWorker port.");
953
2555
  }
954
2556
 
955
- /** Rebuild an Error from the bridge's serialized `{message, detail}` shape, carrying `detail` through. */
2557
+ /**
2558
+ * The SharedWorker reconstruction FACTORY, or `undefined` when the input is a bare instance/port (ADR-0049 D5). A
2559
+ * factory input (`worker: () => SharedWorker`) makes SharedWorker-death recovery a guarantee — the bridge-silence
2560
+ * reconnect and the keepalive reconstruction re-invoke it. A bare-instance input has none: reconstruction is
2561
+ * structurally unavailable (a SharedWorker cannot be rebuilt from itself), so those paths are simply not armed.
2562
+ */
2563
+ function workerFactoryOf(worker: (() => WorkerLike) | WorkerLike | undefined): (() => WorkerLike) | undefined {
2564
+ return typeof worker === "function" ? (worker as () => WorkerLike) : undefined;
2565
+ }
2566
+
2567
+ /**
2568
+ * Auto-derive the elected engine worker factory from the SharedWorker's reported script URL (ADR-0049 D5). The
2569
+ * worker entry is dual-scope, so `new Worker(swScriptUrl, { type: "module" })` boots the SAME entry as a dedicated
2570
+ * engine — no consumer wiring. Returns `undefined` when there is no derivable URL or no `Worker` constructor in
2571
+ * scope (a plain test scope); the caller then requires the `createEngineWorker` override or fails typed.
2572
+ */
2573
+ function deriveEngineWorkerFactory(swScriptUrl: string | undefined): (() => ElectedEngineWorker) | undefined {
2574
+ if (swScriptUrl === undefined) return undefined;
2575
+ const WorkerCtor = (globalThis as { Worker?: new (url: string, options?: { type?: "module" }) => WorkerLike }).Worker;
2576
+ if (WorkerCtor === undefined) return undefined;
2577
+ return () => wrapEngineWorker(new WorkerCtor(swScriptUrl, { type: "module" }));
2578
+ }
2579
+
2580
+ /**
2581
+ * Rebuild an Error from the bridge's serialized {@link BridgeErrorWire} shape, carrying `name` and `detail`
2582
+ * through. Restoring `name` is what keeps a typed worker-side failure (e.g. a restore refused with
2583
+ * `RestoreTargetExistsError`) detectable by the consumer without message matching.
2584
+ */
956
2585
  function rebuildError(error: RpcResultPayload["error"]): Error {
2586
+ if (error && "detail" in error) {
2587
+ const mismatch = executionLimitMismatchFromWire(error.detail);
2588
+ if (mismatch !== undefined) return mismatch;
2589
+ }
957
2590
  const rebuilt = new Error(error?.message ?? "worker rpc failed");
2591
+ if (error?.name !== undefined) {
2592
+ rebuilt.name = error.name;
2593
+ }
958
2594
  if (error && "detail" in error && error.detail !== undefined) {
959
2595
  (rebuilt as Error & { detail?: unknown }).detail = error.detail;
960
2596
  }
961
2597
  return rebuilt;
962
2598
  }
2599
+
2600
+ /**
2601
+ * Rebuild an RPC/subscribe error, reconstructing the typed {@link EngineRelocatedError} when the bridge error's
2602
+ * `detail` carries the clone-safe `{ code: "engine-relocated", outcome }` wire form (ADR-0049 D10). This is the
2603
+ * attach-side reconstruction seam: a relocation failure crossing the pipe as a bridge error surfaces to the
2604
+ * consumer as an `instanceof EngineRelocatedError` with the honest `outcome`. Any other detail rebuilds as a
2605
+ * plain error carrying its `detail` (unchanged behavior).
2606
+ */
2607
+ function rebuildRpcError(error: RpcResultPayload["error"]): Error {
2608
+ if (error && "detail" in error) {
2609
+ const relocated = engineRelocatedFromWire(error.detail);
2610
+ if (relocated !== undefined) return relocated;
2611
+ }
2612
+ return rebuildError(error);
2613
+ }