@pgxsinkit/client 0.2.0 → 0.2.2

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.
@@ -9,8 +9,22 @@
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";
13
- import { getSyncRegistryStorage } 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";
14
28
 
15
29
  import { type ConvergenceTrigger, createIntervalConvergenceTrigger } from "../convergence";
16
30
  import { setSyncDebugSink, syncDebug } from "../debug";
@@ -57,6 +71,7 @@ import {
57
71
  type BridgeCodec,
58
72
  type BridgeEnvelope,
59
73
  type BridgeEvent,
74
+ type BridgeErrorWire,
60
75
  type BridgePort,
61
76
  type ExportArtefactWire,
62
77
  type GuardedQueryWireArgs,
@@ -276,17 +291,30 @@ export function defineSyncWorker<const TRegistry extends SyncTableRegistry>(
276
291
  const placementGate = new Promise<void>((resolve) => {
277
292
  openPlacementGate = resolve;
278
293
  });
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";
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";
284
312
  const createPglite =
285
313
  options.createPglite ??
286
314
  ((storePath: string, backendOverride?: "memory") =>
287
315
  createClientPGlite(storePath, {
288
316
  ...(backendOverride ? { backendOverride } : {}),
289
- durability: provisionDurability,
317
+ durability: currentDurability(),
290
318
  // SW-direct placement grant (ADR-0049 D1): a spare minted in-scope opens OPFS-repacked, matching the boot.
291
319
  ...(placementOpfsAccess ? { hasOpfsSyncAccess: true } : {}),
292
320
  }));
@@ -456,8 +484,8 @@ export function defineSyncWorker<const TRegistry extends SyncTableRegistry>(
456
484
  // exactly once off the booted client's stage promises (`milestonesWired`), then driven purely by them.
457
485
  const milestones = { writeReady: false, bootSettled: false };
458
486
  const stageErrors: {
459
- writeReady?: { message: string; detail?: unknown };
460
- bootSettled?: { message: string; detail?: unknown };
487
+ writeReady?: BridgeErrorWire;
488
+ bootSettled?: BridgeErrorWire;
461
489
  } = {};
462
490
  let milestonesWired = false;
463
491
  const markMilestone = (stage: BootMilestone) => {
@@ -501,6 +529,17 @@ export function defineSyncWorker<const TRegistry extends SyncTableRegistry>(
501
529
  // Resolve the registry from the attach's role (ADR-0032 S3): a single worker file bakes both variants
502
530
  // and the claim/attach settles which one boots — the spare was provisioned before the role was known.
503
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
+ }
504
543
  // storePath-first, matching the `provision` handler's resolution (below): the board sends BOTH a bare
505
544
  // `storeId` (SharedWorker naming, tab-side) AND the real `storePath` (`pgxsinkit-board-<id>`), and the
506
545
  // PGlite store lives at `storePath` — so the provisioned store's path must be what we adopt on.
@@ -565,8 +604,11 @@ export function defineSyncWorker<const TRegistry extends SyncTableRegistry>(
565
604
  // the in-process client. Worker-entry options, not attach options: functions cannot cross the bridge.
566
605
  ...(options.prepareLocalDbBeforeSchema ? { prepareLocalDbBeforeSchema: options.prepareLocalDbBeforeSchema } : {}),
567
606
  ...(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.
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 } : {}),
570
612
  // SW-direct placement grant (ADR-0049 D1): thread a GRANTED probe's grant into the boot create so the engine
571
613
  // home in this SharedWorker scope opens the OPFS-repacked backend. Absent (false) is the honest IDBFS home —
572
614
  // the declared `backend: "idbfs"` mode or a capability-absence fallback. `createSyncClient` forwards it to
@@ -898,6 +940,18 @@ export function defineSyncWorker<const TRegistry extends SyncTableRegistry>(
898
940
  // The testing memory-backend override rides as an explicit wire field (ADR-0036) — a symbol does not
899
941
  // survive structured clone, so the store's backend selection travels here and is passed to createPglite.
900
942
  const backendOverride = provision.testStoreBackend;
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
+ }
901
955
  if (bootPromise != null || provisioned != null || provisionAttempt != null) {
902
956
  postBridgeMessage(port, codec, "provision-ack", {
903
957
  ok: true,
@@ -978,6 +1032,16 @@ export function defineSyncWorker<const TRegistry extends SyncTableRegistry>(
978
1032
  // attach's boot runs, so the boot's own lines (streamed live) are not doubled.
979
1033
  replayRailBufferTo(port);
980
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
+ }
981
1045
  // Restore rides the FIRST (boot) attach only (ADR-0035 decision 6): a restore attach that arrives once
982
1046
  // the engine has already booted CANNOT be honoured — `loadDataDir` is a create-time seed and the store
983
1047
  // is already live. Reject THIS attach with a typed error rather than silently ignoring the backup, so
@@ -985,7 +1049,11 @@ export function defineSyncWorker<const TRegistry extends SyncTableRegistry>(
985
1049
  if (alreadyBooted && attach.restore != null) {
986
1050
  postBridgeMessage(port, codec, "attach-ack", {
987
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.
988
1055
  error: {
1056
+ name: "RestoreIntoRunningStoreError",
989
1057
  message:
990
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.",
991
1059
  },
@@ -1150,9 +1218,29 @@ export function defineSyncWorker<const TRegistry extends SyncTableRegistry>(
1150
1218
  }
1151
1219
  };
1152
1220
 
1153
- 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 }) => {
1154
1224
  ports.add(port);
1155
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
+ }
1156
1244
  if (isBridgeEnvelope(event.data) && event.data.type === "detach") {
1157
1245
  detachPort(port);
1158
1246
  port.removeEventListener("message", listener);
@@ -1165,35 +1253,71 @@ export function defineSyncWorker<const TRegistry extends SyncTableRegistry>(
1165
1253
  };
1166
1254
 
1167
1255
  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();
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 });
1278
+ // Quiesce pending subscribes FIRST (ADR-0040 decision 1 — the pending-before-manager race): flip
1279
+ // `closing`, mark every mid-await subscribe cancelled, and await every in-flight `handleSubscribe` task.
1280
+ // This guarantees the manager exists (if any subscribe created one) BEFORE `dispose()` runs, and that no
1281
+ // subscribe can create a registration afterwards — each resumes into the `closing` early-bail instead.
1282
+ closing = true;
1283
+ for (const pending of pendingSubscribes.values()) pending.cancelled = true;
1284
+ retirementPhase("pending-subscriptions-wait-started", { count: inFlightSubscribes.size });
1285
+ await Promise.allSettled([...inFlightSubscribes]);
1286
+ retirementPhase("pending-subscriptions-wait-completed");
1287
+ // Dispose the manager BEFORE `active.stop()` (ADR-0040 decision 1): it tears down every remaining live
1288
+ // registration and awaits ALL teardowns, so no fire-and-forget unsubscribe is still in flight when the
1289
+ // engine closes (the close-vs-unsubscribe hang). No-op when nothing ever subscribed.
1290
+ liveSubs.clear();
1291
+ retirementPhase("live-query-disposal-started");
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 {
1304
+ ports.clear();
1305
+ setSyncDebugSink(undefined);
1306
+ }
1184
1307
  };
1185
1308
 
1186
1309
  // ─── Global-scope auto-binding (real worker only; tests inject ports via 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.
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.
1192
1317
  //
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";
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);
1197
1321
  if (options.installGlobal === false) {
1198
1322
  // No global bootstrap runs (a plain host driven via `connect` in tests) — open the placement gate at once so
1199
1323
  // the first boot proceeds with no OPFS grant and no engine home (a plain scope has no browser placement).
@@ -1203,8 +1327,9 @@ export function defineSyncWorker<const TRegistry extends SyncTableRegistry>(
1203
1327
  connect,
1204
1328
  closeHost,
1205
1329
  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,
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 } : {}),
1208
1333
  ...(options.executionLimit ? { executionLimit: options.executionLimit } : {}),
1209
1334
  onPlacement: (outcome) => {
1210
1335
  // The resolved OPFS grant + engine home for THIS scope: the SharedWorker placement decision (`shared-worker`
@@ -1228,14 +1353,22 @@ export function defineSyncWorker<const TRegistry extends SyncTableRegistry>(
1228
1353
  };
1229
1354
  }
1230
1355
 
1231
- /** Serialize a thrown value into the bridge's `{message, detail}` error shape (detail only when structured). */
1232
- 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 {
1233
1362
  if (error instanceof ExecutionLimitMismatchError) {
1234
1363
  return { message: error.message, detail: executionLimitMismatchToWire(error) };
1235
1364
  }
1236
1365
  if (error instanceof Error) {
1237
1366
  const detail = (error as Error & { detail?: unknown }).detail;
1238
- 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
+ };
1239
1372
  }
1240
1373
  return { message: String(error) };
1241
1374
  }
@@ -1445,6 +1578,29 @@ export const PLACEMENT_RESULT_KEY = "pgx0049PlacementResult" as const;
1445
1578
  export const DESTROY_QUERY_KEY = "pgx0049DestroyQuery" as const;
1446
1579
  /** The reply to a {@link DESTROY_QUERY_KEY} query — the attached-tab count (querying tab included). */
1447
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
+ }
1448
1604
 
1449
1605
  /** The placement a tab learns from the SharedWorker (the reply payload under {@link PLACEMENT_RESULT_KEY}). */
1450
1606
  export interface PlacementQueryResult {
@@ -1465,7 +1621,7 @@ export interface PlacementQueryResult {
1465
1621
  /** The SharedWorker placement bootstrap's dependencies (all injected so it is unit-testable off-worker). */
1466
1622
  export interface SharedWorkerBootstrapDeps {
1467
1623
  /** 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;
1624
+ connect: (port: BridgePort, connection?: { placementQueriesHandled?: boolean }) => void;
1469
1625
  /** Quiesce and close the in-scope host before SW-direct destruction acknowledges handle release. */
1470
1626
  closeHost?: () => Promise<void>;
1471
1627
  /** Current attached-tab count for the DESTROY verdict in SW-direct mode (the host's own port set). */
@@ -1473,13 +1629,14 @@ export interface SharedWorkerBootstrapDeps {
1473
1629
  /** The opt-in execution limit, threaded into the router in `elected-worker` (router-only) placement. */
1474
1630
  executionLimit?: ExecutionLimitConfig;
1475
1631
  /**
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.
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).
1481
1638
  */
1482
- declaredIdbfs?: boolean;
1639
+ staticStorage?: SyncStorageDeclaration;
1483
1640
  /** Test seam: inject the placement decision (a fake probe result) instead of the real {@link decideSwPlacement}. */
1484
1641
  decidePlacement?: () => Promise<SwPlacementResult>;
1485
1642
  /** Defaults to `globalThis`; tests inject a fake SharedWorker scope. */
@@ -1529,6 +1686,25 @@ function isDestroyQuery(data: unknown): boolean {
1529
1686
  );
1530
1687
  }
1531
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
+
1532
1708
  /**
1533
1709
  * Bootstrap the running worker scope for ADR-0049 placement. A SharedWorker scope runs the placement decision
1534
1710
  * and gates every `onconnect` port on it ({@link wireSharedWorkerPlacement}); any other scope (the dedicated
@@ -1540,25 +1716,11 @@ export function bootstrapWorkerScope(deps: SharedWorkerBootstrapDeps): void {
1540
1716
  const hasSharedWorkerScope =
1541
1717
  typeof (globalScope as { SharedWorkerGlobalScope?: unknown }).SharedWorkerGlobalScope !== "undefined";
1542
1718
  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
- }
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);
1562
1724
  return;
1563
1725
  }
1564
1726
  const hasDedicatedWorkerScope =
@@ -1597,21 +1759,31 @@ export function bootstrapWorkerScope(deps: SharedWorkerBootstrapDeps): void {
1597
1759
  deps.onPlacement?.({ engineHome: undefined, opfsGranted: false });
1598
1760
  }
1599
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
+
1600
1775
  /**
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.
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.
1606
1785
  */
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 {
1786
+ function wireSharedWorkerPlacement(deps: SharedWorkerBootstrapDeps, globalScope: unknown): void {
1615
1787
  const scope = globalScope as WorkerGlobalScopeLike;
1616
1788
  const decide = deps.decidePlacement ?? (() => decideSwPlacement());
1617
1789
  // The SharedWorker's own script URL (ADR-0049 D5) — reported in the placement reply so the winning tab can
@@ -1620,15 +1792,100 @@ function wireSharedWorkerPlacement(
1620
1792
  const swScriptUrl = (globalScope as { location?: { href?: string } }).location?.href;
1621
1793
  let placement: SwPlacementResult | undefined;
1622
1794
  let router: EngineRouter | undefined;
1623
- const pendingPorts: BridgePort[] = [];
1624
- let sharedHostTeardown: Promise<{ error?: { message: string; detail?: unknown } }> | 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;
1625
1805
 
1626
1806
  const currentPeerCount = (): number =>
1627
1807
  placement?.engineHome === "elected-worker" ? (router?.tabCount() ?? 0) : deps.peerCount();
1628
1808
 
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:
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:
1632
1889
  // - SW-direct: the `pgx0049` keepalive control-ping (the router owns that in elected mode).
1633
1890
  // - elected: the tab's `engine-announce` — the SW-side translation into `router.announceEngine`, handing
1634
1891
  // the transferred router-end control port to the router so it stamps an identity + pipes the tabs (the
@@ -1636,27 +1893,48 @@ function wireSharedWorkerPlacement(
1636
1893
  // It coexists with the host's / router's own listener on the same port: each ignores the other's traffic.
1637
1894
  const metaListener = (event: { data: unknown; ports?: readonly ControlPortLike[] }): void => {
1638
1895
  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
- });
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
+ );
1652
1923
  return;
1653
1924
  }
1654
- if (isDestroyQuery(data)) {
1655
- port.postMessage({ [DESTROY_VERDICT_KEY]: { peers: currentPeerCount() } });
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
+ }
1656
1934
  return;
1657
1935
  }
1658
1936
  const control = readControlEnvelope(data);
1659
- if (current.engineHome === "shared-worker") {
1937
+ if (placement.engineHome === "shared-worker") {
1660
1938
  if (control?.type === "control-ping") {
1661
1939
  port.postMessage(
1662
1940
  controlEnvelope({ type: "control-ack", identity: control.identity, pingId: control.pingId }),
@@ -1664,7 +1942,7 @@ function wireSharedWorkerPlacement(
1664
1942
  return;
1665
1943
  }
1666
1944
  if (control?.type === "engine-teardown") {
1667
- const sharedIdentity: EngineIdentity = { swInstanceId: current.swInstanceId, generation: 0 };
1945
+ const sharedIdentity: EngineIdentity = { swInstanceId: placement.swInstanceId, generation: 0 };
1668
1946
  if (!shouldApplyControlMessage(sharedIdentity, control)) return;
1669
1947
  // SW-direct destruction is supervised by the tab, but the exclusive store handles live here. Close
1670
1948
  // the in-scope host first; only the reserved teardown ack proves that quiescence to the tab. The
@@ -1722,11 +2000,6 @@ function wireSharedWorkerPlacement(
1722
2000
  };
1723
2001
  port.addEventListener("message", metaListener);
1724
2002
  port.start?.();
1725
- if (current.engineHome === "shared-worker") {
1726
- deps.connect(port);
1727
- } else {
1728
- router!.attachTab(port as unknown as RouterPort);
1729
- }
1730
2003
  };
1731
2004
 
1732
2005
  // ADR-0049 D1: flip a router-only (`elected-worker`) scope to the in-SharedWorker IDBFS fallback when the elected
@@ -1739,35 +2012,75 @@ function wireSharedWorkerPlacement(
1739
2012
  fellBack = true;
1740
2013
  placement = { engineHome: "shared-worker", swInstanceId: placement?.swInstanceId ?? crypto.randomUUID() };
1741
2014
  deps.onPlacement?.({ engineHome: "shared-worker", opfsGranted: false, storageFallbackReason: reason });
1742
- deps.connect(reportingPort);
2015
+ deps.connect(reportingPort, { placementQueriesHandled: true });
1743
2016
  };
1744
2017
 
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
- });
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();
1762
2033
  }
1763
- for (const port of pendingPorts) attachPort(port);
1764
- pendingPorts.length = 0;
1765
- });
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
+ }
2066
+ });
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
+ }
1766
2075
 
1767
2076
  scope.onconnect = (event: SharedWorkerConnectEvent) => {
1768
2077
  const port = event.ports[0];
1769
2078
  if (!port) return;
1770
- if (placement === undefined) pendingPorts.push(port);
1771
- else attachPort(port);
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);
1772
2085
  };
1773
2086
  }