@pgxsinkit/client 0.1.53 → 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 (85) hide show
  1. package/README.md +22 -0
  2. package/dist/adoption.d.ts +118 -0
  3. package/dist/adoption.d.ts.map +1 -0
  4. package/dist/boot-report.d.ts +54 -15
  5. package/dist/boot-report.d.ts.map +1 -1
  6. package/dist/convergence.d.ts +2 -1
  7. package/dist/convergence.d.ts.map +1 -1
  8. package/dist/export-store.d.ts +1 -1
  9. package/dist/export-store.d.ts.map +1 -1
  10. package/dist/index.d.ts +270 -52
  11. package/dist/index.d.ts.map +1 -1
  12. package/dist/index.js +4492 -1511
  13. package/dist/index.js.map +34 -24
  14. package/dist/live-rows-sql.d.ts +1 -1
  15. package/dist/local-store.d.ts +16 -31
  16. package/dist/local-store.d.ts.map +1 -1
  17. package/dist/local-tables.d.ts +4 -4
  18. package/dist/mutation.d.ts +12 -15
  19. package/dist/mutation.d.ts.map +1 -1
  20. package/dist/opfs-effects.d.ts +51 -0
  21. package/dist/opfs-effects.d.ts.map +1 -0
  22. package/dist/placement-probe.d.ts +75 -0
  23. package/dist/placement-probe.d.ts.map +1 -0
  24. package/dist/schema.d.ts +11 -16
  25. package/dist/schema.d.ts.map +1 -1
  26. package/dist/store-boot.d.ts +77 -0
  27. package/dist/store-boot.d.ts.map +1 -0
  28. package/dist/store-lifecycle.d.ts +153 -0
  29. package/dist/store-lifecycle.d.ts.map +1 -0
  30. package/dist/store-meta.d.ts +190 -0
  31. package/dist/store-meta.d.ts.map +1 -0
  32. package/dist/store-path.d.ts +77 -7
  33. package/dist/store-path.d.ts.map +1 -1
  34. package/dist/sync/apply.d.ts.map +1 -1
  35. package/dist/sync/shape-inbox.d.ts +1 -1
  36. package/dist/sync/types.d.ts +3 -3
  37. package/dist/testing.js.map +3 -3
  38. package/dist/worker/attach-sync-client.d.ts +235 -12
  39. package/dist/worker/attach-sync-client.d.ts.map +1 -1
  40. package/dist/worker/define-sync-worker.d.ts +138 -22
  41. package/dist/worker/define-sync-worker.d.ts.map +1 -1
  42. package/dist/worker/election-coordinator.d.ts +95 -0
  43. package/dist/worker/election-coordinator.d.ts.map +1 -0
  44. package/dist/worker/engine-control.d.ts +265 -0
  45. package/dist/worker/engine-control.d.ts.map +1 -0
  46. package/dist/worker/engine-router.d.ts +75 -0
  47. package/dist/worker/engine-router.d.ts.map +1 -0
  48. package/dist/worker/live-query-manager.d.ts.map +1 -1
  49. package/dist/worker/protocol.d.ts +15 -10
  50. package/dist/worker/protocol.d.ts.map +1 -1
  51. package/dist/worker/sw-placement.d.ts +37 -0
  52. package/dist/worker/sw-placement.d.ts.map +1 -0
  53. package/package.json +4 -3
  54. package/skills/core/SKILL.md +15 -12
  55. package/skills/operating/SKILL.md +103 -46
  56. package/src/adoption.ts +275 -0
  57. package/src/boot-report.ts +70 -17
  58. package/src/convergence.ts +2 -1
  59. package/src/export-store.ts +1 -1
  60. package/src/index.ts +1109 -115
  61. package/src/live-rows-sql.ts +1 -1
  62. package/src/local-store.ts +18 -40
  63. package/src/local-tables.ts +2 -2
  64. package/src/mutation.ts +67 -49
  65. package/src/mutations-api.ts +3 -3
  66. package/src/opfs-effects.ts +160 -0
  67. package/src/placement-probe.ts +168 -0
  68. package/src/schema.ts +17 -22
  69. package/src/store-boot.ts +343 -0
  70. package/src/store-lifecycle.ts +227 -0
  71. package/src/store-meta.ts +459 -0
  72. package/src/store-path.ts +197 -22
  73. package/src/sync/apply.ts +63 -63
  74. package/src/sync/index.ts +2 -2
  75. package/src/sync/shape-inbox.ts +1 -1
  76. package/src/sync/types.ts +3 -3
  77. package/src/testing.ts +2 -2
  78. package/src/worker/attach-sync-client.ts +1556 -97
  79. package/src/worker/define-sync-worker.ts +723 -73
  80. package/src/worker/election-coordinator.ts +462 -0
  81. package/src/worker/engine-control.ts +379 -0
  82. package/src/worker/engine-router.ts +355 -0
  83. package/src/worker/live-query-manager.ts +4 -1
  84. package/src/worker/protocol.ts +13 -10
  85. package/src/worker/sw-placement.ts +64 -0
@@ -0,0 +1,355 @@
1
+ // The ROUTER (ADR-0049 step 6): the SharedWorker-side placement machinery — the "communication centre"
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:
4
+ // - the ATTACH REGISTRY (every tab's bridge port),
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).
8
+ //
9
+ // It deliberately does NOT: spawn workers, decide leadership, or ever inspect RPC payloads. Per attached tab
10
+ // it mints a proxy pipe and TRANSFERS one end to the engine and the other to the tab; from then on that tab's
11
+ // RPC/live-query traffic flows tab↔engine DIRECTLY on the pipe (invariant 6 — the SharedWorker is not in the
12
+ // data path). Because it is transport-agnostic (a `RouterPort`, never a real `SharedWorker`/`Worker`), the
13
+ // whole thing is unit-testable over hand-rolled recording ports with no worker at all — the same discipline
14
+ // `protocol.ts` and `engine-control.ts` follow.
15
+ //
16
+ // WIRE ENVELOPE. The control plane shares the same tab↔SharedWorker transport as today's data-path bridge
17
+ // (`protocol.ts`). To coexist WITHOUT touching `protocol.ts`, every control message travels inside a
18
+ // NAMESPACED envelope `{ [ENGINE_CONTROL_ENVELOPE_KEY]: <EngineControlMessage> }` (`pgx0049`). A bridge
19
+ // envelope (`{ ch: "pgxsinkit-bridge", … }`) has no such key and is ignored here; a control envelope has no
20
+ // `ch`/`v` and is ignored by the bridge router. Step 7's attach client speaks this SAME envelope.
21
+
22
+ import {
23
+ mintEngineIdentity,
24
+ readControlEnvelope,
25
+ shouldApplyControlMessage,
26
+ type EngineControlMessage,
27
+ type EngineIdentity,
28
+ type ExecutionLimitConfig,
29
+ wrapControlEnvelope as envelope,
30
+ } from "./engine-control";
31
+
32
+ /**
33
+ * The namespaced key under which every ADR-0049 control message rides the tab↔SharedWorker transport, so the
34
+ * control plane coexists with the data-path bridge envelope (`protocol.ts`) without any change to it. The tab
35
+ * side (step 7) sends/reads the identical envelope.
36
+ */
37
+ export { ENGINE_CONTROL_ENVELOPE_KEY } from "./engine-control";
38
+
39
+ /**
40
+ * The minimal MessagePort-shaped transport the router needs — the intersection of a real `MessagePort`, a
41
+ * `SharedWorker` connection port, and the pipe ends it mints. Modeled on `protocol.ts`'s `BridgePort` (kept
42
+ * local, not imported, because the router's transfer list is plain `unknown[]` and it never `close()`s a tab
43
+ * port). Injected everywhere so the router is exercised with plain recording ports (no worker) in tests.
44
+ */
45
+ export interface RouterPort {
46
+ postMessage: (message: unknown, transfer?: unknown[]) => void;
47
+ addEventListener: (type: "message", listener: (event: { data: unknown }) => void) => void;
48
+ removeEventListener: (type: "message", listener: (event: { data: unknown }) => void) => void;
49
+ start?: () => void;
50
+ }
51
+
52
+ /** The setTimeout/clearTimeout pair the probe loop schedules on — injectable for deterministic tests. */
53
+ export interface RouterTimers {
54
+ setTimeout(fn: () => void, ms: number): unknown;
55
+ clearTimeout(handle: unknown): void;
56
+ }
57
+
58
+ export interface EngineRouterOptions {
59
+ /** The opaque id of THIS SharedWorker instance — scopes every minted {@link EngineIdentity}'s generation. */
60
+ swInstanceId: string;
61
+ /**
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.
65
+ */
66
+ executionLimit?: ExecutionLimitConfig;
67
+ /** Consecutive unanswered probe pings before an engine-loss verdict (default 3). */
68
+ probeMissThreshold?: number;
69
+ /** Injectable pipe factory (default `() => new MessageChannel()`) so tests can observe both minted ends. */
70
+ createPipe?: () => { port1: RouterPort; port2: RouterPort };
71
+ /** Injectable timers for probe scheduling (default `globalThis`) for deterministic tests. */
72
+ timers?: RouterTimers;
73
+ /** Milliseconds between probe pings once a dispatch is reported overdue (default 2000). */
74
+ probeIntervalMs?: number;
75
+ }
76
+
77
+ export interface EngineRouter {
78
+ /**
79
+ * Register a tab's bridge port. Returns an unregister fn. If an engine is CURRENT and already ready, this
80
+ * late joiner is piped IMMEDIATELY; otherwise it is piped when the current engine's `engine-ready` fans out.
81
+ */
82
+ attachTab(tabPort: RouterPort): () => void;
83
+ /**
84
+ * tab→SW: the leader coordinator announces a fresh engine control channel. Stamps the next
85
+ * {@link EngineIdentity} ({@link mintEngineIdentity}), stores the control channel, and returns the identity.
86
+ * 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).
88
+ */
89
+ announceEngine(controlPort: RouterPort): EngineIdentity;
90
+ /**
91
+ * Fan a relocation notice to every tab: `leader-granted` (untagged) or `engine-retiring` (tagged with the
92
+ * retired identity). BOTH clear the current identity + control channel. Engine-loss verdicts fan
93
+ * `engine-retiring` internally the same way.
94
+ */
95
+ openHandoff(reason: "leader-granted" | "engine-retiring"): void;
96
+ /** The current identity, or `undefined` before the first announce / while relocating. */
97
+ currentIdentity(): EngineIdentity | undefined;
98
+ /** Total attached-tab count (used later for destroy peer-refusal). */
99
+ tabCount(): number;
100
+ }
101
+
102
+ interface TabEntry {
103
+ port: RouterPort;
104
+ listener: (event: { data: unknown }) => void;
105
+ /** A `close`-event listener, present only where the platform supports the MessagePort `close` event (D8). */
106
+ closeListener?: () => void;
107
+ }
108
+
109
+ /** The optional MessagePort `close`-event surface — feature-detected, not part of the structural {@link RouterPort}. */
110
+ interface ClosableRouterPort {
111
+ onclose?: unknown;
112
+ addEventListener: (type: "close", listener: () => void) => void;
113
+ removeEventListener?: (type: "close", listener: () => void) => void;
114
+ }
115
+
116
+ export function createEngineRouter(options: EngineRouterOptions): EngineRouter {
117
+ const { swInstanceId, executionLimit } = options;
118
+ const probeMissThreshold = options.probeMissThreshold ?? 3;
119
+ const probeIntervalMs = options.probeIntervalMs ?? 2000;
120
+ const createPipe =
121
+ options.createPipe ?? (() => new MessageChannel() as unknown as { port1: RouterPort; port2: RouterPort });
122
+ const timers: RouterTimers = options.timers ?? {
123
+ setTimeout: (fn, ms) => globalThis.setTimeout(fn, ms),
124
+ clearTimeout: (handle) => globalThis.clearTimeout(handle as ReturnType<typeof globalThis.setTimeout>),
125
+ };
126
+
127
+ const tabs = new Set<TabEntry>();
128
+
129
+ // Current engine state. `lastMinted` survives a handoff (unlike `currentIdentity`) so the next announce mints
130
+ // the SUCCESSOR generation (gen+1) under this SharedWorker instance, per mintEngineIdentity's contract.
131
+ let currentIdentity: EngineIdentity | undefined;
132
+ let lastMinted: EngineIdentity | undefined;
133
+ let controlPort: RouterPort | undefined;
134
+ let controlListener: ((event: { data: unknown }) => void) | undefined;
135
+ let engineReady = false;
136
+
137
+ // Execution-limit probe loop (one timer at a time; the whole loop keys on `currentIdentity`).
138
+ let probeRunning = false;
139
+ let probeHandle: unknown;
140
+ let missCount = 0;
141
+ let pingSeq = 0;
142
+ let pendingPingId: number | undefined;
143
+
144
+ function fanToTabs(message: EngineControlMessage): void {
145
+ for (const tab of tabs) {
146
+ tab.port.postMessage(envelope(message));
147
+ }
148
+ }
149
+
150
+ /** Mint a fresh proxy pipe: engine end → the control channel, tab end → the tab (both TRANSFERRED). */
151
+ function deliverPipe(tab: TabEntry): void {
152
+ if (currentIdentity === undefined || controlPort === undefined) return;
153
+ const { port1, port2 } = createPipe();
154
+ controlPort.postMessage(envelope({ type: "connect-port", identity: currentIdentity }), [port1]);
155
+ tab.port.postMessage(envelope({ type: "connect-port", identity: currentIdentity }), [port2]);
156
+ }
157
+
158
+ function resetProbe(): void {
159
+ probeRunning = false;
160
+ missCount = 0;
161
+ pendingPingId = undefined;
162
+ if (probeHandle !== undefined) {
163
+ timers.clearTimeout(probeHandle);
164
+ probeHandle = undefined;
165
+ }
166
+ }
167
+
168
+ /** Detach the engine control channel + probe state WITHOUT fanning any notice (used by announce/handoff). */
169
+ function clearEngine(): void {
170
+ resetProbe();
171
+ if (controlPort !== undefined && controlListener !== undefined) {
172
+ controlPort.removeEventListener("message", controlListener);
173
+ }
174
+ controlPort = undefined;
175
+ controlListener = undefined;
176
+ currentIdentity = undefined;
177
+ engineReady = false;
178
+ }
179
+
180
+ /** The engine-loss path: capture the retiring identity, tear down, and fan `engine-retiring` to every tab. */
181
+ function retireCurrentEngine(): void {
182
+ const retiring = currentIdentity;
183
+ clearEngine();
184
+ if (retiring !== undefined) {
185
+ fanToTabs({ type: "engine-retiring", identity: retiring });
186
+ }
187
+ }
188
+
189
+ function scheduleProbe(): void {
190
+ probeHandle = timers.setTimeout(() => {
191
+ probeHandle = undefined;
192
+ // The engine went away between ticks (handoff/verdict) — abandon the loop silently.
193
+ if (currentIdentity === undefined || controlPort === undefined) {
194
+ resetProbe();
195
+ return;
196
+ }
197
+ const pingId = ++pingSeq;
198
+ pendingPingId = pingId;
199
+ 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
+ }
209
+ }, probeIntervalMs);
210
+ }
211
+
212
+ function startProbe(): void {
213
+ if (probeRunning) return;
214
+ probeRunning = true;
215
+ missCount = 0;
216
+ scheduleProbe();
217
+ }
218
+
219
+ // ─── Engine control-channel inbound ──────────────────────────────────────────
220
+ function onControlMessage(data: unknown): void {
221
+ const message = readControlEnvelope(data);
222
+ if (message === undefined) return;
223
+ switch (message.type) {
224
+ case "engine-ready":
225
+ // Gate on the exact identity pair — a stale engine-ready from a superseded generation is discarded.
226
+ if (shouldApplyControlMessage(currentIdentity, message)) {
227
+ engineReady = true;
228
+ for (const tab of tabs) deliverPipe(tab);
229
+ }
230
+ return;
231
+ case "control-ack":
232
+ // A live-but-slow engine answered the PROBE: reset the miss count and STOP the loop (below-threshold
233
+ // probing is never a verdict). Only the pending ping's id for the current identity counts — that ack
234
+ // is CONSUMED here (never fanned to tabs).
235
+ if (shouldApplyControlMessage(currentIdentity, message) && message.pingId === pendingPingId) {
236
+ resetProbe();
237
+ return;
238
+ }
239
+ // Any OTHER engine ack (pingId mismatch or no probe loop running) is the engine's teardown ack
240
+ // (`pingId: -1`, ADR-0049 step 9) — relay it VERBATIM to every tab so the coordinator's identity-matched
241
+ // teardown wait settles. The router never inspects it beyond forwarding.
242
+ fanToTabs(message);
243
+ return;
244
+ default:
245
+ // The engine control channel emits nothing else the router acts on here.
246
+ return;
247
+ }
248
+ }
249
+
250
+ // ─── Tab bridge-port inbound ──────────────────────────────────────────────────
251
+ function onTabMessage(tab: TabEntry, data: unknown): void {
252
+ const message = readControlEnvelope(data);
253
+ if (message === undefined) return;
254
+ switch (message.type) {
255
+ case "control-ping":
256
+ // Keepalive: reply IMMEDIATELY on the same tab, echoing the PING's identity (there may be no current
257
+ // engine yet, and the keepalive is a liveness check of the SharedWorker itself, not of an engine).
258
+ tab.port.postMessage(envelope({ type: "control-ack", identity: message.identity, pingId: message.pingId }));
259
+ return;
260
+ case "overdue-dispatch":
261
+ // Execution limit (ADR D5): only when enabled AND the report is for the CURRENT engine identity.
262
+ if (executionLimit?.maxDispatchMs === undefined) return; // disabled → ignored entirely
263
+ if (!shouldApplyControlMessage(currentIdentity, message)) return; // stale / no engine
264
+ startProbe();
265
+ return;
266
+ case "engine-teardown":
267
+ // The coordinator's teardown handshake (ADR-0049 step 9): forward it VERBATIM to the engine's control
268
+ // channel for the CURRENT identity, so the engine acks + self-closes. A stale teardown is discarded.
269
+ if (!shouldApplyControlMessage(currentIdentity, message)) return;
270
+ controlPort?.postMessage(envelope(message));
271
+ return;
272
+ case "tab-detach":
273
+ // The tab is detaching (ADR-0049 D8): unregister it so `tabCount` (the destroy peer-refusal input) falls.
274
+ // The `detach` bridge envelope rides the tab's pipe (invisible here), so this control signal on the SW
275
+ // port is the router's only view of the departure. Its minted pipe end is simply dropped.
276
+ removeTab(tab);
277
+ return;
278
+ default:
279
+ // Any other control type from a tab is not the router's concern.
280
+ return;
281
+ }
282
+ }
283
+
284
+ /** Unregister a tab: drop it from the registry and detach its listeners (the minted pipe end is dropped). */
285
+ function removeTab(entry: TabEntry): void {
286
+ if (!tabs.has(entry)) return;
287
+ tabs.delete(entry);
288
+ entry.port.removeEventListener("message", entry.listener);
289
+ if (entry.closeListener !== undefined) {
290
+ (entry.port as unknown as ClosableRouterPort).removeEventListener?.("close", entry.closeListener);
291
+ }
292
+ }
293
+
294
+ function attachTab(tabPort: RouterPort): () => void {
295
+ const entry: TabEntry = {
296
+ port: tabPort,
297
+ listener: (event) => onTabMessage(entry, event.data),
298
+ };
299
+ tabPort.addEventListener("message", entry.listener);
300
+ tabPort.start?.();
301
+ // Belt-and-braces peer-departure detection (ADR-0049 D8): where the platform supports the MessagePort
302
+ // `close` event, a CRASHED tab that never sent `tab-detach` is still dropped (its port closes on agent
303
+ // teardown). Feature-detected via `onclose` so the structural `RouterPort` (and unit fakes) need not expose
304
+ // it. RESIDUAL: where the `close` event is UNSUPPORTED, a crashed peer that never sent `tab-detach` leaves a
305
+ // stale `tabCount` until the SharedWorker restarts — a `destroy()` then stays refused; the caller resolves it
306
+ // with `destroy({ force: true })` (the documented escape). A clean `stop()`/`pagehide` always sends `tab-detach`.
307
+ const closable = tabPort as unknown as ClosableRouterPort;
308
+ if ("onclose" in closable) {
309
+ const closeListener = () => removeTab(entry);
310
+ entry.closeListener = closeListener;
311
+ closable.addEventListener("close", closeListener);
312
+ }
313
+ tabs.add(entry);
314
+ // Late joiner: an already-ready engine pipes this tab immediately; otherwise it is piped on engine-ready.
315
+ if (currentIdentity !== undefined && engineReady) {
316
+ deliverPipe(entry);
317
+ }
318
+ return () => removeTab(entry);
319
+ }
320
+
321
+ function announceEngine(port: RouterPort): EngineIdentity {
322
+ clearEngine(); // detach any prior engine's listener/probe (no notice fanned by an announce).
323
+ const minted = mintEngineIdentity(swInstanceId, lastMinted);
324
+ lastMinted = minted;
325
+ currentIdentity = minted;
326
+ controlPort = port;
327
+ controlListener = (event) => onControlMessage(event.data);
328
+ port.addEventListener("message", controlListener);
329
+ port.start?.();
330
+ engineReady = false;
331
+ // ADR-0049 step 9: hand the freshly-minted identity to the engine's control plane FIRST — before any
332
+ // `connect-port` pipe. The engine remembers it (gating every subsequent tagged message) and replies
333
+ // `engine-ready`, which drives the pipe fan-out below.
334
+ port.postMessage(envelope({ type: "assign-identity", identity: minted }));
335
+ return minted;
336
+ }
337
+
338
+ function openHandoff(reason: "leader-granted" | "engine-retiring"): void {
339
+ if (reason === "engine-retiring") {
340
+ retireCurrentEngine();
341
+ return;
342
+ }
343
+ // leader-granted: a fresh engine is about to be spawned — clear the current one and open the window.
344
+ clearEngine();
345
+ fanToTabs({ type: "leader-granted" });
346
+ }
347
+
348
+ return {
349
+ attachTab,
350
+ announceEngine,
351
+ openHandoff,
352
+ currentIdentity: () => currentIdentity,
353
+ tabCount: () => tabs.size,
354
+ };
355
+ }
@@ -5,7 +5,10 @@
5
5
  // BOUNDED ZERO-SUBSCRIBER KEEP-ALIVE (decision 4): when the last subscriber of an entry leaves, a nonzero
6
6
  // effective keep-alive retains the registration for a grace period so a matching resubscribe reuses it
7
7
  // verbatim (no ~400 ms re-materialization); retention is bounded by explicit count/row budgets and defaults
8
- // to OFF (keep-alive 0 → tear down immediately, byte-identical to Slice 3).
8
+ // to OFF (keep-alive 0 → tear down the instant the last subscriber leaves). The 0 default is deliberate:
9
+ // a retained entry still pays a full SQL rerun + diff on every dependent write (PGlite live queries cannot
10
+ // be paused), so keeping one alive is only worthwhile for a genuinely hot, re-mounted query — the default
11
+ // keeps worker memory bounded and never runs surprise standing SQL.
9
12
  //
10
13
  // What stays with the CALLER (`defineSyncWorker`), never this manager (ADR-0040 decision 3): lazy-relation
11
14
  // activation (`prepareQuery`), hydration accounting (`hydratingTablesFor` → `groupReady`), the
@@ -19,7 +19,8 @@ export const BRIDGE_PROTOCOL_VERSION = 1 as const;
19
19
  /**
20
20
  * A structured-clone transferable (an `ArrayBuffer`, a `MessagePort`, …). The library carries no DOM lib
21
21
  * dependency (like the convergence triggers), so this is the toolkit's own name for the type a future
22
- * columnar codec would hand to `postMessage`'s transfer list. v1's identity codec never produces one.
22
+ * columnar codec would hand to `postMessage`'s transfer list. The wire-format-1 identity codec
23
+ * ({@link BRIDGE_PROTOCOL_VERSION}) never produces one.
23
24
  */
24
25
  export type BridgeTransferable = unknown;
25
26
 
@@ -147,6 +148,8 @@ export interface AttachPayload {
147
148
  * memory-store selection travels as this explicit field. Set only by the test lane; never by a browser tab.
148
149
  */
149
150
  testStoreBackend?: "memory";
151
+ /** ADR-0049 D5: the tab's engine-construction limit, checked by the host before it acknowledges attach. */
152
+ executionLimit?: { maxDispatchMs?: number };
150
153
  /**
151
154
  * Restore the store from a backup on THIS attach (ADR-0035 decision 6) — the worker-mode carrier of
152
155
  * `createSyncClient`'s `restoreFrom`. Restore rides the FIRST attach (the boot attach): a `File`/`Blob`
@@ -343,9 +346,9 @@ export interface SubscribePayload {
343
346
  params: unknown[];
344
347
  /**
345
348
  * The unique output aliases the worker wraps the query's columns under so it is safe to MATERIALISE
346
- * (one per output column, in the compiled SQL's column order). ADDITIVE and backward-compatible: an
347
- * older tab omits it and the worker leaves the SQL untouched (name-keyed rows, as before); a newer tab
348
- * supplies it for a JOIN with same-named columns, which `live.query`/`live.incrementalQuery` otherwise
349
+ * (one per output column, in the compiled SQL's column order). When omitted, the worker leaves the SQL
350
+ * untouched and returns name-keyed rows; supply it for a JOIN with same-named columns, which
351
+ * `live.query`/`live.incrementalQuery` otherwise
349
352
  * refuse to materialise (`column "title" specified more than once`). When present, result columns are
350
353
  * the aliases, so {@link pkColumns} must name a PK by its alias.
351
354
  */
@@ -361,9 +364,8 @@ export interface SubscribePayload {
361
364
  /**
362
365
  * Per-subscription keep-alive hint (ms) for the worker's live-query manager (ADR-0040 decision 4): how long
363
366
  * the shared registration should be retained after this subscription's last consumer leaves, so a matching
364
- * resubscribe reuses it verbatim. ADDITIVE and backward-compatible both directions — an older tab omits it
365
- * (the worker falls back to its `liveQueries.defaultKeepAliveMs`), and an older worker ignores it. Absent
366
- * means "no hint".
367
+ * resubscribe reuses it verbatim. When omitted, the worker falls back to
368
+ * `liveQueries.defaultKeepAliveMs`; absent means "no hint".
367
369
  */
368
370
  keepAliveMs?: number;
369
371
  }
@@ -464,9 +466,10 @@ export interface BridgeCodec {
464
466
  }
465
467
 
466
468
  /**
467
- * The v1 identity codec: the body IS the payload, and the transport's structured clone does the real
468
- * copying. No transferables. The only codec shipped in S2 — swapping in a columnar codec later touches
469
- * only this object, never the message types or the router.
469
+ * The identity codec, wire-format version 1 ({@link BRIDGE_PROTOCOL_VERSION}): the body IS the payload,
470
+ * and the transport's structured clone does the real copying. No transferables. The sole codec at this
471
+ * wire version — swapping in a columnar codec later touches only this object, never the message types or
472
+ * the router.
470
473
  */
471
474
  export const identityCodec: BridgeCodec = {
472
475
  encode: (payload) => ({ payload }),
@@ -0,0 +1,64 @@
1
+ // The SharedWorker startup PLACEMENT DECISION (ADR-0049 decision 1/2, plan step 10b). A SharedWorker decides
2
+ // its ENGINE HOME by running the placement probe (`placement-probe.ts`) ONCE at startup — a real
3
+ // `createSyncAccessHandle` open in its own scope — and turns the probe's verdict into a placement result the
4
+ // bootstrap gates every tab connection on. Granted → the engine lives IN the SharedWorker (`shared-worker`,
5
+ // SW-direct, election disabled this lifetime); denied → the SharedWorker is ROUTER-ONLY (`elected-worker`) and
6
+ // each tab's election coordinator spawns the real engine in a dedicated worker.
7
+ //
8
+ // This module is the PURE decision only — it boots NO engine and creates NO router. It is testable off-worker
9
+ // (no real OPFS) via the injectable `probe`/`mintInstanceId` seams, the same discipline `placement-probe.ts`,
10
+ // `engine-router.ts`, and `election-coordinator.ts` follow. The probe is NEVER cached across SW lifetimes
11
+ // (invariant 8): a fresh SharedWorker runs a fresh decision.
12
+
13
+ import { type PlacementProbeResult, probeOpfsSyncAccess } from "../placement-probe";
14
+
15
+ /**
16
+ * The SharedWorker's engine-home decision (ADR-0049 D1). `shared-worker` = the engine boots in this
17
+ * SharedWorker scope (granted OPFS sync access, SW-direct, election never engages); `elected-worker` = the
18
+ * SharedWorker is router-only and each tab elects a dedicated engine worker. `probeError` carries the probe's
19
+ * verbatim denial attribution when NOT granted (diagnostics only, never parsed). `swInstanceId` scopes every
20
+ * minted engine identity's generation (`engine-router.ts`).
21
+ */
22
+ export interface SwPlacementResult {
23
+ engineHome: "shared-worker" | "elected-worker";
24
+ probeError?: string;
25
+ swInstanceId: string;
26
+ /**
27
+ * Present ONLY on a `shared-worker` home that is a CAPABILITY-ABSENCE fallback (ADR-0049 D1), not an OPFS
28
+ * grant: the platform cannot hold sync-access handles in any home, so the engine boots in-SharedWorker on the
29
+ * IDBFS backend with the registry-declared durability. Carries the verbatim probe attribution the fallback
30
+ * boot stamps into `storageFallbackReason` (decision 12). Absent on a granted `shared-worker` (SW-direct OPFS)
31
+ * and on `elected-worker` — an OPFS-capable elected home is not a fallback.
32
+ */
33
+ storageFallbackReason?: string;
34
+ }
35
+
36
+ /** Injectable seams so the decision is deterministic in a Bun unit test (no real OPFS, no real crypto needed). */
37
+ export interface DecideSwPlacementDeps {
38
+ /** The placement probe; defaults to {@link probeOpfsSyncAccess}. Injected in tests to drive both verdicts. */
39
+ probe?: () => Promise<PlacementProbeResult>;
40
+ /** Mint the opaque SharedWorker instance id; defaults to `crypto.randomUUID()`. Injected for deterministic tests. */
41
+ mintInstanceId?: () => string;
42
+ }
43
+
44
+ /**
45
+ * Decide the SharedWorker's engine home ONCE at startup (ADR-0049 D1, invariant 8 — probe per boot, never
46
+ * cached). Runs the placement probe; a granted verdict places the engine in-scope (`shared-worker`), a denied
47
+ * one puts the SharedWorker in router-only mode (`elected-worker`) and carries the probe's verbatim error for
48
+ * diagnostics. This is a PURE decision — no engine boots and no router is created here; the bootstrap
49
+ * (`define-sync-worker.ts`) acts on the result.
50
+ */
51
+ export async function decideSwPlacement(deps?: DecideSwPlacementDeps): Promise<SwPlacementResult> {
52
+ const probe = deps?.probe ?? probeOpfsSyncAccess;
53
+ const mintInstanceId = deps?.mintInstanceId ?? (() => crypto.randomUUID());
54
+ const swInstanceId = mintInstanceId();
55
+ const result = await probe();
56
+ if (result.granted) {
57
+ return { engineHome: "shared-worker", swInstanceId };
58
+ }
59
+ return {
60
+ engineHome: "elected-worker",
61
+ swInstanceId,
62
+ ...(result.error !== undefined ? { probeError: result.error } : {}),
63
+ };
64
+ }