@pgxsinkit/client 0.2.2 → 0.2.3

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.
@@ -30,7 +30,6 @@ import { type ConvergenceTrigger, createIntervalConvergenceTrigger } from "../co
30
30
  import { setSyncDebugSink, syncDebug } from "../debug";
31
31
  import { describeErrorChain } from "../error-chain";
32
32
  import {
33
- type AdoptionDeclaration,
34
33
  type ClientPGlite,
35
34
  createClientPGlite,
36
35
  type CreateSyncClientOptions,
@@ -44,8 +43,9 @@ import {
44
43
  } from "../index";
45
44
  import { wrapLiveQueryForMaterialization } from "../live-rows-sql";
46
45
  import type { LocalStoreVersionEvent } from "../local-store";
46
+ import { createOpfsEffects } from "../opfs-effects";
47
47
  import { type PlacementProbeResult, probeOpfsSyncAccess } from "../placement-probe";
48
- import { META_STORE_UNAVAILABLE, readStoreMetaRecord } from "../store-meta";
48
+ import { idbStoreExists, META_STORE_UNAVAILABLE, readStoreMetaRecord, writeStoreMetaRecord } from "../store-meta";
49
49
  import { readTestStoreMarker, TEST_STORE_BACKEND, type TestStoreMarker } from "../store-path";
50
50
  import {
51
51
  assertSameExecutionLimit,
@@ -133,17 +133,6 @@ export interface DefineSyncWorkerOptions<TRegistry extends SyncTableRegistry> {
133
133
  * Takes a plain store PATH (ADR-0036); the internal `backendOverride` is the test lane's memory selection.
134
134
  */
135
135
  createPglite?: (storePath: string, backendOverride?: "memory") => Promise<ClientPGlite>;
136
- /**
137
- * ADR-0049 (capability-driven engine placement) decision 7, plan step 11b: the consumer's explicit
138
- * reconstructibility DECLARATION authorizing AUTOMATIC adoption of an existing idb-authoritative store into a
139
- * committed OPFS successor. A worker-ENTRY option (baked into the worker file as code, like
140
- * {@link executionLimit}), NEVER an attach option — a tab cannot set it (adoption DELETES local-only data, so
141
- * only the code author may authorize it). Forwarded verbatim to the {@link createSyncClient} boot below. DEFAULT
142
- * OFF (`undefined`): hook absence is never authority — only `"server-reconstructible"` (or the manual
143
- * `adoptStore` API) authorizes deleting the idb predecessor. Honoured only where the engine home grants OPFS
144
- * access (SW-direct / elected placement); inert on the browser-idb fallback where there is no opfs successor.
145
- */
146
- adoption?: AdoptionDeclaration;
147
136
  electricUrl: string;
148
137
  batchWriteUrl: string;
149
138
  /** Static headers on every read + write request (e.g. a gateway `apikey`). See `createSyncClient`. */
@@ -618,10 +607,6 @@ export function defineSyncWorker<const TRegistry extends SyncTableRegistry>(
618
607
  // engine boots IDBFS and stamps this verbatim reason into the BootReport's `storageFallbackReason`. Absent
619
608
  // on a granted opfs boot and on the declared-idbfs mode (which is the contract, not a fallback).
620
609
  ...(placementFallbackReason ? { storageFallbackReason: placementFallbackReason } : {}),
621
- // Adoption declaration (ADR-0049 D7, step 11b): a worker-entry option (never attach-controlled). When the
622
- // engine home grants OPFS access, an existing idb-authoritative store is migrated to a committed opfs
623
- // successor at boot. Default off (absent) — nothing is ever deleted without this explicit declaration.
624
- ...(options.adoption ? { adoption: options.adoption } : {}),
625
610
  // Fresh-store prefetch overlap (ADR-0032 S4): the tab's claim path proved this store a schemaless
626
611
  // spare and forwarded the hint in the attach config, so the shape catch-up overlaps schema exec +
627
612
  // journal recovery + registry reconciliation. Never inferred from "adopting a provisioned store": the board
@@ -965,19 +950,97 @@ export function defineSyncWorker<const TRegistry extends SyncTableRegistry>(
965
950
  // holds access to, not idbfs, so the adopting boot backend matches its engine home. Opens the gate at
966
951
  // once for SW-direct / plain scopes (already settled before any port connects).
967
952
  const attempt = placementGate.then(async () => {
968
- // Provision is only an accelerator, never an authority-recovery path. Read the meta record on EVERY
969
- // persistent placement before minting. If deletion is live, decline the pre-mint and let the first
970
- // attach run createSyncClient's full ordinary phase machine. This closes both granted and denied lanes:
971
- // no replacement (and therefore no journal) can be created beneath a record a later boot must delete.
953
+ // Provision is only an accelerator, never an authority-recovery path: it proceeds ONLY on state the
954
+ // adopting boot would open IDENTICALLY, and DECLINES everything else, leaving the first attach's
955
+ // `createSyncClient` phase machine — the one recovery authority — to own it. The gate follows THIS
956
+ // scope's placement, because the two lanes consult the record differently:
957
+ //
958
+ // GRANTED lane (this scope holds OPFS handles — the full clean-state matrix):
959
+ // - record `opfs-committed` → mint (the warm-reopen accelerator: the factory opens the committed store).
960
+ // - NO record, the commitment namespace is a PROVABLE VIRGIN (no sentinel, no store directory), AND
961
+ // no idb store exists at this path → record `opfs-candidate` BEFORE the mint creates the directory
962
+ // (record-before-directory, invariant 12), then mint. The adopting boot's commitment barrier
963
+ // promotes that candidate to `opfs-committed` pre-expose, so no store is ever left uncommitted.
964
+ // The idb check is load-bearing: a store's backend is fixed at first mint, so a granted home over
965
+ // an existing idb store opens it `idb-authoritative` — an OPFS candidate here would commit an
966
+ // EMPTY store over the user's data.
967
+ // - ANY other state — a live `deleting` authority, a torn `opfs-candidate`, an `idb-authoritative`
968
+ // record, an existing idb store, or recordless residue in the commitment namespace — → DECLINE. No
969
+ // replacement (and therefore no journal) may be created beneath state a later boot must resolve.
970
+ //
971
+ // NO-GRANT lane (the idb provision lane): decline on `deleting`, `opfs-candidate` and
972
+ // `opfs-committed`. A no-grant boot is RECORD-BLIND apart from those three — `resolveFreshBoot`
973
+ // short-circuits straight to idbfs without consulting the record further — so declining on
974
+ // `idb-authoritative` protects nothing the adopting boot would not do identically; it only forfeits
975
+ // the accelerator. The three it DOES honour, all via `resolveDeniedBootAuthority`: `deleting` (finish
976
+ // the handoff — no replacement minted beneath it), `opfs-candidate` (that boot RETIRES the unexposed
977
+ // candidate — sentinel, directory, then idb authority — so nothing may be minted beneath a record it
978
+ // has still to resolve), and `opfs-committed`, which that boot REFUSES typed
979
+ // (`CommittedStoreUnreachableError`) because this home cannot open the committed OPFS store. Minting
980
+ // the idb sibling here is the exact hazard the refusal exists to prevent — and it would be minted
981
+ // BEFORE the attach that refuses, so the accelerator must decline first. Nothing is recorded in this
982
+ // lane: it has no opfs commitment machinery to honour.
983
+ //
984
+ // Whether this provision owes the candidate record; written just before the mint, so losing the race
985
+ // below leaves no orphan record behind.
986
+ let recordCandidateBeforeMint = false;
972
987
  if (backendOverride !== "memory") {
973
988
  const record = await readStoreMetaRecord(storePath);
974
- if (record !== META_STORE_UNAVAILABLE && record?.phase === "deleting") {
975
- syncDebug("worker provision declined — deletion authority is live", { storePath });
989
+ const metaUnavailable = record === META_STORE_UNAVAILABLE;
990
+ const phase = metaUnavailable ? undefined : record?.phase;
991
+ if (phase === "opfs-committed" && !placementOpfsAccess) {
992
+ syncDebug(
993
+ "worker provision declined — the store is committed to OPFS and this home holds no sync access",
994
+ {
995
+ storePath,
996
+ },
997
+ );
976
998
  return;
977
999
  }
1000
+ if (
1001
+ phase !== undefined &&
1002
+ phase !== "opfs-committed" &&
1003
+ (placementOpfsAccess || phase === "deleting" || phase === "opfs-candidate")
1004
+ ) {
1005
+ syncDebug("worker provision declined — the store phase is owned elsewhere", { storePath, phase });
1006
+ return;
1007
+ }
1008
+ if (phase === undefined && placementOpfsAccess) {
1009
+ // A candidate is authoritative only once RECORDED, so a scope that cannot hold a record at all has
1010
+ // no way to mint one.
1011
+ if (metaUnavailable) {
1012
+ syncDebug("worker provision declined — no meta store to record an opfs candidate", { storePath });
1013
+ return;
1014
+ }
1015
+ const observation = await createOpfsEffects(storePath).observeCommitmentNamespace();
1016
+ const virgin =
1017
+ observation !== "unobservable" && !observation.sentinelPresent && !observation.storeDirectoryPresent;
1018
+ if (!virgin) {
1019
+ syncDebug("worker provision declined — the commitment namespace is not a provable virgin", {
1020
+ storePath,
1021
+ observation,
1022
+ });
1023
+ return;
1024
+ }
1025
+ // A pristine commitment namespace is NOT proof of a virgin STORE. A store's backend is fixed at
1026
+ // first mint: a granted home meeting an existing idb store opens it `idb-authoritative` (boot
1027
+ // classification 6, invariant 14), so minting an OPFS candidate here would commit an EMPTY store
1028
+ // over the user's data. Same NON-CREATING check the boot classifier keys on.
1029
+ if (await idbStoreExists(storePath)) {
1030
+ syncDebug("worker provision declined — an idb store already exists at this path", { storePath });
1031
+ return;
1032
+ }
1033
+ recordCandidateBeforeMint = true;
1034
+ }
978
1035
  }
979
1036
  // An attach or another completed provision may have won while the bounded read was in flight.
980
1037
  if (bootPromise != null || provisioned != null) return;
1038
+ // Record-before-directory (invariant 12): the mint's factory creates the store directory, so the
1039
+ // `opfs-candidate` record goes in FIRST — a crash between them leaves a recorded candidate the next boot
1040
+ // deletes and rebuilds, never an unrecorded directory that reads as residue.
1041
+ if (recordCandidateBeforeMint) {
1042
+ await writeStoreMetaRecord(storePath, { phase: "opfs-candidate", updatedAt: Date.now() });
1043
+ }
981
1044
 
982
1045
  const provisionStartedAt = nowStamp();
983
1046
  const pglite = Promise.resolve().then(() => createPglite(storePath, backendOverride));
@@ -1430,9 +1493,10 @@ function isControlPortDelivery(data: unknown): boolean {
1430
1493
  * - `assign-identity` → remember it (gates every subsequent tagged message) and reply `engine-ready`. That
1431
1494
  * signals CONTROL-plane readiness, NOT engine boot — the engine still boots lazily on the FIRST attach, as
1432
1495
  * today (the first `connect-port` pipe's traffic drives `boot`).
1433
- * - `connect-port` (matching identity) + a transferred port → wrap it into a {@link BridgePort} (started if it
1434
- * exposes `start()`, exactly as the implicit scope port is wrapped) and feed it to the SAME `connect(...)`
1435
- * the entry already uses N times — dynamic per-tab pipe acceptance (ADR D4).
1496
+ * - `connect-port` (matching identity) → reply `connect-port-ack` IMMEDIATELY (the router's engine-liveness
1497
+ * proof: a dead engine's realm answers nothing and the router retires it), then wrap the transferred port into
1498
+ * a {@link BridgePort} (started if it exposes `start()`, exactly as the implicit scope port is wrapped) and
1499
+ * feed it to the SAME `connect(...)` the entry already uses N times — dynamic per-tab pipe acceptance (ADR D4).
1436
1500
  * - `control-ping` → reply `control-ack` with the assigned identity (or the ping's, pre-assignment) and the
1437
1501
  * SAME `pingId`. Answered on the event loop, so a WASM-blocked engine cannot answer — which is exactly the
1438
1502
  * execution-limit's liveness signal.
@@ -1463,6 +1527,10 @@ function startEngineControlPlane(
1463
1527
  return;
1464
1528
  case "connect-port": {
1465
1529
  if (!shouldApplyControlMessage(assigned, message)) return; // stale → discard
1530
+ // Answer the router's liveness question FIRST — before the pipe is touched at all. The ack proves only
1531
+ // that this engine's realm still exists (the router's bounded window is armed on the delivery), and the
1532
+ // identity is the assigned one: the gate above just proved they are equal.
1533
+ post({ type: "connect-port-ack", identity: message.identity });
1466
1534
  const transferred = event.ports?.[0];
1467
1535
  if (!transferred) return;
1468
1536
  connect(wrapControlPortAsBridge(transferred));
@@ -133,6 +133,16 @@ export type EngineControlMessage =
133
133
  * this message (outside the JSON body, as a transferable), fed into `SyncWorkerHost.connect` (ADR D4).
134
134
  */
135
135
  | { type: "connect-port"; identity: EngineIdentity }
136
+ /**
137
+ * elected engine → SharedWorker: the engine's control plane RECEIVED a `connect-port` for this identity —
138
+ * the ENGINE-LIVENESS proof the router's bounded ack window waits for. Emitted immediately on receipt, before
139
+ * the pipe is used for anything, because it answers one question only: does the engine's realm still exist?
140
+ * (Under `extendedLifetime` the SharedWorker outlives the tab that spawned the dedicated engine, so a
141
+ * registered engine can be a corpse; where the MessagePort `close` event is unsupported this ack is the only
142
+ * signal available.) Deliberately its OWN type rather than a `control-ack`: the router relays unmatched
143
+ * `control-ack`s to tabs as the teardown-ack, so reusing it would leak into a coordinator's teardown wait.
144
+ */
145
+ | { type: "connect-port-ack"; identity: EngineIdentity }
136
146
  /**
137
147
  * A liveness probe request. Used BOTH as a tab↔SharedWorker keepalive (the leader keepalive) AND as a
138
148
  * SharedWorker↔engine control-channel probe (the execution-limit path). `pingId` correlates the ack.
@@ -176,6 +186,7 @@ type TaggedControlType = Exclude<
176
186
  const TAGGED_CONTROL_TYPES: ReadonlySet<TaggedControlType> = new Set<TaggedControlType>([
177
187
  "engine-ready",
178
188
  "connect-port",
189
+ "connect-port-ack",
179
190
  "control-ping",
180
191
  "control-ack",
181
192
  "overdue-dispatch",
@@ -206,6 +217,7 @@ export function shouldApplyControlMessage(current: EngineIdentity | undefined, m
206
217
  return true;
207
218
  case "engine-ready":
208
219
  case "connect-port":
220
+ case "connect-port-ack":
209
221
  case "control-ping":
210
222
  case "control-ack":
211
223
  case "overdue-dispatch":
@@ -1,10 +1,24 @@
1
1
  // The ROUTER (ADR-0049 step 6): the SharedWorker-side placement machinery — the "communication centre"
2
2
  // (CONTEXT.md § "Language — engine placement"). This module runs INSIDE the SharedWorker and is the single
3
- // role that never moves whatever the engine's home is. It owns exactly four things:
3
+ // role that never moves whatever the engine's home is. It owns exactly five things:
4
4
  // - the ATTACH REGISTRY (every tab's bridge port),
5
5
  // - the CURRENT engine identity + the engine CONTROL CHANNEL,
6
- // - relocation-notice FAN-OUT to every tab, and
7
- // - execution-limit PROBE FORWARDING (tab-reported overdue dispatch → control-channel pings → verdict).
6
+ // - relocation-notice FAN-OUT to every tab,
7
+ // - execution-limit PROBE FORWARDING (tab-reported overdue dispatch → control-channel pings → verdict), and
8
+ // - ENGINE LIVENESS: a registered engine must stay PROVEN LIVE. The router state can outlive an engine —
9
+ // `extendedLifetime` keeps the SharedWorker (and this module's state) alive past the last tab, while an
10
+ // elected DEDICATED engine dies with the tab that spawned it — so a registration is never trusted on age.
11
+ // On the DEFAULT configuration the retirement signals are the ones that carry actual EVIDENCE of death:
12
+ // the engine control port's `close` event (MessagePort `close` is Baseline, so this covers every current
13
+ // browser), the reported paths owned above this module (worker `error`, spawn failure, tab death), and
14
+ // the teardown handshake. SILENCE IS NEVER A VERDICT HERE (ADR-0049 D5): PGlite's synchronous WASM work
15
+ // blocks the engine's event loop, so a legitimate long import stalls the control channel exactly as a
16
+ // corpse does. Timing therefore lives entirely behind the OPT-IN execution limit — with it enabled, an
17
+ // unacked `connect-port` and a tab-reported overdue dispatch both hand the question to the probe loop,
18
+ // which lands on the SAME `retireCurrentEngine` path. RESIDUAL, stated honestly: on a hypothetical
19
+ // platform with no MessagePort `close` event AND the limit disabled, a silently-dead piped engine is not
20
+ // detected by this module — that is the ADR's posture ("the limit is never claimed as death evidence"),
21
+ // not an oversight.
8
22
  //
9
23
  // It deliberately does NOT: spawn workers, decide leadership, or ever inspect RPC payloads. Per attached tab
10
24
  // it mints a proxy pipe and TRANSFERS one end to the engine and the other to the tab; from then on that tab's
@@ -20,6 +34,7 @@
20
34
  // `ch`/`v` and is ignored by the bridge router. Step 7's attach client speaks this SAME envelope.
21
35
 
22
36
  import {
37
+ engineIdentityEquals,
23
38
  mintEngineIdentity,
24
39
  readControlEnvelope,
25
40
  shouldApplyControlMessage,
@@ -59,12 +74,19 @@ export interface EngineRouterOptions {
59
74
  /** The opaque id of THIS SharedWorker instance — scopes every minted {@link EngineIdentity}'s generation. */
60
75
  swInstanceId: string;
61
76
  /**
62
- * Engine-construction execution limit (`undefined`/absent `maxDispatchMs` = DISABLED, ADR D5). The router
63
- * only FORWARDS tab-reported overdue dispatches into control-channel probes when enabled; the verdict
64
- * threshold is {@link probeMissThreshold}. Disabled → overdue reports are ignored entirely.
77
+ * Engine-construction execution limit (`undefined`/absent `maxDispatchMs` = DISABLED, ADR D5). This one
78
+ * option gates ALL of the router's timing machinery: tab-reported overdue dispatches are forwarded into
79
+ * control-channel probes, and delivered pipes are covered by the {@link connectAckTimeoutMs} window, only
80
+ * when it is enabled. Disabled (the default) → overdue reports are ignored, no window is armed, and no
81
+ * amount of engine silence ever produces a verdict.
65
82
  */
66
83
  executionLimit?: ExecutionLimitConfig;
67
- /** Consecutive unanswered probe pings before an engine-loss verdict (default 3). */
84
+ /**
85
+ * Probe pings that each went a FULL {@link probeIntervalMs} unanswered before an engine-loss verdict
86
+ * (default 3). Counting is per-ping, never per-tick: the threshold-th ping owns its own whole interval, so
87
+ * the effective silence before a verdict is `probeMissThreshold × probeIntervalMs` (plus the ack window
88
+ * where the probe started there).
89
+ */
68
90
  probeMissThreshold?: number;
69
91
  /** Injectable pipe factory (default `() => new MessageChannel()`) so tests can observe both minted ends. */
70
92
  createPipe?: () => { port1: RouterPort; port2: RouterPort };
@@ -72,6 +94,14 @@ export interface EngineRouterOptions {
72
94
  timers?: RouterTimers;
73
95
  /** Milliseconds between probe pings once a dispatch is reported overdue (default 2000). */
74
96
  probeIntervalMs?: number;
97
+ /**
98
+ * Milliseconds a delivered `connect-port` may go unacknowledged by the engine before its liveness is
99
+ * QUESTIONED (default 3000). ONLY armed when {@link executionLimit} is enabled — silence is not evidence of
100
+ * death (ADR-0049 D5), so the default configuration never starts this clock. Where it is armed, expiry is
101
+ * still not a verdict: it starts the {@link probeMissThreshold} probe loop, so a live-but-busy engine
102
+ * answers a ping and survives while a corpse is retired.
103
+ */
104
+ connectAckTimeoutMs?: number;
75
105
  }
76
106
 
77
107
  export interface EngineRouter {
@@ -84,7 +114,8 @@ export interface EngineRouter {
84
114
  * tab→SW: the leader coordinator announces a fresh engine control channel. Stamps the next
85
115
  * {@link EngineIdentity} ({@link mintEngineIdentity}), stores the control channel, and returns the identity.
86
116
  * On the engine's `engine-ready` for THIS identity it pipes every attached tab. Any prior engine's control
87
- * listener/probe is cleared first (this does not itself fan a notice).
117
+ * listener/probe is cleared first (this does not itself fan a notice). The announced port is also WATCHED for
118
+ * liveness from here on: its `close` (where the platform has that event) retires this engine.
88
119
  */
89
120
  announceEngine(controlPort: RouterPort): EngineIdentity;
90
121
  /**
@@ -117,6 +148,7 @@ export function createEngineRouter(options: EngineRouterOptions): EngineRouter {
117
148
  const { swInstanceId, executionLimit } = options;
118
149
  const probeMissThreshold = options.probeMissThreshold ?? 3;
119
150
  const probeIntervalMs = options.probeIntervalMs ?? 2000;
151
+ const connectAckTimeoutMs = options.connectAckTimeoutMs ?? 3000;
120
152
  const createPipe =
121
153
  options.createPipe ?? (() => new MessageChannel() as unknown as { port1: RouterPort; port2: RouterPort });
122
154
  const timers: RouterTimers = options.timers ?? {
@@ -132,8 +164,21 @@ export function createEngineRouter(options: EngineRouterOptions): EngineRouter {
132
164
  let lastMinted: EngineIdentity | undefined;
133
165
  let controlPort: RouterPort | undefined;
134
166
  let controlListener: ((event: { data: unknown }) => void) | undefined;
167
+ /** A `close`-event listener on the CONTROL port, present only where the platform has that event (as for tabs). */
168
+ let controlCloseListener: (() => void) | undefined;
135
169
  let engineReady = false;
136
170
 
171
+ // Engine liveness. `teardownForwarded` remembers the identity whose `engine-teardown` this router relayed: the
172
+ // engine acks that and SELF-CLOSES its control end, so that one close is EXPECTED and must stay silent — the
173
+ // coordinator that asked for the teardown owns the retirement. `connectAckHandle` is ONE router-wide window
174
+ // that exists only under the opt-in execution limit (`undefined` on the default configuration); its
175
+ // per-engine — deliberately NOT per-delivery — contract is spelled out on `armConnectAckWindow`.
176
+ let teardownForwarded: EngineIdentity | undefined;
177
+ let connectAckHandle: unknown;
178
+
179
+ /** ADR-0049 D5: every timing-based path in this module (ack window + probe loop) is gated on this opt-in. */
180
+ const executionLimitEnabled = executionLimit?.maxDispatchMs !== undefined;
181
+
137
182
  // Execution-limit probe loop (one timer at a time; the whole loop keys on `currentIdentity`).
138
183
  let probeRunning = false;
139
184
  let probeHandle: unknown;
@@ -147,12 +192,61 @@ export function createEngineRouter(options: EngineRouterOptions): EngineRouter {
147
192
  }
148
193
  }
149
194
 
150
- /** Mint a fresh proxy pipe: engine end → the control channel, tab end → the tab (both TRANSFERRED). */
195
+ /**
196
+ * Mint a fresh proxy pipe: engine end → the control channel, tab end → the tab (both TRANSFERRED). The
197
+ * bounded liveness window over this delivery is armed ONLY under the opt-in execution limit (ADR-0049 D5);
198
+ * with the limit disabled a delivery starts no clock, so a blocked-but-healthy engine is never condemned by
199
+ * a second tab attaching mid-import. The engine still posts `connect-port-ack` either way — harmless, and
200
+ * the handler simply clears a window that was never armed.
201
+ */
151
202
  function deliverPipe(tab: TabEntry): void {
152
203
  if (currentIdentity === undefined || controlPort === undefined) return;
153
204
  const { port1, port2 } = createPipe();
154
205
  controlPort.postMessage(envelope({ type: "connect-port", identity: currentIdentity }), [port1]);
155
206
  tab.port.postMessage(envelope({ type: "connect-port", identity: currentIdentity }), [port2]);
207
+ if (executionLimitEnabled) armConnectAckWindow(currentIdentity);
208
+ }
209
+
210
+ function clearConnectAckWindow(): void {
211
+ if (connectAckHandle !== undefined) {
212
+ timers.clearTimeout(connectAckHandle);
213
+ connectAckHandle = undefined;
214
+ }
215
+ }
216
+
217
+ /**
218
+ * Arm (or RE-arm) the bounded `connect-port-ack` window — reached ONLY under the opt-in execution limit
219
+ * (ADR-0049 D5; the caller gates it). A delivered pipe is the router's one chance to hear from the engine's
220
+ * realm: a live engine acks it immediately, a corpse says nothing — but so does an engine whose event loop
221
+ * is blocked by a long synchronous query, which is exactly why this is not a default-configuration signal.
222
+ * Expiry is deliberately NOT a verdict either — it hands the question to {@link startProbe}, so a
223
+ * live-but-busy engine answers a ping and keeps its registration while a dead one misses
224
+ * `probeMissThreshold` pings and is retired through the same recovery path.
225
+ *
226
+ * ONE WINDOW PER ROUTER, NOT PER DELIVERED PIPE — the deliberate contract (maintainer ruling, review
227
+ * 2026-07-27), which is why re-arming (an `engine-ready` fan-out to N tabs arms it N times, last wins) and
228
+ * an identity-only ack are correct rather than sloppy:
229
+ * - The question this window asks is per-ENGINE — "is that realm processing its control port?" — not
230
+ * per-pipe, so ANY identity-matched `connect-port-ack` answers it and no per-delivery correlation id is
231
+ * carried.
232
+ * - Cross-delivery clearing is SOUND because every `connect-port` rides ONE ordered control port: an
233
+ * engine that acked delivery N is, at that instant, processing a queue that already contains delivery
234
+ * N+1 — the ack is evidence for the whole queued batch, not just its own message.
235
+ * - ACCEPTED RESIDUAL: the engine realm dying SILENTLY (no worker `error`, no MessagePort `close`) in the
236
+ * instants BETWEEN processing consecutive queued deliveries, on a platform without the `close` event,
237
+ * with the execution limit enabled — the later tab then rides a dead pipe with no armed window. That
238
+ * window is vanishingly narrow, the primary wedge (an ALREADY-dead engine being piped — no ack ever
239
+ * arrives, so this window expires and the probe loop retires it) is fully covered, and per-delivery
240
+ * correlation was judged not worth the machinery.
241
+ */
242
+ function armConnectAckWindow(armedFor: EngineIdentity): void {
243
+ clearConnectAckWindow();
244
+ connectAckHandle = timers.setTimeout(() => {
245
+ connectAckHandle = undefined;
246
+ // The engine went away or was superseded between arming and expiry — the question is already answered.
247
+ if (currentIdentity === undefined || !engineIdentityEquals(currentIdentity, armedFor)) return;
248
+ startProbe();
249
+ }, connectAckTimeoutMs);
156
250
  }
157
251
 
158
252
  function resetProbe(): void {
@@ -165,14 +259,22 @@ export function createEngineRouter(options: EngineRouterOptions): EngineRouter {
165
259
  }
166
260
  }
167
261
 
168
- /** Detach the engine control channel + probe state WITHOUT fanning any notice (used by announce/handoff). */
262
+ /** Detach the engine control channel + probe/liveness state WITHOUT fanning any notice (announce/handoff/death). */
169
263
  function clearEngine(): void {
170
264
  resetProbe();
171
- if (controlPort !== undefined && controlListener !== undefined) {
172
- controlPort.removeEventListener("message", controlListener);
265
+ clearConnectAckWindow();
266
+ if (controlPort !== undefined) {
267
+ if (controlListener !== undefined) controlPort.removeEventListener("message", controlListener);
268
+ // Symmetric with the message listener: an announce replaces this port, so leaving its `close` listener
269
+ // attached would leak one per announce AND let a superseded port's close speak for its successor.
270
+ if (controlCloseListener !== undefined) {
271
+ (controlPort as unknown as ClosableRouterPort).removeEventListener?.("close", controlCloseListener);
272
+ }
173
273
  }
174
274
  controlPort = undefined;
175
275
  controlListener = undefined;
276
+ controlCloseListener = undefined;
277
+ teardownForwarded = undefined;
176
278
  currentIdentity = undefined;
177
279
  engineReady = false;
178
280
  }
@@ -186,6 +288,13 @@ export function createEngineRouter(options: EngineRouterOptions): EngineRouter {
186
288
  }
187
289
  }
188
290
 
291
+ /**
292
+ * One tick of the probe loop (execution-limit paths only). A MISS is "a ping that was already posted went a
293
+ * FULL `probeIntervalMs` unanswered" — counted at the START of the tick that finds it outstanding, never in
294
+ * the same tick that posts it. So the first tick posts ping 1 and counts nothing, and the threshold-th ping
295
+ * gets its own whole interval to be answered before the tick that condemns it. `control-ack` for
296
+ * {@link pendingPingId} stops the loop through {@link resetProbe} at any point in between.
297
+ */
189
298
  function scheduleProbe(): void {
190
299
  probeHandle = timers.setTimeout(() => {
191
300
  probeHandle = undefined;
@@ -194,28 +303,54 @@ export function createEngineRouter(options: EngineRouterOptions): EngineRouter {
194
303
  resetProbe();
195
304
  return;
196
305
  }
306
+ if (pendingPingId !== undefined) {
307
+ missCount += 1;
308
+ if (missCount >= probeMissThreshold) {
309
+ // Threshold pings, each unanswered for a full interval → ENGINE-LOSS VERDICT. No further ping is
310
+ // posted (the router never terminates anything; the leader coordinator reacts to `engine-retiring`).
311
+ resetProbe();
312
+ retireCurrentEngine();
313
+ return;
314
+ }
315
+ }
197
316
  const pingId = ++pingSeq;
198
317
  pendingPingId = pingId;
199
318
  controlPort.postMessage(envelope({ type: "control-ping", identity: currentIdentity, pingId }));
200
- missCount += 1;
201
- if (missCount >= probeMissThreshold) {
202
- // Threshold consecutive unanswered pings → ENGINE-LOSS VERDICT (the router never terminates anything;
203
- // the leader coordinator reacts to the fanned `engine-retiring`).
204
- resetProbe();
205
- retireCurrentEngine();
206
- } else {
207
- scheduleProbe();
208
- }
319
+ scheduleProbe();
209
320
  }, probeIntervalMs);
210
321
  }
211
322
 
323
+ /**
324
+ * Start the probe loop. BOTH of its entry points — a tab-reported `overdue-dispatch` and the expiry of the
325
+ * `connect-port-ack` window — exist only while the opt-in execution limit is enabled (ADR-0049 D5), so this
326
+ * is unreachable on the default configuration. Idempotent while a loop is already running.
327
+ */
212
328
  function startProbe(): void {
213
329
  if (probeRunning) return;
214
330
  probeRunning = true;
215
331
  missCount = 0;
332
+ pendingPingId = undefined; // no ping is outstanding at the start of a loop — the first tick counts no miss
216
333
  scheduleProbe();
217
334
  }
218
335
 
336
+ /**
337
+ * The engine control port CLOSED. For the CURRENT engine that is DEATH: the control channel's far end lives in
338
+ * the engine's realm, so its close means that realm is gone (the dedicated engine died with its spawning tab
339
+ * while this SharedWorker survived it). Retire, so the coordinators recover and no new connection is ever piped
340
+ * into the corpse. Two closes are NOT death and must stay silent: one for a port a later announce already
341
+ * SUPERSEDED (identity/port checked, never assumed), and the engine's own close after the teardown handshake
342
+ * this router forwarded — that retirement belongs to the coordinator that asked for it.
343
+ */
344
+ function onControlPortClose(port: RouterPort, announced: EngineIdentity): void {
345
+ if (controlPort !== port) return; // superseded: a later announce owns the registration now
346
+ if (currentIdentity === undefined || !engineIdentityEquals(currentIdentity, announced)) return;
347
+ if (teardownForwarded !== undefined && engineIdentityEquals(teardownForwarded, announced)) {
348
+ clearEngine();
349
+ return;
350
+ }
351
+ retireCurrentEngine();
352
+ }
353
+
219
354
  // ─── Engine control-channel inbound ──────────────────────────────────────────
220
355
  function onControlMessage(data: unknown): void {
221
356
  const message = readControlEnvelope(data);
@@ -228,6 +363,12 @@ export function createEngineRouter(options: EngineRouterOptions): EngineRouter {
228
363
  for (const tab of tabs) deliverPipe(tab);
229
364
  }
230
365
  return;
366
+ case "connect-port-ack":
367
+ // The engine's realm answered for the pipe it was just handed — the liveness question is settled until
368
+ // the next delivery. Identity-gated: a stale generation's ack never speaks for the current engine. With
369
+ // the execution limit disabled no window was ever armed, so this is simply a no-op.
370
+ if (shouldApplyControlMessage(currentIdentity, message)) clearConnectAckWindow();
371
+ return;
231
372
  case "control-ack":
232
373
  // A live-but-slow engine answered the PROBE: reset the miss count and STOP the loop (below-threshold
233
374
  // probing is never a verdict). Only the pending ping's id for the current identity counts — that ack
@@ -267,6 +408,9 @@ export function createEngineRouter(options: EngineRouterOptions): EngineRouter {
267
408
  // The coordinator's teardown handshake (ADR-0049 step 9): forward it VERBATIM to the engine's control
268
409
  // channel for the CURRENT identity, so the engine acks + self-closes. A stale teardown is discarded.
269
410
  if (!shouldApplyControlMessage(currentIdentity, message)) return;
411
+ // Remember it: the self-close that follows is the EXPECTED end of this handshake, not engine death, so
412
+ // the close listener clears the registration silently instead of fanning a retirement notice.
413
+ teardownForwarded = message.identity;
270
414
  controlPort?.postMessage(envelope(message));
271
415
  return;
272
416
  case "tab-detach":
@@ -326,6 +470,17 @@ export function createEngineRouter(options: EngineRouterOptions): EngineRouter {
326
470
  controlPort = port;
327
471
  controlListener = (event) => onControlMessage(event.data);
328
472
  port.addEventListener("message", controlListener);
473
+ // Engine-death detection, feature-detected exactly as `attachTab` does for a tab port: this end's far side
474
+ // lives in the engine's realm, so its `close` is the platform telling us that realm is gone. This is the
475
+ // load-bearing signal (MessagePort `close` is Baseline across current browsers). RESIDUAL: where the event
476
+ // is UNSUPPORTED, the `connect-port-ack` window covers a silently-dead engine only if the opt-in execution
477
+ // limit is enabled — with it disabled, silence is deliberately not read as death (ADR-0049 D5).
478
+ const closable = port as unknown as ClosableRouterPort;
479
+ if ("onclose" in closable) {
480
+ const closeListener = () => onControlPortClose(port, minted);
481
+ controlCloseListener = closeListener;
482
+ closable.addEventListener("close", closeListener);
483
+ }
329
484
  port.start?.();
330
485
  engineReady = false;
331
486
  // ADR-0049 step 9: hand the freshly-minted identity to the engine's control plane FIRST — before any