@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
@@ -9,12 +9,28 @@
9
9
 
10
10
  import { type ParserOptions, type QueryOptions, types } from "@electric-sql/pglite";
11
11
 
12
- import type { SyncRuntimeStatus, SyncTableName, SyncTableRegistry, WriteMode } from "@pgxsinkit/contracts";
12
+ import type {
13
+ ResolvedStorageDeclaration,
14
+ SyncRuntimeStatus,
15
+ SyncStorageDeclaration,
16
+ SyncTableName,
17
+ SyncTableRegistry,
18
+ WriteMode,
19
+ } from "@pgxsinkit/contracts";
20
+ import {
21
+ assertStorageDeclarationCompatible,
22
+ getSyncRegistryStorage,
23
+ isStorageBackend,
24
+ isStorageDurability,
25
+ resolveStorageDeclaration,
26
+ StorageDeclarationRefusedError,
27
+ } from "@pgxsinkit/contracts";
13
28
 
14
29
  import { type ConvergenceTrigger, createIntervalConvergenceTrigger } from "../convergence";
15
30
  import { setSyncDebugSink, syncDebug } from "../debug";
16
31
  import { describeErrorChain } from "../error-chain";
17
32
  import {
33
+ type AdoptionDeclaration,
18
34
  type ClientPGlite,
19
35
  createClientPGlite,
20
36
  type CreateSyncClientOptions,
@@ -28,7 +44,21 @@ import {
28
44
  } from "../index";
29
45
  import { wrapLiveQueryForMaterialization } from "../live-rows-sql";
30
46
  import type { LocalStoreVersionEvent } from "../local-store";
47
+ import { type PlacementProbeResult, probeOpfsSyncAccess } from "../placement-probe";
48
+ import { META_STORE_UNAVAILABLE, readStoreMetaRecord } from "../store-meta";
31
49
  import { readTestStoreMarker, TEST_STORE_BACKEND, type TestStoreMarker } from "../store-path";
50
+ import {
51
+ assertSameExecutionLimit,
52
+ type EngineControlMessage,
53
+ type EngineIdentity,
54
+ ExecutionLimitMismatchError,
55
+ executionLimitMismatchToWire,
56
+ type ExecutionLimitConfig,
57
+ readControlEnvelope,
58
+ shouldApplyControlMessage,
59
+ wrapControlEnvelope as controlEnvelope,
60
+ } from "./engine-control";
61
+ import { createEngineRouter, type EngineRouter, type RouterPort } from "./engine-router";
32
62
  import {
33
63
  createLiveQueryManager,
34
64
  type LiveQueryManager,
@@ -41,6 +71,7 @@ import {
41
71
  type BridgeCodec,
42
72
  type BridgeEnvelope,
43
73
  type BridgeEvent,
74
+ type BridgeErrorWire,
44
75
  type BridgePort,
45
76
  type ExportArtefactWire,
46
77
  type GuardedQueryWireArgs,
@@ -54,6 +85,7 @@ import {
54
85
  type SubscribePayload,
55
86
  type TokenResponsePayload,
56
87
  } from "./protocol";
88
+ import { decideSwPlacement, type SwPlacementResult } from "./sw-placement";
57
89
  import { createWorkerTokenCache } from "./token-cache";
58
90
 
59
91
  // The identity-parser map a guarded bridge read re-applies before executing (ADR-0032 decision 4). It
@@ -102,22 +134,18 @@ export interface DefineSyncWorkerOptions<TRegistry extends SyncTableRegistry> {
102
134
  */
103
135
  createPglite?: (storePath: string, backendOverride?: "memory") => Promise<ClientPGlite>;
104
136
  /**
105
- * Relax PGlite's per-query durability for every store this worker mints (default `true`; ADR-0047). A
106
- * worker-ENTRY option (baked into the worker file as code, like {@link convergenceIntervalMs}), NOT an
107
- * attach option — a tab cannot set it. Forwarded to the worker's default {@link createPglite} factory (the
108
- * provision/spare mint) AND to the {@link createSyncClient} boot, so it governs whichever path mints the
109
- * store. Ignored when a custom {@link createPglite} is injected (that factory owns its own create).
110
- *
111
- * On PGlite's idb backend the per-query synchronous flush to IndexedDB dominates local write latency, so
112
- * the toolkit defaults to relaxed: the query returns before the flush and the flush is scheduled
113
- * asynchronously. Loss window: only the writes not yet covered by a completed flush (typically the last one or two under human-rate input) can be at risk, and only on a
114
- * crash before BOTH their journal rows reach the write API (within ~hundreds of ms of enqueue) AND the
115
- * scheduled idb flush lands — synced tables are recoverable from the server by construction, so this
116
- * relaxes flush TIMING, not persistence (ADR-0036). Opt out with `relaxedDurability: false`.
137
+ * ADR-0049 (capability-driven engine placement) decision 7, plan step 11b: the consumer's explicit
138
+ * reconstructibility DECLARATION authorizing AUTOMATIC adoption of an existing idb-authoritative store into a
139
+ * committed OPFS successor. A worker-ENTRY option (baked into the worker file as code, like
140
+ * {@link executionLimit}), NEVER an attach option — a tab cannot set it (adoption DELETES local-only data, so
141
+ * only the code author may authorize it). Forwarded verbatim to the {@link createSyncClient} boot below. DEFAULT
142
+ * OFF (`undefined`): hook absence is never authority — only `"server-reconstructible"` (or the manual
143
+ * `adoptStore` API) authorizes deleting the idb predecessor. Honoured only where the engine home grants OPFS
144
+ * access (SW-direct / elected placement); inert on the browser-idb fallback where there is no opfs successor.
117
145
  */
118
- relaxedDurability?: boolean;
146
+ adoption?: AdoptionDeclaration;
119
147
  electricUrl: string;
120
- writeUrl: string;
148
+ batchWriteUrl: string;
121
149
  /** Static headers on every read + write request (e.g. a gateway `apikey`). See `createSyncClient`. */
122
150
  requestHeaders?: Record<string, string>;
123
151
  /** Write-only headers merged over {@link requestHeaders} (e.g. region/DB-affinity). See `createSyncClient`. */
@@ -138,6 +166,15 @@ export interface DefineSyncWorkerOptions<TRegistry extends SyncTableRegistry> {
138
166
  * (`flush` + `reconcile` queries). Default 15000.
139
167
  */
140
168
  convergenceIntervalMs?: number;
169
+ /**
170
+ * The opt-in engine-construction EXECUTION LIMIT (ADR-0049 D5), threaded into the ROUTER when this
171
+ * SharedWorker lands in `elected-worker` placement (router-only mode). DISABLED by default (`undefined` /
172
+ * absent `maxDispatchMs`) — no finite worst-case query duration exists, so an absent limit means the router
173
+ * forwards no probe and queries run unbounded; enabling it is a deliberate consumer choice.
174
+ * Elected placement ONLY: on SW-direct (`shared-worker`) the engine home is in-scope and there is no control
175
+ * channel to probe, so an enabled value is rejected as unsupported before engine boot.
176
+ */
177
+ executionLimit?: ExecutionLimitConfig;
141
178
  /** Injected transport binder. Defaults to auto-detecting the SharedWorker/dedicated-worker global scope. */
142
179
  installGlobal?: boolean;
143
180
  /** Injected codec (ADR-0032 S2 §1). Defaults to the v1 identity codec. */
@@ -158,7 +195,7 @@ export interface DefineSyncWorkerOptions<TRegistry extends SyncTableRegistry> {
158
195
  * NOT an attach option: the hook is a function and functions cannot cross the bridge, so a tab can never
159
196
  * supply it — the worker owns it. Use it for DDL that must precede the registry's local tables (extensions,
160
197
  * a bespoke schema search_path). On a fresh store the registry-derived local tables do NOT yet exist when
161
- * this runs (that ordering is what distinguishes it from {@link prepareLocalDb}).
198
+ * this runs (that ordering is what distinguishes it from {@link prepareLocalDbAfterSchema}).
162
199
  *
163
200
  * Runs on the storePath, {@link precreatedPglite}, and restore boots; SKIPPED entirely on the
164
201
  * {@link pgliteInstance} path (the caller owns schema/prepare/reconcile there). On a restore boot it still
@@ -168,7 +205,7 @@ export interface DefineSyncWorkerOptions<TRegistry extends SyncTableRegistry> {
168
205
  prepareLocalDbBeforeSchema?: CreateSyncClientOptions<TRegistry>["prepareLocalDbBeforeSchema"];
169
206
  /**
170
207
  * App-level schema prep run IN THE WORKER, against the engine's own local store, AFTER the registry schema
171
- * exec — forwarded verbatim to {@link CreateSyncClientOptions.prepareLocalDb}, same timing as the in-process
208
+ * exec — forwarded verbatim to {@link CreateSyncClientOptions.prepareLocalDbAfterSchema}, same timing as the in-process
172
209
  * client. Like {@link prepareLocalDbBeforeSchema} this is a worker-ENTRY option, never an attach option (the
173
210
  * tab never sees it — functions cannot cross the bridge). Use it for app-level indexes, views, or migrations
174
211
  * that depend on the registry's local tables, which DO exist by the time this runs.
@@ -176,15 +213,16 @@ export interface DefineSyncWorkerOptions<TRegistry extends SyncTableRegistry> {
176
213
  * Runs on the storePath, {@link precreatedPglite}, and restore boots; SKIPPED entirely on the
177
214
  * {@link pgliteInstance} path (the caller owns schema/prepare/reconcile there).
178
215
  */
179
- prepareLocalDb?: CreateSyncClientOptions<TRegistry>["prepareLocalDb"];
216
+ prepareLocalDbAfterSchema?: CreateSyncClientOptions<TRegistry>["prepareLocalDbAfterSchema"];
180
217
  /**
181
218
  * Bounded zero-subscriber keep-alive for the live-query manager (ADR-0040 decision 4). When an entry's last
182
219
  * subscriber leaves, a nonzero effective keep-alive retains its PGlite registration + diff state for a grace
183
220
  * period so a matching resubscribe (e.g. a re-mounted route across tabs) reuses it verbatim — no ~400 ms
184
221
  * re-materialization. Bounded by explicit budgets; DEFAULTS OFF (`defaultKeepAliveMs: 0` → tear a query
185
- * down the instant its last consumer leaves, byte-identical to the pre-keep-alive behaviour). Standing
186
- * argument for the 0 default: a retained entry STILL pays a full SQL rerun + diff on every dependent write —
187
- * PGlite live queries cannot be paused — so retention only pays off for a genuinely hot, re-mounted query.
222
+ * down the instant its last consumer leaves). The 0 default is justified: a retained entry STILL pays a
223
+ * full SQL rerun + diff on every dependent write — PGlite live queries cannot be paused — so retention
224
+ * only pays off for a genuinely hot, re-mounted query, and the default keeps worker memory bounded with
225
+ * no surprise standing SQL reruns.
188
226
  */
189
227
  liveQueries?: {
190
228
  /** Baseline retention (ms) for a zero-subscriber entry; floored by each subscriber's own hint. Default 0. */
@@ -225,15 +263,60 @@ export function defineSyncWorker<const TRegistry extends SyncTableRegistry>(
225
263
  const codec = options.codec ?? identityCodec;
226
264
  const tokenExpiryMarginMs = options.tokenExpiryMarginMs ?? 30_000;
227
265
  const convergenceIntervalMs = options.convergenceIntervalMs ?? 15_000;
266
+ // ADR-0049 D1: the placement probe's OPFS grant for THIS SharedWorker lifetime. Set true only by a GRANTED
267
+ // `shared-worker` (SW-direct) probe, so both the provision-mint (default `createPglite` factory) and the boot
268
+ // create (below) resolve the OPFS-repacked backend. False is the honest capability-absence invariant — the
269
+ // engine home in this scope opens IDBFS: the registry-declared `backend: "idbfs"` mode (no probe ran), or a
270
+ // capability-absence fallback (every home's probe denied / the OPFS API absent). Read at CALL time — every mint
271
+ // that consults it runs only after a port has connected, and connections are gated on the resolved placement.
272
+ let placementOpfsAccess = false;
273
+ // ADR-0049 D1/D12: the verbatim reason this scope's engine opened IDBFS while OPFS was CAPABLE (a fallback,
274
+ // not the declared-idbfs mode). Set alongside `placementOpfsAccess = false` by the bootstrap's capability-absence
275
+ // fallback outcome; threaded into the boot's `storageFallbackReason`. Absent for a granted opfs boot AND for the
276
+ // declared `backend: "idbfs"` mode (that is the contract, not a fallback — no reason to report).
277
+ let placementFallbackReason: string | undefined;
278
+ // ADR-0049 decision 12 (diagnostics): the resolved engine home for THIS SharedWorker scope, threaded into the
279
+ // boot's {@link BootReport} (`engineHome`). Set alongside `placementOpfsAccess` when the placement decision
280
+ // resolves. Both the SharedWorker and an elected dedicated-engine worker run the probe; only a plain test/Node
281
+ // scope that has no browser placement omits `engineHome`.
282
+ let placementEngineHome: SwPlacementResult["engineHome"] | undefined;
283
+ // ADR-0049 step 10b (bug fix — elected engine self-probe): the boot's OPFS grant may be decided ASYNCHRONOUSLY
284
+ // (the SharedWorker placement decision, or — for the elected DEDICATED engine — that scope's own OPFS probe).
285
+ // Both resolve BEFORE the first attach in practice, but the elected engine's probe races the incoming
286
+ // `connect-port` pipe, so `boot()` AWAITS this gate before reading `placementOpfsAccess`/`placementEngineHome` —
287
+ // guaranteeing the grant is threaded into the boot options (invariant 8: probed per boot, never assumed). Opened
288
+ // by {@link bootstrapWorkerScope}'s `onPlacement` (SharedWorker decision OR dedicated-engine probe OR the plain
289
+ // test/Node scope's immediate settle); opened immediately when no global bootstrap runs (`installGlobal:false`).
290
+ let openPlacementGate!: () => void;
291
+ const placementGate = new Promise<void>((resolve) => {
292
+ openPlacementGate = resolve;
293
+ });
294
+ // ─── The store's BOUND storage declaration (ADR-0050) ────────────────────────────────────────────
295
+ // Bound at the FIRST provision/attach payload: the registry-attached static declaration is authoritative,
296
+ // the payload's wire declaration fills the silent fields, capability defaults close the rest. Immutable for
297
+ // the engine's lifetime — a later payload whose explicit field disagrees is refused typed (the handlers ack
298
+ // the `StorageDeclarationRefusedError` through `serializeError`, so the tab rebuilds it by name).
299
+ let engineStorage: ResolvedStorageDeclaration | undefined;
300
+ const bindEngineStorage = (wire: SyncStorageDeclaration | undefined): void => {
301
+ if (engineStorage === undefined) {
302
+ engineStorage = resolveStorageDeclaration(getSyncRegistryStorage(options.registry), wire);
303
+ } else {
304
+ assertStorageDeclarationCompatible(engineStorage, wire);
305
+ }
306
+ };
307
+ // Durability (ADR-0047) comes from the bound declaration. The provision/spare mint does not run through
308
+ // `createSyncClient` (which resolves it for the boot create), so resolve it here — AT MINT TIME, after the
309
+ // provision payload bound the declaration (a construction-time constant could never see a wire declaration).
310
+ const currentDurability = () =>
311
+ engineStorage?.durability ?? getSyncRegistryStorage(options.registry)?.durability ?? "relaxed";
228
312
  const createPglite =
229
313
  options.createPglite ??
230
314
  ((storePath: string, backendOverride?: "memory") =>
231
- // Relaxed durability (ADR-0047): the default factory forwards the worker-entry choice into
232
- // `createClientPGlite`, which resolves the `?? true` default. A store minted for a spare/provision
233
- // (`provision` handler) is thus created under the same durability mode the boot create uses.
234
315
  createClientPGlite(storePath, {
235
316
  ...(backendOverride ? { backendOverride } : {}),
236
- ...(options.relaxedDurability != null ? { relaxedDurability: options.relaxedDurability } : {}),
317
+ durability: currentDurability(),
318
+ // SW-direct placement grant (ADR-0049 D1): a spare minted in-scope opens OPFS-repacked, matching the boot.
319
+ ...(placementOpfsAccess ? { hasOpfsSyncAccess: true } : {}),
237
320
  }));
238
321
  // A testing acknowledgment (ADR-0036) spread into THIS worker's options — needed when a test injects a
239
322
  // non-persistent BYO store (`precreatedPglite` / `pgliteInstance` / a memory-returning `createPglite`),
@@ -289,6 +372,10 @@ export function defineSyncWorker<const TRegistry extends SyncTableRegistry>(
289
372
  pglite: Promise<ClientPGlite>;
290
373
  stamp: Promise<{ initdbMs: number; provisionReadyAt: number }>;
291
374
  } | null = null;
375
+ // A provision request performs a bounded authority read before it may mint. An attach that arrives during
376
+ // that read waits for the attempt to settle, then either adopts the minted store or runs the ordinary boot
377
+ // path. This keeps provision a pure accelerator without racing a replacement underneath live deletion.
378
+ let provisionAttempt: Promise<void> | null = null;
292
379
 
293
380
  // ─── Outbound-convergence gate — the tab's Offline toggle over the bridge (ADR-0032 S3) ───────────
294
381
  // The worker owns convergence; the tab forwards its Offline flag as `set-online`. When suppressed the
@@ -397,8 +484,8 @@ export function defineSyncWorker<const TRegistry extends SyncTableRegistry>(
397
484
  // exactly once off the booted client's stage promises (`milestonesWired`), then driven purely by them.
398
485
  const milestones = { writeReady: false, bootSettled: false };
399
486
  const stageErrors: {
400
- writeReady?: { message: string; detail?: unknown };
401
- bootSettled?: { message: string; detail?: unknown };
487
+ writeReady?: BridgeErrorWire;
488
+ bootSettled?: BridgeErrorWire;
402
489
  } = {};
403
490
  let milestonesWired = false;
404
491
  const markMilestone = (stage: BootMilestone) => {
@@ -420,7 +507,19 @@ export function defineSyncWorker<const TRegistry extends SyncTableRegistry>(
420
507
  ...(stageErrors.bootSettled ? { bootSettledError: stageErrors.bootSettled } : {}),
421
508
  });
422
509
 
423
- const boot = (attach: AttachPayload): Promise<SyncClient<TRegistry>> => {
510
+ const boot = async (attach: AttachPayload): Promise<SyncClient<TRegistry>> => {
511
+ await placementGate;
512
+ // Provision owns no recovery policy. Wait only for its bounded pre-mint check/create attempt; a declined
513
+ // attempt leaves `provisioned` null and this attach continues through createSyncClient's full phase machine.
514
+ await provisionAttempt?.catch(() => undefined);
515
+ const attachLimit = attach.executionLimit?.maxDispatchMs;
516
+ if (placementEngineHome === "shared-worker" && attachLimit !== undefined) {
517
+ throw new Error(
518
+ "[pgxsinkit] executionLimit is unsupported for SharedWorker-direct placement; it is available only " +
519
+ "when the engine runs in elected-worker placement (ADR-0049 D5).",
520
+ );
521
+ }
522
+ assertSameExecutionLimit(options.executionLimit?.maxDispatchMs, attachLimit);
424
523
  if (bootPromise) return bootPromise;
425
524
  // The tab is the auth owner: seed the cache with the token it presented at attach (decision 3).
426
525
  tokenCache.push(attach.token);
@@ -430,6 +529,17 @@ export function defineSyncWorker<const TRegistry extends SyncTableRegistry>(
430
529
  // Resolve the registry from the attach's role (ADR-0032 S3): a single worker file bakes both variants
431
530
  // and the claim/attach settles which one boots — the spare was provisioned before the role was known.
432
531
  const registry = options.resolveRegistry?.(attach.config?.role) ?? options.registry;
532
+ // ADR-0050: placement and engine binding were resolved against `options.registry`'s static declaration —
533
+ // the spare was placed before any role existed, so a role-selected registry cannot re-home the store. A
534
+ // role registry whose static declaration EXPLICITLY conflicts with that bound resolution is refused typed
535
+ // here (the attach fails), never silently booted under the wrong placement. Role variants sharing one
536
+ // worker must agree on storage.
537
+ if (registry !== options.registry) {
538
+ assertStorageDeclarationCompatible(
539
+ engineStorage ?? resolveStorageDeclaration(getSyncRegistryStorage(options.registry), undefined),
540
+ getSyncRegistryStorage(registry) ?? {},
541
+ );
542
+ }
433
543
  // storePath-first, matching the `provision` handler's resolution (below): the board sends BOTH a bare
434
544
  // `storeId` (SharedWorker naming, tab-side) AND the real `storePath` (`pgxsinkit-board-<id>`), and the
435
545
  // PGlite store lives at `storePath` — so the provisioned store's path must be what we adopt on.
@@ -465,10 +575,13 @@ export function defineSyncWorker<const TRegistry extends SyncTableRegistry>(
465
575
  if (restoreFrom) {
466
576
  syncDebug("worker restoring store from backup", { storePath, byteLength: attach.restore!.buffer.byteLength });
467
577
  }
578
+ // Gate the store create on the resolved placement grant (ADR-0049 step 10b, elected-engine self-probe fix):
579
+ // `placementOpfsAccess` / `placementEngineHome` are read INSIDE this `.then`, after the probe settles, so the
580
+ // elected dedicated engine boots the OPFS-repacked backend it actually holds instead of racing to `idbfs`.
468
581
  bootPromise = createSyncClient<TRegistry>({
469
582
  registry,
470
583
  electricUrl: options.electricUrl,
471
- writeUrl: options.writeUrl,
584
+ batchWriteUrl: options.batchWriteUrl,
472
585
  storePath,
473
586
  // Re-stamp the internal testing marker (ADR-0036) so `createSyncClient`'s option handling selects the
474
587
  // memory backend on its fallback create and/or bypasses the BYO refusal for an injected test store —
@@ -480,20 +593,38 @@ export function defineSyncWorker<const TRegistry extends SyncTableRegistry>(
480
593
  // Boot observability (ADR-0034): label the report `worker`, and forward the provision stamp so an
481
594
  // adopted spare's initdb cost is reported rather than a create this boot never ran.
482
595
  bootMode: "worker",
596
+ // ADR-0049 decision 12 diagnostics: stamp the resolved engine home into the BootReport. This is
597
+ // `"shared-worker"` for the in-scope host or `"elected-worker"` for the elected dedicated engine; it is
598
+ // omitted only for a plain test/Node scope with no browser placement.
599
+ ...(placementEngineHome ? { engineHome: placementEngineHome } : {}),
483
600
  ...(provisionStamp ? { provisionStamp } : {}),
484
601
  ...(precreatedPglite ? { precreatedPglite } : {}),
485
602
  ...(options.pgliteInstance && restoreFrom == null ? { pgliteInstance: options.pgliteInstance } : {}),
486
603
  // App-level schema prep runs IN THE WORKER around the registry schema exec (before/after), exactly as
487
604
  // the in-process client. Worker-entry options, not attach options: functions cannot cross the bridge.
488
605
  ...(options.prepareLocalDbBeforeSchema ? { prepareLocalDbBeforeSchema: options.prepareLocalDbBeforeSchema } : {}),
489
- ...(options.prepareLocalDb ? { prepareLocalDb: options.prepareLocalDb } : {}),
490
- // Relaxed durability (ADR-0047): forward the worker-entry choice to the client-owned boot create too
491
- // (the storePath / precreated-fallback path inside createSyncClient), so a worker that never adopts a
492
- // provisioned spare still mints its store under the chosen durability mode.
493
- ...(options.relaxedDurability != null ? { relaxedDurability: options.relaxedDurability } : {}),
606
+ ...(options.prepareLocalDbAfterSchema ? { prepareLocalDbAfterSchema: options.prepareLocalDbAfterSchema } : {}),
607
+ // Durability (ADR-0047/ADR-0050): thread the store's BOUND declaration (registry static + first wire
608
+ // declaration + defaults, bound in the attach handler above) into `createSyncClient`'s single storage
609
+ // resolution point. Registry-only stores pass their own static values back — a no-op; wire-declared
610
+ // stores are how the board's toggle reaches the mint. Conflicts were already refused at the handler.
611
+ ...(engineStorage ? { storage: engineStorage } : {}),
612
+ // SW-direct placement grant (ADR-0049 D1): thread a GRANTED probe's grant into the boot create so the engine
613
+ // home in this SharedWorker scope opens the OPFS-repacked backend. Absent (false) is the honest IDBFS home —
614
+ // the declared `backend: "idbfs"` mode or a capability-absence fallback. `createSyncClient` forwards it to
615
+ // its `createClientPGlite` boot create.
616
+ ...(placementOpfsAccess ? { hasOpfsSyncAccess: true } : {}),
617
+ // ADR-0049 D1/D12: on a capability-absence fallback (OPFS was capable but no home could hold handles) the
618
+ // engine boots IDBFS and stamps this verbatim reason into the BootReport's `storageFallbackReason`. Absent
619
+ // on a granted opfs boot and on the declared-idbfs mode (which is the contract, not a fallback).
620
+ ...(placementFallbackReason ? { storageFallbackReason: placementFallbackReason } : {}),
621
+ // Adoption declaration (ADR-0049 D7, step 11b): a worker-entry option (never attach-controlled). When the
622
+ // engine home grants OPFS access, an existing idb-authoritative store is migrated to a committed opfs
623
+ // successor at boot. Default off (absent) — nothing is ever deleted without this explicit declaration.
624
+ ...(options.adoption ? { adoption: options.adoption } : {}),
494
625
  // Fresh-store prefetch overlap (ADR-0032 S4): the tab's claim path proved this store a schemaless
495
626
  // spare and forwarded the hint in the attach config, so the shape catch-up overlaps schema exec +
496
- // journal recovery + reconcile. Never inferred from "adopting a provisioned store": the board
627
+ // journal recovery + registry reconciliation. Never inferred from "adopting a provisioned store": the board
497
628
  // provisions a worker even for a MAPPED (returning) user, whose idb is NOT fresh — only the claim
498
629
  // path's explicit hint distinguishes them.
499
630
  ...(attach.config?.freshStore === true ? { freshStore: true } : {}),
@@ -711,7 +842,7 @@ export function defineSyncWorker<const TRegistry extends SyncTableRegistry>(
711
842
 
712
843
  // Render the query safe to materialise: a JOIN with same-named columns fails BOTH live APIs' temp-view
713
844
  // creation (`column "title" specified more than once`) unless every output column has a unique alias.
714
- // No `fields` → SQL unchanged (backward-compatible name-keyed rows; the aliased path keys by alias). The
845
+ // No `fields` → SQL unchanged (the default name-keyed row shape; the aliased path keys by alias). The
715
846
  // wrap stays caller-side (ADR-0040 decision 3): the manager receives POST-WRAP SQL as its query input.
716
847
  const materialSql = wrapLiveQueryForMaterialization(sql, fields);
717
848
  // Early bail BEFORE the manager is created (ADR-0040 decision 1 — the pending-before-manager close race):
@@ -809,7 +940,19 @@ export function defineSyncWorker<const TRegistry extends SyncTableRegistry>(
809
940
  // The testing memory-backend override rides as an explicit wire field (ADR-0036) — a symbol does not
810
941
  // survive structured clone, so the store's backend selection travels here and is passed to createPglite.
811
942
  const backendOverride = provision.testStoreBackend;
812
- if (bootPromise != null || provisioned != null) {
943
+ // ADR-0050: bind (or confirm) the store's storage declaration BEFORE the mint — the mint's durability
944
+ // comes from it. An explicit disagreement with the bound declaration refuses THIS provision typed.
945
+ try {
946
+ bindEngineStorage(provision.storage);
947
+ } catch (error) {
948
+ postBridgeMessage(port, codec, "provision-ack", {
949
+ ok: false,
950
+ error: serializeError(error),
951
+ ...(provision.storeId ? { storeId: provision.storeId } : {}),
952
+ });
953
+ break;
954
+ }
955
+ if (bootPromise != null || provisioned != null || provisionAttempt != null) {
813
956
  postBridgeMessage(port, codec, "provision-ack", {
814
957
  ok: true,
815
958
  ...(provision.storeId ? { storeId: provision.storeId } : {}),
@@ -817,19 +960,48 @@ export function defineSyncWorker<const TRegistry extends SyncTableRegistry>(
817
960
  break;
818
961
  }
819
962
  // Stamp the spare's create timing (ADR-0034): initdb cost + the monotonic instant it became ready,
820
- // so an adopting boot can compute how long it sat idle before adoption.
821
- const provisionStartedAt = nowStamp();
822
- const pglite = createPglite(storePath, backendOverride);
823
- const stamp = pglite.then(() => {
824
- const readyAt = nowStamp();
825
- return { initdbMs: readyAt - provisionStartedAt, provisionReadyAt: readyAt };
963
+ // so an adopting boot can compute how long it sat idle before adoption. Gated on the placement grant
964
+ // (ADR-0049 elected engine self-probe): the elected dedicated engine pre-spawns the OPFS-repacked store it
965
+ // holds access to, not idbfs, so the adopting boot backend matches its engine home. Opens the gate at
966
+ // once for SW-direct / plain scopes (already settled before any port connects).
967
+ const attempt = placementGate.then(async () => {
968
+ // Provision is only an accelerator, never an authority-recovery path. Read the meta record on EVERY
969
+ // persistent placement before minting. If deletion is live, decline the pre-mint and let the first
970
+ // attach run createSyncClient's full ordinary phase machine. This closes both granted and denied lanes:
971
+ // no replacement (and therefore no journal) can be created beneath a record a later boot must delete.
972
+ if (backendOverride !== "memory") {
973
+ const record = await readStoreMetaRecord(storePath);
974
+ if (record !== META_STORE_UNAVAILABLE && record?.phase === "deleting") {
975
+ syncDebug("worker provision declined — deletion authority is live", { storePath });
976
+ return;
977
+ }
978
+ }
979
+ // An attach or another completed provision may have won while the bounded read was in flight.
980
+ if (bootPromise != null || provisioned != null) return;
981
+
982
+ const provisionStartedAt = nowStamp();
983
+ const pglite = Promise.resolve().then(() => createPglite(storePath, backendOverride));
984
+ const stamp = pglite.then(() => {
985
+ const readyAt = nowStamp();
986
+ return { initdbMs: readyAt - provisionStartedAt, provisionReadyAt: readyAt };
987
+ });
988
+ provisioned = { storePath, pglite, stamp };
989
+ // Guard unobserved rejections when no attach ever adopts the spare (the page navigated away).
990
+ void pglite.catch(() => undefined);
991
+ void stamp.catch(() => undefined);
992
+ syncDebug("worker store provisioned", { storePath });
993
+ await pglite;
826
994
  });
827
- provisioned = { storePath, pglite, stamp };
828
- // Guard an unobserved rejection when no attach ever adopts it (the page navigated away).
829
- void pglite.catch(() => undefined);
830
- void stamp.catch(() => undefined);
831
- syncDebug("worker store provisioned", { storePath });
832
- void pglite.then(
995
+ provisionAttempt = attempt;
996
+ void attempt.then(
997
+ () => {
998
+ if (provisionAttempt === attempt) provisionAttempt = null;
999
+ },
1000
+ () => {
1001
+ if (provisionAttempt === attempt) provisionAttempt = null;
1002
+ },
1003
+ );
1004
+ void attempt.then(
833
1005
  () =>
834
1006
  postBridgeMessage(port, codec, "provision-ack", {
835
1007
  ok: true,
@@ -860,6 +1032,16 @@ export function defineSyncWorker<const TRegistry extends SyncTableRegistry>(
860
1032
  // attach's boot runs, so the boot's own lines (streamed live) are not doubled.
861
1033
  replayRailBufferTo(port);
862
1034
  const alreadyBooted = bootPromise !== null;
1035
+ // ADR-0050: bind (or confirm) the store's storage declaration BEFORE anything boots or joins. An
1036
+ // explicit disagreement — with the registry-attached declaration, or with what an earlier
1037
+ // provision/attach bound — refuses THIS attach typed (`StorageDeclarationRefusedError` by name);
1038
+ // the engine keeps running its bound mode. Never a silently different storage mode.
1039
+ try {
1040
+ bindEngineStorage(attach.storage);
1041
+ } catch (error) {
1042
+ postBridgeMessage(port, codec, "attach-ack", { alreadyBooted, error: serializeError(error) });
1043
+ break;
1044
+ }
863
1045
  // Restore rides the FIRST (boot) attach only (ADR-0035 decision 6): a restore attach that arrives once
864
1046
  // the engine has already booted CANNOT be honoured — `loadDataDir` is a create-time seed and the store
865
1047
  // is already live. Reject THIS attach with a typed error rather than silently ignoring the backup, so
@@ -867,7 +1049,11 @@ export function defineSyncWorker<const TRegistry extends SyncTableRegistry>(
867
1049
  if (alreadyBooted && attach.restore != null) {
868
1050
  postBridgeMessage(port, codec, "attach-ack", {
869
1051
  alreadyBooted,
1052
+ // `name` (BridgeErrorWire) makes this refusal type-detectable tab-side, like the
1053
+ // `RestoreTargetExistsError` the createSyncClient path throws — both mean "a store is already
1054
+ // there; this restore lost the race", the only refusals a consumer may fall back from.
870
1055
  error: {
1056
+ name: "RestoreIntoRunningStoreError",
871
1057
  message:
872
1058
  "[pgxsinkit] cannot restore into a running store: the worker engine has already booted, and a store backup can only seed a brand-new store on the FIRST attach (ADR-0035 decision 6). Restore into a fresh worker instead.",
873
1059
  },
@@ -937,7 +1123,7 @@ export function defineSyncWorker<const TRegistry extends SyncTableRegistry>(
937
1123
  // hanging on the ack (ADR-0032 FIX 1), and clear `bootPromise` so a later attach retries the
938
1124
  // boot. Do NOT clear `provisioned`: a resolved provisioned PGlite holds the only open handle on
939
1125
  // that store, so a retry must adopt it (createSyncClient falls back internally if it rejected).
940
- bootPromise = null;
1126
+ if (!alreadyBooted) bootPromise = null;
941
1127
  postBridgeMessage(port, codec, "attach-ack", {
942
1128
  alreadyBooted,
943
1129
  error: serializeError(error),
@@ -1032,9 +1218,29 @@ export function defineSyncWorker<const TRegistry extends SyncTableRegistry>(
1032
1218
  }
1033
1219
  };
1034
1220
 
1035
- const connect = (port: BridgePort) => {
1221
+ // The host's own placement identity for DIRECT connections (no bootstrapWorkerScope): minted once per host.
1222
+ const hostInstanceId = crypto.randomUUID();
1223
+ const connect = (port: BridgePort, connection?: { placementQueriesHandled?: boolean }) => {
1036
1224
  ports.add(port);
1037
1225
  const listener = (event: { data: unknown }) => {
1226
+ // A DIRECTLY-connected host IS the in-scope engine home, so it answers the placement query itself —
1227
+ // `electionRequired: false`, exactly what `bootstrapWorkerScope`'s meta listener reports for SW-direct.
1228
+ // This makes "every host answers the placement query" true on EVERY transport (including plain test
1229
+ // ports), which a restore-bearing attach RELIES on: it awaits the reply to route the one-shot restore
1230
+ // artifact to the port that reaches the engine. The real SharedWorker bootstrap owns this query on
1231
+ // bootstrapped ports; answering here as well minted a second, unrelated identity and could poison teardown.
1232
+ if (isPlacementQuery(event.data)) {
1233
+ if (connection?.placementQueriesHandled !== true) {
1234
+ port.postMessage({
1235
+ [PLACEMENT_RESULT_KEY]: {
1236
+ engineHome: "shared-worker",
1237
+ electionRequired: false,
1238
+ swInstanceId: hostInstanceId,
1239
+ } satisfies PlacementQueryResult,
1240
+ });
1241
+ }
1242
+ return;
1243
+ }
1038
1244
  if (isBridgeEnvelope(event.data) && event.data.type === "detach") {
1039
1245
  detachPort(port);
1040
1246
  port.removeEventListener("message", listener);
@@ -1046,38 +1252,123 @@ export function defineSyncWorker<const TRegistry extends SyncTableRegistry>(
1046
1252
  port.start?.();
1047
1253
  };
1048
1254
 
1049
- // ─── Global-scope auto-binding (real worker only; tests inject ports via connect) ─────────────────
1050
- if (options.installGlobal !== false) bindGlobalScope(connect);
1051
-
1052
- return {
1053
- connect,
1054
- whenBooted,
1055
- close: async () => {
1255
+ const closeHost = async (): Promise<void> => {
1256
+ const closeStartedAt = nowStamp();
1257
+ const retirementPhase = (phase: string, data?: Record<string, unknown>): void =>
1258
+ syncDebug("worker retirement phase", {
1259
+ phase,
1260
+ workerElapsedMs: Math.max(0, nowStamp() - closeStartedAt),
1261
+ ...(data ?? {}),
1262
+ });
1263
+ retirementPhase("host-close-started", {
1264
+ pendingSubscribes: inFlightSubscribes.size,
1265
+ liveSubscriptions: liveSubs.size,
1266
+ hasBoot: bootPromise !== null,
1267
+ hasProvisionedStore: provisioned !== null,
1268
+ });
1269
+ try {
1270
+ // Halt ALL engine activity BEFORE draining subscribes or disposing live queries (ADR-0040 + the halt-first
1271
+ // teardown rule): abort the shape-stream long-polls, the write fetches, and convergence NOW. Otherwise those
1272
+ // two steps below race an engine still committing shape data into the live queries they are trying to tear
1273
+ // down, and never settle — closeHost then parks before it ever reaches active.stop(). The awaited teardown is
1274
+ // unchanged; active.stop() below (idempotent halt inside) still runs the full close.
1275
+ const active = client ?? (bootPromise ? await bootPromise.catch(() => null) : null);
1276
+ active?.haltActivity();
1277
+ retirementPhase("activity-halted", { activeClient: active !== null });
1056
1278
  // Quiesce pending subscribes FIRST (ADR-0040 decision 1 — the pending-before-manager race): flip
1057
1279
  // `closing`, mark every mid-await subscribe cancelled, and await every in-flight `handleSubscribe` task.
1058
1280
  // This guarantees the manager exists (if any subscribe created one) BEFORE `dispose()` runs, and that no
1059
1281
  // subscribe can create a registration afterwards — each resumes into the `closing` early-bail instead.
1060
1282
  closing = true;
1061
1283
  for (const pending of pendingSubscribes.values()) pending.cancelled = true;
1284
+ retirementPhase("pending-subscriptions-wait-started", { count: inFlightSubscribes.size });
1062
1285
  await Promise.allSettled([...inFlightSubscribes]);
1286
+ retirementPhase("pending-subscriptions-wait-completed");
1063
1287
  // Dispose the manager BEFORE `active.stop()` (ADR-0040 decision 1): it tears down every remaining live
1064
1288
  // registration and awaits ALL teardowns, so no fire-and-forget unsubscribe is still in flight when the
1065
1289
  // engine closes (the close-vs-unsubscribe hang). No-op when nothing ever subscribed.
1066
1290
  liveSubs.clear();
1291
+ retirementPhase("live-query-disposal-started");
1067
1292
  await liveManager?.dispose();
1293
+ retirementPhase("live-query-disposal-completed");
1294
+ retirementPhase("active-client-stop-started", { activeClient: active !== null });
1295
+ await active?.stop();
1296
+ retirementPhase("active-client-stop-completed");
1297
+ retirementPhase("host-close-completed");
1298
+ } catch (error) {
1299
+ retirementPhase("host-close-failed", {
1300
+ message: error instanceof Error ? error.message : String(error),
1301
+ });
1302
+ throw error;
1303
+ } finally {
1068
1304
  ports.clear();
1069
1305
  setSyncDebugSink(undefined);
1070
- const active = client ?? (bootPromise ? await bootPromise.catch(() => null) : null);
1071
- await active?.stop();
1072
- },
1306
+ }
1307
+ };
1308
+
1309
+ // ─── Global-scope auto-binding (real worker only; tests inject ports via connect) ─────────────────
1310
+ // ADR-0049 D1 + ADR-0050: a SharedWorker scope routes through the PLACEMENT bootstrap — it decides its engine
1311
+ // home once and gates every `onconnect` port on that decision (SW-direct host connect vs router-only
1312
+ // `attachTab`). WHEN the decision runs is the storage declaration's call (ADR-0050): a registry-attached
1313
+ // STATIC declaration is authoritative and decides at scope startup; a registry-silent scope DEFERS the
1314
+ // decision until the first port's declaration message arrives, because `backend: "idbfs"` selects SW-direct
1315
+ // and skips the probe — the declaration must be known before the probe can be (not) run. A dedicated engine
1316
+ // worker still delegates to `bindGlobalScope` (the step-9 control plane); a plain test/Node scope is a no-op.
1317
+ //
1318
+ // The static declaration is read off the DEFAULT registry (placement is decided before any attach settles a
1319
+ // role) — storage is a data-contract property, so role variants baked into one worker file share it.
1320
+ const staticStorage = getSyncRegistryStorage(options.registry);
1321
+ if (options.installGlobal === false) {
1322
+ // No global bootstrap runs (a plain host driven via `connect` in tests) — open the placement gate at once so
1323
+ // the first boot proceeds with no OPFS grant and no engine home (a plain scope has no browser placement).
1324
+ openPlacementGate();
1325
+ } else {
1326
+ bootstrapWorkerScope({
1327
+ connect,
1328
+ closeHost,
1329
+ peerCount: () => ports.size,
1330
+ // ADR-0050: the registry-attached static declaration, when present, decides placement at startup —
1331
+ // `backend: "idbfs"` means no probe, no election, in-SW idbfs engine (ADR-0049 D1's declared opt-out).
1332
+ ...(staticStorage ? { staticStorage } : {}),
1333
+ ...(options.executionLimit ? { executionLimit: options.executionLimit } : {}),
1334
+ onPlacement: (outcome) => {
1335
+ // The resolved OPFS grant + engine home for THIS scope: the SharedWorker placement decision (`shared-worker`
1336
+ // ⇒ granted in-scope engine, or a capability-absence idbfs fallback carrying `storageFallbackReason`), the
1337
+ // elected DEDICATED engine's OWN-scope probe (`elected-worker` carrying its real probe verdict), or a plain
1338
+ // test/Node scope (no home, no grant). Threaded into the boot's grant/BootReport and OPENS the boot gate.
1339
+ // ADR-0049 decision 12: `placementEngineHome` stamps the report; `placementFallbackReason` stamps the
1340
+ // capability-absence idbfs fallback's `storageFallbackReason`.
1341
+ placementOpfsAccess = outcome.opfsGranted;
1342
+ placementEngineHome = outcome.engineHome;
1343
+ placementFallbackReason = outcome.storageFallbackReason;
1344
+ openPlacementGate();
1345
+ },
1346
+ });
1347
+ }
1348
+
1349
+ return {
1350
+ connect,
1351
+ whenBooted,
1352
+ close: closeHost,
1073
1353
  };
1074
1354
  }
1075
1355
 
1076
- /** Serialize a thrown value into the bridge's `{message, detail}` error shape (detail only when structured). */
1077
- function serializeError(error: unknown): { message: string; detail?: unknown } {
1356
+ /**
1357
+ * Serialize a thrown value into the bridge's {@link BridgeErrorWire} shape. `name` is carried whenever the
1358
+ * error's is not the bare `"Error"` default, so a typed refusal (e.g. `RestoreTargetExistsError`) stays
1359
+ * type-detectable after the tab rebuilds it; `detail` only when structured.
1360
+ */
1361
+ function serializeError(error: unknown): BridgeErrorWire {
1362
+ if (error instanceof ExecutionLimitMismatchError) {
1363
+ return { message: error.message, detail: executionLimitMismatchToWire(error) };
1364
+ }
1078
1365
  if (error instanceof Error) {
1079
1366
  const detail = (error as Error & { detail?: unknown }).detail;
1080
- return { message: error.message, ...(detail !== undefined ? { detail } : {}) };
1367
+ return {
1368
+ message: error.message,
1369
+ ...(error.name && error.name !== "Error" ? { name: error.name } : {}),
1370
+ ...(detail !== undefined ? { detail } : {}),
1371
+ };
1081
1372
  }
1082
1373
  return { message: String(error) };
1083
1374
  }
@@ -1085,11 +1376,127 @@ function serializeError(error: unknown): { message: string; detail?: unknown } {
1085
1376
  interface SharedWorkerConnectEvent {
1086
1377
  ports: BridgePort[];
1087
1378
  }
1379
+ /**
1380
+ * A message event that may carry transferred `MessagePort`s (the `ports` array). The engine-entry control plane
1381
+ * (ADR-0049 step 9) reads it for the delivered control channel and for each dynamically transferred pipe end.
1382
+ */
1383
+ interface ScopeMessageEvent {
1384
+ data: unknown;
1385
+ ports?: readonly ControlPortLike[];
1386
+ }
1088
1387
  interface WorkerGlobalScopeLike {
1089
1388
  onconnect?: (event: SharedWorkerConnectEvent) => void;
1090
1389
  postMessage?: (message: unknown) => void;
1091
- addEventListener?: (type: "message", listener: (event: { data: unknown }) => void) => void;
1390
+ addEventListener?: (type: "message", listener: (event: ScopeMessageEvent) => void) => void;
1092
1391
  removeEventListener?: (type: "message", listener: (event: { data: unknown }) => void) => void;
1392
+ /** Present on a real `DedicatedWorkerGlobalScope` (`self.close()`); the entry self-closes on teardown. */
1393
+ close?: () => void;
1394
+ }
1395
+
1396
+ /**
1397
+ * The structural `MessagePort` shape the engine-entry control plane needs: the control channel end delivered on
1398
+ * the implicit port, and each transferred pipe end wrapped into a {@link BridgePort}. No DOM lib — structural
1399
+ * typing only, matching the router's `RouterPort` discipline.
1400
+ */
1401
+ interface ControlPortLike {
1402
+ postMessage: (message: unknown, transfer?: unknown[]) => void;
1403
+ addEventListener: (type: "message", listener: (event: ScopeMessageEvent) => void) => void;
1404
+ removeEventListener?: (type: "message", listener: (event: ScopeMessageEvent) => void) => void;
1405
+ start?: () => void;
1406
+ }
1407
+
1408
+ /**
1409
+ * The literal key of the CONTROL-CHANNEL DELIVERY message (ADR-0049 step 9). The spawning coordinator's step-10
1410
+ * wiring posts `{ [CONTROL_PORT_DELIVERY_KEY]: true }` on the elected engine worker's IMPLICIT port WITH the
1411
+ * engine end of the announce control channel as a transferred `MessagePort`. The engine entry starts that port
1412
+ * and runs its control plane on it. Distinct namespace from the data-path bridge envelope and the `pgx0049`
1413
+ * control envelope, so it is unambiguous on the shared implicit-port transport.
1414
+ */
1415
+ export const CONTROL_PORT_DELIVERY_KEY = "pgx0049ControlPort" as const;
1416
+
1417
+ /** Is this a control-channel DELIVERY message (`{ [CONTROL_PORT_DELIVERY_KEY]: true }`)? */
1418
+ function isControlPortDelivery(data: unknown): boolean {
1419
+ return (
1420
+ typeof data === "object" &&
1421
+ data !== null &&
1422
+ (data as { [CONTROL_PORT_DELIVERY_KEY]?: unknown })[CONTROL_PORT_DELIVERY_KEY] === true
1423
+ );
1424
+ }
1425
+
1426
+ /**
1427
+ * The elected-engine-worker CONTROL PLANE (ADR-0049 step 9) — grown on the dedicated-worker ENTRY, leaving the
1428
+ * engine CORE (`SyncWorkerHost.connect`) untouched. Runs on the delivered control channel:
1429
+ *
1430
+ * - `assign-identity` → remember it (gates every subsequent tagged message) and reply `engine-ready`. That
1431
+ * signals CONTROL-plane readiness, NOT engine boot — the engine still boots lazily on the FIRST attach, as
1432
+ * today (the first `connect-port` pipe's traffic drives `boot`).
1433
+ * - `connect-port` (matching identity) + a transferred port → wrap it into a {@link BridgePort} (started if it
1434
+ * exposes `start()`, exactly as the implicit scope port is wrapped) and feed it to the SAME `connect(...)`
1435
+ * the entry already uses N times — dynamic per-tab pipe acceptance (ADR D4).
1436
+ * - `control-ping` → reply `control-ack` with the assigned identity (or the ping's, pre-assignment) and the
1437
+ * SAME `pingId`. Answered on the event loop, so a WASM-blocked engine cannot answer — which is exactly the
1438
+ * execution-limit's liveness signal.
1439
+ * - `engine-retiring` (matching) → a no-op hook for now (flush opportunities are engine-CORE concerns wired in
1440
+ * a later step).
1441
+ * - `engine-teardown` (matching) → reply `control-ack` with `pingId: -1` (the teardown ack the router relays)
1442
+ * then self-close the scope AFTER a microtask, so the ack flushes before the worker goes.
1443
+ *
1444
+ * Stale (post-assignment mismatch) tagged messages are discarded via {@link shouldApplyControlMessage}.
1445
+ */
1446
+ function startEngineControlPlane(
1447
+ controlPort: ControlPortLike,
1448
+ connect: (port: BridgePort) => void,
1449
+ closeScope: () => void,
1450
+ ): () => void {
1451
+ let assigned: EngineIdentity | undefined;
1452
+ const post = (message: EngineControlMessage): void => controlPort.postMessage(controlEnvelope(message));
1453
+ const listener = (event: ScopeMessageEvent): void => {
1454
+ const message = readControlEnvelope(event.data);
1455
+ if (message === undefined) return;
1456
+ switch (message.type) {
1457
+ case "assign-identity":
1458
+ assigned = message.identity;
1459
+ post({ type: "engine-ready", identity: message.identity });
1460
+ return;
1461
+ case "control-ping":
1462
+ post({ type: "control-ack", identity: assigned ?? message.identity, pingId: message.pingId });
1463
+ return;
1464
+ case "connect-port": {
1465
+ if (!shouldApplyControlMessage(assigned, message)) return; // stale → discard
1466
+ const transferred = event.ports?.[0];
1467
+ if (!transferred) return;
1468
+ connect(wrapControlPortAsBridge(transferred));
1469
+ return;
1470
+ }
1471
+ case "engine-retiring":
1472
+ // No-op hook for now (matching-identity only) — later steps wire the engine-core flush opportunity.
1473
+ void shouldApplyControlMessage(assigned, message);
1474
+ return;
1475
+ case "engine-teardown":
1476
+ if (!shouldApplyControlMessage(assigned, message)) return; // stale → discard
1477
+ post({ type: "control-ack", identity: message.identity, pingId: -1 });
1478
+ // Defer the close a microtask so the teardown ack flushes before the scope goes.
1479
+ void Promise.resolve().then(closeScope);
1480
+ return;
1481
+ default:
1482
+ return;
1483
+ }
1484
+ };
1485
+ controlPort.addEventListener("message", listener);
1486
+ controlPort.start?.();
1487
+ // Return a disposer that detaches THIS plane's listener, so a repeat control-port delivery (the keepalive
1488
+ // SW-reconstruction re-announce, step 11b follow-up 2) can REPLACE this channel and have the old one ignored.
1489
+ return () => controlPort.removeEventListener?.("message", listener);
1490
+ }
1491
+
1492
+ /** Wrap a transferred raw port into the {@link BridgePort} the engine's `connect(...)` consumes (started if able). */
1493
+ function wrapControlPortAsBridge(port: ControlPortLike): BridgePort {
1494
+ port.start?.();
1495
+ return {
1496
+ postMessage: (message, transfer) => port.postMessage(message, transfer),
1497
+ addEventListener: (type, listener) => port.addEventListener(type, listener),
1498
+ removeEventListener: (type, listener) => port.removeEventListener?.(type, listener),
1499
+ };
1093
1500
  }
1094
1501
 
1095
1502
  /**
@@ -1097,13 +1504,16 @@ interface WorkerGlobalScopeLike {
1097
1504
  * tab, each carrying a port); a dedicated `DedicatedWorkerGlobalScope` has no `onconnect` but IS itself the
1098
1505
  * single implicit port (`self.postMessage`/`addEventListener`). Neither exists in a plain test/Node context,
1099
1506
  * where the host is driven via {@link SyncWorkerHost.connect} directly — so this is a no-op there.
1507
+ *
1508
+ * `globalScope` defaults to `globalThis` (the real worker binding); tests inject a fake scope to exercise the
1509
+ * dedicated-worker control-plane arm (ADR-0049 step 9) without a real Worker.
1100
1510
  */
1101
- function bindGlobalScope(connect: (port: BridgePort) => void): void {
1102
- const scope = globalThis as unknown as WorkerGlobalScopeLike;
1511
+ export function bindGlobalScope(connect: (port: BridgePort) => void, globalScope: unknown = globalThis): void {
1512
+ const scope = globalScope as WorkerGlobalScopeLike;
1103
1513
  const hasSharedWorkerScope =
1104
- typeof (globalThis as { SharedWorkerGlobalScope?: unknown }).SharedWorkerGlobalScope !== "undefined";
1514
+ typeof (globalScope as { SharedWorkerGlobalScope?: unknown }).SharedWorkerGlobalScope !== "undefined";
1105
1515
  const hasDedicatedWorkerScope =
1106
- typeof (globalThis as { DedicatedWorkerGlobalScope?: unknown }).DedicatedWorkerGlobalScope !== "undefined";
1516
+ typeof (globalScope as { DedicatedWorkerGlobalScope?: unknown }).DedicatedWorkerGlobalScope !== "undefined";
1107
1517
 
1108
1518
  if (hasSharedWorkerScope) {
1109
1519
  scope.onconnect = (event: SharedWorkerConnectEvent) => {
@@ -1113,11 +1523,564 @@ function bindGlobalScope(connect: (port: BridgePort) => void): void {
1113
1523
  return;
1114
1524
  }
1115
1525
  if (hasDedicatedWorkerScope && scope.postMessage && scope.addEventListener && scope.removeEventListener) {
1116
- // The dedicated worker's own global scope IS the single port.
1117
- connect({
1526
+ // The dedicated worker's own global scope IS the single implicit port (the tab's engine port). Wrap it as a
1527
+ // bridge port and connect it — the same engine serves that one port for the worker's whole lifetime.
1528
+ const scopePort: BridgePort = {
1118
1529
  postMessage: (message: unknown) => scope.postMessage!(message),
1119
1530
  addEventListener: (type, listener) => scope.addEventListener!(type, listener),
1120
1531
  removeEventListener: (type, listener) => scope.removeEventListener!(type, listener),
1532
+ };
1533
+ connect(scopePort);
1534
+ // ADR-0049 step 9 (elected engine home): the implicit port ALSO carries the control-channel DELIVERY
1535
+ // message. On it, start the engine's control plane — dynamic pipe acceptance, probe replies, and
1536
+ // retirement/teardown — all identity-tagged. The engine CORE is untouched: transferred pipes flow into the
1537
+ // SAME `connect` above. The scope port's own baseline connect is unchanged.
1538
+ // A repeat delivery REPLACES the live control plane (ADR-0049 step 11b follow-up 2): when the leader-keepalive
1539
+ // reconstructs a dead SharedWorker it re-announces with a FRESH control channel and re-delivers this engine's
1540
+ // end. Dispose the previous plane's listener first so stale traffic on the dead old channel is ignored; the
1541
+ // engine CORE (`connect`) is untouched — pipes still flow into the same engine.
1542
+ let disposeControlPlane: (() => void) | undefined;
1543
+ scope.addEventListener("message", (event: ScopeMessageEvent) => {
1544
+ if (!isControlPortDelivery(event.data)) return;
1545
+ const controlPort = event.ports?.[0];
1546
+ if (!controlPort) return;
1547
+ disposeControlPlane?.();
1548
+ disposeControlPlane = startEngineControlPlane(controlPort, connect, () => scope.close?.());
1549
+ });
1550
+ }
1551
+ }
1552
+
1553
+ // ─── ADR-0049 D1: the SharedWorker placement bootstrap ───────────────────────────────────────────────
1554
+ // The SharedWorker arm decides its ENGINE HOME once at startup and gates each tab connection on that decision:
1555
+ // `shared-worker` (SW-direct) connects the port to the in-scope engine host; `elected-worker` (router-only)
1556
+ // hands the port to a `createEngineRouter` and NEVER boots the engine in-scope. The probe is UNCONDITIONAL —
1557
+ // every scope runs `decideSwPlacement` — with ONE exception: a registry declaring `backend: "idbfs"`
1558
+ // (`deps.declaredIdbfs`) skips the probe and binds the in-SW engine host on idbfs (the declared mode). Both modes
1559
+ // answer a tab's PLACEMENT query and DESTROY peer-count query; SW-direct additionally answers `pgx0049` keepalive
1560
+ // pings on each port (the router owns those in elected mode). A dedicated-worker scope (the elected engine worker)
1561
+ // still routes through `bindGlobalScope` (the step-9 control plane), unchanged.
1562
+
1563
+ /**
1564
+ * The PLACEMENT-QUERY envelope key: a tab posts `{ [PLACEMENT_QUERY_KEY]: true }` on its SharedWorker
1565
+ * connection to learn the engine home; the SharedWorker replies `{ [PLACEMENT_RESULT_KEY]: PlacementQueryResult }`.
1566
+ * A distinct namespace from the data-path bridge envelope and the `pgx0049` control envelope, so it is
1567
+ * unambiguous on the shared tab↔SharedWorker transport (the attach client reads it off the raw message).
1568
+ */
1569
+ export const PLACEMENT_QUERY_KEY = "pgx0049Placement" as const;
1570
+ /** The reply to a {@link PLACEMENT_QUERY_KEY} query — carries the engine home, `electionRequired`, and SW id. */
1571
+ export const PLACEMENT_RESULT_KEY = "pgx0049PlacementResult" as const;
1572
+ /**
1573
+ * The DESTROY peer-count query key (ADR-0049 D8, plan fault row "`destroy()` with peers attached → refused").
1574
+ * A tab about to destroy the store posts `{ [DESTROY_QUERY_KEY]: true }`; the SharedWorker — which alone knows
1575
+ * the attached-tab count — replies `{ [DESTROY_VERDICT_KEY]: { peers } }`. `peers` INCLUDES the querying tab, so
1576
+ * `peers > 1` means other tabs still hold the store and destruction is refused.
1577
+ */
1578
+ export const DESTROY_QUERY_KEY = "pgx0049DestroyQuery" as const;
1579
+ /** The reply to a {@link DESTROY_QUERY_KEY} query — the attached-tab count (querying tab included). */
1580
+ export const DESTROY_VERDICT_KEY = "pgx0049DestroyVerdict" as const;
1581
+ /**
1582
+ * The DECLARATION-MESSAGE envelope key (ADR-0050): the tab posts `{ [DECLARATION_KEY]: SyncStorageDeclaration }`
1583
+ * on EVERY worker port BEFORE its placement query — always, even when the app declared nothing (an empty `{}`
1584
+ * meaning "no opinion: capability defaults"). The bootstrap defers its placement decision until the first one
1585
+ * arrives (a registry-attached static declaration decides at startup instead), binds the first arrival for the
1586
+ * worker/store lifetime, and refuses explicit conflicts. The worker NAME carries the store path only — never
1587
+ * configuration; that was the fault this key replaces.
1588
+ */
1589
+ export const DECLARATION_KEY = "pgx0050Declaration" as const;
1590
+ /**
1591
+ * The reply when a declaration (or an engine-bound message on an undeclared port) is REFUSED (ADR-0050):
1592
+ * `{ [DECLARATION_REFUSED_KEY]: { message, name } }`. `name` is the stable typed-error name
1593
+ * (`StorageDeclarationRefusedError`) so the tab rebuilds the refusal typed and fails its boot loudly —
1594
+ * never a silent old value, never a hang.
1595
+ */
1596
+ export const DECLARATION_REFUSED_KEY = "pgx0050DeclarationRefused" as const;
1597
+
1598
+ /** The {@link DECLARATION_REFUSED_KEY} reply payload. */
1599
+ export interface DeclarationRefusedWire {
1600
+ message: string;
1601
+ /** The stable typed-error name (`StorageDeclarationRefusedError`) for the tab-side rebuild. */
1602
+ name: string;
1603
+ }
1604
+
1605
+ /** The placement a tab learns from the SharedWorker (the reply payload under {@link PLACEMENT_RESULT_KEY}). */
1606
+ export interface PlacementQueryResult {
1607
+ engineHome: SwPlacementResult["engineHome"];
1608
+ /** True in `elected-worker` mode — the tab's election coordinator must spawn the engine worker. */
1609
+ electionRequired: boolean;
1610
+ swInstanceId: string;
1611
+ /**
1612
+ * The SharedWorker's OWN script URL (`self.location.href`, ADR-0049 D5). In `elected-worker` mode the winning
1613
+ * tab constructs the elected engine as `new Worker(swScriptUrl, { type: "module" })` — the worker entry is
1614
+ * dual-scope (one file serves both homes), so no consumer wiring is needed; a `createEngineWorker` override is
1615
+ * only for entries that cannot be reconstructed from their URL as a module worker. Absent when the scope cannot
1616
+ * report its location (a plain test scope) — then a tab with no override fails attach with a typed wiring error.
1617
+ */
1618
+ swScriptUrl?: string;
1619
+ }
1620
+
1621
+ /** The SharedWorker placement bootstrap's dependencies (all injected so it is unit-testable off-worker). */
1622
+ export interface SharedWorkerBootstrapDeps {
1623
+ /** The engine host `connect` — used in SW-direct (`shared-worker`) placement to pipe a port to the in-scope engine. */
1624
+ connect: (port: BridgePort, connection?: { placementQueriesHandled?: boolean }) => void;
1625
+ /** Quiesce and close the in-scope host before SW-direct destruction acknowledges handle release. */
1626
+ closeHost?: () => Promise<void>;
1627
+ /** Current attached-tab count for the DESTROY verdict in SW-direct mode (the host's own port set). */
1628
+ peerCount: () => number;
1629
+ /** The opt-in execution limit, threaded into the router in `elected-worker` (router-only) placement. */
1630
+ executionLimit?: ExecutionLimitConfig;
1631
+ /**
1632
+ * The registry-attached STATIC storage declaration (ADR-0050) — authoritative when present: it binds the
1633
+ * store's declaration and decides placement AT SCOPE STARTUP (no wait for a declaration message).
1634
+ * `backend: "idbfs"` skips the probe entirely and binds the in-SharedWorker engine host on idbfs (ADR-0049
1635
+ * D1's declared opt-out — the declared mode, not a fallback); any other resolution runs the UNCONDITIONAL
1636
+ * placement probe. Absent: the scope is registry-silent and DEFERS its placement decision until the first
1637
+ * port's declaration message arrives (whose explicit fields then bind).
1638
+ */
1639
+ staticStorage?: SyncStorageDeclaration;
1640
+ /** Test seam: inject the placement decision (a fake probe result) instead of the real {@link decideSwPlacement}. */
1641
+ decidePlacement?: () => Promise<SwPlacementResult>;
1642
+ /** Defaults to `globalThis`; tests inject a fake SharedWorker scope. */
1643
+ globalScope?: unknown;
1644
+ /**
1645
+ * Notified once the placement grant for THIS scope resolves (SharedWorker decision, dedicated-engine probe, or
1646
+ * the plain-scope immediate settle). The entry threads `opfsGranted` into its `hasOpfsSyncAccess` boot grant and
1647
+ * `engineHome` into the BootReport, and opens its boot gate. `engineHome` is `undefined` for a plain test/Node
1648
+ * scope (no home) so the report omits it, exactly as before placement.
1649
+ */
1650
+ onPlacement?: (outcome: PlacementBootstrapOutcome) => void;
1651
+ /**
1652
+ * Test seam: inject the DEDICATED elected-engine scope's OPFS probe (a fake verdict) instead of the real
1653
+ * {@link probeOpfsSyncAccess}. Defaults to the real probe (invariant 8 — a real `createSyncAccessHandle` open in
1654
+ * the engine's own scope, per boot, never sniffed or cached).
1655
+ */
1656
+ probe?: () => Promise<PlacementProbeResult>;
1657
+ }
1658
+
1659
+ /** The resolved placement grant for a worker scope, threaded to the entry's boot grant + BootReport engine home. */
1660
+ export interface PlacementBootstrapOutcome {
1661
+ /** The engine home for this scope; `undefined` for a plain test/Node scope (the report then omits it). */
1662
+ engineHome: SwPlacementResult["engineHome"] | undefined;
1663
+ /** True when THIS scope actually holds OPFS sync-access (in-scope SW-direct, or the elected engine's own probe). */
1664
+ opfsGranted: boolean;
1665
+ /**
1666
+ * The verbatim reason this scope's engine opened IDBFS while OPFS was CAPABLE (ADR-0049 D1/D12, a
1667
+ * capability-absence fallback) — stamped into the boot's `storageFallbackReason`. Absent on a granted opfs boot
1668
+ * AND on the declared `backend: "idbfs"` mode (the contract, not a fallback).
1669
+ */
1670
+ storageFallbackReason?: string;
1671
+ }
1672
+
1673
+ /** Is this a raw `{ [PLACEMENT_QUERY_KEY]: true }` placement query? */
1674
+ function isPlacementQuery(data: unknown): boolean {
1675
+ return (
1676
+ typeof data === "object" &&
1677
+ data !== null &&
1678
+ (data as { [PLACEMENT_QUERY_KEY]?: unknown })[PLACEMENT_QUERY_KEY] === true
1679
+ );
1680
+ }
1681
+
1682
+ /** Is this a raw `{ [DESTROY_QUERY_KEY]: true }` destroy peer-count query? */
1683
+ function isDestroyQuery(data: unknown): boolean {
1684
+ return (
1685
+ typeof data === "object" && data !== null && (data as { [DESTROY_QUERY_KEY]?: unknown })[DESTROY_QUERY_KEY] === true
1686
+ );
1687
+ }
1688
+
1689
+ /** Narrow a raw `{ [DECLARATION_KEY]: SyncStorageDeclaration }` declaration message, or `undefined` for foreign traffic. */
1690
+ function readDeclarationMessage(data: unknown): SyncStorageDeclaration | undefined {
1691
+ if (typeof data !== "object" || data === null) return undefined;
1692
+ const raw = (data as { [DECLARATION_KEY]?: unknown })[DECLARATION_KEY];
1693
+ if (typeof raw !== "object" || raw === null) return undefined;
1694
+ return raw as SyncStorageDeclaration;
1695
+ }
1696
+
1697
+ /** A declared field with a value outside the contract's vocabulary — refused loudly, never ignored (ADR-0050). */
1698
+ function invalidDeclarationField(declaration: SyncStorageDeclaration): string | undefined {
1699
+ if (declaration.backend !== undefined && !isStorageBackend(declaration.backend)) {
1700
+ return `backend "${String(declaration.backend)}"`;
1701
+ }
1702
+ if (declaration.durability !== undefined && !isStorageDurability(declaration.durability)) {
1703
+ return `durability "${String(declaration.durability)}"`;
1704
+ }
1705
+ return undefined;
1706
+ }
1707
+
1708
+ /**
1709
+ * Bootstrap the running worker scope for ADR-0049 placement. A SharedWorker scope runs the placement decision
1710
+ * and gates every `onconnect` port on it ({@link wireSharedWorkerPlacement}); any other scope (the dedicated
1711
+ * elected-engine worker, or a plain test/Node scope) delegates to {@link bindGlobalScope} unchanged. Called by
1712
+ * `defineSyncWorker` in place of the old direct `bindGlobalScope(connect)`.
1713
+ */
1714
+ export function bootstrapWorkerScope(deps: SharedWorkerBootstrapDeps): void {
1715
+ const globalScope = deps.globalScope ?? globalThis;
1716
+ const hasSharedWorkerScope =
1717
+ typeof (globalScope as { SharedWorkerGlobalScope?: unknown }).SharedWorkerGlobalScope !== "undefined";
1718
+ if (hasSharedWorkerScope) {
1719
+ // ADR-0050: the storage declaration decides HOW placement runs. A registry-attached static declaration
1720
+ // binds and decides at startup; a registry-silent scope defers to the first port's declaration message.
1721
+ // Either way, `backend: "idbfs"` never probes (ADR-0049 D1's declared opt-out — SW-direct on idbfs, the
1722
+ // declared mode, not a fallback) and any other resolution runs the UNCONDITIONAL placement probe.
1723
+ wireSharedWorkerPlacement(deps, globalScope);
1724
+ return;
1725
+ }
1726
+ const hasDedicatedWorkerScope =
1727
+ typeof (globalScope as { DedicatedWorkerGlobalScope?: unknown }).DedicatedWorkerGlobalScope !== "undefined";
1728
+ if (hasDedicatedWorkerScope) {
1729
+ // ADR-0049 D1 (elected engine self-probe): the elected DEDICATED engine holds OPFS access in its OWN scope, so
1730
+ // it probes THIS scope's real `createSyncAccessHandle` (invariant 8 — per boot, never sniffed/cached) and
1731
+ // threads the verdict as the `elected-worker` home's OPFS grant, opening the boot gate. The step-9 control plane
1732
+ // (dynamic pipe acceptance, probe replies, teardown) is still wired by `bindGlobalScope`, unchanged. A DENIED
1733
+ // dedicated probe is capability absence in this home: the engine opens idbfs, and the outcome carries a verbatim
1734
+ // `storageFallbackReason` so the boot's BootReport shows the fallback (decision 12) rather than a silent idb.
1735
+ bindGlobalScope(deps.connect, globalScope);
1736
+ const probe = deps.probe ?? probeOpfsSyncAccess;
1737
+ void probe().then(
1738
+ (result) =>
1739
+ deps.onPlacement?.({
1740
+ engineHome: "elected-worker",
1741
+ opfsGranted: result.granted,
1742
+ ...(result.granted
1743
+ ? {}
1744
+ : { storageFallbackReason: `elected engine OPFS probe denied (${result.error ?? "no attribution"})` }),
1745
+ }),
1746
+ // The probe answers (never rejects); this guard only protects against an injected fake that throws — still
1747
+ // open the gate with no grant so the boot cannot deadlock, falling back to the honest idb backend.
1748
+ () =>
1749
+ deps.onPlacement?.({
1750
+ engineHome: "elected-worker",
1751
+ opfsGranted: false,
1752
+ storageFallbackReason: "elected engine OPFS probe threw",
1753
+ }),
1754
+ );
1755
+ return;
1756
+ }
1757
+ // A plain test/Node scope: no engine home, no OPFS grant — settle the gate immediately (no browser placement).
1758
+ bindGlobalScope(deps.connect, globalScope);
1759
+ deps.onPlacement?.({ engineHome: undefined, opfsGranted: false });
1760
+ }
1761
+
1762
+ /** Per-port bootstrap state (ADR-0050): declared gates engine routing; queries queue until placement resolves. */
1763
+ interface BootstrapPortState {
1764
+ /** This port's declaration message arrived (and was compatible) — the routing gate (contract point 3). */
1765
+ declared: boolean;
1766
+ /** The port was handed to the engine host / router (exactly once). */
1767
+ routed: boolean;
1768
+ /** Placement/destroy queries that arrived before the placement decision — answered on resolve, in order. */
1769
+ queuedQueries: unknown[];
1770
+ /** A DECLARED port's engine-bound/control traffic that arrived while placement was still pending — redelivered
1771
+ in arrival order after routing (the sender contract is "declaration first, then anything", ADR-0050). */
1772
+ queuedTraffic: Array<{ data: unknown; ports?: readonly ControlPortLike[] }>;
1773
+ }
1774
+
1775
+ /**
1776
+ * Wire the SharedWorker arm for placement (ADR-0049 D1 + ADR-0050). Every `onconnect` port is started
1777
+ * immediately under a live meta listener; the placement decision runs when the store's storage declaration is
1778
+ * KNOWN — at scope startup for a registry-attached static declaration, else on the FIRST port's declaration
1779
+ * message (`backend: "idbfs"` never probes; anything else runs the unconditional probe). The first arrival
1780
+ * binds the declaration for the worker lifetime; later explicit conflicts — and engine-bound traffic on a
1781
+ * port that has not declared — are refused typed (`DECLARATION_REFUSED_KEY`), never silently honoured. A port
1782
+ * is routed to the engine host (`shared-worker`) or the router (`elected-worker`) once it has declared AND
1783
+ * placement is resolved; placement/destroy queries queue until the decision and are answered after routing,
1784
+ * so a conforming tab's engine-bound follow-up always finds the engine listener installed.
1785
+ */
1786
+ function wireSharedWorkerPlacement(deps: SharedWorkerBootstrapDeps, globalScope: unknown): void {
1787
+ const scope = globalScope as WorkerGlobalScopeLike;
1788
+ const decide = deps.decidePlacement ?? (() => decideSwPlacement());
1789
+ // The SharedWorker's own script URL (ADR-0049 D5) — reported in the placement reply so the winning tab can
1790
+ // construct the elected engine as `new Worker(swScriptUrl, { type: "module" })` with no consumer wiring. Absent
1791
+ // when the scope cannot report its location (a plain test scope); a tab with no override then fails attach typed.
1792
+ const swScriptUrl = (globalScope as { location?: { href?: string } }).location?.href;
1793
+ let placement: SwPlacementResult | undefined;
1794
+ let router: EngineRouter | undefined;
1795
+ // Whether a `shared-worker` home holds the OPFS grant — true only on the PROBING path (a granted probe placed
1796
+ // the engine in-scope on OPFS-repacked); false when `backend: "idbfs"` was declared (no probe ran). A
1797
+ // capability-absence fallback (`storageFallbackReason`) is idbfs regardless.
1798
+ let opfsGrantedForSharedHome = false;
1799
+ // ADR-0050: the store's BOUND storage declaration — the registry-attached static declaration at wire time,
1800
+ // else the first declaration message's resolution. Immutable once set; later arrivals only confirm.
1801
+ let boundDeclaration: ResolvedStorageDeclaration | undefined;
1802
+ let decisionStarted = false;
1803
+ const portStates = new Map<BridgePort, BootstrapPortState>();
1804
+ let sharedHostTeardown: Promise<{ error?: BridgeErrorWire }> | undefined;
1805
+
1806
+ const currentPeerCount = (): number =>
1807
+ placement?.engineHome === "elected-worker" ? (router?.tabCount() ?? 0) : deps.peerCount();
1808
+
1809
+ /** Refuse a declaration (or a pre-declaration engine-bound message) TYPED on the offending port (ADR-0050). */
1810
+ const refuseDeclaration = (port: BridgePort, error: unknown): void => {
1811
+ const message = error instanceof Error ? error.message : String(error);
1812
+ port.postMessage({
1813
+ [DECLARATION_REFUSED_KEY]: { message, name: "StorageDeclarationRefusedError" } satisfies DeclarationRefusedWire,
1814
+ });
1815
+ };
1816
+
1817
+ /** Answer a queued-or-live placement query on `port` from the RESOLVED placement. */
1818
+ const answerPlacementQuery = (port: BridgePort): void => {
1819
+ const live = placement!;
1820
+ port.postMessage({
1821
+ [PLACEMENT_RESULT_KEY]: {
1822
+ engineHome: live.engineHome,
1823
+ electionRequired: live.engineHome === "elected-worker",
1824
+ swInstanceId: live.swInstanceId,
1825
+ ...(swScriptUrl !== undefined ? { swScriptUrl } : {}),
1826
+ } satisfies PlacementQueryResult,
1827
+ });
1828
+ };
1829
+
1830
+ /**
1831
+ * Redeliver one queued traffic entry by re-dispatching a real `message` event on the port — EXACTLY
1832
+ * equivalent to live delivery: every listener registered by then (the meta listener AND the routed engine
1833
+ * host's / router's) sees it in registration order, each ignoring the other's traffic as they already do on
1834
+ * a live routed port. Requires an EventTarget-backed port (every real MessagePort is; structural test ports
1835
+ * must be too to exercise replay — without `dispatchEvent` the entry is dropped, the pre-queue behavior).
1836
+ */
1837
+ const redeliver = (port: BridgePort, entry: { data: unknown; ports?: readonly ControlPortLike[] }): void => {
1838
+ const target = port as unknown as { dispatchEvent?: (event: unknown) => boolean };
1839
+ if (typeof target.dispatchEvent !== "function" || typeof MessageEvent === "undefined") return;
1840
+ target.dispatchEvent(
1841
+ new MessageEvent("message", {
1842
+ data: entry.data,
1843
+ ...(entry.ports ? { ports: entry.ports as unknown as MessagePort[] } : {}),
1844
+ }),
1845
+ );
1846
+ };
1847
+
1848
+ /** Hand a declared port to the resolved engine home — the host (SW-direct) or the router (elected). */
1849
+ const routePort = (port: BridgePort, state: BootstrapPortState): void => {
1850
+ if (state.routed) return;
1851
+ state.routed = true;
1852
+ if (placement!.engineHome === "shared-worker") {
1853
+ deps.connect(port, { placementQueriesHandled: true });
1854
+ } else {
1855
+ router!.attachTab(port as unknown as RouterPort);
1856
+ }
1857
+ };
1858
+
1859
+ /** A port's declaration message: bind the first (start the decision), confirm-or-refuse the rest (ADR-0050). */
1860
+ const handleDeclaration = (port: BridgePort, state: BootstrapPortState, wire: SyncStorageDeclaration): void => {
1861
+ const invalid = invalidDeclarationField(wire);
1862
+ if (invalid !== undefined) {
1863
+ refuseDeclaration(port, new StorageDeclarationRefusedError(`storage declaration carries an unknown ${invalid}`));
1864
+ return;
1865
+ }
1866
+ if (boundDeclaration === undefined) {
1867
+ // First arrival binds (the registry-silent scope; a static declaration bound at wire time instead). A
1868
+ // single wire source cannot conflict with an absent static one, so this resolution never throws here.
1869
+ boundDeclaration = resolveStorageDeclaration(deps.staticStorage, wire);
1870
+ state.declared = true;
1871
+ startDecision(boundDeclaration.backend);
1872
+ } else {
1873
+ try {
1874
+ assertStorageDeclarationCompatible(boundDeclaration, wire);
1875
+ } catch (error) {
1876
+ refuseDeclaration(port, error);
1877
+ return;
1878
+ }
1879
+ state.declared = true;
1880
+ }
1881
+ if (placement !== undefined) routePort(port, state);
1882
+ };
1883
+
1884
+ const installPortListener = (port: BridgePort, state: BootstrapPortState): void => {
1885
+ // The meta listener is installed (and the port STARTED) at `onconnect`, before any placement exists — it
1886
+ // must be, because the declaration message that UNBLOCKS the placement decision arrives on this port
1887
+ // (ADR-0050). It answers the placement + destroy-peer queries on EVERY port (both modes, queued until the
1888
+ // decision resolves) and, per mode:
1889
+ // - SW-direct: the `pgx0049` keepalive control-ping (the router owns that in elected mode).
1890
+ // - elected: the tab's `engine-announce` — the SW-side translation into `router.announceEngine`, handing
1891
+ // the transferred router-end control port to the router so it stamps an identity + pipes the tabs (the
1892
+ // router itself does not react to `engine-announce`; the SharedWorker scope drives it).
1893
+ // It coexists with the host's / router's own listener on the same port: each ignores the other's traffic.
1894
+ const metaListener = (event: { data: unknown; ports?: readonly ControlPortLike[] }): void => {
1895
+ const data = event.data;
1896
+ const declaration = readDeclarationMessage(data);
1897
+ if (declaration !== undefined) {
1898
+ handleDeclaration(port, state, declaration);
1899
+ return;
1900
+ }
1901
+ if (isPlacementQuery(data) || isDestroyQuery(data)) {
1902
+ // Meta queries: answerable the moment placement resolves (declaration-independent — a query is not
1903
+ // engine-bound), queued in arrival order until then.
1904
+ if (placement === undefined) {
1905
+ state.queuedQueries.push(data);
1906
+ return;
1907
+ }
1908
+ if (isPlacementQuery(data)) answerPlacementQuery(port);
1909
+ else port.postMessage({ [DESTROY_VERDICT_KEY]: { peers: currentPeerCount() } });
1910
+ return;
1911
+ }
1912
+ if (!state.declared && isBridgeEnvelope(data)) {
1913
+ // Contract point 3 (ADR-0050): an engine-bound message (provision/attach/…) before this port's
1914
+ // declaration is a protocol violation — refused typed, never buffered, never silently dropped. The
1915
+ // port itself is not poisoned: a declaration may still arrive and route it.
1916
+ refuseDeclaration(
1917
+ port,
1918
+ new StorageDeclarationRefusedError(
1919
+ "engine-bound message received before the port's storage declaration — the declaration message " +
1920
+ "must precede provision/attach on every worker port (ADR-0050)",
1921
+ ),
1922
+ );
1923
+ return;
1924
+ }
1925
+ if (placement === undefined) {
1926
+ // A DECLARED port's engine-bound/control traffic while the placement decision is still pending: the
1927
+ // sender contract is "declaration first, then anything" (ADR-0050) — a bridge-silence reconnect or a
1928
+ // keepalive SW reconstruction posts declaration + attach/announce back-to-back without awaiting a
1929
+ // placement reply. QUEUE it and redeliver after routing (the drain), never drop it. Undeclared-port
1930
+ // control traffic and non-protocol junk keep the drop (a conforming sender always declares first).
1931
+ if (state.declared && (isBridgeEnvelope(data) || readControlEnvelope(data) !== undefined)) {
1932
+ state.queuedTraffic.push({ data, ...(event.ports?.length ? { ports: event.ports } : {}) });
1933
+ }
1934
+ return;
1935
+ }
1936
+ const control = readControlEnvelope(data);
1937
+ if (placement.engineHome === "shared-worker") {
1938
+ if (control?.type === "control-ping") {
1939
+ port.postMessage(
1940
+ controlEnvelope({ type: "control-ack", identity: control.identity, pingId: control.pingId }),
1941
+ );
1942
+ return;
1943
+ }
1944
+ if (control?.type === "engine-teardown") {
1945
+ const sharedIdentity: EngineIdentity = { swInstanceId: placement.swInstanceId, generation: 0 };
1946
+ if (!shouldApplyControlMessage(sharedIdentity, control)) return;
1947
+ // SW-direct destruction is supervised by the tab, but the exclusive store handles live here. Close
1948
+ // the in-scope host first; only the reserved teardown ack proves that quiescence to the tab. The
1949
+ // SharedWorker scope then closes itself so a later attach starts a fresh, rebootable host even when
1950
+ // `extendedLifetime` would otherwise retain this closed scope.
1951
+ sharedHostTeardown ??= Promise.resolve()
1952
+ .then(() => deps.closeHost?.())
1953
+ .then(
1954
+ () => ({}),
1955
+ (error: unknown) => ({ error: serializeError(error) }),
1956
+ );
1957
+ void sharedHostTeardown.then((result) => {
1958
+ port.postMessage(
1959
+ controlEnvelope({
1960
+ type: "control-ack",
1961
+ identity: sharedIdentity,
1962
+ pingId: -1,
1963
+ ...(result.error ? { error: result.error } : {}),
1964
+ }),
1965
+ );
1966
+ // A task boundary, not merely a microtask: give the posted success/failure acknowledgement a delivery
1967
+ // turn before closing the SharedWorker global. A close failure poisons this lifetime just as surely as
1968
+ // a successful close retires it; never retain a rejected teardown promise in a live scope.
1969
+ globalThis.setTimeout(() => scope.close?.(), 0);
1970
+ });
1971
+ }
1972
+ return;
1973
+ }
1974
+ // elected-worker (router-only): the tab's coordinator drives leadership over this port.
1975
+ // - `leader-granted`: the newly-granted leader is about to (re)spawn its engine. Open the router's handoff
1976
+ // window NOW (fan `leader-granted` to EVERY tab) so in-flight ops settle by outcome and new ops QUEUE
1977
+ // across the spawn→announce→pipe gap, then flush onto the fresh pipe (invariants 5 + 9). Without this the
1978
+ // coordinator's `leader-granted` was DROPPED here, so on a leadership change (succession) a tab kept
1979
+ // dispatching onto the DEAD engine's pipe until the replacement pipe arrived — the elected-flow gap the
1980
+ // step-12 succession/relocation lanes surfaced (the router already owned `openHandoff`; nothing called it).
1981
+ // - `engine-announce`: translate into `router.announceEngine`, handing the transferred router-end control
1982
+ // port to the router so it stamps an identity + pipes the tabs (the router does not react to it itself).
1983
+ if (control?.type === "leader-granted") {
1984
+ router!.openHandoff("leader-granted");
1985
+ return;
1986
+ }
1987
+ if (control?.type === "engine-announce") {
1988
+ const announced = event.ports?.[0];
1989
+ if (announced) router!.announceEngine(announced as unknown as RouterPort);
1990
+ return;
1991
+ }
1992
+ // ADR-0049 D1 capability-absence fallback: the tab's elected DEDICATED engine probed its OWN scope and was
1993
+ // DENIED — no home on this platform can hold sync-access handles. Abandon election and boot the IN-SCOPE
1994
+ // idbfs engine here (with the registry-declared durability), stamping the reported reason into the fallback
1995
+ // boot's `storageFallbackReason` (decision 12). This tab's port is connected to the in-scope host now; other
1996
+ // tabs re-establish through their placement re-query on reconnect.
1997
+ if (control?.type === "engine-fallback") {
1998
+ fallBackToIdbfs(control.reason, port);
1999
+ }
2000
+ };
2001
+ port.addEventListener("message", metaListener);
2002
+ port.start?.();
2003
+ };
2004
+
2005
+ // ADR-0049 D1: flip a router-only (`elected-worker`) scope to the in-SharedWorker IDBFS fallback when the elected
2006
+ // engine reports its own probe was denied (capability absence in every home). Idempotent — the first report wins.
2007
+ // Re-threads the placement onto the entry (so the lazily-booting in-scope engine opens idbfs with the fallback
2008
+ // reason) and connects the reporting tab's port to the in-scope host. Peer tabs re-establish via placement re-query.
2009
+ let fellBack = false;
2010
+ const fallBackToIdbfs = (reason: string, reportingPort: BridgePort): void => {
2011
+ if (fellBack) return;
2012
+ fellBack = true;
2013
+ placement = { engineHome: "shared-worker", swInstanceId: placement?.swInstanceId ?? crypto.randomUUID() };
2014
+ deps.onPlacement?.({ engineHome: "shared-worker", opfsGranted: false, storageFallbackReason: reason });
2015
+ deps.connect(reportingPort, { placementQueriesHandled: true });
2016
+ };
2017
+
2018
+ /**
2019
+ * Run the placement decision for the BOUND backend (ADR-0050) — exactly once, the moment the declaration is
2020
+ * known (scope startup for a static declaration, first declaration message otherwise). `idbfs` NEVER probes:
2021
+ * the engine binds in-SharedWorker on idb, the declared mode, not a fallback (ADR-0049 D1). Anything else
2022
+ * runs the unconditional probe.
2023
+ */
2024
+ function startDecision(backend: ResolvedStorageDeclaration["backend"]): void {
2025
+ if (decisionStarted) return;
2026
+ decisionStarted = true;
2027
+ let decision: Promise<SwPlacementResult>;
2028
+ if (backend === "idbfs") {
2029
+ decision = Promise.resolve({ engineHome: "shared-worker", swInstanceId: crypto.randomUUID() });
2030
+ } else {
2031
+ opfsGrantedForSharedHome = true;
2032
+ decision = decide();
2033
+ }
2034
+ void decision.then((result) => {
2035
+ placement = result;
2036
+ // `shared-worker` ⇒ the engine boots in-scope: holding OPFS access on a GRANTED probe, or on IDBFS with a
2037
+ // `storageFallbackReason` when the decision is a capability-absence fallback (or the declared idbfs mode,
2038
+ // no reason). `elected-worker` ⇒ router-only, no in-scope grant (each tab's elected DEDICATED engine
2039
+ // probes its own scope). Thread grant + home + fallback reason, open the boot gate.
2040
+ const isSharedFallback = result.engineHome === "shared-worker" && result.storageFallbackReason !== undefined;
2041
+ deps.onPlacement?.({
2042
+ engineHome: result.engineHome,
2043
+ opfsGranted: result.engineHome === "shared-worker" && opfsGrantedForSharedHome && !isSharedFallback,
2044
+ ...(isSharedFallback ? { storageFallbackReason: result.storageFallbackReason } : {}),
2045
+ });
2046
+ if (result.engineHome === "elected-worker") {
2047
+ router = createEngineRouter({
2048
+ swInstanceId: result.swInstanceId,
2049
+ ...(deps.executionLimit ? { executionLimit: deps.executionLimit } : {}),
2050
+ });
2051
+ }
2052
+ // Drain: route every DECLARED port first (the engine listener must exist before the tab's next message),
2053
+ // THEN answer its queued meta queries — the conforming tab only sends engine-bound traffic after the
2054
+ // placement reply, so this ordering closes the gap by construction. Queued declared-port traffic (a
2055
+ // reconnect's attach, a reconstruction's announce) redelivers LAST, onto the fully-routed port.
2056
+ for (const [port, state] of portStates) {
2057
+ if (state.declared) routePort(port, state);
2058
+ for (const queued of state.queuedQueries) {
2059
+ if (isPlacementQuery(queued)) answerPlacementQuery(port);
2060
+ else port.postMessage({ [DESTROY_VERDICT_KEY]: { peers: currentPeerCount() } });
2061
+ }
2062
+ state.queuedQueries.length = 0;
2063
+ const traffic = state.queuedTraffic.splice(0);
2064
+ for (const entry of traffic) redeliver(port, entry);
2065
+ }
1121
2066
  });
1122
2067
  }
2068
+
2069
+ // ADR-0050: a registry-attached static declaration is authoritative — bind it and decide at scope startup,
2070
+ // no wait. (A registry-silent scope binds off the first declaration message instead; see handleDeclaration.)
2071
+ if (deps.staticStorage !== undefined) {
2072
+ boundDeclaration = resolveStorageDeclaration(deps.staticStorage, undefined);
2073
+ startDecision(boundDeclaration.backend);
2074
+ }
2075
+
2076
+ scope.onconnect = (event: SharedWorkerConnectEvent) => {
2077
+ const port = event.ports[0];
2078
+ if (!port) return;
2079
+ // Start every port immediately under the live meta listener (ADR-0050): the declaration message that
2080
+ // unblocks the deferred placement decision arrives here, so the old buffer-unstarted-until-placement gate
2081
+ // is structurally impossible now. Engine routing is still gated — per port — on declared + resolved.
2082
+ const state: BootstrapPortState = { declared: false, routed: false, queuedQueries: [], queuedTraffic: [] };
2083
+ portStates.set(port, state);
2084
+ installPortListener(port, state);
2085
+ };
1123
2086
  }