@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,379 @@
1
+ // The control-plane protocol (ADR-0049 step 5). This module defines the PURE types + rules the router
2
+ // (communication centre), the elected engine worker, and the attach client all share for engine placement
3
+ // and relocation. It is deliberately IO-FREE and worker-FREE — no `postMessage`, no MessagePort handling,
4
+ // no timers — so the whole control plane is unit-testable with no worker at all (the same discipline the
5
+ // bridge `protocol.ts` follows). Later steps wire these types into `protocol.ts`, the router, the attach
6
+ // client, and the engine entry; this file only owns the vocabulary.
7
+ //
8
+ // Bounded-context terms (CONTEXT.md § "Language — engine placement") are used exactly: engine identity,
9
+ // handoff window, engine home, communication centre, elected engine worker.
10
+
11
+ // ─── A. Engine identity (ADR D4, invariant 7; CONTEXT "Engine identity") ─────────
12
+
13
+ /** Namespaced wire key shared by every placement control-plane participant. */
14
+ export const ENGINE_CONTROL_ENVELOPE_KEY = "pgx0049" as const;
15
+
16
+ /** Wrap a control message in the namespaced envelope used beside the bridge protocol. */
17
+ export function wrapControlEnvelope(message: EngineControlMessage): {
18
+ [ENGINE_CONTROL_ENVELOPE_KEY]: EngineControlMessage;
19
+ } {
20
+ return { [ENGINE_CONTROL_ENVELOPE_KEY]: message };
21
+ }
22
+
23
+ /** Read a control message from its namespaced envelope, ignoring unrelated bridge traffic. */
24
+ export function readControlEnvelope(data: unknown): EngineControlMessage | undefined {
25
+ if (typeof data !== "object" || data === null) return undefined;
26
+ const message = (data as { [ENGINE_CONTROL_ENVELOPE_KEY]?: unknown })[ENGINE_CONTROL_ENVELOPE_KEY];
27
+ if (typeof message !== "object" || message === null) return undefined;
28
+ if (typeof (message as { type?: unknown }).type !== "string") return undefined;
29
+ return message as EngineControlMessage;
30
+ }
31
+
32
+ /**
33
+ * The PAIR naming one announced engine: the SharedWorker instance that stamped it plus a generation
34
+ * counter that is monotonic ONLY within that one SharedWorker instance (it resets with the SharedWorker).
35
+ * Authority and staleness checks always compare the pair — never the bare counter — because two different
36
+ * SharedWorker instances can each hold a generation `0`.
37
+ */
38
+ export interface EngineIdentity {
39
+ /** Opaque id of the SharedWorker instance that minted this identity. Scopes {@link generation}. */
40
+ swInstanceId: string;
41
+ /** Monotonic counter WITHIN one `swInstanceId`; resets to 0 under a new SharedWorker instance. */
42
+ generation: number;
43
+ }
44
+
45
+ /** Two identities are equal only when BOTH fields match (the pair, never the bare counter). */
46
+ export function engineIdentityEquals(a: EngineIdentity, b: EngineIdentity): boolean {
47
+ return a.swInstanceId === b.swInstanceId && a.generation === b.generation;
48
+ }
49
+
50
+ /**
51
+ * Staleness rule (invariant 7): a tagged message is applied ONLY when its identity equals the CURRENT
52
+ * identity exactly — the pair, never the bare counter (it resets with the SharedWorker). So a message is
53
+ * STALE precisely when it is not `engineIdentityEquals` the current identity.
54
+ */
55
+ export function isStaleIdentity(current: EngineIdentity, tagged: EngineIdentity): boolean {
56
+ return !engineIdentityEquals(current, tagged);
57
+ }
58
+
59
+ /**
60
+ * Mint the next identity that THIS SharedWorker instance (`swInstanceId`) should announce.
61
+ *
62
+ * - No `previous` → generation `0` (the first engine this SharedWorker announces).
63
+ * - `previous` belongs to the SAME `swInstanceId` → `previous.generation + 1` (a succession within one
64
+ * SharedWorker: a fresh elected engine worker replacing the last).
65
+ * - `previous` belongs to a DIFFERENT `swInstanceId` (a re-announce arriving at a NEW SharedWorker
66
+ * instance, after SharedWorker death recovery) → the counter RESTARTS at `0` under the new instance id.
67
+ * The generation is scoped to one SharedWorker instance, so it cannot carry across instances.
68
+ */
69
+ export function mintEngineIdentity(swInstanceId: string, previous?: EngineIdentity): EngineIdentity {
70
+ const sameInstance = previous !== undefined && previous.swInstanceId === swInstanceId;
71
+ return { swInstanceId, generation: sameInstance ? previous.generation + 1 : 0 };
72
+ }
73
+
74
+ // ─── B. Control-plane message union (ADR D4; plan "Protocol changes") ────────────
75
+
76
+ /**
77
+ * The identity-tagged control plane the communication centre, the elected engine worker, and the tab
78
+ * coordinators exchange (distinct from the data-path bridge in `protocol.ts`; the SharedWorker never sees
79
+ * RPC payloads). Payload interfaces mirror `protocol.ts` conventions: a discriminating `type`, typed
80
+ * fields only, and MessagePorts travelling as transferables OUTSIDE the JSON body (see individual members).
81
+ * Identity-tagged members carry the {@link EngineIdentity} they belong to so a stale one is discarded.
82
+ */
83
+ export type EngineControlMessage =
84
+ // ── untagged (no identity exists yet, or the SharedWorker stamps it) ──
85
+ /**
86
+ * SharedWorker → tab (the lock holder): the leader lock was granted; SPAWN the engine. Pre-spawn, so no
87
+ * identity exists yet — it OPENS the handoff window on the attach side (a relocation notice, CONTEXT
88
+ * "Handoff window"). Untagged: there is no engine identity to compare against before the engine exists.
89
+ */
90
+ | { type: "leader-granted" }
91
+ /**
92
+ * tab → SharedWorker: the freshly spawned engine's MessagePort is announced so the SharedWorker can
93
+ * stamp it with a minted {@link EngineIdentity}. The announce ITSELF carries no identity (the SharedWorker
94
+ * mints it on receipt). The engine's control MessagePort travels as a TRANSFERABLE outside this JSON body
95
+ * (the same way `protocol.ts` transfers ports — never a serialized field), so nothing is typed here.
96
+ */
97
+ | { type: "engine-announce" }
98
+ /**
99
+ * tab → SharedWorker (ADR-0049 D8): this tab is detaching — UNREGISTER it from the router so `tabCount`
100
+ * (the destroy peer-refusal input) falls. The platform fires no SharedWorker port-close event and the tab's
101
+ * `detach` bridge envelope rides the per-tab PIPE (which the router never sees), so this control-plane signal
102
+ * on the SW port is the only channel the router observes. Untagged + always-applied: it names no engine (it
103
+ * concerns the tab's own registration), and a detaching tab must be dropped regardless of the current engine
104
+ * generation. The router stays payload-blind — this is a `pgx0049` control message, never a bridge envelope.
105
+ */
106
+ | { type: "tab-detach" }
107
+ /**
108
+ * elected engine → SharedWorker (ADR-0049 D1, capability-absence fallback): the elected dedicated engine's
109
+ * OWN-scope OPFS probe was DENIED (or the OPFS API is absent/throwing in the dedicated home too), so no home on
110
+ * this platform can hold sync-access handles. The engine reports that here so the router-only SharedWorker
111
+ * abandons election and boots the in-scope IDBFS engine instead (with the registry-declared durability) — the
112
+ * declared-idbfs shape reached by capability detection rather than declaration. Untagged: it names no engine
113
+ * (the engine never became authoritative — it is reporting that it cannot host), and the SharedWorker must act
114
+ * on it regardless of the current generation. `reason` is the verbatim probe attribution stamped into the
115
+ * fallback boot's `storageFallbackReason` (decision 12).
116
+ */
117
+ | { type: "engine-fallback"; reason: string }
118
+ /**
119
+ * SharedWorker → engine (ADR-0049 step 9): the identity the router just minted for this engine, handed to
120
+ * the elected engine worker's control plane RIGHT AFTER the router stamps the `engine-announce` (before any
121
+ * `connect-port`). Although it carries an {@link EngineIdentity}, it is ALWAYS-APPLIED — it is the ASSIGNMENT
122
+ * itself, so it is never gated on the receiver's (still-absent or stale) current identity; every subsequent
123
+ * tagged message the engine receives is compared against THIS assigned identity. The engine remembers it and
124
+ * replies `engine-ready` (control-plane readiness, NOT engine boot — the engine still boots lazily on first
125
+ * attach). Sits with the untagged members in {@link shouldApplyControlMessage}'s always-apply set.
126
+ */
127
+ | { type: "assign-identity"; identity: EngineIdentity }
128
+ // ── identity-tagged ──
129
+ /** SharedWorker → tab: the announced engine is live under this identity (the stamp fan-out). */
130
+ | { type: "engine-ready"; identity: EngineIdentity }
131
+ /**
132
+ * SharedWorker → engine: accept a per-tab proxy pipe. The tab-end MessagePort is transferred ALONGSIDE
133
+ * this message (outside the JSON body, as a transferable), fed into `SyncWorkerHost.connect` (ADR D4).
134
+ */
135
+ | { type: "connect-port"; identity: EngineIdentity }
136
+ /**
137
+ * A liveness probe request. Used BOTH as a tab↔SharedWorker keepalive (the leader keepalive) AND as a
138
+ * SharedWorker↔engine control-channel probe (the execution-limit path). `pingId` correlates the ack.
139
+ */
140
+ | { type: "control-ping"; identity: EngineIdentity; pingId: number }
141
+ /**
142
+ * The answer to a {@link EngineControlMessage} `control-ping`; `pingId` echoes the request. ONE reserved
143
+ * value: `pingId: -1` is the TEARDOWN ack by convention (ADR-0049 step 9) — the engine emits it in reply to
144
+ * an `engine-teardown` (not to any real ping), the router RELAYS it to every tab, and the coordinator's
145
+ * teardown wait settles on it. A `-1` therefore never correlates a probe ping (those start at 1).
146
+ */
147
+ | {
148
+ type: "control-ack";
149
+ identity: EngineIdentity;
150
+ pingId: number;
151
+ /** Present only when the reserved teardown acknowledgement reports that host close failed. */
152
+ error?: { message: string; detail?: unknown };
153
+ }
154
+ /**
155
+ * tab → SharedWorker: an execution-limit report — a dispatch has been outstanding `elapsedMs` past the
156
+ * configured limit (ADR D5). The SharedWorker then probes the engine's control channel; it is NOT itself
157
+ * a death verdict (the limit CONVERTS slow to terminated only after the probe threshold).
158
+ */
159
+ | { type: "overdue-dispatch"; identity: EngineIdentity; elapsedMs: number }
160
+ /**
161
+ * The retirement notice that PRECEDES every DELIBERATE termination — last-claim teardown, BFCache exit,
162
+ * and execution-limit termination all send it first (ADR D5), so the attach side opens the handoff window
163
+ * and queues new calls instead of racing a dying engine.
164
+ */
165
+ | { type: "engine-retiring"; identity: EngineIdentity }
166
+ /** The teardown handshake after a retirement notice; ack/timeout settles the lock callback. */
167
+ | { type: "engine-teardown"; identity: EngineIdentity };
168
+
169
+ /** Discriminants that carry an {@link EngineIdentity} and are therefore staleness-gated. `assign-identity`
170
+ carries one but is the ASSIGNMENT itself (always-applied), so it is excluded here alongside the untagged. */
171
+ type TaggedControlType = Exclude<
172
+ EngineControlMessage,
173
+ { type: "leader-granted" | "engine-announce" | "assign-identity" | "tab-detach" | "engine-fallback" }
174
+ >["type"];
175
+
176
+ const TAGGED_CONTROL_TYPES: ReadonlySet<TaggedControlType> = new Set<TaggedControlType>([
177
+ "engine-ready",
178
+ "connect-port",
179
+ "control-ping",
180
+ "control-ack",
181
+ "overdue-dispatch",
182
+ "engine-retiring",
183
+ "engine-teardown",
184
+ ]);
185
+
186
+ /**
187
+ * Whether a received control message should be APPLIED given the receiver's current engine identity.
188
+ *
189
+ * - ALWAYS-APPLY members (`leader-granted`, `engine-announce`, `assign-identity`, `tab-detach`, `engine-fallback`)
190
+ * always apply — `leader-granted`/`engine-announce`/`tab-detach`/`engine-fallback` carry no identity to compare
191
+ * (they precede any engine, mint an identity, concern the tab's own registration, or report that no engine can
192
+ * host), and `assign-identity` IS the assignment, so it applies unconditionally.
193
+ * - IDENTITY-TAGGED members apply only when `current` is set AND the identities match exactly (the pair,
194
+ * invariant 7). A tagged message with no current identity, or a stale identity, is discarded.
195
+ *
196
+ * The switch is exhaustive with a `never`-guard: a new union member fails to type-check until it is
197
+ * classified here (the runtime exhaustiveness test pairs with this compile-time guard).
198
+ */
199
+ export function shouldApplyControlMessage(current: EngineIdentity | undefined, message: EngineControlMessage): boolean {
200
+ switch (message.type) {
201
+ case "leader-granted":
202
+ case "engine-announce":
203
+ case "assign-identity":
204
+ case "tab-detach":
205
+ case "engine-fallback":
206
+ return true;
207
+ case "engine-ready":
208
+ case "connect-port":
209
+ case "control-ping":
210
+ case "control-ack":
211
+ case "overdue-dispatch":
212
+ case "engine-retiring":
213
+ case "engine-teardown":
214
+ return current !== undefined && engineIdentityEquals(current, message.identity);
215
+ default: {
216
+ const unreachable: never = message;
217
+ throw new Error(`[pgxsinkit] unclassified engine-control message: ${String(unreachable)}`);
218
+ }
219
+ }
220
+ }
221
+
222
+ /** Runtime companion to {@link shouldApplyControlMessage}'s compile-time guard: is this type staleness-gated? */
223
+ export function isTaggedControlType(type: EngineControlMessage["type"]): type is TaggedControlType {
224
+ return TAGGED_CONTROL_TYPES.has(type as TaggedControlType);
225
+ }
226
+
227
+ // ─── C. Execution limit (ADR D5 — opt-in, elected-placement-only) ────────────────
228
+
229
+ /**
230
+ * The opt-in execution limit (ADR D5). ONE engine-construction value; DISABLED BY DEFAULT — no finite
231
+ * worst-case query duration exists, and the limit CONVERTS slow to terminated by policy, so enabling it
232
+ * must be a deliberate consumer choice (the public contract). When enabled, the limit
233
+ * CONVERTS slow to terminated after the control-probe threshold — it is NEVER claimed as death evidence.
234
+ * This feature is ELECTED-PLACEMENT ONLY: on SharedWorker-direct placement (WebKit) the option is rejected
235
+ * as unsupported — that rejection is wired in a later step; this module only defines the config + the
236
+ * cross-tab mismatch rule.
237
+ */
238
+ export interface ExecutionLimitConfig {
239
+ /** ms; `undefined` = DISABLED (the default — preserves unbounded queries). */
240
+ maxDispatchMs?: number;
241
+ }
242
+
243
+ /**
244
+ * Thrown at attach when a tab's execution-limit value disagrees with the engine's construction value
245
+ * (ADR D5): every tab must carry the SAME config. Named + `[pgxsinkit]`-prefixed like the repo's other
246
+ * protocol errors so a consumer can `instanceof`-branch it.
247
+ */
248
+ export class ExecutionLimitMismatchError extends Error {
249
+ readonly engineValue: number | undefined;
250
+ readonly attachValue: number | undefined;
251
+
252
+ constructor(engineValue: number | undefined, attachValue: number | undefined) {
253
+ super(
254
+ `[pgxsinkit] execution-limit mismatch: this tab attaches with ${describeLimit(attachValue)} but the ` +
255
+ `running engine was constructed with ${describeLimit(engineValue)} (ADR-0049 D5). The execution ` +
256
+ "limit is ONE engine-construction value; every tab attaching to a store must carry the same value " +
257
+ "(including both disabled). Align the tabs' configuration.",
258
+ );
259
+ this.name = "ExecutionLimitMismatchError";
260
+ this.engineValue = engineValue;
261
+ this.attachValue = attachValue;
262
+ }
263
+ }
264
+
265
+ const EXECUTION_LIMIT_MISMATCH_CODE = "execution-limit-mismatch";
266
+
267
+ export function executionLimitMismatchToWire(error: ExecutionLimitMismatchError): {
268
+ code: typeof EXECUTION_LIMIT_MISMATCH_CODE;
269
+ engineValue?: number;
270
+ attachValue?: number;
271
+ } {
272
+ return {
273
+ code: EXECUTION_LIMIT_MISMATCH_CODE,
274
+ ...(error.engineValue !== undefined ? { engineValue: error.engineValue } : {}),
275
+ ...(error.attachValue !== undefined ? { attachValue: error.attachValue } : {}),
276
+ };
277
+ }
278
+
279
+ export function executionLimitMismatchFromWire(detail: unknown): ExecutionLimitMismatchError | undefined {
280
+ if (typeof detail !== "object" || detail === null) return undefined;
281
+ const candidate = detail as { code?: unknown; engineValue?: unknown; attachValue?: unknown };
282
+ if (candidate.code !== EXECUTION_LIMIT_MISMATCH_CODE) return undefined;
283
+ const engineValue = typeof candidate.engineValue === "number" ? candidate.engineValue : undefined;
284
+ const attachValue = typeof candidate.attachValue === "number" ? candidate.attachValue : undefined;
285
+ return new ExecutionLimitMismatchError(engineValue, attachValue);
286
+ }
287
+
288
+ function describeLimit(value: number | undefined): string {
289
+ return value === undefined ? "the limit DISABLED (undefined)" : `maxDispatchMs=${value}`;
290
+ }
291
+
292
+ /**
293
+ * Attach-time guard (ADR D5): every tab must carry the SAME execution-limit value as the running engine.
294
+ * Any mismatch — including one side disabled (`undefined`) and the other set — throws
295
+ * {@link ExecutionLimitMismatchError}. Equal values (both `undefined`, or the same number) pass.
296
+ */
297
+ export function assertSameExecutionLimit(engineValue: number | undefined, attachValue: number | undefined): void {
298
+ if (engineValue !== attachValue) {
299
+ throw new ExecutionLimitMismatchError(engineValue, attachValue);
300
+ }
301
+ }
302
+
303
+ // ─── D. EngineRelocatedError (ADR D10, invariant 5; CONTEXT "Handoff window") ─────
304
+
305
+ /**
306
+ * The two honest relocation outcomes (ADR D10, invariant 5). There is deliberately NO blanket "retryable":
307
+ * - `"not-dispatched"` — the call NEVER reached the engine (a queued call failed on the handoff queue's
308
+ * cap/deadline, or was never sent). SAFE TO RETRY.
309
+ * - `"unknown"` — a DISPATCHED mutation whose response was lost to relocation. Its journal update MAY
310
+ * already exist and there is NO mutation-dedup key, so it must be inspected/reconciled, NEVER auto-retried.
311
+ *
312
+ * A dispatched READ that lost its response is NOT a third outcome: repeating a read is safe, so that is the
313
+ * CALLER'S policy (repeat the read), not a distinct wire value.
314
+ */
315
+ export type EngineRelocatedOutcome = "not-dispatched" | "unknown";
316
+
317
+ /** The stable clone-safe discriminator carried on the wire (ADR D10). Consumers branch on this, never prose. */
318
+ export const ENGINE_RELOCATED_CODE = "engine-relocated";
319
+
320
+ /**
321
+ * The clone-safe wire form of a relocation failure (ADR D10). It travels inside the EXISTING bridge error
322
+ * `detail` field — the `{ message, detail }` error shape in `protocol.ts` (~line 330, e.g.
323
+ * `RpcResultPayload.error`) — so no new protocol field is needed. The attach side (step 7) calls
324
+ * {@link engineRelocatedFromWire} on every bridge error `detail` to reconstruct the typed error.
325
+ */
326
+ export interface EngineRelocatedWire {
327
+ code: typeof ENGINE_RELOCATED_CODE;
328
+ outcome: EngineRelocatedOutcome;
329
+ }
330
+
331
+ /**
332
+ * The exported, consumer-visible relocation error (ADR D10, invariant 5). Consumers branch on `code` +
333
+ * `outcome`, never on message prose — but the message NAMES the semantics so a developer hitting it in a
334
+ * log understands immediately. `[pgxsinkit]`-prefixed like the repo's other errors.
335
+ */
336
+ export class EngineRelocatedError extends Error {
337
+ readonly code = ENGINE_RELOCATED_CODE;
338
+ readonly outcome: EngineRelocatedOutcome;
339
+
340
+ constructor(outcome: EngineRelocatedOutcome) {
341
+ super(relocatedMessage(outcome));
342
+ this.name = "EngineRelocatedError";
343
+ this.outcome = outcome;
344
+ }
345
+ }
346
+
347
+ function relocatedMessage(outcome: EngineRelocatedOutcome): string {
348
+ if (outcome === "not-dispatched") {
349
+ return (
350
+ "[pgxsinkit] the call was not dispatched to the engine before it relocated (ADR-0049 D10). It never " +
351
+ "reached the engine, so it is SAFE TO RETRY."
352
+ );
353
+ }
354
+ return (
355
+ "[pgxsinkit] a dispatched mutation's response was lost when the engine relocated (ADR-0049 D10, " +
356
+ "outcome UNKNOWN). Its journal update may ALREADY exist and there is no mutation-dedup key, so " +
357
+ "INSPECT/RECONCILE the store — NEVER auto-retry. (A dispatched READ, by contrast, is safe for the " +
358
+ "caller to repeat.)"
359
+ );
360
+ }
361
+
362
+ /** Encode a {@link EngineRelocatedError} to its clone-safe wire form for the bridge error `detail` field. */
363
+ export function engineRelocatedToWire(error: EngineRelocatedError): EngineRelocatedWire {
364
+ return { code: ENGINE_RELOCATED_CODE, outcome: error.outcome };
365
+ }
366
+
367
+ /**
368
+ * Reconstruct a typed {@link EngineRelocatedError} from a bridge error's `detail` (step 7 calls this on
369
+ * every bridge error detail). STRICT shape check: returns `undefined` for anything that is not exactly the
370
+ * `{ code: "engine-relocated", outcome }` wire form (a foreign/absent detail, a wrong code, a bogus or
371
+ * missing outcome, a non-object) — so a non-relocation error is never misclassified.
372
+ */
373
+ export function engineRelocatedFromWire(detail: unknown): EngineRelocatedError | undefined {
374
+ if (typeof detail !== "object" || detail === null) return undefined;
375
+ const candidate = detail as { code?: unknown; outcome?: unknown };
376
+ if (candidate.code !== ENGINE_RELOCATED_CODE) return undefined;
377
+ if (candidate.outcome !== "not-dispatched" && candidate.outcome !== "unknown") return undefined;
378
+ return new EngineRelocatedError(candidate.outcome);
379
+ }