@pgxsinkit/client 0.1.53 → 0.2.1

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 +286 -51
  11. package/dist/index.d.ts.map +1 -1
  12. package/dist/index.js +4795 -1519
  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 +18 -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 +300 -16
  39. package/dist/worker/attach-sync-client.d.ts.map +1 -1
  40. package/dist/worker/define-sync-worker.d.ts +164 -23
  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 +266 -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 +47 -31
  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 +142 -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 +1157 -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 +115 -53
  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 +1753 -102
  79. package/src/worker/define-sync-worker.ts +1034 -71
  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 +46 -16
  85. package/src/worker/sw-placement.ts +64 -0
@@ -0,0 +1,462 @@
1
+ // The ELECTION COORDINATOR (ADR-0049 step 8): the TAB-SIDE, one-per-tab-per-store owner of leader
2
+ // participation — the "election coordinator" of CONTEXT.md § "Language — engine placement". Exactly one lives
3
+ // per tab per store; both pre-attach provisioning and attach flow through it so a tab NEVER queues behind
4
+ // itself on the leader lock (invariant 2). It owns:
5
+ // - the LEADER LOCK claim lifecycle (claim-counted: first claim queues the lock ONCE; last-claim release
6
+ // retires the engine and settles the lock),
7
+ // - the GRANT DUTIES on election (leader-granted → spawn the elected engine worker → engine-announce),
8
+ // - the LEADER KEEPALIVE (the ONE standing timer) with SharedWorker reconstruction on missed acks,
9
+ // - engine-loss handling (reported worker error → respawn; the router's execution-limit verdict →
10
+ // deliberate terminate → VFS ownership release → respawn), and
11
+ // - the BFCache release/reclaim hooks.
12
+ //
13
+ // It is fully IO-injected — `navigator.locks`, the engine-worker spawner, the control-channel factory, the SW
14
+ // bridge port, timers, and the page-lifecycle subscription are all deps — so the whole contract is unit-
15
+ // testable with no real worker, no real `navigator.locks`, and no real sleeps (the same discipline the router
16
+ // and `engine-control.ts` follow). It speaks the SAME namespaced control envelope the router does
17
+ // (`{ [ENGINE_CONTROL_ENVELOPE_KEY]: <EngineControlMessage> }`, `pgx0049`), so it coexists with the data-path
18
+ // bridge (`protocol.ts`) untouched.
19
+ //
20
+ // WIRE NOTES (envelope-shape choices this step pins down):
21
+ // - IDENTITY LEARNING. The router's `announceEngine` mints the engine identity SW-side; the tab learns it
22
+ // from the next identity-tagged fan-out it observes (`engine-ready` / `connect-port`). That learned
23
+ // identity tags the retirement notice + teardown and gates the execution-limit verdict.
24
+ // - KEEPALIVE IDENTITY. The leader keepalive is a liveness check of the SharedWorker ITSELF, not of any
25
+ // engine, so its `control-ping` carries a coordinator-local nonce identity ({@link KEEPALIVE_IDENTITY}) and
26
+ // acks are matched by `pingId` ALONE (the router echoes the ping's identity verbatim). No magic sentinel
27
+ // is compared — the identity field is deliberately irrelevant here.
28
+ // - TEARDOWN ACK. The teardown handshake awaits a `control-ack` carrying the RETIRING engine's identity (the
29
+ // same identity stamped on the `engine-teardown`). The keepalive is stopped at the START of retirement, so
30
+ // no keepalive ack competes; when the identity was never learned the teardown uses a placeholder and any
31
+ // `control-ack` settles it. Either way the `teardownAckTimeoutMs` timer guarantees completion.
32
+
33
+ import { storeIdentityComponent } from "../store-path";
34
+ import {
35
+ engineIdentityEquals,
36
+ type EngineControlMessage,
37
+ type EngineIdentity,
38
+ readControlEnvelope as readEnvelope,
39
+ wrapControlEnvelope as envelope,
40
+ } from "./engine-control";
41
+
42
+ /** The prefix every per-store leader lock name carries (CONTEXT "Leader lock"). */
43
+ export const LEADER_LOCK_PREFIX = "pgx-leader-";
44
+
45
+ /**
46
+ * The per-store leader-lock name: {@link LEADER_LOCK_PREFIX} + the injective store-identity component (D11,
47
+ * invariant 10). Using {@link storeIdentityComponent} keeps the lock name on the SAME one canonical encoding as
48
+ * every other browser-side identity surface (OPFS namespaces, the meta record key, the SharedWorker name), so
49
+ * two distinct store paths can never collapse to one lock (e.g. `"foo/bar"` → `pgx-leader-foo%2Fbar`).
50
+ */
51
+ export function leaderLockName(storePath: string): string {
52
+ return LEADER_LOCK_PREFIX + storeIdentityComponent(storePath);
53
+ }
54
+
55
+ /** A minimal MessagePort-shaped end — only ever TRANSFERRED across the SW bridge, never called on here. */
56
+ type ControlChannel = { port1: unknown; port2: unknown };
57
+
58
+ /** The tab's SW bridge port (control plane): where the coordinator posts `pgx0049` envelopes and reads acks. */
59
+ export interface SwBridgePort {
60
+ postMessage(message: unknown, transfer?: unknown[]): void;
61
+ addEventListener(type: "message", listener: (event: { data: unknown }) => void): void;
62
+ removeEventListener(type: "message", listener: (event: { data: unknown }) => void): void;
63
+ }
64
+
65
+ export interface CoordinatorDeps {
66
+ /** navigator.locks-shaped, injectable: `request(name, {signal}, callback)` — the callback's returned promise
67
+ HOLDS the lock; resolving it releases the lock, aborting the signal cancels a still-queued request. */
68
+ locks: {
69
+ request(name: string, options: { signal?: AbortSignal }, callback: () => Promise<void>): Promise<void>;
70
+ };
71
+ /** Spawn the elected engine worker; returns a handle with `terminate()` and an error-event subscription. */
72
+ spawnEngineWorker: () => { terminate(): void; onError(listener: (message: string) => void): void };
73
+ /** Create the engine control MessageChannel; default `() => new MessageChannel()` — injectable so tests see
74
+ both ends. The ROUTER end (`port1`) is transferred to the SharedWorker via `engine-announce`; the ENGINE
75
+ end (`port2`) is wired to the elected engine worker in step 9. */
76
+ createControlChannel?: () => ControlChannel;
77
+ /** The tab's SW bridge port (control plane): the coordinator posts `pgx0049` envelopes (leader-granted,
78
+ engine-announce with the transferred control port, engine-retiring, engine-teardown, control-ping) and
79
+ receives control-acks + relocation notices on it. */
80
+ swPort: SwBridgePort;
81
+ /** Reconstruct the SharedWorker via the attach worker FACTORY (ADR-0049 D5) → the NEW swPort. Absent only for a
82
+ bare-instance attach input, where a SharedWorker cannot be rebuilt from itself: keepalive recovery is then
83
+ structurally unavailable (the still-live engine + grant are untouched; recovery narrows to leader-op-or-reload). */
84
+ reconstructSw?: () => SwBridgePort;
85
+ /** Await the VFS ownership release after a deliberate terminate (step 10 wires the real wait; tests fake it). */
86
+ awaitOwnershipRelease: () => Promise<void>;
87
+ timers: { setTimeout(fn: () => void, ms: number): unknown; clearTimeout(handle: unknown): void };
88
+ /** Page-lifecycle subscription seam (BFCache): `pagehide`/`pageshow`; injectable. */
89
+ pageLifecycle?: { onPageHide(listener: (persisted: boolean) => void): void; onPageShow(listener: () => void): void };
90
+ }
91
+
92
+ export interface ElectionCoordinatorOptions {
93
+ storePath: string;
94
+ /** ms between leader-keepalive pings (default 20000). */
95
+ keepaliveIntervalMs?: number;
96
+ /** consecutive unanswered keepalive pings before SharedWorker reconstruction (default 2). */
97
+ keepaliveMissThreshold?: number;
98
+ /** ms to wait for the teardown ack before terminating anyway (default 3000). */
99
+ teardownAckTimeoutMs?: number;
100
+ }
101
+
102
+ export interface ElectionCoordinator {
103
+ /** Claim for a pre-attach provision (optionally expiry-bounded — an abandoned warmed provision retires
104
+ itself when the timer fires). Returns an idempotent release fn (invariant 2). */
105
+ claimForProvision(opts?: { expiryMs?: number }): () => void;
106
+ /** Claim for one attachment. Returns an idempotent release fn (invariant 2). */
107
+ claimForAttach(): () => void;
108
+ /** True while this tab holds the granted leader lock. */
109
+ isLeader(): boolean;
110
+ /** True while an elected engine worker handle is held. */
111
+ hasEngine(): boolean;
112
+ /**
113
+ * Deliberately RETIRE this tab's elected engine and resolve once its teardown handshake has completed — the
114
+ * point at which the engine's EXCLUSIVE OPFS sync-access handle is provably released (ADR-0049 D8). The
115
+ * destroy supervisor awaits this BEFORE deleting the backend store so `deleteBackendStore` never races the
116
+ * engine's async handle release (which surfaced as `NoModificationAllowedError`). Runs the retirement notice →
117
+ * `engine-teardown` → ack/timeout → terminate → lock-settle sequence, then awaits the ownership-release seam.
118
+ * A no-op (resolves at once) when this tab holds no engine (not the leader). Idempotent.
119
+ */
120
+ retireEngine(): Promise<void>;
121
+ }
122
+
123
+ /** The keepalive's nonce identity: the ping probes the SharedWorker's liveness, NOT an engine — acks are
124
+ matched by `pingId` alone, so this identity is deliberately never compared for staleness. */
125
+ const KEEPALIVE_IDENTITY: EngineIdentity = { swInstanceId: "keepalive", generation: 0 };
126
+
127
+ /** The identity a retirement uses when the engine identity was never learned (no fan-out observed yet). The
128
+ notice/teardown still fire so the attach side opens its handoff window; there is at most one engine under a
129
+ grant, so identity precision is unnecessary. */
130
+ const RETIRE_UNKNOWN_IDENTITY: EngineIdentity = { swInstanceId: "", generation: -1 };
131
+
132
+ type LockState = "idle" | "queued" | "granted";
133
+
134
+ interface EngineHandle {
135
+ terminate(): void;
136
+ onError(listener: (message: string) => void): void;
137
+ }
138
+
139
+ interface TeardownWait {
140
+ identity: EngineIdentity;
141
+ finish: () => void;
142
+ }
143
+
144
+ export function createElectionCoordinator(
145
+ deps: CoordinatorDeps,
146
+ options: ElectionCoordinatorOptions,
147
+ ): ElectionCoordinator {
148
+ const lockName = leaderLockName(options.storePath);
149
+ const keepaliveIntervalMs = options.keepaliveIntervalMs ?? 20000;
150
+ const keepaliveMissThreshold = options.keepaliveMissThreshold ?? 2;
151
+ const teardownAckTimeoutMs = options.teardownAckTimeoutMs ?? 3000;
152
+ const createControlChannel = deps.createControlChannel ?? (() => new MessageChannel() as unknown as ControlChannel);
153
+
154
+ // ── claim + lock lifecycle ──
155
+ let claimCount = 0;
156
+ let lockState: LockState = "idle";
157
+ let abortController: AbortController | undefined;
158
+ let grantSettle: (() => void) | undefined; // resolving this releases the held lock
159
+
160
+ // ── SW bridge + engine state ──
161
+ let swPort = deps.swPort;
162
+ let engineHandle: EngineHandle | undefined;
163
+ let currentIdentity: EngineIdentity | undefined;
164
+ let retiring = false;
165
+ let teardownWait: TeardownWait | undefined;
166
+ let bfcacheSuspended = false;
167
+
168
+ // ── keepalive state (the one standing timer) ──
169
+ let keepaliveHandle: unknown;
170
+ let keepaliveMisses = 0;
171
+ let pendingKeepalivePingId: number | undefined;
172
+ let pingSeq = 0;
173
+
174
+ function post(message: EngineControlMessage, transfer?: unknown[]): void {
175
+ swPort.postMessage(envelope(message), transfer);
176
+ }
177
+
178
+ // ─── SW bridge inbound ──────────────────────────────────────────────────────
179
+ const onSwMessage = (event: { data: unknown }): void => {
180
+ const message = readEnvelope(event.data);
181
+ if (message !== undefined) handleControlMessage(message);
182
+ };
183
+ function attachSwListener(): void {
184
+ swPort.addEventListener("message", onSwMessage);
185
+ }
186
+ function detachSwListener(): void {
187
+ swPort.removeEventListener("message", onSwMessage);
188
+ }
189
+
190
+ function handleControlMessage(message: EngineControlMessage): void {
191
+ switch (message.type) {
192
+ case "control-ack":
193
+ // Teardown ack (matches the retiring engine's identity) settles the teardown wait; keepalive is
194
+ // stopped during retirement, so no keepalive ack competes. Otherwise it is a keepalive ack —
195
+ // identity-irrelevant, matched by pingId only.
196
+ if (teardownWait !== undefined && teardownAckMatches(message.identity)) {
197
+ teardownWait.finish();
198
+ return;
199
+ }
200
+ if (message.pingId === pendingKeepalivePingId) {
201
+ keepaliveMisses = 0;
202
+ pendingKeepalivePingId = undefined;
203
+ }
204
+ return;
205
+ case "engine-retiring":
206
+ // The router's execution-limit verdict for OUR current engine (tagged with the retired identity).
207
+ if (isLeader() && currentIdentity !== undefined && engineIdentityEquals(currentIdentity, message.identity)) {
208
+ void onExecutionLimitVerdict();
209
+ }
210
+ return;
211
+ case "engine-ready":
212
+ case "connect-port":
213
+ // The identity-tagged fan-out that teaches the coordinator its current engine identity.
214
+ currentIdentity = message.identity;
215
+ return;
216
+ default:
217
+ // leader-granted / engine-announce are outbound-only from the tab; control-ping / overdue-dispatch
218
+ // are never received here. Nothing to apply.
219
+ return;
220
+ }
221
+ }
222
+
223
+ function teardownAckMatches(acked: EngineIdentity): boolean {
224
+ if (teardownWait === undefined) return false;
225
+ // Identity never learned → the teardown carried the placeholder; accept any ack (no other ack source
226
+ // once keepalive is stopped).
227
+ if (engineIdentityEquals(teardownWait.identity, RETIRE_UNKNOWN_IDENTITY)) return true;
228
+ return engineIdentityEquals(teardownWait.identity, acked);
229
+ }
230
+
231
+ // ─── lock lifecycle ─────────────────────────────────────────────────────────
232
+ function queueLock(): void {
233
+ if (lockState !== "idle") return;
234
+ lockState = "queued";
235
+ const controller = new AbortController();
236
+ abortController = controller;
237
+ const callback = (): Promise<void> =>
238
+ new Promise<void>((resolve) => {
239
+ abortController = undefined;
240
+ lockState = "granted";
241
+ grantSettle = resolve;
242
+ // Queue→grant race: every claim vanished while queued — settle immediately, never spawn an engine.
243
+ if (claimCount === 0) {
244
+ settleGrant();
245
+ return;
246
+ }
247
+ onGranted();
248
+ });
249
+ void deps.locks.request(lockName, { signal: controller.signal }, callback);
250
+ }
251
+
252
+ function settleGrant(): void {
253
+ const resolve = grantSettle;
254
+ grantSettle = undefined;
255
+ lockState = "idle";
256
+ resolve?.();
257
+ }
258
+
259
+ function addClaim(): () => void {
260
+ claimCount += 1;
261
+ if (claimCount === 1) queueLock();
262
+ let released = false;
263
+ return () => {
264
+ if (released) return;
265
+ released = true;
266
+ releaseClaim();
267
+ };
268
+ }
269
+
270
+ function releaseClaim(): void {
271
+ if (claimCount === 0) return;
272
+ claimCount -= 1;
273
+ if (claimCount > 0) return;
274
+ if (lockState === "queued") {
275
+ // Queued non-leader: cancel the pending request via its AbortSignal (fault row "queued non-leaders
276
+ // cancel via AbortSignal").
277
+ abortController?.abort();
278
+ abortController = undefined;
279
+ lockState = "idle";
280
+ } else if (lockState === "granted") {
281
+ void runRetirement();
282
+ }
283
+ }
284
+
285
+ // ─── grant duties ───────────────────────────────────────────────────────────
286
+ function onGranted(): void {
287
+ // leader-granted FIRST — it opens the router's handoff window pre-spawn (the attach side queues new calls).
288
+ post({ type: "leader-granted" });
289
+ spawnEngine();
290
+ announce();
291
+ startKeepalive();
292
+ }
293
+
294
+ function spawnEngine(): void {
295
+ engineHandle = deps.spawnEngineWorker();
296
+ engineHandle.onError((message) => onEngineError(message));
297
+ }
298
+
299
+ function announce(): void {
300
+ // Fresh control channel every announce: the ROUTER end (port1) is transferred to the SharedWorker (→
301
+ // router.announceEngine); the ENGINE end (port2) is wired to the elected engine worker in step 9.
302
+ const channel = createControlChannel();
303
+ post({ type: "engine-announce" }, [channel.port1]);
304
+ }
305
+
306
+ // ─── the single leader keepalive ────────────────────────────────────────────
307
+ function startKeepalive(): void {
308
+ keepaliveMisses = 0;
309
+ pendingKeepalivePingId = undefined;
310
+ scheduleKeepalive();
311
+ }
312
+
313
+ function scheduleKeepalive(): void {
314
+ keepaliveHandle = deps.timers.setTimeout(() => {
315
+ keepaliveHandle = undefined;
316
+ const pingId = ++pingSeq;
317
+ pendingKeepalivePingId = pingId;
318
+ post({ type: "control-ping", identity: KEEPALIVE_IDENTITY, pingId });
319
+ keepaliveMisses += 1;
320
+ if (keepaliveMisses >= keepaliveMissThreshold) {
321
+ onKeepaliveThreshold();
322
+ } else {
323
+ scheduleKeepalive();
324
+ }
325
+ }, keepaliveIntervalMs);
326
+ }
327
+
328
+ function stopKeepalive(): void {
329
+ if (keepaliveHandle !== undefined) {
330
+ deps.timers.clearTimeout(keepaliveHandle);
331
+ keepaliveHandle = undefined;
332
+ }
333
+ keepaliveMisses = 0;
334
+ pendingKeepalivePingId = undefined;
335
+ }
336
+
337
+ function onKeepaliveThreshold(): void {
338
+ stopKeepalive();
339
+ if (deps.reconstructSw === undefined) {
340
+ // A bare-instance attach input has no factory to rebuild the SharedWorker from, so keepalive recovery is
341
+ // structurally unavailable here: stop the keepalive and do nothing else (the still-live engine + grant are
342
+ // untouched — recovery narrows to a leader op or a page reload). A factory input never reaches this branch.
343
+ return;
344
+ }
345
+ // SharedWorker-death recovery is the LOCK HOLDER's causal duty: reconstruct via the factory, move the
346
+ // control plane to the new port, re-announce the still-live engine (a fresh control channel), and resume.
347
+ detachSwListener();
348
+ swPort = deps.reconstructSw();
349
+ attachSwListener();
350
+ announce();
351
+ startKeepalive();
352
+ }
353
+
354
+ // ─── engine loss ────────────────────────────────────────────────────────────
355
+ function onEngineError(_message: string): void {
356
+ if (!isLeader()) return;
357
+ // Reported worker death: respawn under the SAME grant (respawn, not re-queue — the leader lock is still
358
+ // held; failover cost is one cold engine boot, ADR D3).
359
+ engineHandle?.terminate();
360
+ currentIdentity = undefined;
361
+ spawnEngine();
362
+ announce();
363
+ }
364
+
365
+ async function onExecutionLimitVerdict(): Promise<void> {
366
+ // The router's execution-limit verdict: DELIBERATE termination (idempotent) → await the VFS ownership
367
+ // release that agent termination guarantees → respawn under the still-held grant (ADR D5).
368
+ engineHandle?.terminate();
369
+ engineHandle = undefined;
370
+ currentIdentity = undefined;
371
+ await deps.awaitOwnershipRelease();
372
+ if (!isLeader()) return; // the grant may have been released while awaiting
373
+ spawnEngine();
374
+ announce();
375
+ }
376
+
377
+ // ─── deliberate retirement (last-claim / BFCache) ───────────────────────────
378
+ async function runRetirement(): Promise<void> {
379
+ if (retiring) return;
380
+ retiring = true;
381
+ const identity = currentIdentity ?? RETIRE_UNKNOWN_IDENTITY;
382
+ // Stop the keepalive FIRST so no keepalive ack competes with the teardown ack.
383
+ stopKeepalive();
384
+ // The retirement notice PRECEDES the teardown — the attach side opens its handoff window and queues new
385
+ // calls before the engine goes (ADR D5, "deliberate retirement opens the window first").
386
+ post({ type: "engine-retiring", identity });
387
+ post({ type: "engine-teardown", identity });
388
+ await awaitTeardownAck(identity);
389
+ engineHandle?.terminate();
390
+ engineHandle = undefined;
391
+ currentIdentity = undefined;
392
+ retiring = false;
393
+ settleGrant(); // resolve the lock-holding promise → release the leader lock
394
+ }
395
+
396
+ function awaitTeardownAck(identity: EngineIdentity): Promise<void> {
397
+ return new Promise<void>((resolve) => {
398
+ const finish = (): void => {
399
+ if (teardownWait === undefined) return;
400
+ teardownWait = undefined;
401
+ deps.timers.clearTimeout(timeoutHandle);
402
+ resolve();
403
+ };
404
+ const timeoutHandle = deps.timers.setTimeout(finish, teardownAckTimeoutMs);
405
+ teardownWait = { identity, finish };
406
+ });
407
+ }
408
+
409
+ // ─── BFCache hooks ──────────────────────────────────────────────────────────
410
+ deps.pageLifecycle?.onPageHide((persisted) => {
411
+ // Persisted freeze (BFCache entry, D2): release leader authority + retire the engine, but PRESERVE the
412
+ // claim count so pageshow can re-queue. A non-persisted pagehide is ordinary navigation — the lock is
413
+ // released structurally on agent teardown, nothing special here.
414
+ if (persisted && lockState === "granted") {
415
+ bfcacheSuspended = true;
416
+ void runRetirement();
417
+ }
418
+ });
419
+ deps.pageLifecycle?.onPageShow(() => {
420
+ if (!bfcacheSuspended) return;
421
+ bfcacheSuspended = false;
422
+ // Claims were never decremented across the freeze, so a surviving claim re-queues the leader lock.
423
+ if (claimCount > 0) queueLock();
424
+ });
425
+
426
+ attachSwListener();
427
+
428
+ function isLeader(): boolean {
429
+ return lockState === "granted";
430
+ }
431
+
432
+ return {
433
+ claimForProvision(opts) {
434
+ const release = addClaim();
435
+ if (opts?.expiryMs === undefined) return release;
436
+ // Abandoned warmed provision (D2): auto-release this claim when the expiry fires (which, if it is the
437
+ // last claim while granted, runs the retirement sequence).
438
+ const handle = deps.timers.setTimeout(() => release(), opts.expiryMs);
439
+ return () => {
440
+ deps.timers.clearTimeout(handle);
441
+ release();
442
+ };
443
+ },
444
+ claimForAttach() {
445
+ return addClaim();
446
+ },
447
+ isLeader,
448
+ hasEngine() {
449
+ return engineHandle !== undefined;
450
+ },
451
+ async retireEngine() {
452
+ // Nothing to retire when this tab holds no engine (not the leader): the store's OPFS handle, if any, is
453
+ // held by another tab's engine — the peer-refusal gate already covered that (destroy refuses with peers).
454
+ if (!isLeader() || engineHandle === undefined) return;
455
+ // Run the graceful retirement (notice → teardown → ack/timeout → terminate → lock settle); `runRetirement`
456
+ // awaits the teardown ack (the release point) before terminating. Then await the ownership-release seam so
457
+ // a consumer/test can gate on the agent actually dropping the exclusive handle (default: resolved).
458
+ await runRetirement();
459
+ await deps.awaitOwnershipRelease();
460
+ },
461
+ };
462
+ }