@pgxsinkit/client 0.1.51 → 0.2.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (96) 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/error-chain.d.ts +9 -0
  9. package/dist/error-chain.d.ts.map +1 -0
  10. package/dist/export-dump.d.ts.map +1 -1
  11. package/dist/export-store.d.ts +1 -1
  12. package/dist/export-store.d.ts.map +1 -1
  13. package/dist/index.d.ts +309 -38
  14. package/dist/index.d.ts.map +1 -1
  15. package/dist/index.js +4628 -1489
  16. package/dist/index.js.map +36 -24
  17. package/dist/live-rows-sql.d.ts +1 -1
  18. package/dist/local-store.d.ts +16 -31
  19. package/dist/local-store.d.ts.map +1 -1
  20. package/dist/local-tables.d.ts +10 -4
  21. package/dist/local-tables.d.ts.map +1 -1
  22. package/dist/mutation.d.ts +12 -15
  23. package/dist/mutation.d.ts.map +1 -1
  24. package/dist/opfs-effects.d.ts +51 -0
  25. package/dist/opfs-effects.d.ts.map +1 -0
  26. package/dist/placement-probe.d.ts +75 -0
  27. package/dist/placement-probe.d.ts.map +1 -0
  28. package/dist/schema.d.ts +11 -16
  29. package/dist/schema.d.ts.map +1 -1
  30. package/dist/store-boot.d.ts +77 -0
  31. package/dist/store-boot.d.ts.map +1 -0
  32. package/dist/store-lifecycle.d.ts +153 -0
  33. package/dist/store-lifecycle.d.ts.map +1 -0
  34. package/dist/store-meta.d.ts +190 -0
  35. package/dist/store-meta.d.ts.map +1 -0
  36. package/dist/store-path.d.ts +77 -7
  37. package/dist/store-path.d.ts.map +1 -1
  38. package/dist/sync/apply.d.ts +12 -1
  39. package/dist/sync/apply.d.ts.map +1 -1
  40. package/dist/sync/index.d.ts.map +1 -1
  41. package/dist/sync/shape-inbox.d.ts +1 -1
  42. package/dist/sync/types.d.ts +3 -3
  43. package/dist/testing.js.map +3 -3
  44. package/dist/worker/attach-sync-client.d.ts +239 -13
  45. package/dist/worker/attach-sync-client.d.ts.map +1 -1
  46. package/dist/worker/define-sync-worker.d.ts +162 -5
  47. package/dist/worker/define-sync-worker.d.ts.map +1 -1
  48. package/dist/worker/election-coordinator.d.ts +95 -0
  49. package/dist/worker/election-coordinator.d.ts.map +1 -0
  50. package/dist/worker/engine-control.d.ts +265 -0
  51. package/dist/worker/engine-control.d.ts.map +1 -0
  52. package/dist/worker/engine-router.d.ts +75 -0
  53. package/dist/worker/engine-router.d.ts.map +1 -0
  54. package/dist/worker/live-query-manager.d.ts.map +1 -1
  55. package/dist/worker/live-query-params-guard.d.ts +14 -0
  56. package/dist/worker/live-query-params-guard.d.ts.map +1 -0
  57. package/dist/worker/protocol.d.ts +32 -11
  58. package/dist/worker/protocol.d.ts.map +1 -1
  59. package/dist/worker/sw-placement.d.ts +37 -0
  60. package/dist/worker/sw-placement.d.ts.map +1 -0
  61. package/package.json +4 -3
  62. package/skills/core/SKILL.md +15 -8
  63. package/skills/operating/SKILL.md +114 -34
  64. package/src/adoption.ts +275 -0
  65. package/src/boot-report.ts +70 -17
  66. package/src/convergence.ts +2 -1
  67. package/src/error-chain.ts +26 -0
  68. package/src/export-dump.ts +5 -1
  69. package/src/export-store.ts +1 -1
  70. package/src/index.ts +1246 -118
  71. package/src/live-rows-sql.ts +1 -1
  72. package/src/local-store.ts +18 -40
  73. package/src/local-tables.ts +9 -2
  74. package/src/mutation.ts +67 -49
  75. package/src/mutations-api.ts +3 -3
  76. package/src/opfs-effects.ts +160 -0
  77. package/src/placement-probe.ts +168 -0
  78. package/src/schema.ts +17 -22
  79. package/src/store-boot.ts +343 -0
  80. package/src/store-lifecycle.ts +227 -0
  81. package/src/store-meta.ts +459 -0
  82. package/src/store-path.ts +197 -22
  83. package/src/sync/apply.ts +227 -89
  84. package/src/sync/index.ts +33 -9
  85. package/src/sync/shape-inbox.ts +1 -1
  86. package/src/sync/types.ts +3 -3
  87. package/src/testing.ts +2 -2
  88. package/src/worker/attach-sync-client.ts +1675 -117
  89. package/src/worker/define-sync-worker.ts +810 -50
  90. package/src/worker/election-coordinator.ts +462 -0
  91. package/src/worker/engine-control.ts +379 -0
  92. package/src/worker/engine-router.ts +355 -0
  93. package/src/worker/live-query-manager.ts +10 -1
  94. package/src/worker/live-query-params-guard.ts +57 -0
  95. package/src/worker/protocol.ts +41 -10
  96. package/src/worker/sw-placement.ts +64 -0
@@ -7,11 +7,16 @@
7
7
  // port) behind {@link SyncWorkerHost.connect} — the same entry a test drives with a plain `MessageChannel`
8
8
  // port, so no real Worker is needed to exercise the whole protocol.
9
9
 
10
+ import { type ParserOptions, type QueryOptions, types } from "@electric-sql/pglite";
11
+
10
12
  import type { SyncRuntimeStatus, SyncTableName, SyncTableRegistry, WriteMode } from "@pgxsinkit/contracts";
13
+ import { getSyncRegistryStorage } from "@pgxsinkit/contracts";
11
14
 
12
15
  import { type ConvergenceTrigger, createIntervalConvergenceTrigger } from "../convergence";
13
16
  import { setSyncDebugSink, syncDebug } from "../debug";
17
+ import { describeErrorChain } from "../error-chain";
14
18
  import {
19
+ type AdoptionDeclaration,
15
20
  type ClientPGlite,
16
21
  createClientPGlite,
17
22
  type CreateSyncClientOptions,
@@ -25,7 +30,21 @@ import {
25
30
  } from "../index";
26
31
  import { wrapLiveQueryForMaterialization } from "../live-rows-sql";
27
32
  import type { LocalStoreVersionEvent } from "../local-store";
33
+ import { type PlacementProbeResult, probeOpfsSyncAccess } from "../placement-probe";
34
+ import { META_STORE_UNAVAILABLE, readStoreMetaRecord } from "../store-meta";
28
35
  import { readTestStoreMarker, TEST_STORE_BACKEND, type TestStoreMarker } from "../store-path";
36
+ import {
37
+ assertSameExecutionLimit,
38
+ type EngineControlMessage,
39
+ type EngineIdentity,
40
+ ExecutionLimitMismatchError,
41
+ executionLimitMismatchToWire,
42
+ type ExecutionLimitConfig,
43
+ readControlEnvelope,
44
+ shouldApplyControlMessage,
45
+ wrapControlEnvelope as controlEnvelope,
46
+ } from "./engine-control";
47
+ import { createEngineRouter, type EngineRouter, type RouterPort } from "./engine-router";
29
48
  import {
30
49
  createLiveQueryManager,
31
50
  type LiveQueryManager,
@@ -40,6 +59,7 @@ import {
40
59
  type BridgeEvent,
41
60
  type BridgePort,
42
61
  type ExportArtefactWire,
62
+ type GuardedQueryWireArgs,
43
63
  identityCodec,
44
64
  isBridgeEnvelope,
45
65
  postBridgeMessage,
@@ -50,8 +70,32 @@ import {
50
70
  type SubscribePayload,
51
71
  type TokenResponsePayload,
52
72
  } from "./protocol";
73
+ import { decideSwPlacement, type SwPlacementResult } from "./sw-placement";
53
74
  import { createWorkerTokenCache } from "./token-cache";
54
75
 
76
+ // The identity-parser map a guarded bridge read re-applies before executing (ADR-0032 decision 4). It
77
+ // MIRRORS the fixed `parsers` constant in `drizzle-orm/pglite`'s session VERBATIM (pinned to
78
+ // drizzle-orm@1.0.0-rc.4, `drizzle-orm/pglite/session.js`): identity parsers so the listed OIDs come back as
79
+ // raw STRINGS — exactly what the in-process drizzle session receives, because it passes this same map into
80
+ // `pglite.query`. The members are: the scalar OIDs `types.TIMESTAMP` / `TIMESTAMPTZ` / `INTERVAL` / `DATE`,
81
+ // and the array OIDs 1115 = `timestamp[]`, 1185 = `timestamptz[]`, 1187 = `interval[]`, 1182 = `date[]`, and
82
+ // 1231 = `numeric[]` (NOT temporal — drizzle's list is mirrored verbatim, whatever its members). Over the
83
+ // bridge the map is FUNCTIONS (non-serializable), so the attach side strips the options down to `rowMode`
84
+ // and this worker re-applies the identical map. We do NOT import drizzle's private constant — this is a
85
+ // deliberate, version-pinned mirror.
86
+ const identityParser = (value: string): string => value;
87
+ const DRIZZLE_PGLITE_IDENTITY_PARSERS: ParserOptions = {
88
+ [types.TIMESTAMP]: identityParser,
89
+ [types.TIMESTAMPTZ]: identityParser,
90
+ [types.INTERVAL]: identityParser,
91
+ [types.DATE]: identityParser,
92
+ 1231: identityParser,
93
+ 1115: identityParser,
94
+ 1185: identityParser,
95
+ 1187: identityParser,
96
+ 1182: identityParser,
97
+ };
98
+
55
99
  export interface DefineSyncWorkerOptions<TRegistry extends SyncTableRegistry> {
56
100
  /**
57
101
  * The sync registry — imported as CODE by the worker file, never cloned into it (ADR-0032 decision 4).
@@ -74,8 +118,19 @@ export interface DefineSyncWorkerOptions<TRegistry extends SyncTableRegistry> {
74
118
  * Takes a plain store PATH (ADR-0036); the internal `backendOverride` is the test lane's memory selection.
75
119
  */
76
120
  createPglite?: (storePath: string, backendOverride?: "memory") => Promise<ClientPGlite>;
121
+ /**
122
+ * ADR-0049 (capability-driven engine placement) decision 7, plan step 11b: the consumer's explicit
123
+ * reconstructibility DECLARATION authorizing AUTOMATIC adoption of an existing idb-authoritative store into a
124
+ * committed OPFS successor. A worker-ENTRY option (baked into the worker file as code, like
125
+ * {@link executionLimit}), NEVER an attach option — a tab cannot set it (adoption DELETES local-only data, so
126
+ * only the code author may authorize it). Forwarded verbatim to the {@link createSyncClient} boot below. DEFAULT
127
+ * OFF (`undefined`): hook absence is never authority — only `"server-reconstructible"` (or the manual
128
+ * `adoptStore` API) authorizes deleting the idb predecessor. Honoured only where the engine home grants OPFS
129
+ * access (SW-direct / elected placement); inert on the browser-idb fallback where there is no opfs successor.
130
+ */
131
+ adoption?: AdoptionDeclaration;
77
132
  electricUrl: string;
78
- writeUrl: string;
133
+ batchWriteUrl: string;
79
134
  /** Static headers on every read + write request (e.g. a gateway `apikey`). See `createSyncClient`. */
80
135
  requestHeaders?: Record<string, string>;
81
136
  /** Write-only headers merged over {@link requestHeaders} (e.g. region/DB-affinity). See `createSyncClient`. */
@@ -96,6 +151,15 @@ export interface DefineSyncWorkerOptions<TRegistry extends SyncTableRegistry> {
96
151
  * (`flush` + `reconcile` queries). Default 15000.
97
152
  */
98
153
  convergenceIntervalMs?: number;
154
+ /**
155
+ * The opt-in engine-construction EXECUTION LIMIT (ADR-0049 D5), threaded into the ROUTER when this
156
+ * SharedWorker lands in `elected-worker` placement (router-only mode). DISABLED by default (`undefined` /
157
+ * absent `maxDispatchMs`) — no finite worst-case query duration exists, so an absent limit means the router
158
+ * forwards no probe and queries run unbounded; enabling it is a deliberate consumer choice.
159
+ * Elected placement ONLY: on SW-direct (`shared-worker`) the engine home is in-scope and there is no control
160
+ * channel to probe, so an enabled value is rejected as unsupported before engine boot.
161
+ */
162
+ executionLimit?: ExecutionLimitConfig;
99
163
  /** Injected transport binder. Defaults to auto-detecting the SharedWorker/dedicated-worker global scope. */
100
164
  installGlobal?: boolean;
101
165
  /** Injected codec (ADR-0032 S2 §1). Defaults to the v1 identity codec. */
@@ -109,14 +173,41 @@ export interface DefineSyncWorkerOptions<TRegistry extends SyncTableRegistry> {
109
173
  precreatedPglite?: CreateSyncClientOptions<TRegistry>["precreatedPglite"];
110
174
  /** A fully-provisioned PGlite (forwarded to {@link CreateSyncClientOptions.pgliteInstance}; caller owns schema). */
111
175
  pgliteInstance?: CreateSyncClientOptions<TRegistry>["pgliteInstance"];
176
+ /**
177
+ * App-level schema prep run IN THE WORKER, against the engine's own local store, BEFORE the registry
178
+ * schema exec — forwarded verbatim to {@link CreateSyncClientOptions.prepareLocalDbBeforeSchema}, same
179
+ * timing as the in-process client. This is a worker-ENTRY option (baked into the worker file as code),
180
+ * NOT an attach option: the hook is a function and functions cannot cross the bridge, so a tab can never
181
+ * supply it — the worker owns it. Use it for DDL that must precede the registry's local tables (extensions,
182
+ * a bespoke schema search_path). On a fresh store the registry-derived local tables do NOT yet exist when
183
+ * this runs (that ordering is what distinguishes it from {@link prepareLocalDbAfterSchema}).
184
+ *
185
+ * Runs on the storePath, {@link precreatedPglite}, and restore boots; SKIPPED entirely on the
186
+ * {@link pgliteInstance} path (the caller owns schema/prepare/reconcile there). On a restore boot it still
187
+ * runs, but the store already carries the registry tables from the backup's datadir, so the "tables absent"
188
+ * invariant does not hold there.
189
+ */
190
+ prepareLocalDbBeforeSchema?: CreateSyncClientOptions<TRegistry>["prepareLocalDbBeforeSchema"];
191
+ /**
192
+ * App-level schema prep run IN THE WORKER, against the engine's own local store, AFTER the registry schema
193
+ * exec — forwarded verbatim to {@link CreateSyncClientOptions.prepareLocalDbAfterSchema}, same timing as the in-process
194
+ * client. Like {@link prepareLocalDbBeforeSchema} this is a worker-ENTRY option, never an attach option (the
195
+ * tab never sees it — functions cannot cross the bridge). Use it for app-level indexes, views, or migrations
196
+ * that depend on the registry's local tables, which DO exist by the time this runs.
197
+ *
198
+ * Runs on the storePath, {@link precreatedPglite}, and restore boots; SKIPPED entirely on the
199
+ * {@link pgliteInstance} path (the caller owns schema/prepare/reconcile there).
200
+ */
201
+ prepareLocalDbAfterSchema?: CreateSyncClientOptions<TRegistry>["prepareLocalDbAfterSchema"];
112
202
  /**
113
203
  * Bounded zero-subscriber keep-alive for the live-query manager (ADR-0040 decision 4). When an entry's last
114
204
  * subscriber leaves, a nonzero effective keep-alive retains its PGlite registration + diff state for a grace
115
205
  * period so a matching resubscribe (e.g. a re-mounted route across tabs) reuses it verbatim — no ~400 ms
116
206
  * re-materialization. Bounded by explicit budgets; DEFAULTS OFF (`defaultKeepAliveMs: 0` → tear a query
117
- * down the instant its last consumer leaves, byte-identical to the pre-keep-alive behaviour). Standing
118
- * argument for the 0 default: a retained entry STILL pays a full SQL rerun + diff on every dependent write —
119
- * PGlite live queries cannot be paused — so retention only pays off for a genuinely hot, re-mounted query.
207
+ * down the instant its last consumer leaves). The 0 default is justified: a retained entry STILL pays a
208
+ * full SQL rerun + diff on every dependent write — PGlite live queries cannot be paused — so retention
209
+ * only pays off for a genuinely hot, re-mounted query, and the default keeps worker memory bounded with
210
+ * no surprise standing SQL reruns.
120
211
  */
121
212
  liveQueries?: {
122
213
  /** Baseline retention (ms) for a zero-subscriber entry; floored by each subscriber's own hint. Default 0. */
@@ -157,10 +248,48 @@ export function defineSyncWorker<const TRegistry extends SyncTableRegistry>(
157
248
  const codec = options.codec ?? identityCodec;
158
249
  const tokenExpiryMarginMs = options.tokenExpiryMarginMs ?? 30_000;
159
250
  const convergenceIntervalMs = options.convergenceIntervalMs ?? 15_000;
251
+ // ADR-0049 D1: the placement probe's OPFS grant for THIS SharedWorker lifetime. Set true only by a GRANTED
252
+ // `shared-worker` (SW-direct) probe, so both the provision-mint (default `createPglite` factory) and the boot
253
+ // create (below) resolve the OPFS-repacked backend. False is the honest capability-absence invariant — the
254
+ // engine home in this scope opens IDBFS: the registry-declared `backend: "idbfs"` mode (no probe ran), or a
255
+ // capability-absence fallback (every home's probe denied / the OPFS API absent). Read at CALL time — every mint
256
+ // that consults it runs only after a port has connected, and connections are gated on the resolved placement.
257
+ let placementOpfsAccess = false;
258
+ // ADR-0049 D1/D12: the verbatim reason this scope's engine opened IDBFS while OPFS was CAPABLE (a fallback,
259
+ // not the declared-idbfs mode). Set alongside `placementOpfsAccess = false` by the bootstrap's capability-absence
260
+ // fallback outcome; threaded into the boot's `storageFallbackReason`. Absent for a granted opfs boot AND for the
261
+ // declared `backend: "idbfs"` mode (that is the contract, not a fallback — no reason to report).
262
+ let placementFallbackReason: string | undefined;
263
+ // ADR-0049 decision 12 (diagnostics): the resolved engine home for THIS SharedWorker scope, threaded into the
264
+ // boot's {@link BootReport} (`engineHome`). Set alongside `placementOpfsAccess` when the placement decision
265
+ // resolves. Both the SharedWorker and an elected dedicated-engine worker run the probe; only a plain test/Node
266
+ // scope that has no browser placement omits `engineHome`.
267
+ let placementEngineHome: SwPlacementResult["engineHome"] | undefined;
268
+ // ADR-0049 step 10b (bug fix — elected engine self-probe): the boot's OPFS grant may be decided ASYNCHRONOUSLY
269
+ // (the SharedWorker placement decision, or — for the elected DEDICATED engine — that scope's own OPFS probe).
270
+ // Both resolve BEFORE the first attach in practice, but the elected engine's probe races the incoming
271
+ // `connect-port` pipe, so `boot()` AWAITS this gate before reading `placementOpfsAccess`/`placementEngineHome` —
272
+ // guaranteeing the grant is threaded into the boot options (invariant 8: probed per boot, never assumed). Opened
273
+ // by {@link bootstrapWorkerScope}'s `onPlacement` (SharedWorker decision OR dedicated-engine probe OR the plain
274
+ // test/Node scope's immediate settle); opened immediately when no global bootstrap runs (`installGlobal:false`).
275
+ let openPlacementGate!: () => void;
276
+ const placementGate = new Promise<void>((resolve) => {
277
+ openPlacementGate = resolve;
278
+ });
279
+ // Durability (ADR-0047) is registry-declared. The provision/spare mint does not run through
280
+ // `createSyncClient` (which resolves it for the boot create), so resolve it here off the DEFAULT registry —
281
+ // provision is role-agnostic (the role is settled only at claim/attach), and durability binds every store
282
+ // this worker mints regardless of role — and thread the resolved mode into the internal carrier.
283
+ const provisionDurability = getSyncRegistryStorage(options.registry)?.durability ?? "relaxed";
160
284
  const createPglite =
161
285
  options.createPglite ??
162
286
  ((storePath: string, backendOverride?: "memory") =>
163
- createClientPGlite(storePath, backendOverride ? { backendOverride } : undefined));
287
+ createClientPGlite(storePath, {
288
+ ...(backendOverride ? { backendOverride } : {}),
289
+ durability: provisionDurability,
290
+ // SW-direct placement grant (ADR-0049 D1): a spare minted in-scope opens OPFS-repacked, matching the boot.
291
+ ...(placementOpfsAccess ? { hasOpfsSyncAccess: true } : {}),
292
+ }));
164
293
  // A testing acknowledgment (ADR-0036) spread into THIS worker's options — needed when a test injects a
165
294
  // non-persistent BYO store (`precreatedPglite` / `pgliteInstance` / a memory-returning `createPglite`),
166
295
  // which `createSyncClient` would otherwise refuse. Forwarded to the boot below. A browser worker never
@@ -215,6 +344,10 @@ export function defineSyncWorker<const TRegistry extends SyncTableRegistry>(
215
344
  pglite: Promise<ClientPGlite>;
216
345
  stamp: Promise<{ initdbMs: number; provisionReadyAt: number }>;
217
346
  } | null = null;
347
+ // A provision request performs a bounded authority read before it may mint. An attach that arrives during
348
+ // that read waits for the attempt to settle, then either adopts the minted store or runs the ordinary boot
349
+ // path. This keeps provision a pure accelerator without racing a replacement underneath live deletion.
350
+ let provisionAttempt: Promise<void> | null = null;
218
351
 
219
352
  // ─── Outbound-convergence gate — the tab's Offline toggle over the bridge (ADR-0032 S3) ───────────
220
353
  // The worker owns convergence; the tab forwards its Offline flag as `set-online`. When suppressed the
@@ -346,7 +479,19 @@ export function defineSyncWorker<const TRegistry extends SyncTableRegistry>(
346
479
  ...(stageErrors.bootSettled ? { bootSettledError: stageErrors.bootSettled } : {}),
347
480
  });
348
481
 
349
- const boot = (attach: AttachPayload): Promise<SyncClient<TRegistry>> => {
482
+ const boot = async (attach: AttachPayload): Promise<SyncClient<TRegistry>> => {
483
+ await placementGate;
484
+ // Provision owns no recovery policy. Wait only for its bounded pre-mint check/create attempt; a declined
485
+ // attempt leaves `provisioned` null and this attach continues through createSyncClient's full phase machine.
486
+ await provisionAttempt?.catch(() => undefined);
487
+ const attachLimit = attach.executionLimit?.maxDispatchMs;
488
+ if (placementEngineHome === "shared-worker" && attachLimit !== undefined) {
489
+ throw new Error(
490
+ "[pgxsinkit] executionLimit is unsupported for SharedWorker-direct placement; it is available only " +
491
+ "when the engine runs in elected-worker placement (ADR-0049 D5).",
492
+ );
493
+ }
494
+ assertSameExecutionLimit(options.executionLimit?.maxDispatchMs, attachLimit);
350
495
  if (bootPromise) return bootPromise;
351
496
  // The tab is the auth owner: seed the cache with the token it presented at attach (decision 3).
352
497
  tokenCache.push(attach.token);
@@ -391,10 +536,13 @@ export function defineSyncWorker<const TRegistry extends SyncTableRegistry>(
391
536
  if (restoreFrom) {
392
537
  syncDebug("worker restoring store from backup", { storePath, byteLength: attach.restore!.buffer.byteLength });
393
538
  }
539
+ // Gate the store create on the resolved placement grant (ADR-0049 step 10b, elected-engine self-probe fix):
540
+ // `placementOpfsAccess` / `placementEngineHome` are read INSIDE this `.then`, after the probe settles, so the
541
+ // elected dedicated engine boots the OPFS-repacked backend it actually holds instead of racing to `idbfs`.
394
542
  bootPromise = createSyncClient<TRegistry>({
395
543
  registry,
396
544
  electricUrl: options.electricUrl,
397
- writeUrl: options.writeUrl,
545
+ batchWriteUrl: options.batchWriteUrl,
398
546
  storePath,
399
547
  // Re-stamp the internal testing marker (ADR-0036) so `createSyncClient`'s option handling selects the
400
548
  // memory backend on its fallback create and/or bypasses the BYO refusal for an injected test store —
@@ -406,12 +554,35 @@ export function defineSyncWorker<const TRegistry extends SyncTableRegistry>(
406
554
  // Boot observability (ADR-0034): label the report `worker`, and forward the provision stamp so an
407
555
  // adopted spare's initdb cost is reported rather than a create this boot never ran.
408
556
  bootMode: "worker",
557
+ // ADR-0049 decision 12 diagnostics: stamp the resolved engine home into the BootReport. This is
558
+ // `"shared-worker"` for the in-scope host or `"elected-worker"` for the elected dedicated engine; it is
559
+ // omitted only for a plain test/Node scope with no browser placement.
560
+ ...(placementEngineHome ? { engineHome: placementEngineHome } : {}),
409
561
  ...(provisionStamp ? { provisionStamp } : {}),
410
562
  ...(precreatedPglite ? { precreatedPglite } : {}),
411
563
  ...(options.pgliteInstance && restoreFrom == null ? { pgliteInstance: options.pgliteInstance } : {}),
564
+ // App-level schema prep runs IN THE WORKER around the registry schema exec (before/after), exactly as
565
+ // the in-process client. Worker-entry options, not attach options: functions cannot cross the bridge.
566
+ ...(options.prepareLocalDbBeforeSchema ? { prepareLocalDbBeforeSchema: options.prepareLocalDbBeforeSchema } : {}),
567
+ ...(options.prepareLocalDbAfterSchema ? { prepareLocalDbAfterSchema: options.prepareLocalDbAfterSchema } : {}),
568
+ // Durability (ADR-0047) is registry-declared: `createSyncClient` resolves it from `registry` at its own
569
+ // mint seam, so this boot needs no durability forward — the same `registry` decides the boot create's mode.
570
+ // SW-direct placement grant (ADR-0049 D1): thread a GRANTED probe's grant into the boot create so the engine
571
+ // home in this SharedWorker scope opens the OPFS-repacked backend. Absent (false) is the honest IDBFS home —
572
+ // the declared `backend: "idbfs"` mode or a capability-absence fallback. `createSyncClient` forwards it to
573
+ // its `createClientPGlite` boot create.
574
+ ...(placementOpfsAccess ? { hasOpfsSyncAccess: true } : {}),
575
+ // ADR-0049 D1/D12: on a capability-absence fallback (OPFS was capable but no home could hold handles) the
576
+ // engine boots IDBFS and stamps this verbatim reason into the BootReport's `storageFallbackReason`. Absent
577
+ // on a granted opfs boot and on the declared-idbfs mode (which is the contract, not a fallback).
578
+ ...(placementFallbackReason ? { storageFallbackReason: placementFallbackReason } : {}),
579
+ // Adoption declaration (ADR-0049 D7, step 11b): a worker-entry option (never attach-controlled). When the
580
+ // engine home grants OPFS access, an existing idb-authoritative store is migrated to a committed opfs
581
+ // successor at boot. Default off (absent) — nothing is ever deleted without this explicit declaration.
582
+ ...(options.adoption ? { adoption: options.adoption } : {}),
412
583
  // Fresh-store prefetch overlap (ADR-0032 S4): the tab's claim path proved this store a schemaless
413
584
  // spare and forwarded the hint in the attach config, so the shape catch-up overlaps schema exec +
414
- // journal recovery + reconcile. Never inferred from "adopting a provisioned store": the board
585
+ // journal recovery + registry reconciliation. Never inferred from "adopting a provisioned store": the board
415
586
  // provisions a worker even for a MAPPED (returning) user, whose idb is NOT fresh — only the claim
416
587
  // path's explicit hint distinguishes them.
417
588
  ...(attach.config?.freshStore === true ? { freshStore: true } : {}),
@@ -428,7 +599,9 @@ export function defineSyncWorker<const TRegistry extends SyncTableRegistry>(
428
599
  onQuarantine: (details) => broadcastEvent({ kind: "quarantine", details }),
429
600
  onReject: (details) => broadcastEvent({ kind: "reject", details }),
430
601
  onSchemaChange: (event: LocalStoreVersionEvent) => broadcastEvent({ kind: "schema-change", event }),
431
- onSyncError: (error) => broadcastEvent({ kind: "sync-error", message: error.message }),
602
+ // The cause chain, not just the wrapper message: the bridge carries a string, and dropping
603
+ // `.cause` here hid the actual database error from every tab (SQLSTATE, detail).
604
+ onSyncError: (error) => broadcastEvent({ kind: "sync-error", message: describeErrorChain(error) }),
432
605
  // Boot observability (ADR-0034): broadcast the finalized report to currently-attached ports (one-shot
433
606
  // push). Later tabs read the same report via the `bootReport` pull RPC — there is no replay event.
434
607
  onBootReport: (report) => broadcastEvent({ kind: "boot-report", report }),
@@ -445,6 +618,22 @@ export function defineSyncWorker<const TRegistry extends SyncTableRegistry>(
445
618
 
446
619
  // ─── Write / mutation-state RPC dispatch ─────────────────────────────────────────────────────────
447
620
  const dispatchRpc = async (active: SyncClient<TRegistry>, op: RpcOp, args: unknown[]): Promise<unknown> => {
621
+ // Guarded-read parser re-application (ADR-0032 decision 4). A guarded read compiled by the tab's
622
+ // Drizzle-over-bridge arrives as the {@link GuardedQueryWireArgs} tuple `[sql, params?, { rowMode? }, use?]`:
623
+ // the `parsers` map drizzle's pglite session normally passes could not cross the bridge (it is FUNCTIONS,
624
+ // not clonable), so the tab stripped it and we re-apply the identical map here before executing. Without it
625
+ // PGlite's default parsers would turn the identity-parsed OIDs (temporal OIDs + `numeric[]`) into `Date`s
626
+ // and numbers, whereas the in-process drizzle session sees them as raw STRINGS — so a guarded read would
627
+ // diverge from its in-process twin exactly on those columns. Typed against `GuardedQueryWireArgs` so the
628
+ // decode here shares the wire contract with the tab-side encoders (attach-sync-client).
629
+ const runGuardedQueryRpc = (): Promise<unknown> => {
630
+ const [sql, params, options, use] = args as unknown as GuardedQueryWireArgs;
631
+ const queryOptions: QueryOptions = {
632
+ ...(options?.rowMode ? { rowMode: options.rowMode } : {}),
633
+ parsers: DRIZZLE_PGLITE_IDENTITY_PARSERS,
634
+ };
635
+ return active.guardedRawQuery(sql, params, queryOptions, use as readonly SyncTableName<TRegistry>[] | undefined);
636
+ };
448
637
  type TableKey = SyncTableName<TRegistry>;
449
638
  switch (op) {
450
639
  case "create":
@@ -491,6 +680,10 @@ export function defineSyncWorker<const TRegistry extends SyncTableRegistry>(
491
680
  return active.desync(args[0] as TableKey);
492
681
  case "discardEphemeral":
493
682
  return active.discardEphemeral(args[0] as TableKey);
683
+ case "ensureSynced":
684
+ // Lazy activation (ADR-0021) on the worker's real client. Engine-wide but additive/idempotent — a tab
685
+ // activating a group another tab already started is a no-op, so no cross-tab revert hazard (cf. desync).
686
+ return active.ensureSynced(args[0] as readonly TableKey[]);
494
687
  case "readMutationDetails":
495
688
  return active.readMutationDetails(args[0] as TableKey | undefined);
496
689
  case "diagnostics":
@@ -503,6 +696,12 @@ export function defineSyncWorker<const TRegistry extends SyncTableRegistry>(
503
696
  return active.rawQuery(args[0] as string, args[1] as unknown[] | undefined, args[2] as RawQueryOptions);
504
697
  case "rawExec":
505
698
  return active.rawExec(args[0] as string, args[1] as RawQueryOptions);
699
+ case "guardedQuery":
700
+ // Guarded one-shot Drizzle read (ADR-0032 decision 4): the ADR-0041 read gate + the ADR-0021
701
+ // lazy-group guard run worker-side inside the engine's `guardedRawQuery`, so a read referencing a
702
+ // lazy relation activates its group exactly as in-process. The full `Results` structured-clones back
703
+ // and drizzle's own mapping (relational/nested included) runs on the tab.
704
+ return runGuardedQueryRpc();
506
705
  case "bootReport":
507
706
  // Boot observability (ADR-0034): the worker engine's stored report (or null). Pull, so a late tab
508
707
  // reads a boot predating it; the report structured-clones across the bridge as a plain object.
@@ -601,7 +800,7 @@ export function defineSyncWorker<const TRegistry extends SyncTableRegistry>(
601
800
 
602
801
  // Render the query safe to materialise: a JOIN with same-named columns fails BOTH live APIs' temp-view
603
802
  // creation (`column "title" specified more than once`) unless every output column has a unique alias.
604
- // No `fields` → SQL unchanged (backward-compatible name-keyed rows; the aliased path keys by alias). The
803
+ // No `fields` → SQL unchanged (the default name-keyed row shape; the aliased path keys by alias). The
605
804
  // wrap stays caller-side (ADR-0040 decision 3): the manager receives POST-WRAP SQL as its query input.
606
805
  const materialSql = wrapLiveQueryForMaterialization(sql, fields);
607
806
  // Early bail BEFORE the manager is created (ADR-0040 decision 1 — the pending-before-manager close race):
@@ -699,7 +898,7 @@ export function defineSyncWorker<const TRegistry extends SyncTableRegistry>(
699
898
  // The testing memory-backend override rides as an explicit wire field (ADR-0036) — a symbol does not
700
899
  // survive structured clone, so the store's backend selection travels here and is passed to createPglite.
701
900
  const backendOverride = provision.testStoreBackend;
702
- if (bootPromise != null || provisioned != null) {
901
+ if (bootPromise != null || provisioned != null || provisionAttempt != null) {
703
902
  postBridgeMessage(port, codec, "provision-ack", {
704
903
  ok: true,
705
904
  ...(provision.storeId ? { storeId: provision.storeId } : {}),
@@ -707,19 +906,48 @@ export function defineSyncWorker<const TRegistry extends SyncTableRegistry>(
707
906
  break;
708
907
  }
709
908
  // Stamp the spare's create timing (ADR-0034): initdb cost + the monotonic instant it became ready,
710
- // so an adopting boot can compute how long it sat idle before adoption.
711
- const provisionStartedAt = nowStamp();
712
- const pglite = createPglite(storePath, backendOverride);
713
- const stamp = pglite.then(() => {
714
- const readyAt = nowStamp();
715
- return { initdbMs: readyAt - provisionStartedAt, provisionReadyAt: readyAt };
909
+ // so an adopting boot can compute how long it sat idle before adoption. Gated on the placement grant
910
+ // (ADR-0049 elected engine self-probe): the elected dedicated engine pre-spawns the OPFS-repacked store it
911
+ // holds access to, not idbfs, so the adopting boot backend matches its engine home. Opens the gate at
912
+ // once for SW-direct / plain scopes (already settled before any port connects).
913
+ const attempt = placementGate.then(async () => {
914
+ // Provision is only an accelerator, never an authority-recovery path. Read the meta record on EVERY
915
+ // persistent placement before minting. If deletion is live, decline the pre-mint and let the first
916
+ // attach run createSyncClient's full ordinary phase machine. This closes both granted and denied lanes:
917
+ // no replacement (and therefore no journal) can be created beneath a record a later boot must delete.
918
+ if (backendOverride !== "memory") {
919
+ const record = await readStoreMetaRecord(storePath);
920
+ if (record !== META_STORE_UNAVAILABLE && record?.phase === "deleting") {
921
+ syncDebug("worker provision declined — deletion authority is live", { storePath });
922
+ return;
923
+ }
924
+ }
925
+ // An attach or another completed provision may have won while the bounded read was in flight.
926
+ if (bootPromise != null || provisioned != null) return;
927
+
928
+ const provisionStartedAt = nowStamp();
929
+ const pglite = Promise.resolve().then(() => createPglite(storePath, backendOverride));
930
+ const stamp = pglite.then(() => {
931
+ const readyAt = nowStamp();
932
+ return { initdbMs: readyAt - provisionStartedAt, provisionReadyAt: readyAt };
933
+ });
934
+ provisioned = { storePath, pglite, stamp };
935
+ // Guard unobserved rejections when no attach ever adopts the spare (the page navigated away).
936
+ void pglite.catch(() => undefined);
937
+ void stamp.catch(() => undefined);
938
+ syncDebug("worker store provisioned", { storePath });
939
+ await pglite;
716
940
  });
717
- provisioned = { storePath, pglite, stamp };
718
- // Guard an unobserved rejection when no attach ever adopts it (the page navigated away).
719
- void pglite.catch(() => undefined);
720
- void stamp.catch(() => undefined);
721
- syncDebug("worker store provisioned", { storePath });
722
- void pglite.then(
941
+ provisionAttempt = attempt;
942
+ void attempt.then(
943
+ () => {
944
+ if (provisionAttempt === attempt) provisionAttempt = null;
945
+ },
946
+ () => {
947
+ if (provisionAttempt === attempt) provisionAttempt = null;
948
+ },
949
+ );
950
+ void attempt.then(
723
951
  () =>
724
952
  postBridgeMessage(port, codec, "provision-ack", {
725
953
  ok: true,
@@ -827,7 +1055,7 @@ export function defineSyncWorker<const TRegistry extends SyncTableRegistry>(
827
1055
  // hanging on the ack (ADR-0032 FIX 1), and clear `bootPromise` so a later attach retries the
828
1056
  // boot. Do NOT clear `provisioned`: a resolved provisioned PGlite holds the only open handle on
829
1057
  // that store, so a retry must adopt it (createSyncClient falls back internally if it rejected).
830
- bootPromise = null;
1058
+ if (!alreadyBooted) bootPromise = null;
831
1059
  postBridgeMessage(port, codec, "attach-ack", {
832
1060
  alreadyBooted,
833
1061
  error: serializeError(error),
@@ -936,35 +1164,75 @@ export function defineSyncWorker<const TRegistry extends SyncTableRegistry>(
936
1164
  port.start?.();
937
1165
  };
938
1166
 
1167
+ const closeHost = async (): Promise<void> => {
1168
+ // Quiesce pending subscribes FIRST (ADR-0040 decision 1 — the pending-before-manager race): flip
1169
+ // `closing`, mark every mid-await subscribe cancelled, and await every in-flight `handleSubscribe` task.
1170
+ // This guarantees the manager exists (if any subscribe created one) BEFORE `dispose()` runs, and that no
1171
+ // subscribe can create a registration afterwards — each resumes into the `closing` early-bail instead.
1172
+ closing = true;
1173
+ for (const pending of pendingSubscribes.values()) pending.cancelled = true;
1174
+ await Promise.allSettled([...inFlightSubscribes]);
1175
+ // Dispose the manager BEFORE `active.stop()` (ADR-0040 decision 1): it tears down every remaining live
1176
+ // registration and awaits ALL teardowns, so no fire-and-forget unsubscribe is still in flight when the
1177
+ // engine closes (the close-vs-unsubscribe hang). No-op when nothing ever subscribed.
1178
+ liveSubs.clear();
1179
+ await liveManager?.dispose();
1180
+ ports.clear();
1181
+ setSyncDebugSink(undefined);
1182
+ const active = client ?? (bootPromise ? await bootPromise.catch(() => null) : null);
1183
+ await active?.stop();
1184
+ };
1185
+
939
1186
  // ─── Global-scope auto-binding (real worker only; tests inject ports via connect) ─────────────────
940
- if (options.installGlobal !== false) bindGlobalScope(connect);
1187
+ // ADR-0049 D1: a SharedWorker scope routes through the PLACEMENT bootstrap — it decides its engine home once at
1188
+ // startup (an UNCONDITIONAL probe) and gates every `onconnect` port on that decision (SW-direct host connect vs
1189
+ // router-only `attachTab`). The ONE exception is a registry that DECLARES `backend: "idbfs"` (read below): no
1190
+ // probe runs and the engine boots in-SharedWorker on idbfs — the declared mode, not a fallback. A dedicated
1191
+ // engine worker still delegates to `bindGlobalScope` (the step-9 control plane); a plain test/Node scope is a no-op.
1192
+ //
1193
+ // The declared backend is read off the DEFAULT registry (placement is decided once at startup, before any
1194
+ // attach settles a role) — the same seam `provisionDurability` above reads. Storage is a data-contract property,
1195
+ // so role variants baked into one worker file share it.
1196
+ const declaredIdbfs = getSyncRegistryStorage(options.registry)?.backend === "idbfs";
1197
+ if (options.installGlobal === false) {
1198
+ // No global bootstrap runs (a plain host driven via `connect` in tests) — open the placement gate at once so
1199
+ // the first boot proceeds with no OPFS grant and no engine home (a plain scope has no browser placement).
1200
+ openPlacementGate();
1201
+ } else {
1202
+ bootstrapWorkerScope({
1203
+ connect,
1204
+ closeHost,
1205
+ peerCount: () => ports.size,
1206
+ // ADR-0049 D1: `backend: "idbfs"` is the one declared opt-out — no probe, no election, in-SW idbfs engine.
1207
+ declaredIdbfs,
1208
+ ...(options.executionLimit ? { executionLimit: options.executionLimit } : {}),
1209
+ onPlacement: (outcome) => {
1210
+ // The resolved OPFS grant + engine home for THIS scope: the SharedWorker placement decision (`shared-worker`
1211
+ // ⇒ granted in-scope engine, or a capability-absence idbfs fallback carrying `storageFallbackReason`), the
1212
+ // elected DEDICATED engine's OWN-scope probe (`elected-worker` carrying its real probe verdict), or a plain
1213
+ // test/Node scope (no home, no grant). Threaded into the boot's grant/BootReport and OPENS the boot gate.
1214
+ // ADR-0049 decision 12: `placementEngineHome` stamps the report; `placementFallbackReason` stamps the
1215
+ // capability-absence idbfs fallback's `storageFallbackReason`.
1216
+ placementOpfsAccess = outcome.opfsGranted;
1217
+ placementEngineHome = outcome.engineHome;
1218
+ placementFallbackReason = outcome.storageFallbackReason;
1219
+ openPlacementGate();
1220
+ },
1221
+ });
1222
+ }
941
1223
 
942
1224
  return {
943
1225
  connect,
944
1226
  whenBooted,
945
- close: async () => {
946
- // Quiesce pending subscribes FIRST (ADR-0040 decision 1 — the pending-before-manager race): flip
947
- // `closing`, mark every mid-await subscribe cancelled, and await every in-flight `handleSubscribe` task.
948
- // This guarantees the manager exists (if any subscribe created one) BEFORE `dispose()` runs, and that no
949
- // subscribe can create a registration afterwards — each resumes into the `closing` early-bail instead.
950
- closing = true;
951
- for (const pending of pendingSubscribes.values()) pending.cancelled = true;
952
- await Promise.allSettled([...inFlightSubscribes]);
953
- // Dispose the manager BEFORE `active.stop()` (ADR-0040 decision 1): it tears down every remaining live
954
- // registration and awaits ALL teardowns, so no fire-and-forget unsubscribe is still in flight when the
955
- // engine closes (the close-vs-unsubscribe hang). No-op when nothing ever subscribed.
956
- liveSubs.clear();
957
- await liveManager?.dispose();
958
- ports.clear();
959
- setSyncDebugSink(undefined);
960
- const active = client ?? (bootPromise ? await bootPromise.catch(() => null) : null);
961
- await active?.stop();
962
- },
1227
+ close: closeHost,
963
1228
  };
964
1229
  }
965
1230
 
966
1231
  /** Serialize a thrown value into the bridge's `{message, detail}` error shape (detail only when structured). */
967
1232
  function serializeError(error: unknown): { message: string; detail?: unknown } {
1233
+ if (error instanceof ExecutionLimitMismatchError) {
1234
+ return { message: error.message, detail: executionLimitMismatchToWire(error) };
1235
+ }
968
1236
  if (error instanceof Error) {
969
1237
  const detail = (error as Error & { detail?: unknown }).detail;
970
1238
  return { message: error.message, ...(detail !== undefined ? { detail } : {}) };
@@ -975,11 +1243,127 @@ function serializeError(error: unknown): { message: string; detail?: unknown } {
975
1243
  interface SharedWorkerConnectEvent {
976
1244
  ports: BridgePort[];
977
1245
  }
1246
+ /**
1247
+ * A message event that may carry transferred `MessagePort`s (the `ports` array). The engine-entry control plane
1248
+ * (ADR-0049 step 9) reads it for the delivered control channel and for each dynamically transferred pipe end.
1249
+ */
1250
+ interface ScopeMessageEvent {
1251
+ data: unknown;
1252
+ ports?: readonly ControlPortLike[];
1253
+ }
978
1254
  interface WorkerGlobalScopeLike {
979
1255
  onconnect?: (event: SharedWorkerConnectEvent) => void;
980
1256
  postMessage?: (message: unknown) => void;
981
- addEventListener?: (type: "message", listener: (event: { data: unknown }) => void) => void;
1257
+ addEventListener?: (type: "message", listener: (event: ScopeMessageEvent) => void) => void;
982
1258
  removeEventListener?: (type: "message", listener: (event: { data: unknown }) => void) => void;
1259
+ /** Present on a real `DedicatedWorkerGlobalScope` (`self.close()`); the entry self-closes on teardown. */
1260
+ close?: () => void;
1261
+ }
1262
+
1263
+ /**
1264
+ * The structural `MessagePort` shape the engine-entry control plane needs: the control channel end delivered on
1265
+ * the implicit port, and each transferred pipe end wrapped into a {@link BridgePort}. No DOM lib — structural
1266
+ * typing only, matching the router's `RouterPort` discipline.
1267
+ */
1268
+ interface ControlPortLike {
1269
+ postMessage: (message: unknown, transfer?: unknown[]) => void;
1270
+ addEventListener: (type: "message", listener: (event: ScopeMessageEvent) => void) => void;
1271
+ removeEventListener?: (type: "message", listener: (event: ScopeMessageEvent) => void) => void;
1272
+ start?: () => void;
1273
+ }
1274
+
1275
+ /**
1276
+ * The literal key of the CONTROL-CHANNEL DELIVERY message (ADR-0049 step 9). The spawning coordinator's step-10
1277
+ * wiring posts `{ [CONTROL_PORT_DELIVERY_KEY]: true }` on the elected engine worker's IMPLICIT port WITH the
1278
+ * engine end of the announce control channel as a transferred `MessagePort`. The engine entry starts that port
1279
+ * and runs its control plane on it. Distinct namespace from the data-path bridge envelope and the `pgx0049`
1280
+ * control envelope, so it is unambiguous on the shared implicit-port transport.
1281
+ */
1282
+ export const CONTROL_PORT_DELIVERY_KEY = "pgx0049ControlPort" as const;
1283
+
1284
+ /** Is this a control-channel DELIVERY message (`{ [CONTROL_PORT_DELIVERY_KEY]: true }`)? */
1285
+ function isControlPortDelivery(data: unknown): boolean {
1286
+ return (
1287
+ typeof data === "object" &&
1288
+ data !== null &&
1289
+ (data as { [CONTROL_PORT_DELIVERY_KEY]?: unknown })[CONTROL_PORT_DELIVERY_KEY] === true
1290
+ );
1291
+ }
1292
+
1293
+ /**
1294
+ * The elected-engine-worker CONTROL PLANE (ADR-0049 step 9) — grown on the dedicated-worker ENTRY, leaving the
1295
+ * engine CORE (`SyncWorkerHost.connect`) untouched. Runs on the delivered control channel:
1296
+ *
1297
+ * - `assign-identity` → remember it (gates every subsequent tagged message) and reply `engine-ready`. That
1298
+ * signals CONTROL-plane readiness, NOT engine boot — the engine still boots lazily on the FIRST attach, as
1299
+ * today (the first `connect-port` pipe's traffic drives `boot`).
1300
+ * - `connect-port` (matching identity) + a transferred port → wrap it into a {@link BridgePort} (started if it
1301
+ * exposes `start()`, exactly as the implicit scope port is wrapped) and feed it to the SAME `connect(...)`
1302
+ * the entry already uses N times — dynamic per-tab pipe acceptance (ADR D4).
1303
+ * - `control-ping` → reply `control-ack` with the assigned identity (or the ping's, pre-assignment) and the
1304
+ * SAME `pingId`. Answered on the event loop, so a WASM-blocked engine cannot answer — which is exactly the
1305
+ * execution-limit's liveness signal.
1306
+ * - `engine-retiring` (matching) → a no-op hook for now (flush opportunities are engine-CORE concerns wired in
1307
+ * a later step).
1308
+ * - `engine-teardown` (matching) → reply `control-ack` with `pingId: -1` (the teardown ack the router relays)
1309
+ * then self-close the scope AFTER a microtask, so the ack flushes before the worker goes.
1310
+ *
1311
+ * Stale (post-assignment mismatch) tagged messages are discarded via {@link shouldApplyControlMessage}.
1312
+ */
1313
+ function startEngineControlPlane(
1314
+ controlPort: ControlPortLike,
1315
+ connect: (port: BridgePort) => void,
1316
+ closeScope: () => void,
1317
+ ): () => void {
1318
+ let assigned: EngineIdentity | undefined;
1319
+ const post = (message: EngineControlMessage): void => controlPort.postMessage(controlEnvelope(message));
1320
+ const listener = (event: ScopeMessageEvent): void => {
1321
+ const message = readControlEnvelope(event.data);
1322
+ if (message === undefined) return;
1323
+ switch (message.type) {
1324
+ case "assign-identity":
1325
+ assigned = message.identity;
1326
+ post({ type: "engine-ready", identity: message.identity });
1327
+ return;
1328
+ case "control-ping":
1329
+ post({ type: "control-ack", identity: assigned ?? message.identity, pingId: message.pingId });
1330
+ return;
1331
+ case "connect-port": {
1332
+ if (!shouldApplyControlMessage(assigned, message)) return; // stale → discard
1333
+ const transferred = event.ports?.[0];
1334
+ if (!transferred) return;
1335
+ connect(wrapControlPortAsBridge(transferred));
1336
+ return;
1337
+ }
1338
+ case "engine-retiring":
1339
+ // No-op hook for now (matching-identity only) — later steps wire the engine-core flush opportunity.
1340
+ void shouldApplyControlMessage(assigned, message);
1341
+ return;
1342
+ case "engine-teardown":
1343
+ if (!shouldApplyControlMessage(assigned, message)) return; // stale → discard
1344
+ post({ type: "control-ack", identity: message.identity, pingId: -1 });
1345
+ // Defer the close a microtask so the teardown ack flushes before the scope goes.
1346
+ void Promise.resolve().then(closeScope);
1347
+ return;
1348
+ default:
1349
+ return;
1350
+ }
1351
+ };
1352
+ controlPort.addEventListener("message", listener);
1353
+ controlPort.start?.();
1354
+ // Return a disposer that detaches THIS plane's listener, so a repeat control-port delivery (the keepalive
1355
+ // SW-reconstruction re-announce, step 11b follow-up 2) can REPLACE this channel and have the old one ignored.
1356
+ return () => controlPort.removeEventListener?.("message", listener);
1357
+ }
1358
+
1359
+ /** Wrap a transferred raw port into the {@link BridgePort} the engine's `connect(...)` consumes (started if able). */
1360
+ function wrapControlPortAsBridge(port: ControlPortLike): BridgePort {
1361
+ port.start?.();
1362
+ return {
1363
+ postMessage: (message, transfer) => port.postMessage(message, transfer),
1364
+ addEventListener: (type, listener) => port.addEventListener(type, listener),
1365
+ removeEventListener: (type, listener) => port.removeEventListener?.(type, listener),
1366
+ };
983
1367
  }
984
1368
 
985
1369
  /**
@@ -987,13 +1371,16 @@ interface WorkerGlobalScopeLike {
987
1371
  * tab, each carrying a port); a dedicated `DedicatedWorkerGlobalScope` has no `onconnect` but IS itself the
988
1372
  * single implicit port (`self.postMessage`/`addEventListener`). Neither exists in a plain test/Node context,
989
1373
  * where the host is driven via {@link SyncWorkerHost.connect} directly — so this is a no-op there.
1374
+ *
1375
+ * `globalScope` defaults to `globalThis` (the real worker binding); tests inject a fake scope to exercise the
1376
+ * dedicated-worker control-plane arm (ADR-0049 step 9) without a real Worker.
990
1377
  */
991
- function bindGlobalScope(connect: (port: BridgePort) => void): void {
992
- const scope = globalThis as unknown as WorkerGlobalScopeLike;
1378
+ export function bindGlobalScope(connect: (port: BridgePort) => void, globalScope: unknown = globalThis): void {
1379
+ const scope = globalScope as WorkerGlobalScopeLike;
993
1380
  const hasSharedWorkerScope =
994
- typeof (globalThis as { SharedWorkerGlobalScope?: unknown }).SharedWorkerGlobalScope !== "undefined";
1381
+ typeof (globalScope as { SharedWorkerGlobalScope?: unknown }).SharedWorkerGlobalScope !== "undefined";
995
1382
  const hasDedicatedWorkerScope =
996
- typeof (globalThis as { DedicatedWorkerGlobalScope?: unknown }).DedicatedWorkerGlobalScope !== "undefined";
1383
+ typeof (globalScope as { DedicatedWorkerGlobalScope?: unknown }).DedicatedWorkerGlobalScope !== "undefined";
997
1384
 
998
1385
  if (hasSharedWorkerScope) {
999
1386
  scope.onconnect = (event: SharedWorkerConnectEvent) => {
@@ -1003,11 +1390,384 @@ function bindGlobalScope(connect: (port: BridgePort) => void): void {
1003
1390
  return;
1004
1391
  }
1005
1392
  if (hasDedicatedWorkerScope && scope.postMessage && scope.addEventListener && scope.removeEventListener) {
1006
- // The dedicated worker's own global scope IS the single port.
1007
- connect({
1393
+ // The dedicated worker's own global scope IS the single implicit port (the tab's engine port). Wrap it as a
1394
+ // bridge port and connect it — the same engine serves that one port for the worker's whole lifetime.
1395
+ const scopePort: BridgePort = {
1008
1396
  postMessage: (message: unknown) => scope.postMessage!(message),
1009
1397
  addEventListener: (type, listener) => scope.addEventListener!(type, listener),
1010
1398
  removeEventListener: (type, listener) => scope.removeEventListener!(type, listener),
1399
+ };
1400
+ connect(scopePort);
1401
+ // ADR-0049 step 9 (elected engine home): the implicit port ALSO carries the control-channel DELIVERY
1402
+ // message. On it, start the engine's control plane — dynamic pipe acceptance, probe replies, and
1403
+ // retirement/teardown — all identity-tagged. The engine CORE is untouched: transferred pipes flow into the
1404
+ // SAME `connect` above. The scope port's own baseline connect is unchanged.
1405
+ // A repeat delivery REPLACES the live control plane (ADR-0049 step 11b follow-up 2): when the leader-keepalive
1406
+ // reconstructs a dead SharedWorker it re-announces with a FRESH control channel and re-delivers this engine's
1407
+ // end. Dispose the previous plane's listener first so stale traffic on the dead old channel is ignored; the
1408
+ // engine CORE (`connect`) is untouched — pipes still flow into the same engine.
1409
+ let disposeControlPlane: (() => void) | undefined;
1410
+ scope.addEventListener("message", (event: ScopeMessageEvent) => {
1411
+ if (!isControlPortDelivery(event.data)) return;
1412
+ const controlPort = event.ports?.[0];
1413
+ if (!controlPort) return;
1414
+ disposeControlPlane?.();
1415
+ disposeControlPlane = startEngineControlPlane(controlPort, connect, () => scope.close?.());
1011
1416
  });
1012
1417
  }
1013
1418
  }
1419
+
1420
+ // ─── ADR-0049 D1: the SharedWorker placement bootstrap ───────────────────────────────────────────────
1421
+ // The SharedWorker arm decides its ENGINE HOME once at startup and gates each tab connection on that decision:
1422
+ // `shared-worker` (SW-direct) connects the port to the in-scope engine host; `elected-worker` (router-only)
1423
+ // hands the port to a `createEngineRouter` and NEVER boots the engine in-scope. The probe is UNCONDITIONAL —
1424
+ // every scope runs `decideSwPlacement` — with ONE exception: a registry declaring `backend: "idbfs"`
1425
+ // (`deps.declaredIdbfs`) skips the probe and binds the in-SW engine host on idbfs (the declared mode). Both modes
1426
+ // answer a tab's PLACEMENT query and DESTROY peer-count query; SW-direct additionally answers `pgx0049` keepalive
1427
+ // pings on each port (the router owns those in elected mode). A dedicated-worker scope (the elected engine worker)
1428
+ // still routes through `bindGlobalScope` (the step-9 control plane), unchanged.
1429
+
1430
+ /**
1431
+ * The PLACEMENT-QUERY envelope key: a tab posts `{ [PLACEMENT_QUERY_KEY]: true }` on its SharedWorker
1432
+ * connection to learn the engine home; the SharedWorker replies `{ [PLACEMENT_RESULT_KEY]: PlacementQueryResult }`.
1433
+ * A distinct namespace from the data-path bridge envelope and the `pgx0049` control envelope, so it is
1434
+ * unambiguous on the shared tab↔SharedWorker transport (the attach client reads it off the raw message).
1435
+ */
1436
+ export const PLACEMENT_QUERY_KEY = "pgx0049Placement" as const;
1437
+ /** The reply to a {@link PLACEMENT_QUERY_KEY} query — carries the engine home, `electionRequired`, and SW id. */
1438
+ export const PLACEMENT_RESULT_KEY = "pgx0049PlacementResult" as const;
1439
+ /**
1440
+ * The DESTROY peer-count query key (ADR-0049 D8, plan fault row "`destroy()` with peers attached → refused").
1441
+ * A tab about to destroy the store posts `{ [DESTROY_QUERY_KEY]: true }`; the SharedWorker — which alone knows
1442
+ * the attached-tab count — replies `{ [DESTROY_VERDICT_KEY]: { peers } }`. `peers` INCLUDES the querying tab, so
1443
+ * `peers > 1` means other tabs still hold the store and destruction is refused.
1444
+ */
1445
+ export const DESTROY_QUERY_KEY = "pgx0049DestroyQuery" as const;
1446
+ /** The reply to a {@link DESTROY_QUERY_KEY} query — the attached-tab count (querying tab included). */
1447
+ export const DESTROY_VERDICT_KEY = "pgx0049DestroyVerdict" as const;
1448
+
1449
+ /** The placement a tab learns from the SharedWorker (the reply payload under {@link PLACEMENT_RESULT_KEY}). */
1450
+ export interface PlacementQueryResult {
1451
+ engineHome: SwPlacementResult["engineHome"];
1452
+ /** True in `elected-worker` mode — the tab's election coordinator must spawn the engine worker. */
1453
+ electionRequired: boolean;
1454
+ swInstanceId: string;
1455
+ /**
1456
+ * The SharedWorker's OWN script URL (`self.location.href`, ADR-0049 D5). In `elected-worker` mode the winning
1457
+ * tab constructs the elected engine as `new Worker(swScriptUrl, { type: "module" })` — the worker entry is
1458
+ * dual-scope (one file serves both homes), so no consumer wiring is needed; a `createEngineWorker` override is
1459
+ * only for entries that cannot be reconstructed from their URL as a module worker. Absent when the scope cannot
1460
+ * report its location (a plain test scope) — then a tab with no override fails attach with a typed wiring error.
1461
+ */
1462
+ swScriptUrl?: string;
1463
+ }
1464
+
1465
+ /** The SharedWorker placement bootstrap's dependencies (all injected so it is unit-testable off-worker). */
1466
+ export interface SharedWorkerBootstrapDeps {
1467
+ /** The engine host `connect` — used in SW-direct (`shared-worker`) placement to pipe a port to the in-scope engine. */
1468
+ connect: (port: BridgePort) => void;
1469
+ /** Quiesce and close the in-scope host before SW-direct destruction acknowledges handle release. */
1470
+ closeHost?: () => Promise<void>;
1471
+ /** Current attached-tab count for the DESTROY verdict in SW-direct mode (the host's own port set). */
1472
+ peerCount: () => number;
1473
+ /** The opt-in execution limit, threaded into the router in `elected-worker` (router-only) placement. */
1474
+ executionLimit?: ExecutionLimitConfig;
1475
+ /**
1476
+ * The registry declared `backend: "idbfs"` (ADR-0049 D1) — the ONE opt-out. TRUE: skip the probe entirely and
1477
+ * bind the in-SharedWorker engine host on the idbfs backend (the declared mode, not a fallback; the placement
1478
+ * query answers `electionRequired: false`). FALSE (the default, `backend: "opfs"`): run the UNCONDITIONAL
1479
+ * placement probe — a granted verdict boots the engine in-scope on OPFS-repacked, a denied one goes router-only
1480
+ * and each tab elects a dedicated engine worker.
1481
+ */
1482
+ declaredIdbfs?: boolean;
1483
+ /** Test seam: inject the placement decision (a fake probe result) instead of the real {@link decideSwPlacement}. */
1484
+ decidePlacement?: () => Promise<SwPlacementResult>;
1485
+ /** Defaults to `globalThis`; tests inject a fake SharedWorker scope. */
1486
+ globalScope?: unknown;
1487
+ /**
1488
+ * Notified once the placement grant for THIS scope resolves (SharedWorker decision, dedicated-engine probe, or
1489
+ * the plain-scope immediate settle). The entry threads `opfsGranted` into its `hasOpfsSyncAccess` boot grant and
1490
+ * `engineHome` into the BootReport, and opens its boot gate. `engineHome` is `undefined` for a plain test/Node
1491
+ * scope (no home) so the report omits it, exactly as before placement.
1492
+ */
1493
+ onPlacement?: (outcome: PlacementBootstrapOutcome) => void;
1494
+ /**
1495
+ * Test seam: inject the DEDICATED elected-engine scope's OPFS probe (a fake verdict) instead of the real
1496
+ * {@link probeOpfsSyncAccess}. Defaults to the real probe (invariant 8 — a real `createSyncAccessHandle` open in
1497
+ * the engine's own scope, per boot, never sniffed or cached).
1498
+ */
1499
+ probe?: () => Promise<PlacementProbeResult>;
1500
+ }
1501
+
1502
+ /** The resolved placement grant for a worker scope, threaded to the entry's boot grant + BootReport engine home. */
1503
+ export interface PlacementBootstrapOutcome {
1504
+ /** The engine home for this scope; `undefined` for a plain test/Node scope (the report then omits it). */
1505
+ engineHome: SwPlacementResult["engineHome"] | undefined;
1506
+ /** True when THIS scope actually holds OPFS sync-access (in-scope SW-direct, or the elected engine's own probe). */
1507
+ opfsGranted: boolean;
1508
+ /**
1509
+ * The verbatim reason this scope's engine opened IDBFS while OPFS was CAPABLE (ADR-0049 D1/D12, a
1510
+ * capability-absence fallback) — stamped into the boot's `storageFallbackReason`. Absent on a granted opfs boot
1511
+ * AND on the declared `backend: "idbfs"` mode (the contract, not a fallback).
1512
+ */
1513
+ storageFallbackReason?: string;
1514
+ }
1515
+
1516
+ /** Is this a raw `{ [PLACEMENT_QUERY_KEY]: true }` placement query? */
1517
+ function isPlacementQuery(data: unknown): boolean {
1518
+ return (
1519
+ typeof data === "object" &&
1520
+ data !== null &&
1521
+ (data as { [PLACEMENT_QUERY_KEY]?: unknown })[PLACEMENT_QUERY_KEY] === true
1522
+ );
1523
+ }
1524
+
1525
+ /** Is this a raw `{ [DESTROY_QUERY_KEY]: true }` destroy peer-count query? */
1526
+ function isDestroyQuery(data: unknown): boolean {
1527
+ return (
1528
+ typeof data === "object" && data !== null && (data as { [DESTROY_QUERY_KEY]?: unknown })[DESTROY_QUERY_KEY] === true
1529
+ );
1530
+ }
1531
+
1532
+ /**
1533
+ * Bootstrap the running worker scope for ADR-0049 placement. A SharedWorker scope runs the placement decision
1534
+ * and gates every `onconnect` port on it ({@link wireSharedWorkerPlacement}); any other scope (the dedicated
1535
+ * elected-engine worker, or a plain test/Node scope) delegates to {@link bindGlobalScope} unchanged. Called by
1536
+ * `defineSyncWorker` in place of the old direct `bindGlobalScope(connect)`.
1537
+ */
1538
+ export function bootstrapWorkerScope(deps: SharedWorkerBootstrapDeps): void {
1539
+ const globalScope = deps.globalScope ?? globalThis;
1540
+ const hasSharedWorkerScope =
1541
+ typeof (globalScope as { SharedWorkerGlobalScope?: unknown }).SharedWorkerGlobalScope !== "undefined";
1542
+ if (hasSharedWorkerScope) {
1543
+ if (deps.declaredIdbfs) {
1544
+ // ADR-0049 D1 declared opt-out (`backend: "idbfs"`): NEVER probe, NEVER go router-only — bind the in-SW
1545
+ // engine host on the idbfs backend (no OPFS grant). This is the store's DECLARED mode, not a fallback, so it
1546
+ // carries no `storageFallbackReason`. The meta listener answers the placement query `electionRequired: false`,
1547
+ // so a tab keeps the SW-port attach path.
1548
+ wireSharedWorkerPlacement(
1549
+ {
1550
+ ...deps,
1551
+ decidePlacement: () => Promise.resolve({ engineHome: "shared-worker", swInstanceId: crypto.randomUUID() }),
1552
+ },
1553
+ globalScope,
1554
+ false,
1555
+ );
1556
+ } else {
1557
+ // ADR-0049 D1 default (`backend: "opfs"`): run the UNCONDITIONAL placement probe. A granted probe boots the
1558
+ // engine in-SW on OPFS-repacked (SW-direct); a denied one goes router-only + election; a capability-absence
1559
+ // decision (`shared-worker` carrying `storageFallbackReason`) boots the in-SW idbfs fallback.
1560
+ wireSharedWorkerPlacement(deps, globalScope, true);
1561
+ }
1562
+ return;
1563
+ }
1564
+ const hasDedicatedWorkerScope =
1565
+ typeof (globalScope as { DedicatedWorkerGlobalScope?: unknown }).DedicatedWorkerGlobalScope !== "undefined";
1566
+ if (hasDedicatedWorkerScope) {
1567
+ // ADR-0049 D1 (elected engine self-probe): the elected DEDICATED engine holds OPFS access in its OWN scope, so
1568
+ // it probes THIS scope's real `createSyncAccessHandle` (invariant 8 — per boot, never sniffed/cached) and
1569
+ // threads the verdict as the `elected-worker` home's OPFS grant, opening the boot gate. The step-9 control plane
1570
+ // (dynamic pipe acceptance, probe replies, teardown) is still wired by `bindGlobalScope`, unchanged. A DENIED
1571
+ // dedicated probe is capability absence in this home: the engine opens idbfs, and the outcome carries a verbatim
1572
+ // `storageFallbackReason` so the boot's BootReport shows the fallback (decision 12) rather than a silent idb.
1573
+ bindGlobalScope(deps.connect, globalScope);
1574
+ const probe = deps.probe ?? probeOpfsSyncAccess;
1575
+ void probe().then(
1576
+ (result) =>
1577
+ deps.onPlacement?.({
1578
+ engineHome: "elected-worker",
1579
+ opfsGranted: result.granted,
1580
+ ...(result.granted
1581
+ ? {}
1582
+ : { storageFallbackReason: `elected engine OPFS probe denied (${result.error ?? "no attribution"})` }),
1583
+ }),
1584
+ // The probe answers (never rejects); this guard only protects against an injected fake that throws — still
1585
+ // open the gate with no grant so the boot cannot deadlock, falling back to the honest idb backend.
1586
+ () =>
1587
+ deps.onPlacement?.({
1588
+ engineHome: "elected-worker",
1589
+ opfsGranted: false,
1590
+ storageFallbackReason: "elected engine OPFS probe threw",
1591
+ }),
1592
+ );
1593
+ return;
1594
+ }
1595
+ // A plain test/Node scope: no engine home, no OPFS grant — settle the gate immediately (no browser placement).
1596
+ bindGlobalScope(deps.connect, globalScope);
1597
+ deps.onPlacement?.({ engineHome: undefined, opfsGranted: false });
1598
+ }
1599
+
1600
+ /**
1601
+ * Wire the SharedWorker arm for placement (ADR-0049 D1). Decides the engine home ONCE, then per `onconnect` port:
1602
+ * installs a meta listener answering the placement + destroy-peer queries (and, on SW-direct, the `pgx0049`
1603
+ * keepalive ping), and routes the port to the engine host (`shared-worker`) or the router (`elected-worker`).
1604
+ * Ports that connect BEFORE the (async) decision resolves are buffered and drained on resolve — the engine host is
1605
+ * never touched in `elected-worker` mode until (and unless) the capability-absence fallback flips it to SW-direct.
1606
+ */
1607
+ function wireSharedWorkerPlacement(
1608
+ deps: SharedWorkerBootstrapDeps,
1609
+ globalScope: unknown,
1610
+ /** Whether a GRANTED `shared-worker` home holds the OPFS grant — TRUE in the default probing mode (a granted
1611
+ probe placed the engine in-scope on OPFS-repacked), FALSE in the declared `backend: "idbfs"` mode (no probe
1612
+ ran). A capability-absence fallback (`shared-worker` carrying `storageFallbackReason`) is idbfs regardless. */
1613
+ opfsGrantedForSharedHome: boolean,
1614
+ ): void {
1615
+ const scope = globalScope as WorkerGlobalScopeLike;
1616
+ const decide = deps.decidePlacement ?? (() => decideSwPlacement());
1617
+ // The SharedWorker's own script URL (ADR-0049 D5) — reported in the placement reply so the winning tab can
1618
+ // construct the elected engine as `new Worker(swScriptUrl, { type: "module" })` with no consumer wiring. Absent
1619
+ // when the scope cannot report its location (a plain test scope); a tab with no override then fails attach typed.
1620
+ const swScriptUrl = (globalScope as { location?: { href?: string } }).location?.href;
1621
+ let placement: SwPlacementResult | undefined;
1622
+ let router: EngineRouter | undefined;
1623
+ const pendingPorts: BridgePort[] = [];
1624
+ let sharedHostTeardown: Promise<{ error?: { message: string; detail?: unknown } }> | undefined;
1625
+
1626
+ const currentPeerCount = (): number =>
1627
+ placement?.engineHome === "elected-worker" ? (router?.tabCount() ?? 0) : deps.peerCount();
1628
+
1629
+ const attachPort = (port: BridgePort): void => {
1630
+ const current = placement!;
1631
+ // The meta listener answers the placement + destroy-peer queries on EVERY port (both modes) and, per mode:
1632
+ // - SW-direct: the `pgx0049` keepalive control-ping (the router owns that in elected mode).
1633
+ // - elected: the tab's `engine-announce` — the SW-side translation into `router.announceEngine`, handing
1634
+ // the transferred router-end control port to the router so it stamps an identity + pipes the tabs (the
1635
+ // router itself does not react to `engine-announce`; the SharedWorker scope drives it).
1636
+ // It coexists with the host's / router's own listener on the same port: each ignores the other's traffic.
1637
+ const metaListener = (event: { data: unknown; ports?: readonly ControlPortLike[] }): void => {
1638
+ const data = event.data;
1639
+ if (isPlacementQuery(data)) {
1640
+ // Read `placement` LIVE (not the captured `current`): a capability-absence fallback can flip a router-only
1641
+ // scope to `shared-worker` after this port attached, and the reply must reflect the current home + carry
1642
+ // the SharedWorker's own script URL (ADR-0049 D5) for the tab's engine auto-derivation.
1643
+ const live = placement ?? current;
1644
+ port.postMessage({
1645
+ [PLACEMENT_RESULT_KEY]: {
1646
+ engineHome: live.engineHome,
1647
+ electionRequired: live.engineHome === "elected-worker",
1648
+ swInstanceId: live.swInstanceId,
1649
+ ...(swScriptUrl !== undefined ? { swScriptUrl } : {}),
1650
+ } satisfies PlacementQueryResult,
1651
+ });
1652
+ return;
1653
+ }
1654
+ if (isDestroyQuery(data)) {
1655
+ port.postMessage({ [DESTROY_VERDICT_KEY]: { peers: currentPeerCount() } });
1656
+ return;
1657
+ }
1658
+ const control = readControlEnvelope(data);
1659
+ if (current.engineHome === "shared-worker") {
1660
+ if (control?.type === "control-ping") {
1661
+ port.postMessage(
1662
+ controlEnvelope({ type: "control-ack", identity: control.identity, pingId: control.pingId }),
1663
+ );
1664
+ return;
1665
+ }
1666
+ if (control?.type === "engine-teardown") {
1667
+ const sharedIdentity: EngineIdentity = { swInstanceId: current.swInstanceId, generation: 0 };
1668
+ if (!shouldApplyControlMessage(sharedIdentity, control)) return;
1669
+ // SW-direct destruction is supervised by the tab, but the exclusive store handles live here. Close
1670
+ // the in-scope host first; only the reserved teardown ack proves that quiescence to the tab. The
1671
+ // SharedWorker scope then closes itself so a later attach starts a fresh, rebootable host even when
1672
+ // `extendedLifetime` would otherwise retain this closed scope.
1673
+ sharedHostTeardown ??= Promise.resolve()
1674
+ .then(() => deps.closeHost?.())
1675
+ .then(
1676
+ () => ({}),
1677
+ (error: unknown) => ({ error: serializeError(error) }),
1678
+ );
1679
+ void sharedHostTeardown.then((result) => {
1680
+ port.postMessage(
1681
+ controlEnvelope({
1682
+ type: "control-ack",
1683
+ identity: sharedIdentity,
1684
+ pingId: -1,
1685
+ ...(result.error ? { error: result.error } : {}),
1686
+ }),
1687
+ );
1688
+ // A task boundary, not merely a microtask: give the posted success/failure acknowledgement a delivery
1689
+ // turn before closing the SharedWorker global. A close failure poisons this lifetime just as surely as
1690
+ // a successful close retires it; never retain a rejected teardown promise in a live scope.
1691
+ globalThis.setTimeout(() => scope.close?.(), 0);
1692
+ });
1693
+ }
1694
+ return;
1695
+ }
1696
+ // elected-worker (router-only): the tab's coordinator drives leadership over this port.
1697
+ // - `leader-granted`: the newly-granted leader is about to (re)spawn its engine. Open the router's handoff
1698
+ // window NOW (fan `leader-granted` to EVERY tab) so in-flight ops settle by outcome and new ops QUEUE
1699
+ // across the spawn→announce→pipe gap, then flush onto the fresh pipe (invariants 5 + 9). Without this the
1700
+ // coordinator's `leader-granted` was DROPPED here, so on a leadership change (succession) a tab kept
1701
+ // dispatching onto the DEAD engine's pipe until the replacement pipe arrived — the elected-flow gap the
1702
+ // step-12 succession/relocation lanes surfaced (the router already owned `openHandoff`; nothing called it).
1703
+ // - `engine-announce`: translate into `router.announceEngine`, handing the transferred router-end control
1704
+ // port to the router so it stamps an identity + pipes the tabs (the router does not react to it itself).
1705
+ if (control?.type === "leader-granted") {
1706
+ router!.openHandoff("leader-granted");
1707
+ return;
1708
+ }
1709
+ if (control?.type === "engine-announce") {
1710
+ const announced = event.ports?.[0];
1711
+ if (announced) router!.announceEngine(announced as unknown as RouterPort);
1712
+ return;
1713
+ }
1714
+ // ADR-0049 D1 capability-absence fallback: the tab's elected DEDICATED engine probed its OWN scope and was
1715
+ // DENIED — no home on this platform can hold sync-access handles. Abandon election and boot the IN-SCOPE
1716
+ // idbfs engine here (with the registry-declared durability), stamping the reported reason into the fallback
1717
+ // boot's `storageFallbackReason` (decision 12). This tab's port is connected to the in-scope host now; other
1718
+ // tabs re-establish through their placement re-query on reconnect.
1719
+ if (control?.type === "engine-fallback") {
1720
+ fallBackToIdbfs(control.reason, port);
1721
+ }
1722
+ };
1723
+ port.addEventListener("message", metaListener);
1724
+ port.start?.();
1725
+ if (current.engineHome === "shared-worker") {
1726
+ deps.connect(port);
1727
+ } else {
1728
+ router!.attachTab(port as unknown as RouterPort);
1729
+ }
1730
+ };
1731
+
1732
+ // ADR-0049 D1: flip a router-only (`elected-worker`) scope to the in-SharedWorker IDBFS fallback when the elected
1733
+ // engine reports its own probe was denied (capability absence in every home). Idempotent — the first report wins.
1734
+ // Re-threads the placement onto the entry (so the lazily-booting in-scope engine opens idbfs with the fallback
1735
+ // reason) and connects the reporting tab's port to the in-scope host. Peer tabs re-establish via placement re-query.
1736
+ let fellBack = false;
1737
+ const fallBackToIdbfs = (reason: string, reportingPort: BridgePort): void => {
1738
+ if (fellBack) return;
1739
+ fellBack = true;
1740
+ placement = { engineHome: "shared-worker", swInstanceId: placement?.swInstanceId ?? crypto.randomUUID() };
1741
+ deps.onPlacement?.({ engineHome: "shared-worker", opfsGranted: false, storageFallbackReason: reason });
1742
+ deps.connect(reportingPort);
1743
+ };
1744
+
1745
+ void decide().then((result) => {
1746
+ placement = result;
1747
+ // `shared-worker` ⇒ the engine boots in-scope: holding OPFS access on a GRANTED probe, or on IDBFS with a
1748
+ // `storageFallbackReason` when the decision is a capability-absence fallback. `elected-worker` ⇒ router-only, no
1749
+ // in-scope grant (each tab's elected DEDICATED engine probes its own scope). Thread grant + home + fallback
1750
+ // reason, open the boot gate. The fallback is idbfs regardless of `opfsGrantedForSharedHome`.
1751
+ const isSharedFallback = result.engineHome === "shared-worker" && result.storageFallbackReason !== undefined;
1752
+ deps.onPlacement?.({
1753
+ engineHome: result.engineHome,
1754
+ opfsGranted: result.engineHome === "shared-worker" && opfsGrantedForSharedHome && !isSharedFallback,
1755
+ ...(isSharedFallback ? { storageFallbackReason: result.storageFallbackReason } : {}),
1756
+ });
1757
+ if (result.engineHome === "elected-worker") {
1758
+ router = createEngineRouter({
1759
+ swInstanceId: result.swInstanceId,
1760
+ ...(deps.executionLimit ? { executionLimit: deps.executionLimit } : {}),
1761
+ });
1762
+ }
1763
+ for (const port of pendingPorts) attachPort(port);
1764
+ pendingPorts.length = 0;
1765
+ });
1766
+
1767
+ scope.onconnect = (event: SharedWorkerConnectEvent) => {
1768
+ const port = event.ports[0];
1769
+ if (!port) return;
1770
+ if (placement === undefined) pendingPorts.push(port);
1771
+ else attachPort(port);
1772
+ };
1773
+ }