@pgxsinkit/client 0.2.2 → 0.2.4

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 (38) hide show
  1. package/dist/boot-report.d.ts +3 -3
  2. package/dist/index.d.ts +35 -119
  3. package/dist/index.d.ts.map +1 -1
  4. package/dist/index.js +259 -392
  5. package/dist/index.js.map +14 -15
  6. package/dist/opfs-effects.d.ts +1 -1
  7. package/dist/store-boot.d.ts +82 -18
  8. package/dist/store-boot.d.ts.map +1 -1
  9. package/dist/store-lifecycle.d.ts +5 -66
  10. package/dist/store-lifecycle.d.ts.map +1 -1
  11. package/dist/store-meta.d.ts +20 -21
  12. package/dist/store-meta.d.ts.map +1 -1
  13. package/dist/worker/attach-sync-client.d.ts +51 -5
  14. package/dist/worker/attach-sync-client.d.ts.map +1 -1
  15. package/dist/worker/define-sync-worker.d.ts +1 -12
  16. package/dist/worker/define-sync-worker.d.ts.map +1 -1
  17. package/dist/worker/election-coordinator.d.ts.map +1 -1
  18. package/dist/worker/engine-control.d.ts +13 -0
  19. package/dist/worker/engine-control.d.ts.map +1 -1
  20. package/dist/worker/engine-router.d.ts +21 -5
  21. package/dist/worker/engine-router.d.ts.map +1 -1
  22. package/package.json +3 -3
  23. package/skills/core/SKILL.md +3 -2
  24. package/skills/operating/SKILL.md +40 -8
  25. package/src/boot-report.ts +3 -3
  26. package/src/index.ts +159 -486
  27. package/src/opfs-effects.ts +2 -2
  28. package/src/store-boot.ts +183 -71
  29. package/src/store-lifecycle.ts +12 -96
  30. package/src/store-meta.ts +33 -33
  31. package/src/worker/attach-sync-client.ts +194 -21
  32. package/src/worker/define-sync-worker.ts +94 -26
  33. package/src/worker/election-coordinator.ts +6 -1
  34. package/src/worker/engine-control.ts +12 -0
  35. package/src/worker/engine-router.ts +176 -21
  36. package/dist/adoption.d.ts +0 -118
  37. package/dist/adoption.d.ts.map +0 -1
  38. package/src/adoption.ts +0 -275
package/dist/index.js CHANGED
@@ -16,131 +16,6 @@ var __export = (target, all) => {
16
16
  var __esm = (fn, res) => () => (fn && (res = fn(fn = 0)), res);
17
17
  var __require = import.meta.require;
18
18
 
19
- // packages/client/src/store-lifecycle.ts
20
- async function runCommitmentBarrier(effects) {
21
- await effects.strictSyncReturns();
22
- await effects.publishSentinel();
23
- await effects.setPhase("opfs-committed");
24
- }
25
- async function beginFreshCandidate(effects) {
26
- await effects.writeCandidateRecord();
27
- await effects.createStoreDirectory();
28
- }
29
- async function resumeDeletion(effects) {
30
- await effects.deleteSentinel();
31
- await effects.deleteBackendStore();
32
- await effects.deleteMetaRecord();
33
- }
34
- async function runDestruction(effects) {
35
- await effects.setPhase("deleting");
36
- await resumeDeletion(effects);
37
- }
38
- function classifyAdoptionRecovery(obs) {
39
- return obs.sentinelPresent ? { action: "complete-adoption" } : { action: "teardown-and-restart" };
40
- }
41
- async function completeAdoption(effects) {
42
- await effects.setPhase("opfs-committed");
43
- await effects.deleteIdbPredecessor();
44
- }
45
- function journalOwesNothing(counts) {
46
- return counts.pending + counts.sending + counts.failed + counts.quarantined + counts.conflicted === 0;
47
- }
48
-
49
- // packages/client/src/adoption.ts
50
- async function awaitAdoptionGate(ready, deadlineMs) {
51
- let timer;
52
- const deadline = new Promise((_, reject) => {
53
- timer = setTimeout(() => reject(new Error("[pgxsinkit] adoption gate unmet: the eager Consistency groups did not complete their initial " + `catch-up within ${deadlineMs}ms (offline, unauthorized, or the server was unreachable). The idb ` + "store stays authoritative.")), deadlineMs);
54
- });
55
- try {
56
- await Promise.race([ready, deadline]);
57
- } finally {
58
- if (timer !== undefined)
59
- clearTimeout(timer);
60
- }
61
- }
62
- function buildAdoptionEffects(options) {
63
- let candidate;
64
- return {
65
- bootIdbPreExpose: () => options.readIdbJournal(),
66
- async strictSyncAndCloseIdb() {},
67
- setPhase: (phase) => options.setPhase(phase),
68
- async buildCandidateThroughGate() {
69
- candidate = await options.buildCandidate();
70
- await awaitAdoptionGate(candidate.ready, options.gateDeadlineMs ?? DEFAULT_ADOPTION_GATE_DEADLINE_MS);
71
- },
72
- async commitCandidate() {
73
- const active = candidate;
74
- if (active === undefined)
75
- throw new Error("[pgxsinkit] adoption: commit called before the candidate was built");
76
- await runCommitmentBarrier({
77
- strictSyncReturns: () => active.strictSync(),
78
- publishSentinel: () => options.publishSentinel(),
79
- setPhase: (phase) => options.setPhase(phase)
80
- });
81
- await active.close().catch(() => {
82
- return;
83
- });
84
- candidate = undefined;
85
- },
86
- deleteIdbPredecessor: () => options.deleteIdbPredecessor(),
87
- async teardownCandidate() {
88
- if (candidate !== undefined) {
89
- await candidate.close().catch(() => {
90
- return;
91
- });
92
- candidate = undefined;
93
- }
94
- await options.deleteSentinel();
95
- await options.deleteStoreDirectory();
96
- }
97
- };
98
- }
99
- function errorText(error) {
100
- return error instanceof Error ? error.message : String(error);
101
- }
102
- async function runTransition(effects) {
103
- const counts = await effects.bootIdbPreExpose();
104
- if (!journalOwesNothing(counts))
105
- return { adopted: false, reason: "journal-owed" };
106
- await effects.strictSyncAndCloseIdb();
107
- await effects.setPhase("adopting");
108
- try {
109
- await effects.buildCandidateThroughGate();
110
- } catch (error) {
111
- await effects.teardownCandidate();
112
- await effects.setPhase("idb-authoritative");
113
- return { adopted: false, reason: "gate-failed", error: errorText(error) };
114
- }
115
- try {
116
- await effects.commitCandidate();
117
- } catch (error) {
118
- await effects.teardownCandidate();
119
- await effects.setPhase("idb-authoritative");
120
- return { adopted: false, reason: "barrier-failed", error: errorText(error) };
121
- }
122
- try {
123
- await effects.deleteIdbPredecessor();
124
- } catch (error) {
125
- return { adopted: true, predecessorCleanupPending: errorText(error) };
126
- }
127
- return { adopted: true };
128
- }
129
- function runAdoptionTransition(declaration, effects) {
130
- if (declaration !== "server-reconstructible") {
131
- return Promise.resolve({ adopted: false, reason: "not-declared" });
132
- }
133
- return runTransition(effects);
134
- }
135
- function runManualAdoption(effects) {
136
- return runTransition(effects);
137
- }
138
- function adoptionEligible(declaration, verdict, hasOpfsSyncAccess) {
139
- return declaration === "server-reconstructible" && hasOpfsSyncAccess && verdict.action === "boot-idb-authoritative";
140
- }
141
- var DEFAULT_ADOPTION_GATE_DEADLINE_MS = 30000;
142
- var init_adoption = () => {};
143
-
144
19
  // packages/client/src/debug.ts
145
20
  function setSyncDebugSink(sink) {
146
21
  syncDebugSink = sink;
@@ -4971,6 +4846,26 @@ var init_shape_sync = __esm(() => {
4971
4846
  init_sync_auth();
4972
4847
  });
4973
4848
 
4849
+ // packages/client/src/store-lifecycle.ts
4850
+ async function runCommitmentBarrier(effects) {
4851
+ await effects.strictSyncReturns();
4852
+ await effects.publishSentinel();
4853
+ await effects.setPhase("opfs-committed");
4854
+ }
4855
+ async function beginFreshCandidate(effects) {
4856
+ await effects.writeCandidateRecord();
4857
+ await effects.createStoreDirectory();
4858
+ }
4859
+ async function resumeDeletion(effects) {
4860
+ await effects.deleteSentinel();
4861
+ await effects.deleteBackendStore();
4862
+ await effects.deleteMetaRecord();
4863
+ }
4864
+ async function runDestruction(effects) {
4865
+ await effects.setPhase("deleting");
4866
+ await resumeDeletion(effects);
4867
+ }
4868
+
4974
4869
  // packages/client/src/store-meta.ts
4975
4870
  var exports_store_meta = {};
4976
4871
  __export(exports_store_meta, {
@@ -4990,8 +4885,6 @@ function classifyStoreBoot(obs) {
4990
4885
  switch (record.phase) {
4991
4886
  case "deleting":
4992
4887
  return { action: "resume-deletion" };
4993
- case "adopting":
4994
- return { action: "adoption-recovery" };
4995
4888
  case "opfs-committed":
4996
4889
  return { action: "open-committed" };
4997
4890
  case "opfs-candidate":
@@ -5181,7 +5074,6 @@ var init_store_meta = __esm(() => {
5181
5074
  VALID_PHASES = new Set([
5182
5075
  "idb-authoritative",
5183
5076
  "opfs-candidate",
5184
- "adopting",
5185
5077
  "opfs-committed",
5186
5078
  "deleting"
5187
5079
  ]);
@@ -5232,17 +5124,34 @@ function resolveHasIndexedDb(meta) {
5232
5124
  return meta.indexedDB != null;
5233
5125
  return typeof globalThis.indexedDB !== "undefined";
5234
5126
  }
5235
- async function recoverDeniedBootDeletion(storePath, deps) {
5127
+ function committedStoreUnreachableFromWire(detail) {
5128
+ if (typeof detail !== "object" || detail === null)
5129
+ return;
5130
+ const candidate = detail;
5131
+ if (candidate.code !== COMMITTED_STORE_UNREACHABLE_CODE)
5132
+ return;
5133
+ if (typeof candidate.storePath !== "string")
5134
+ return;
5135
+ return new CommittedStoreUnreachableError(candidate.storePath);
5136
+ }
5137
+ async function resolveDeniedBootAuthority(storePath, deps) {
5236
5138
  const meta = deps?.meta;
5237
5139
  const record = await readStoreMetaRecord(storePath, meta);
5238
- if (record === META_STORE_UNAVAILABLE || record?.phase !== "deleting")
5140
+ if (record === META_STORE_UNAVAILABLE)
5141
+ return false;
5142
+ const phase = record?.phase;
5143
+ if (phase === "opfs-committed")
5144
+ throw new CommittedStoreUnreachableError(storePath);
5145
+ if (phase !== "deleting" && phase !== "opfs-candidate")
5239
5146
  return false;
5240
5147
  const effects = createOpfsEffects(storePath, deps?.opfs);
5241
5148
  if (await effects.observeCommitmentNamespace() === "unobservable") {
5242
- throw new Error(`[pgxsinkit] cannot resume deletion for ${JSON.stringify(storePath)}: the OPFS commitment namespace is ` + "unobservable in this scope, so sentinel removal cannot be confirmed.");
5149
+ throw new Error(`[pgxsinkit] cannot settle ${JSON.stringify(storePath)} for an IDB boot (record phase ` + `${JSON.stringify(phase)}): the OPFS commitment namespace is unobservable in this scope, so sentinel ` + "removal cannot be confirmed.");
5243
5150
  }
5244
- await deleteIdbDatabase(storePath, meta);
5151
+ if (phase === "deleting")
5152
+ await deleteIdbDatabase(storePath, meta);
5245
5153
  await effects.deleteSentinel();
5154
+ await effects.deleteStoreDirectory();
5246
5155
  await writeStoreMetaRecord(storePath, { phase: "idb-authoritative", updatedAt: Date.now() }, meta);
5247
5156
  return true;
5248
5157
  }
@@ -5280,6 +5189,10 @@ async function resolveStoreBoot(storePath, opts) {
5280
5189
  const metaResult = await readStoreMetaRecord(storePath, meta);
5281
5190
  const metaUnavailable = metaResult === META_STORE_UNAVAILABLE;
5282
5191
  const record = metaUnavailable ? undefined : metaResult;
5192
+ const committedFastVerdict = record?.phase === "opfs-committed" ? classifyStoreBoot({ record, opfs: "unobservable", idbStoreExists: false }) : undefined;
5193
+ if (committedFastVerdict?.action === "open-committed") {
5194
+ return { dataDir: opfsDataDir, storageBackend: "opfs-repacked", verdict: committedFastVerdict };
5195
+ }
5283
5196
  const opfsObservation = await effects.observeCommitmentNamespace();
5284
5197
  const idbPresent = metaUnavailable ? false : await idbExists(storePath);
5285
5198
  const verdict = classifyStoreBoot({ record, opfs: opfsObservation, idbStoreExists: idbPresent });
@@ -5298,35 +5211,17 @@ async function resolveStoreBoot(storePath, opts) {
5298
5211
  case "delete-candidate-and-rebuild":
5299
5212
  await effects.deleteSentinel();
5300
5213
  await effects.deleteStoreDirectory();
5301
- return finishVirginCreate(verdict);
5214
+ await deleteStoreMetaRecord(storePath, meta);
5215
+ continue;
5302
5216
  case "repair-record-then-open-committed":
5303
5217
  await writePhase("opfs-committed");
5304
- if (idbPresent)
5305
- await deleteIdbDatabase(storePath, meta);
5306
5218
  return { dataDir: opfsDataDir, storageBackend: "opfs-repacked", verdict };
5307
5219
  case "open-committed":
5308
- if (idbPresent)
5309
- await deleteIdbDatabase(storePath, meta);
5310
5220
  return { dataDir: opfsDataDir, storageBackend: "opfs-repacked", verdict };
5311
5221
  case "boot-idb-authoritative":
5312
5222
  if (record == null)
5313
5223
  await writePhase("idb-authoritative");
5314
5224
  return { dataDir: idbDataDir, storageBackend: "idbfs", verdict };
5315
- case "adoption-recovery": {
5316
- const sentinelPresent = opfsObservation !== "unobservable" && opfsObservation.sentinelPresent;
5317
- const recovery = classifyAdoptionRecovery({ sentinelPresent });
5318
- if (recovery.action === "complete-adoption") {
5319
- await completeAdoption({
5320
- setPhase: writePhase,
5321
- deleteIdbPredecessor: () => deleteIdbDatabase(storePath, meta)
5322
- });
5323
- return { dataDir: opfsDataDir, storageBackend: "opfs-repacked", verdict };
5324
- }
5325
- await effects.deleteSentinel();
5326
- await effects.deleteStoreDirectory();
5327
- await writePhase("idb-authoritative");
5328
- return { dataDir: idbDataDir, storageBackend: "idbfs", verdict };
5329
- }
5330
5225
  case "virgin-create":
5331
5226
  return finishVirginCreate(verdict);
5332
5227
  default: {
@@ -5337,11 +5232,22 @@ async function resolveStoreBoot(storePath, opts) {
5337
5232
  }
5338
5233
  throw new Error("[pgxsinkit] store boot did not settle after resuming a deletion (bounded re-classification exhausted).");
5339
5234
  }
5340
- var MAX_DELETION_RECLASSIFY = 4;
5235
+ var MAX_DELETION_RECLASSIFY = 4, COMMITTED_STORE_UNREACHABLE_CODE = "committed-store-unreachable", CommittedStoreUnreachableError;
5341
5236
  var init_store_boot = __esm(() => {
5342
5237
  init_opfs_effects();
5343
5238
  init_store_meta();
5344
5239
  init_store_path();
5240
+ CommittedStoreUnreachableError = class CommittedStoreUnreachableError extends Error {
5241
+ code = COMMITTED_STORE_UNREACHABLE_CODE;
5242
+ storePath;
5243
+ detail;
5244
+ constructor(storePath) {
5245
+ super(`[pgxsinkit] refusing to boot ${JSON.stringify(storePath)} here: its store meta record says the store is ` + "COMMITTED to the OPFS backend, and this boot's engine home holds no OPFS sync-access grant \u2014 so it " + "cannot open that store. Booting the IndexedDB store at the same path would mint an EMPTY sibling: the " + "app would look wiped and offline writes would fork into a store no OPFS-capable boot ever opens. " + "Either boot from an engine home that HOLDS a grant (worker mode's elected engine worker, or the " + "SharedWorker-direct home), or destroy the store first \u2014 call " + `\`destroyStoreArtifacts(${JSON.stringify(storePath)})\` (exported from \`@pgxsinkit/client\`), which is ` + "path-addressed and needs no grant: it deletes BOTH backends plus the commitment sentinel and the meta " + "record (quiesce any live worker for the path first, `quiesceStoreWorker`) \u2014 and let the next boot " + "rebuild it (ADR-0049 invariant 3; ADR-0050 never a silently different storage mode).");
5246
+ this.name = "CommittedStoreUnreachableError";
5247
+ this.storePath = storePath;
5248
+ this.detail = { code: COMMITTED_STORE_UNREACHABLE_CODE, storePath };
5249
+ }
5250
+ };
5345
5251
  });
5346
5252
 
5347
5253
  // packages/client/src/sync/nudge.ts
@@ -6950,6 +6856,7 @@ function shouldApplyControlMessage(current, message) {
6950
6856
  return true;
6951
6857
  case "engine-ready":
6952
6858
  case "connect-port":
6859
+ case "connect-port-ack":
6953
6860
  case "control-ping":
6954
6861
  case "control-ack":
6955
6862
  case "overdue-dispatch":
@@ -7008,6 +6915,7 @@ var init_engine_control = __esm(() => {
7008
6915
  TAGGED_CONTROL_TYPES = new Set([
7009
6916
  "engine-ready",
7010
6917
  "connect-port",
6918
+ "connect-port-ack",
7011
6919
  "control-ping",
7012
6920
  "control-ack",
7013
6921
  "overdue-dispatch",
@@ -7040,6 +6948,7 @@ function createEngineRouter(options) {
7040
6948
  const { swInstanceId, executionLimit } = options;
7041
6949
  const probeMissThreshold = options.probeMissThreshold ?? 3;
7042
6950
  const probeIntervalMs = options.probeIntervalMs ?? 2000;
6951
+ const connectAckTimeoutMs = options.connectAckTimeoutMs ?? 3000;
7043
6952
  const createPipe = options.createPipe ?? (() => new MessageChannel);
7044
6953
  const timers = options.timers ?? {
7045
6954
  setTimeout: (fn, ms) => globalThis.setTimeout(fn, ms),
@@ -7050,7 +6959,11 @@ function createEngineRouter(options) {
7050
6959
  let lastMinted;
7051
6960
  let controlPort;
7052
6961
  let controlListener;
6962
+ let controlCloseListener;
7053
6963
  let engineReady = false;
6964
+ let teardownForwarded;
6965
+ let connectAckHandle;
6966
+ const executionLimitEnabled = executionLimit?.maxDispatchMs !== undefined;
7054
6967
  let probeRunning = false;
7055
6968
  let probeHandle;
7056
6969
  let missCount = 0;
@@ -7067,6 +6980,23 @@ function createEngineRouter(options) {
7067
6980
  const { port1, port2 } = createPipe();
7068
6981
  controlPort.postMessage(wrapControlEnvelope({ type: "connect-port", identity: currentIdentity }), [port1]);
7069
6982
  tab.port.postMessage(wrapControlEnvelope({ type: "connect-port", identity: currentIdentity }), [port2]);
6983
+ if (executionLimitEnabled)
6984
+ armConnectAckWindow(currentIdentity);
6985
+ }
6986
+ function clearConnectAckWindow() {
6987
+ if (connectAckHandle !== undefined) {
6988
+ timers.clearTimeout(connectAckHandle);
6989
+ connectAckHandle = undefined;
6990
+ }
6991
+ }
6992
+ function armConnectAckWindow(armedFor) {
6993
+ clearConnectAckWindow();
6994
+ connectAckHandle = timers.setTimeout(() => {
6995
+ connectAckHandle = undefined;
6996
+ if (currentIdentity === undefined || !engineIdentityEquals(currentIdentity, armedFor))
6997
+ return;
6998
+ startProbe();
6999
+ }, connectAckTimeoutMs);
7070
7000
  }
7071
7001
  function resetProbe() {
7072
7002
  probeRunning = false;
@@ -7079,11 +7009,18 @@ function createEngineRouter(options) {
7079
7009
  }
7080
7010
  function clearEngine() {
7081
7011
  resetProbe();
7082
- if (controlPort !== undefined && controlListener !== undefined) {
7083
- controlPort.removeEventListener("message", controlListener);
7012
+ clearConnectAckWindow();
7013
+ if (controlPort !== undefined) {
7014
+ if (controlListener !== undefined)
7015
+ controlPort.removeEventListener("message", controlListener);
7016
+ if (controlCloseListener !== undefined) {
7017
+ controlPort.removeEventListener?.("close", controlCloseListener);
7018
+ }
7084
7019
  }
7085
7020
  controlPort = undefined;
7086
7021
  controlListener = undefined;
7022
+ controlCloseListener = undefined;
7023
+ teardownForwarded = undefined;
7087
7024
  currentIdentity = undefined;
7088
7025
  engineReady = false;
7089
7026
  }
@@ -7101,16 +7038,18 @@ function createEngineRouter(options) {
7101
7038
  resetProbe();
7102
7039
  return;
7103
7040
  }
7041
+ if (pendingPingId !== undefined) {
7042
+ missCount += 1;
7043
+ if (missCount >= probeMissThreshold) {
7044
+ resetProbe();
7045
+ retireCurrentEngine();
7046
+ return;
7047
+ }
7048
+ }
7104
7049
  const pingId = ++pingSeq;
7105
7050
  pendingPingId = pingId;
7106
7051
  controlPort.postMessage(wrapControlEnvelope({ type: "control-ping", identity: currentIdentity, pingId }));
7107
- missCount += 1;
7108
- if (missCount >= probeMissThreshold) {
7109
- resetProbe();
7110
- retireCurrentEngine();
7111
- } else {
7112
- scheduleProbe();
7113
- }
7052
+ scheduleProbe();
7114
7053
  }, probeIntervalMs);
7115
7054
  }
7116
7055
  function startProbe() {
@@ -7118,8 +7057,20 @@ function createEngineRouter(options) {
7118
7057
  return;
7119
7058
  probeRunning = true;
7120
7059
  missCount = 0;
7060
+ pendingPingId = undefined;
7121
7061
  scheduleProbe();
7122
7062
  }
7063
+ function onControlPortClose(port, announced) {
7064
+ if (controlPort !== port)
7065
+ return;
7066
+ if (currentIdentity === undefined || !engineIdentityEquals(currentIdentity, announced))
7067
+ return;
7068
+ if (teardownForwarded !== undefined && engineIdentityEquals(teardownForwarded, announced)) {
7069
+ clearEngine();
7070
+ return;
7071
+ }
7072
+ retireCurrentEngine();
7073
+ }
7123
7074
  function onControlMessage(data) {
7124
7075
  const message = readControlEnvelope(data);
7125
7076
  if (message === undefined)
@@ -7132,6 +7083,10 @@ function createEngineRouter(options) {
7132
7083
  deliverPipe(tab);
7133
7084
  }
7134
7085
  return;
7086
+ case "connect-port-ack":
7087
+ if (shouldApplyControlMessage(currentIdentity, message))
7088
+ clearConnectAckWindow();
7089
+ return;
7135
7090
  case "control-ack":
7136
7091
  if (shouldApplyControlMessage(currentIdentity, message) && message.pingId === pendingPingId) {
7137
7092
  resetProbe();
@@ -7161,6 +7116,7 @@ function createEngineRouter(options) {
7161
7116
  case "engine-teardown":
7162
7117
  if (!shouldApplyControlMessage(currentIdentity, message))
7163
7118
  return;
7119
+ teardownForwarded = message.identity;
7164
7120
  controlPort?.postMessage(wrapControlEnvelope(message));
7165
7121
  return;
7166
7122
  case "tab-detach":
@@ -7206,6 +7162,12 @@ function createEngineRouter(options) {
7206
7162
  controlPort = port;
7207
7163
  controlListener = (event) => onControlMessage(event.data);
7208
7164
  port.addEventListener("message", controlListener);
7165
+ const closable = port;
7166
+ if ("onclose" in closable) {
7167
+ const closeListener = () => onControlPortClose(port, minted);
7168
+ controlCloseListener = closeListener;
7169
+ closable.addEventListener("close", closeListener);
7170
+ }
7209
7171
  port.start?.();
7210
7172
  engineReady = false;
7211
7173
  port.postMessage(wrapControlEnvelope({ type: "assign-identity", identity: minted }));
@@ -7539,7 +7501,6 @@ function defineSyncWorker(options) {
7539
7501
  ...engineStorage ? { storage: engineStorage } : {},
7540
7502
  ...placementOpfsAccess ? { hasOpfsSyncAccess: true } : {},
7541
7503
  ...placementFallbackReason ? { storageFallbackReason: placementFallbackReason } : {},
7542
- ...options.adoption ? { adoption: options.adoption } : {},
7543
7504
  ...attach.config?.freshStore === true ? { freshStore: true } : {},
7544
7505
  getAuthToken: getWorkerAuthToken,
7545
7506
  autoSync: gatedTrigger,
@@ -7738,15 +7699,47 @@ function defineSyncWorker(options) {
7738
7699
  break;
7739
7700
  }
7740
7701
  const attempt = placementGate.then(async () => {
7702
+ let recordCandidateBeforeMint = false;
7741
7703
  if (backendOverride !== "memory") {
7742
7704
  const record = await readStoreMetaRecord(storePath);
7743
- if (record !== META_STORE_UNAVAILABLE && record?.phase === "deleting") {
7744
- syncDebug("worker provision declined \u2014 deletion authority is live", { storePath });
7705
+ const metaUnavailable = record === META_STORE_UNAVAILABLE;
7706
+ const phase = metaUnavailable ? undefined : record?.phase;
7707
+ if (phase === "opfs-committed" && !placementOpfsAccess) {
7708
+ syncDebug("worker provision declined \u2014 the store is committed to OPFS and this home holds no sync access", {
7709
+ storePath
7710
+ });
7745
7711
  return;
7746
7712
  }
7713
+ if (phase !== undefined && phase !== "opfs-committed" && (placementOpfsAccess || phase === "deleting" || phase === "opfs-candidate")) {
7714
+ syncDebug("worker provision declined \u2014 the store phase is owned elsewhere", { storePath, phase });
7715
+ return;
7716
+ }
7717
+ if (phase === undefined && placementOpfsAccess) {
7718
+ if (metaUnavailable) {
7719
+ syncDebug("worker provision declined \u2014 no meta store to record an opfs candidate", { storePath });
7720
+ return;
7721
+ }
7722
+ const observation = await createOpfsEffects(storePath).observeCommitmentNamespace();
7723
+ const virgin = observation !== "unobservable" && !observation.sentinelPresent && !observation.storeDirectoryPresent;
7724
+ if (!virgin) {
7725
+ syncDebug("worker provision declined \u2014 the commitment namespace is not a provable virgin", {
7726
+ storePath,
7727
+ observation
7728
+ });
7729
+ return;
7730
+ }
7731
+ if (await idbStoreExists(storePath)) {
7732
+ syncDebug("worker provision declined \u2014 an idb store already exists at this path", { storePath });
7733
+ return;
7734
+ }
7735
+ recordCandidateBeforeMint = true;
7736
+ }
7747
7737
  }
7748
7738
  if (bootPromise != null || provisioned != null)
7749
7739
  return;
7740
+ if (recordCandidateBeforeMint) {
7741
+ await writeStoreMetaRecord(storePath, { phase: "opfs-candidate", updatedAt: Date.now() });
7742
+ }
7750
7743
  const provisionStartedAt = nowStamp();
7751
7744
  const pglite = Promise.resolve().then(() => createPglite(storePath, backendOverride));
7752
7745
  const stamp = pglite.then(() => {
@@ -8045,6 +8038,7 @@ function startEngineControlPlane(controlPort, connect, closeScope) {
8045
8038
  case "connect-port": {
8046
8039
  if (!shouldApplyControlMessage(assigned, message))
8047
8040
  return;
8041
+ post({ type: "connect-port-ack", identity: message.identity });
8048
8042
  const transferred = event.ports?.[0];
8049
8043
  if (!transferred)
8050
8044
  return;
@@ -8362,6 +8356,7 @@ var init_define_sync_worker = __esm(() => {
8362
8356
  init_convergence();
8363
8357
  init_src();
8364
8358
  init_live_rows_sql();
8359
+ init_opfs_effects();
8365
8360
  init_placement_probe();
8366
8361
  init_store_meta();
8367
8362
  init_store_path();
@@ -8469,7 +8464,11 @@ function createElectionCoordinator(deps, options) {
8469
8464
  }
8470
8465
  onGranted();
8471
8466
  });
8472
- deps.locks.request(lockName, { signal: controller.signal }, callback);
8467
+ deps.locks.request(lockName, { signal: controller.signal }, callback).catch((error) => {
8468
+ if (controller.signal.aborted && error instanceof Error && error.name === "AbortError")
8469
+ return;
8470
+ throw error;
8471
+ });
8473
8472
  }
8474
8473
  function settleGrant() {
8475
8474
  const resolve = grantSettle;
@@ -8664,6 +8663,7 @@ __export(exports_attach_sync_client, {
8664
8663
  createStoreDestructionEffects: () => createStoreDestructionEffects,
8665
8664
  attachSyncClient: () => attachSyncClient,
8666
8665
  StoreDestroyRefusedError: () => StoreDestroyRefusedError,
8666
+ ProvisionExpiredError: () => ProvisionExpiredError,
8667
8667
  ElectedEngineUnconstructibleError: () => ElectedEngineUnconstructibleError
8668
8668
  });
8669
8669
  import { StorageDeclarationRefusedError as StorageDeclarationRefusedError2 } from "@pgxsinkit/contracts";
@@ -8900,6 +8900,11 @@ function adoptOrRegisterCoordinator(storePath, build) {
8900
8900
  let entry = sharedCoordinators.get(storePath);
8901
8901
  if (entry === undefined) {
8902
8902
  entry = { coordinator: build(), refs: 0 };
8903
+ const pending = pendingProvisionPipes.get(storePath);
8904
+ if (pending !== undefined) {
8905
+ pendingProvisionPipes.delete(storePath);
8906
+ entry.provisionPipe = pending;
8907
+ }
8903
8908
  sharedCoordinators.set(storePath, entry);
8904
8909
  }
8905
8910
  entry.refs += 1;
@@ -8921,19 +8926,35 @@ function releaseSharedCoordinator(storePath) {
8921
8926
  if (entry.refs <= 0) {
8922
8927
  entry.provisionPipe?.pipe.close?.();
8923
8928
  sharedCoordinators.delete(storePath);
8929
+ const pending = pendingProvisionPipes.get(storePath);
8930
+ if (pending !== undefined) {
8931
+ pendingProvisionPipes.delete(storePath);
8932
+ pending.pipe.close?.();
8933
+ }
8924
8934
  }
8925
8935
  }
8926
8936
  function stashProvisionPipe(storePath, pipe, identity) {
8927
8937
  const entry = sharedCoordinators.get(storePath);
8938
+ const previous = entry !== undefined ? entry.provisionPipe : pendingProvisionPipes.get(storePath);
8939
+ if (previous !== undefined && previous.pipe !== pipe && !engineIdentityEquals(previous.identity, identity)) {
8940
+ previous.pipe.close?.();
8941
+ }
8928
8942
  if (entry !== undefined)
8929
8943
  entry.provisionPipe = { pipe, identity };
8944
+ else
8945
+ pendingProvisionPipes.set(storePath, { pipe, identity });
8930
8946
  }
8931
8947
  function takeProvisionPipe(storePath) {
8932
8948
  const entry = sharedCoordinators.get(storePath);
8933
- const stashed = entry?.provisionPipe;
8934
- if (entry !== undefined)
8949
+ if (entry?.provisionPipe !== undefined) {
8950
+ const stashed = entry.provisionPipe;
8935
8951
  delete entry.provisionPipe;
8936
- return stashed;
8952
+ return stashed;
8953
+ }
8954
+ const pending = pendingProvisionPipes.get(storePath);
8955
+ if (pending !== undefined)
8956
+ pendingProvisionPipes.delete(storePath);
8957
+ return pending;
8937
8958
  }
8938
8959
  function setProvisionRelease(storePath, release) {
8939
8960
  const entry = sharedCoordinators.get(storePath);
@@ -9961,6 +9982,7 @@ function provisionSyncWorker(options) {
9961
9982
  clearTimeout: (handle) => globalThis.clearTimeout(handle)
9962
9983
  };
9963
9984
  const storePath = options.storePath ?? options.storeId ?? "pgxsinkit-overlay-v1";
9985
+ const expiryMs = options.provisionExpiryMs ?? 60000;
9964
9986
  const memoryOverride = readTestStoreMarker(options) === "memory";
9965
9987
  const provisionPayload = {
9966
9988
  ...options.storeId ? { storeId: options.storeId } : {},
@@ -9972,6 +9994,7 @@ function provisionSyncWorker(options) {
9972
9994
  const provision = new Promise((resolve, reject) => {
9973
9995
  let settled = false;
9974
9996
  const ackRemovers = [];
9997
+ let settlementHandle;
9975
9998
  const controlListener = (event) => {
9976
9999
  const placement = readPlacementResult(event.data);
9977
10000
  if (placement !== undefined) {
@@ -9994,8 +10017,12 @@ function provisionSyncWorker(options) {
9994
10017
  port.removeEventListener("message", controlListener);
9995
10018
  for (const remove of ackRemovers)
9996
10019
  remove();
10020
+ timers.clearTimeout(settlementHandle);
9997
10021
  fn();
9998
10022
  };
10023
+ settlementHandle = timers.setTimeout(() => {
10024
+ settle(() => reject(new ProvisionExpiredError(storePath, expiryMs)));
10025
+ }, expiryMs);
9999
10026
  const awaitAckOn = (ackPort) => {
10000
10027
  const ackListener = (message) => {
10001
10028
  if (!isBridgeEnvelope(message.data) || message.data.type !== "provision-ack")
@@ -10012,11 +10039,9 @@ function provisionSyncWorker(options) {
10012
10039
  postBridgeMessage(target, codec, "provision", provisionPayload);
10013
10040
  };
10014
10041
  let placementDecided = false;
10015
- let piped = false;
10016
10042
  const onProvisionPipe = (pipe, identity) => {
10017
- if (piped || pipe === undefined)
10043
+ if (settled || pipe === undefined)
10018
10044
  return;
10019
- piped = true;
10020
10045
  stashProvisionPipe(storePath, pipe, identity);
10021
10046
  postProvisionOn(pipe);
10022
10047
  };
@@ -10046,7 +10071,6 @@ function provisionSyncWorker(options) {
10046
10071
  ...pageLifecycle ? { pageLifecycle } : {}
10047
10072
  }));
10048
10073
  const releaseProvisionClaim = coordinator.claimForProvision();
10049
- const expiryMs = options.provisionExpiryMs ?? 60000;
10050
10074
  let released = false;
10051
10075
  const expiryHandle = timers.setTimeout(() => {
10052
10076
  if (released)
@@ -10112,6 +10136,9 @@ function rebuildError(error) {
10112
10136
  const mismatch = executionLimitMismatchFromWire(error.detail);
10113
10137
  if (mismatch !== undefined)
10114
10138
  return mismatch;
10139
+ const unreachable = committedStoreUnreachableFromWire(error.detail);
10140
+ if (unreachable !== undefined)
10141
+ return unreachable;
10115
10142
  }
10116
10143
  const rebuilt = new Error(error?.message ?? "worker rpc failed");
10117
10144
  if (error?.name !== undefined) {
@@ -10130,10 +10157,11 @@ function rebuildRpcError(error) {
10130
10157
  }
10131
10158
  return rebuildError(error);
10132
10159
  }
10133
- var StoreDestroyRefusedError, ElectedEngineUnconstructibleError, MUTATION_RPC_OPS, sharedCoordinators;
10160
+ var StoreDestroyRefusedError, ElectedEngineUnconstructibleError, ProvisionExpiredError, MUTATION_RPC_OPS, sharedCoordinators, pendingProvisionPipes;
10134
10161
  var init_attach_sync_client = __esm(() => {
10135
10162
  init_src();
10136
10163
  init_opfs_effects();
10164
+ init_store_boot();
10137
10165
  init_store_meta();
10138
10166
  init_store_path();
10139
10167
  init_store_path();
@@ -10156,6 +10184,16 @@ var init_attach_sync_client = __esm(() => {
10156
10184
  this.name = "ElectedEngineUnconstructibleError";
10157
10185
  }
10158
10186
  };
10187
+ ProvisionExpiredError = class ProvisionExpiredError extends Error {
10188
+ storePath;
10189
+ expiryMs;
10190
+ constructor(storePath, expiryMs) {
10191
+ super(`[pgxsinkit] provisionSyncWorker("${storePath}"): the provision did not settle within ${expiryMs}ms \u2014 the ` + `SharedWorker connection may be dead or the elected engine never came up. The deadline bounds THIS ` + `promise; the worker-side create attempt follows the placement. SW-direct: the attempt is left running, ` + `so a later attach adopts it if it completed and waits on it if it is stuck, and a retry re-acks the ` + `same attempt rather than starting a second open. Elected: this deadline also releases the provision ` + `claim, and a LAST-claim release retires and terminates the engine, so the next attach elects a fresh ` + `one. Retrying is safe either way.`);
10192
+ this.name = "ProvisionExpiredError";
10193
+ this.storePath = storePath;
10194
+ this.expiryMs = expiryMs;
10195
+ }
10196
+ };
10159
10197
  MUTATION_RPC_OPS = new Set([
10160
10198
  "create",
10161
10199
  "update",
@@ -10173,6 +10211,7 @@ var init_attach_sync_client = __esm(() => {
10173
10211
  "rawExec"
10174
10212
  ]);
10175
10213
  sharedCoordinators = new Map;
10214
+ pendingProvisionPipes = new Map;
10176
10215
  });
10177
10216
 
10178
10217
  // packages/client/src/index.ts
@@ -10187,6 +10226,9 @@ import {
10187
10226
  isClaimsDependentRowFilter,
10188
10227
  resolveStorageDeclaration as resolveStorageDeclaration2
10189
10228
  } from "@pgxsinkit/contracts";
10229
+ function isOpfsRepackedPersistent(instance) {
10230
+ return instance[OPFS_REPACKED_PERSISTENT] === true;
10231
+ }
10190
10232
  async function openWithBoundedRetries(open, backoffMs) {
10191
10233
  let lastError;
10192
10234
  for (let attempt = 1;attempt <= OPFS_OPEN_ATTEMPTS; attempt += 1) {
@@ -10206,7 +10248,7 @@ async function createClientPGlite(store, options) {
10206
10248
  const storePath = normalised.storePath;
10207
10249
  const backendOverride = options?.backendOverride ?? normalised.backendOverride;
10208
10250
  if (options?.hasOpfsSyncAccess !== true && backendOverride !== "memory") {
10209
- await recoverDeniedBootDeletion(storePath);
10251
+ await resolveDeniedBootAuthority(storePath);
10210
10252
  }
10211
10253
  const dataDir = options?.hasOpfsSyncAccess ? resolveStoreDataDir(storePath, backendOverride, { hasIndexedDb: true, hasOpfsSyncAccess: true }) : resolveStoreDataDir(storePath, backendOverride);
10212
10254
  const dataDirScheme = dataDir.slice(0, dataDir.indexOf(":") + 1);
@@ -10252,144 +10294,6 @@ async function createClientPGlite(store, options) {
10252
10294
  }, { ...dataDirScheme ? { dataDir: dataDirScheme } : {}, relaxedDurability });
10253
10295
  return pglite;
10254
10296
  }
10255
- function deleteAdoptionIdbPredecessor(storePath, meta) {
10256
- const idb = meta != null && "indexedDB" in meta ? meta.indexedDB : globalThis.indexedDB;
10257
- if (idb?.deleteDatabase == null)
10258
- return Promise.resolve();
10259
- const name = storeIndexedDbDatabaseName(storePath);
10260
- return new Promise((resolve, reject) => {
10261
- let settled = false;
10262
- let timeout;
10263
- const finish = (error) => {
10264
- if (settled)
10265
- return;
10266
- settled = true;
10267
- if (timeout !== undefined)
10268
- clearTimeout(timeout);
10269
- if (error === undefined)
10270
- resolve();
10271
- else
10272
- reject(error);
10273
- };
10274
- let request;
10275
- try {
10276
- request = idb.deleteDatabase(name);
10277
- } catch (error) {
10278
- finish(error);
10279
- return;
10280
- }
10281
- request.onsuccess = () => finish();
10282
- request.onerror = () => finish(request.error ?? new Error(`indexedDB deletion failed for ${name}`));
10283
- request.onblocked = () => {
10284
- return;
10285
- };
10286
- timeout = setTimeout(() => finish(new Error(`indexedDB deletion timed out while blocked for ${name}`)), 5000);
10287
- });
10288
- }
10289
- function buildRealAdoptionEffects(storePath, ctx) {
10290
- const opfs = createOpfsEffects(storePath, ctx.opfs);
10291
- const createPglite = ctx.createPglite ?? createClientPGlite;
10292
- const setPhase = (phase) => writeStoreMetaRecord(storePath, { phase, updatedAt: Date.now() }, ctx.meta);
10293
- return buildAdoptionEffects({
10294
- async readIdbJournal() {
10295
- const idbPglite = await createPglite(storePath, { durability: "strict" });
10296
- try {
10297
- const runtime = createMutationRuntime({
10298
- db: idbPglite,
10299
- registry: ctx.registry,
10300
- batchWriteUrl: ctx.batchWriteUrl,
10301
- ownsMetaTable: true
10302
- });
10303
- const stats = await runtime.readMutationStats();
10304
- return {
10305
- pending: stats.pendingCount,
10306
- sending: stats.sendingCount,
10307
- acked: stats.ackedCount,
10308
- failed: stats.failedCount,
10309
- quarantined: stats.quarantinedCount,
10310
- conflicted: stats.conflictedCount,
10311
- rejected: stats.rejectedCount
10312
- };
10313
- } finally {
10314
- await idbPglite.close();
10315
- }
10316
- },
10317
- setPhase,
10318
- async buildCandidate() {
10319
- if (!ctx.syncEnabled) {
10320
- throw new Error("[pgxsinkit] adoption gate unmet: sync is disabled (`syncEnabled: false`), so the opfs successor " + "cannot be reconstructed online. The idb store stays authoritative.");
10321
- }
10322
- const candidate = await createSyncClient({
10323
- registry: ctx.registry,
10324
- electricUrl: ctx.electricUrl,
10325
- batchWriteUrl: ctx.batchWriteUrl,
10326
- storePath,
10327
- hasOpfsSyncAccess: true,
10328
- freshStore: true,
10329
- syncEnabled: true,
10330
- [ADOPTION_CANDIDATE_BUILD]: true,
10331
- [INTERNAL_PGLITE_CREATE]: createPglite,
10332
- ...ctx.getAuthToken ? { getAuthToken: ctx.getAuthToken } : {},
10333
- ...ctx.requestHeaders ? { requestHeaders: ctx.requestHeaders } : {}
10334
- });
10335
- const strictSync = candidate.pglite.strictSync;
10336
- if (typeof strictSync !== "function") {
10337
- await candidate.stop().catch(() => {
10338
- return;
10339
- });
10340
- throw new Error("[pgxsinkit] adoption: the candidate store does not expose `strictSync()` \u2014 the commitment barrier " + "requires an OPFS-repacked engine (data-before-authority, invariant 3).");
10341
- }
10342
- return {
10343
- ready: candidate.ready,
10344
- strictSync: () => strictSync.call(candidate.pglite),
10345
- close: () => candidate.stop()
10346
- };
10347
- },
10348
- publishSentinel: () => opfs.publishSentinel(),
10349
- deleteSentinel: () => opfs.deleteSentinel(),
10350
- deleteStoreDirectory: () => opfs.deleteStoreDirectory(),
10351
- deleteIdbPredecessor: () => deleteAdoptionIdbPredecessor(storePath, ctx.meta),
10352
- ...ctx.gateDeadlineMs != null ? { gateDeadlineMs: ctx.gateDeadlineMs } : {}
10353
- });
10354
- }
10355
- function realAdoptionSeams(ctx, seams) {
10356
- return {
10357
- idbStoreExists: seams?.idbStoreExists ?? ((sp) => idbStoreExists(sp, ctx.meta)),
10358
- resolveStoreBoot: seams?.resolveStoreBoot ?? ((sp) => resolveStoreBoot(sp, {
10359
- hasOpfsSyncAccess: true,
10360
- ...ctx.meta || ctx.opfs ? { deps: { ...ctx.meta ? { meta: ctx.meta } : {}, ...ctx.opfs ? { opfs: ctx.opfs } : {} } } : {}
10361
- })),
10362
- buildEffects: seams?.buildEffects ?? ((sp) => buildRealAdoptionEffects(sp, ctx)),
10363
- log: seams?.log ?? ((message, data) => syncDebug(message, data))
10364
- };
10365
- }
10366
- async function runBootAdoption(storePath, declaration, ctx, seamsOverride) {
10367
- const seams = realAdoptionSeams(ctx, seamsOverride);
10368
- if (!await seams.idbStoreExists(storePath))
10369
- return { bootHasOpfs: true };
10370
- const resolution = await seams.resolveStoreBoot(storePath);
10371
- const verdict = resolution.verdict;
10372
- if (verdict === undefined || !adoptionEligible(declaration, verdict, true)) {
10373
- const bootHasOpfs = resolution.storageBackend === "opfs-repacked";
10374
- seams.log("boot adoption not eligible \u2014 using the classifier's resolved backend", {
10375
- action: verdict?.action,
10376
- storageBackend: resolution.storageBackend
10377
- });
10378
- return { bootHasOpfs };
10379
- }
10380
- const outcome = await runAdoptionTransition(declaration, seams.buildEffects(storePath));
10381
- if (outcome.adopted) {
10382
- seams.log("boot adoption committed the opfs successor; idb predecessor deleted", {
10383
- ...outcome.predecessorCleanupPending ? { predecessorCleanupPending: outcome.predecessorCleanupPending } : {}
10384
- });
10385
- return { bootHasOpfs: true, outcome };
10386
- }
10387
- seams.log("boot adoption deferred/failed \u2014 idb stays authoritative", {
10388
- reason: outcome.reason,
10389
- ...outcome.error ? { error: outcome.error } : {}
10390
- });
10391
- return { bootHasOpfs: false, outcome };
10392
- }
10393
10297
  function storageBackendFromDataDir(dataDir) {
10394
10298
  if (dataDir == null)
10395
10299
  return;
@@ -10409,9 +10313,14 @@ function verdictNeedsCommitmentBarrier(verdict, storageBackend) {
10409
10313
  return verdict?.action === "virgin-create" || verdict?.action === "delete-candidate-and-rebuild";
10410
10314
  }
10411
10315
  async function resolveFreshBoot(storePath, hasOpfsSyncAccess, backendOverride, seams) {
10316
+ const bootDeps = {
10317
+ ...seams?.meta ? { meta: seams.meta } : {},
10318
+ ...seams?.opfs ? { opfs: seams.opfs } : {},
10319
+ ...seams?.idbExists ? { idbExists: seams.idbExists } : {}
10320
+ };
10412
10321
  if (!hasOpfsSyncAccess || backendOverride === "memory") {
10413
10322
  if (!hasOpfsSyncAccess && backendOverride !== "memory")
10414
- await recoverDeniedBootDeletion(storePath);
10323
+ await resolveDeniedBootAuthority(storePath, bootDeps);
10415
10324
  return {
10416
10325
  bootHasOpfs: false,
10417
10326
  storageBackend: backendOverride === "memory" ? "memory" : "idbfs",
@@ -10420,13 +10329,7 @@ async function resolveFreshBoot(storePath, hasOpfsSyncAccess, backendOverride, s
10420
10329
  }
10421
10330
  const runResolve = seams?.resolveStoreBoot ?? ((sp) => resolveStoreBoot(sp, {
10422
10331
  hasOpfsSyncAccess: true,
10423
- ...seams?.meta || seams?.opfs || seams?.idbExists ? {
10424
- deps: {
10425
- ...seams?.meta ? { meta: seams.meta } : {},
10426
- ...seams?.opfs ? { opfs: seams.opfs } : {},
10427
- ...seams?.idbExists ? { idbExists: seams.idbExists } : {}
10428
- }
10429
- } : {}
10332
+ ...seams?.meta || seams?.opfs || seams?.idbExists ? { deps: bootDeps } : {}
10430
10333
  }));
10431
10334
  const resolution = await runResolve(storePath);
10432
10335
  const bootHasOpfs = resolution.storageBackend === "opfs-repacked";
@@ -10461,6 +10364,19 @@ async function runFreshCommitmentBarrier(storePath, strictSyncReturns, seams) {
10461
10364
  storePath
10462
10365
  });
10463
10366
  }
10367
+ async function resolveAdoptedCommitmentBarrier(storePath, seams) {
10368
+ const metaResult = await readStoreMetaRecord(storePath, seams?.meta);
10369
+ const metaUnavailable = metaResult === META_STORE_UNAVAILABLE;
10370
+ const record = metaUnavailable ? undefined : metaResult;
10371
+ const needsCommitmentBarrier = !metaUnavailable && (record === undefined || record.phase === "opfs-candidate");
10372
+ (seams?.log ?? ((message, data) => syncDebug(message, data)))("boot adopted store commitment resolved", {
10373
+ storePath,
10374
+ phase: record?.phase ?? null,
10375
+ ...metaUnavailable ? { metaStoreUnavailable: true } : {},
10376
+ needsCommitmentBarrier
10377
+ });
10378
+ return needsCommitmentBarrier;
10379
+ }
10464
10380
  function formatOpenFailureReason(error) {
10465
10381
  if (error instanceof Error)
10466
10382
  return `${error.name || "Error"}: ${error.message}`;
@@ -10475,26 +10391,6 @@ async function fallbackVirginCandidateToIdb(storePath, openError, seams) {
10475
10391
  (seams?.log ?? ((message, data) => syncDebug(message, data)))("boot fresh commitment: opfs candidate uncreatable after bounded retries \u2014 session idbfs fallback", { storePath, reason });
10476
10392
  return reason;
10477
10393
  }
10478
- async function adoptStore(options) {
10479
- const storePath = options.storePath ?? "pgxsinkit-overlay-v1";
10480
- const isStoreLive = options.seams?.isStoreLive ?? ((sp) => liveStorePaths.has(sp));
10481
- if (isStoreLive(storePath))
10482
- throw new StoreInUseError(storePath);
10483
- const ctx = {
10484
- registry: options.registry,
10485
- electricUrl: options.electricUrl,
10486
- batchWriteUrl: options.batchWriteUrl,
10487
- ...options.getAuthToken ? { getAuthToken: options.getAuthToken } : {},
10488
- ...options.requestHeaders ? { requestHeaders: options.requestHeaders } : {},
10489
- syncEnabled: options.syncEnabled ?? true,
10490
- ...options.gateDeadlineMs != null ? { gateDeadlineMs: options.gateDeadlineMs } : {},
10491
- ...options.seams?.meta ? { meta: options.seams.meta } : {},
10492
- ...options.seams?.opfs ? { opfs: options.seams.opfs } : {},
10493
- ...options.seams?.createPglite ? { createPglite: options.seams.createPglite } : {}
10494
- };
10495
- const effects = options.seams?.buildEffects?.(storePath) ?? buildRealAdoptionEffects(storePath, ctx);
10496
- return runManualAdoption(effects);
10497
- }
10498
10394
  function replAdapter(client) {
10499
10395
  return {
10500
10396
  query: (sql7, params, options) => client.rawQuery(sql7, params, options),
@@ -10502,8 +10398,6 @@ function replAdapter(client) {
10502
10398
  };
10503
10399
  }
10504
10400
  async function createSyncClient(options) {
10505
- const adoptionCandidateBuild = options[ADOPTION_CANDIDATE_BUILD] === true;
10506
- const createPglite = options[INTERNAL_PGLITE_CREATE] ?? createClientPGlite;
10507
10401
  validateLiveQueryPolicy(options.liveQueries);
10508
10402
  const status = {
10509
10403
  phase: "booting",
@@ -10583,7 +10477,7 @@ async function createSyncClient(options) {
10583
10477
  const timedCreate = async () => {
10584
10478
  const startedAt = performance.now();
10585
10479
  const resolvedDataDir = bootHasOpfsSyncAccess ? resolveStoreDataDir(fallbackStorePath, backendOverride, { hasIndexedDb: true, hasOpfsSyncAccess: true }) : resolveStoreDataDir(fallbackStorePath, backendOverride);
10586
- const created = await createPglite(fallbackStorePath, {
10480
+ const created = await createClientPGlite(fallbackStorePath, {
10587
10481
  ...createClientOptions,
10588
10482
  ...bootHasOpfsSyncAccess ? { hasOpfsSyncAccess: true } : {}
10589
10483
  });
@@ -10595,26 +10489,10 @@ async function createSyncClient(options) {
10595
10489
  bootReportBuilder.setPgliteCreateMs(performance.now() - startedAt);
10596
10490
  return created;
10597
10491
  };
10598
- const runBootAdoptionIfDeclared = async () => {
10599
- if (!bootHasOpfsSyncAccess || options.adoption !== "server-reconstructible" || restoreBoot)
10600
- return;
10601
- const { bootHasOpfs, outcome } = await runBootAdoption(fallbackStorePath, options.adoption, {
10602
- registry: options.registry,
10603
- electricUrl: options.electricUrl,
10604
- batchWriteUrl: options.batchWriteUrl,
10605
- ...options.getAuthToken ? { getAuthToken: options.getAuthToken } : {},
10606
- ...options.requestHeaders ? { requestHeaders: options.requestHeaders } : {},
10607
- syncEnabled: options.syncEnabled ?? true
10608
- });
10609
- bootHasOpfsSyncAccess = bootHasOpfs;
10610
- if (!bootHasOpfs && outcome && outcome.adopted === false) {
10611
- storageFallbackReason = `adoption deferred (${outcome.reason})`;
10612
- }
10613
- };
10614
10492
  const refuseIfNonPersistent = (instance) => {
10615
10493
  if (testStoreMarker !== undefined)
10616
10494
  return;
10617
- if (instance[OPFS_REPACKED_PERSISTENT] === true)
10495
+ if (isOpfsRepackedPersistent(instance))
10618
10496
  return;
10619
10497
  const observedDataDir = instance.dataDir;
10620
10498
  const observed = classifyNonPersistentDataDir(observedDataDir);
@@ -10623,16 +10501,9 @@ async function createSyncClient(options) {
10623
10501
  };
10624
10502
  const openOwnedStore = async () => {
10625
10503
  if (!bootHasOpfsSyncAccess && backendOverride !== "memory") {
10626
- await recoverDeniedBootDeletion(fallbackStorePath);
10504
+ await resolveDeniedBootAuthority(fallbackStorePath);
10627
10505
  }
10628
- if (!adoptionCandidateBuild)
10629
- await runBootAdoptionIfDeclared();
10630
- if (adoptionCandidateBuild) {
10631
- const opfs = createOpfsEffects(fallbackStorePath);
10632
- await opfs.deleteSentinel();
10633
- await opfs.deleteStoreDirectory();
10634
- await opfs.getStoreDirectoryHandle();
10635
- } else if (bootHasOpfsSyncAccess) {
10506
+ if (bootHasOpfsSyncAccess) {
10636
10507
  const fresh = await resolveFreshBoot(fallbackStorePath, bootHasOpfsSyncAccess, backendOverride);
10637
10508
  if (!fresh.bootHasOpfs && storageFallbackReason == null) {
10638
10509
  storageFallbackReason = `recordless idb store opened in place (invariant 14; verdict ${fresh.verdict?.action ?? "unknown"})`;
@@ -10685,9 +10556,12 @@ async function createSyncClient(options) {
10685
10556
  bootReportBuilder.setStorageBackend(byoBackend);
10686
10557
  }
10687
10558
  }
10559
+ const adoptedCommitmentGate = (options.pgliteInstance != null || adoptedPrecreated) && backendOverride !== "memory" && isOpfsRepackedPersistent(pglite) ? resolveAdoptedCommitmentBarrier(fallbackStorePath) : null;
10560
+ if (adoptedCommitmentGate)
10561
+ adoptedCommitmentGate.catch(() => {
10562
+ return;
10563
+ });
10688
10564
  const ownsStoreLifecycle = !options.pgliteInstance;
10689
- if (ownsStoreLifecycle)
10690
- liveStorePaths.add(fallbackStorePath);
10691
10565
  if (adoptedPrecreated && options.provisionStamp) {
10692
10566
  const stamp = await options.provisionStamp.catch(() => null);
10693
10567
  if (stamp) {
@@ -10785,8 +10659,12 @@ async function createSyncClient(options) {
10785
10659
  const currentFingerprint = computeLocalSchemaFingerprint(options.registry);
10786
10660
  const storedFingerprint = await readStoredLocalSchemaFingerprint(pglite, options.registry);
10787
10661
  if (storedFingerprint === currentFingerprint) {
10662
+ syncDebug("boot local schema fingerprint match \u2014 durable exec skipped");
10788
10663
  bootReportBuilder.setSchemaFastPath({ skipped: true, fingerprintMatch: true });
10789
10664
  } else {
10665
+ syncDebug("boot local schema fingerprint mismatch \u2014 replaying durable schema", {
10666
+ hadStored: storedFingerprint != null
10667
+ });
10790
10668
  await pglite.exec(generateDurableLocalSchemaSql(options.registry));
10791
10669
  await writeStoredLocalSchemaFingerprint(pglite, options.registry, currentFingerprint);
10792
10670
  bootReportBuilder.setSchemaFastPath({ skipped: false, fingerprintMatch: false });
@@ -10862,7 +10740,6 @@ async function createSyncClient(options) {
10862
10740
  const isSyncPending = () => syncEnabled && sync == null && !disposed;
10863
10741
  const quiesceTailForTeardown = async () => {
10864
10742
  disposed = true;
10865
- liveStorePaths.delete(fallbackStorePath);
10866
10743
  const disposedError = new ClientDisposedError;
10867
10744
  rejectWriteReady(disposedError);
10868
10745
  rejectReady(disposedError);
@@ -11395,6 +11272,8 @@ async function createSyncClient(options) {
11395
11272
  subscribeLiveRows: client.subscribeLiveRows,
11396
11273
  query: (sql7, params) => pglite.query(sql7, params)
11397
11274
  });
11275
+ if (adoptedCommitmentGate)
11276
+ commitmentBarrierPending = await adoptedCommitmentGate;
11398
11277
  if (commitmentBarrierPending) {
11399
11278
  await runFreshCommitmentBarrier(fallbackStorePath, resolveEngineStrictSync(pglite));
11400
11279
  }
@@ -11498,9 +11377,8 @@ function getClientProjection2(entry, tableKey) {
11498
11377
  }
11499
11378
  return entry.clientProjection;
11500
11379
  }
11501
- var WriteNotReadyError, ClientDisposedError, OPFS_OPEN_ATTEMPTS = 10, OPFS_OPEN_BACKOFF_MS = 100, OPFS_STORE_EXTENT_SIZE = 65536, OPFS_REPACKED_PERSISTENT, StoreInUseError, liveStorePaths, ADOPTION_CANDIDATE_BUILD, INTERNAL_PGLITE_CREATE;
11380
+ var WriteNotReadyError, ClientDisposedError, OPFS_OPEN_ATTEMPTS = 10, OPFS_OPEN_BACKOFF_MS = 100, OPFS_STORE_EXTENT_SIZE = 65536, OPFS_REPACKED_PERSISTENT;
11502
11381
  var init_src = __esm(() => {
11503
- init_adoption();
11504
11382
  init_boot_report();
11505
11383
  init_convergence();
11506
11384
  init_export_data();
@@ -11524,7 +11402,6 @@ var init_src = __esm(() => {
11524
11402
  init_live_rows_sql();
11525
11403
  init_export_dump();
11526
11404
  init_export_data();
11527
- init_adoption();
11528
11405
  init_lifecycle_slot();
11529
11406
  init_attach_sync_client();
11530
11407
  init_engine_control();
@@ -11552,15 +11429,6 @@ var init_src = __esm(() => {
11552
11429
  }
11553
11430
  };
11554
11431
  OPFS_REPACKED_PERSISTENT = Symbol.for("pgxsinkit.opfsRepackedPersistent");
11555
- StoreInUseError = class StoreInUseError extends Error {
11556
- constructor(storePath) {
11557
- super(`[pgxsinkit] adoptStore(${JSON.stringify(storePath)}) refused: a live client is currently holding this ` + "store. Adoption is a creation-path migration \u2014 call it INSTEAD of createSyncClient, before any client " + "opens the store (stop/destroy the existing client first).");
11558
- this.name = "StoreInUseError";
11559
- }
11560
- };
11561
- liveStorePaths = new Set;
11562
- ADOPTION_CANDIDATE_BUILD = Symbol("pgxsinkit.adoptionCandidateBuild");
11563
- INTERNAL_PGLITE_CREATE = Symbol("pgxsinkit.internalPgliteCreate");
11564
11432
  });
11565
11433
  init_src();
11566
11434
 
@@ -11574,14 +11442,12 @@ export {
11574
11442
  setSyncDebugSink,
11575
11443
  seedLiveDiffState,
11576
11444
  runThrowawayCloneDump,
11577
- runManualAdoption,
11578
11445
  runFreshCommitmentBarrier,
11579
- runBootAdoption,
11580
- runAdoptionTransition,
11581
11446
  rowKey,
11582
11447
  resolveStoreDataDir,
11583
11448
  resolveStoreBoot,
11584
11449
  resolveFreshBoot,
11450
+ resolveAdoptedCommitmentBarrier,
11585
11451
  replAdapter,
11586
11452
  quiesceStoreWorker,
11587
11453
  provisionSyncWorker,
@@ -11618,16 +11484,15 @@ export {
11618
11484
  createClientPGlite,
11619
11485
  createBrowserConvergenceTrigger,
11620
11486
  computeLiveDiff,
11487
+ committedStoreUnreachableFromWire,
11621
11488
  buildRegistryReadHandles,
11622
11489
  buildLazyGuardIndex,
11623
11490
  attachSyncClient,
11624
11491
  assertLazyRefsActivated,
11625
- adoptionEligible,
11626
- adoptStore,
11627
11492
  WriteNotReadyError,
11628
- StoreInUseError,
11629
11493
  StoreDestroyRefusedError,
11630
11494
  RestoreTargetExistsError,
11495
+ ProvisionExpiredError,
11631
11496
  NonPersistentStoreError,
11632
11497
  LiveRowsMaterializer,
11633
11498
  LifecycleBusyError,
@@ -11639,9 +11504,11 @@ export {
11639
11504
  ENGINE_RELOCATED_CODE,
11640
11505
  DataExportDrainError,
11641
11506
  DEFAULT_DRAIN_TIMEOUT_MS,
11507
+ CommittedStoreUnreachableError,
11642
11508
  ClientDisposedError,
11509
+ COMMITTED_STORE_UNREACHABLE_CODE,
11643
11510
  BRIDGE_PROTOCOL_VERSION,
11644
11511
  BRIDGE_CHANNEL
11645
11512
  };
11646
11513
 
11647
- //# debugId=62F3E6980D885DE664756E2164756E21
11514
+ //# debugId=582CBA608D95429364756E2164756E21