@pgxsinkit/client 0.1.51 → 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 (96) 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/error-chain.d.ts +9 -0
  9. package/dist/error-chain.d.ts.map +1 -0
  10. package/dist/export-dump.d.ts.map +1 -1
  11. package/dist/export-store.d.ts +1 -1
  12. package/dist/export-store.d.ts.map +1 -1
  13. package/dist/index.d.ts +309 -38
  14. package/dist/index.d.ts.map +1 -1
  15. package/dist/index.js +4628 -1489
  16. package/dist/index.js.map +36 -24
  17. package/dist/live-rows-sql.d.ts +1 -1
  18. package/dist/local-store.d.ts +16 -31
  19. package/dist/local-store.d.ts.map +1 -1
  20. package/dist/local-tables.d.ts +10 -4
  21. package/dist/local-tables.d.ts.map +1 -1
  22. package/dist/mutation.d.ts +12 -15
  23. package/dist/mutation.d.ts.map +1 -1
  24. package/dist/opfs-effects.d.ts +51 -0
  25. package/dist/opfs-effects.d.ts.map +1 -0
  26. package/dist/placement-probe.d.ts +75 -0
  27. package/dist/placement-probe.d.ts.map +1 -0
  28. package/dist/schema.d.ts +11 -16
  29. package/dist/schema.d.ts.map +1 -1
  30. package/dist/store-boot.d.ts +77 -0
  31. package/dist/store-boot.d.ts.map +1 -0
  32. package/dist/store-lifecycle.d.ts +153 -0
  33. package/dist/store-lifecycle.d.ts.map +1 -0
  34. package/dist/store-meta.d.ts +190 -0
  35. package/dist/store-meta.d.ts.map +1 -0
  36. package/dist/store-path.d.ts +77 -7
  37. package/dist/store-path.d.ts.map +1 -1
  38. package/dist/sync/apply.d.ts +12 -1
  39. package/dist/sync/apply.d.ts.map +1 -1
  40. package/dist/sync/index.d.ts.map +1 -1
  41. package/dist/sync/shape-inbox.d.ts +1 -1
  42. package/dist/sync/types.d.ts +3 -3
  43. package/dist/testing.js.map +3 -3
  44. package/dist/worker/attach-sync-client.d.ts +239 -13
  45. package/dist/worker/attach-sync-client.d.ts.map +1 -1
  46. package/dist/worker/define-sync-worker.d.ts +162 -5
  47. package/dist/worker/define-sync-worker.d.ts.map +1 -1
  48. package/dist/worker/election-coordinator.d.ts +95 -0
  49. package/dist/worker/election-coordinator.d.ts.map +1 -0
  50. package/dist/worker/engine-control.d.ts +265 -0
  51. package/dist/worker/engine-control.d.ts.map +1 -0
  52. package/dist/worker/engine-router.d.ts +75 -0
  53. package/dist/worker/engine-router.d.ts.map +1 -0
  54. package/dist/worker/live-query-manager.d.ts.map +1 -1
  55. package/dist/worker/live-query-params-guard.d.ts +14 -0
  56. package/dist/worker/live-query-params-guard.d.ts.map +1 -0
  57. package/dist/worker/protocol.d.ts +32 -11
  58. package/dist/worker/protocol.d.ts.map +1 -1
  59. package/dist/worker/sw-placement.d.ts +37 -0
  60. package/dist/worker/sw-placement.d.ts.map +1 -0
  61. package/package.json +4 -3
  62. package/skills/core/SKILL.md +15 -8
  63. package/skills/operating/SKILL.md +114 -34
  64. package/src/adoption.ts +275 -0
  65. package/src/boot-report.ts +70 -17
  66. package/src/convergence.ts +2 -1
  67. package/src/error-chain.ts +26 -0
  68. package/src/export-dump.ts +5 -1
  69. package/src/export-store.ts +1 -1
  70. package/src/index.ts +1246 -118
  71. package/src/live-rows-sql.ts +1 -1
  72. package/src/local-store.ts +18 -40
  73. package/src/local-tables.ts +9 -2
  74. package/src/mutation.ts +67 -49
  75. package/src/mutations-api.ts +3 -3
  76. package/src/opfs-effects.ts +160 -0
  77. package/src/placement-probe.ts +168 -0
  78. package/src/schema.ts +17 -22
  79. package/src/store-boot.ts +343 -0
  80. package/src/store-lifecycle.ts +227 -0
  81. package/src/store-meta.ts +459 -0
  82. package/src/store-path.ts +197 -22
  83. package/src/sync/apply.ts +227 -89
  84. package/src/sync/index.ts +33 -9
  85. package/src/sync/shape-inbox.ts +1 -1
  86. package/src/sync/types.ts +3 -3
  87. package/src/testing.ts +2 -2
  88. package/src/worker/attach-sync-client.ts +1675 -117
  89. package/src/worker/define-sync-worker.ts +810 -50
  90. package/src/worker/election-coordinator.ts +462 -0
  91. package/src/worker/engine-control.ts +379 -0
  92. package/src/worker/engine-router.ts +355 -0
  93. package/src/worker/live-query-manager.ts +10 -1
  94. package/src/worker/live-query-params-guard.ts +57 -0
  95. package/src/worker/protocol.ts +41 -10
  96. package/src/worker/sw-placement.ts +64 -0
@@ -0,0 +1,275 @@
1
+ // Adoption orchestrator + declaration surface — ADR-0049 (capability-driven engine placement) decision 7,
2
+ // plan step 11a. The automatic and manual adoption transitions that turn an existing idb-authoritative store
3
+ // into a committed opfs successor, expressed as ONE pure, effect-injected sequence over the plan's
4
+ // "Adoption sequence (exclusive, quiescent — D7)" and its adoption crash rows. CONTEXT § "Language — engine
5
+ // placement" terms are used exactly: "Adoption gate", "Adoption-bootstrap gate", "Drain predicate".
6
+ //
7
+ // EFFECT-INJECTED BY CONSTRUCTION. Like `store-lifecycle.ts`, this module touches NO IndexedDB, OPFS, or
8
+ // PGlite: every side effect is a method on an injected {@link AdoptionEffects}. Plan step 11b wires the REAL
9
+ // effects into the boot path (`createSyncClient` / `defineSyncWorker`) — the pre-expose idb boot, the drain
10
+ // read, the opfs candidate build via the normal server bootstrap through the Adoption-bootstrap gate, the
11
+ // shared commitment barrier (`runCommitmentBarrier` from `store-lifecycle.ts`), and the predecessor deletion.
12
+ // Here the orchestrator owns only the DECISION SEQUENCE and its failure recovery; wiring is NOT this step.
13
+ //
14
+ // INVARIANTS (ADR-0049): the transition runs at boot BEFORE any engine is exposed — the caller guarantees
15
+ // pre-expose exclusivity (invariant 3, no-race-by-construction), so the drain predicate cannot be raced by a
16
+ // concurrent mutation. Automatic adoption is default OFF and consults the declaration FIRST (invariant 4 — no
17
+ // silent local-only data loss; hook absence is never authority because `rawExec` writes documented local-only
18
+ // state on any store). The idb predecessor is deleted ONLY after the commitment barrier publishes
19
+ // (invariant 3/4 — commitment precedes exposure; nothing strands, nothing is silently lost).
20
+
21
+ import { journalOwesNothing, runCommitmentBarrier, type JournalStatusCounts } from "./store-lifecycle";
22
+ import type { StoreBootVerdict, StoreMetaPhase } from "./store-meta";
23
+
24
+ /**
25
+ * The consumer's explicit reconstructibility declaration (ADR-0049 D7). `"server-reconstructible"` authorizes
26
+ * AUTOMATIC adoption: the store is server-reconstructible and its local-only data is disposable. DEFAULT OFF
27
+ * (`undefined`) — hook absence is NEVER authority: `rawExec` writes documented local-only state on any store,
28
+ * so only this explicit declaration (or the manual adoption API) authorizes deleting the idb predecessor.
29
+ */
30
+ export type AdoptionDeclaration = "server-reconstructible" | undefined;
31
+
32
+ /**
33
+ * The effects the adoption transition drives, in the one order it always runs them (step 11b supplies the real
34
+ * implementations). The transition is a strict data-before-authority sequence: prove the idb store owes the
35
+ * server nothing, reconstruct an opfs successor through the Adoption-bootstrap gate, commit it via the shared
36
+ * barrier, and only THEN delete the predecessor.
37
+ */
38
+ export interface AdoptionEffects {
39
+ /**
40
+ * Boot the idb engine PRE-EXPOSE (never surfaced to tabs — invariant 3) and return the journal status
41
+ * counts the drain predicate reads. The engine is booted solely to read the journal; the caller never
42
+ * exposes THIS booted instance until adoption defers (journal owed) or fails.
43
+ */
44
+ bootIdbPreExpose(): Promise<JournalStatusCounts>;
45
+ /** Strict-sync the never-exposed idb engine, then close it (all handles released) before building the successor. */
46
+ strictSyncAndCloseIdb(): Promise<void>;
47
+ /** Advance the store meta record phase. The transition calls it with `"adopting"` and, on failure, `"idb-authoritative"`. */
48
+ setPhase(phase: StoreMetaPhase): Promise<void>;
49
+ /**
50
+ * Build the opfs candidate via the normal server bootstrap path AND await the Adoption-bootstrap gate:
51
+ * authorized online reconstruction — the initial catch-up of the eager Consistency groups a valid initial
52
+ * store requires ("authorized" includes legitimately anonymous/public shapes). Resolves ONLY when the gate
53
+ * passed; THROWS on gate failure (offline, unauthorized, `syncEnabled: false`, or a bootstrap error).
54
+ */
55
+ buildCandidateThroughGate(): Promise<void>;
56
+ /**
57
+ * Run the shared commitment barrier on the CANDIDATE engine: `strictSync()` returns with VFS health good →
58
+ * sentinel → `opfs-committed`. Step 11b wires `runCommitmentBarrier` (store-lifecycle.ts) with real effects;
59
+ * here it is one injected step. It MUST be all-or-nothing: a barrier failure publishes NOTHING (invariant 3),
60
+ * so a throw leaves the idb store authoritative and the candidate uncommitted.
61
+ */
62
+ commitCandidate(): Promise<void>;
63
+ /** Delete the idb predecessor now the opfs successor is committed. Idempotent: absent counts as deleted. */
64
+ deleteIdbPredecessor(): Promise<void>;
65
+ /**
66
+ * Tear down a failed candidate: delete the stale sentinel (if any) AND the candidate directory,
67
+ * delete-if-present (a barrier-gap crash's sentinel must never survive). Recreate-only; idempotent.
68
+ */
69
+ teardownCandidate(): Promise<void>;
70
+ }
71
+
72
+ /** The narrow candidate surface the real boot wiring hands this module. */
73
+ export interface AdoptionCandidateHandle {
74
+ ready: Promise<void>;
75
+ strictSync(): Promise<void>;
76
+ close(): Promise<void>;
77
+ }
78
+
79
+ /** IO callbacks needed to construct the real stateful adoption effects without importing the client entrypoint. */
80
+ export interface AdoptionEffectBuilderOptions {
81
+ readIdbJournal(): Promise<JournalStatusCounts>;
82
+ setPhase(phase: StoreMetaPhase): Promise<void>;
83
+ buildCandidate(): Promise<AdoptionCandidateHandle>;
84
+ publishSentinel(): Promise<void>;
85
+ deleteSentinel(): Promise<void>;
86
+ deleteStoreDirectory(): Promise<void>;
87
+ deleteIdbPredecessor(): Promise<void>;
88
+ gateDeadlineMs?: number;
89
+ }
90
+
91
+ const DEFAULT_ADOPTION_GATE_DEADLINE_MS = 30_000;
92
+
93
+ async function awaitAdoptionGate(ready: Promise<void>, deadlineMs: number): Promise<void> {
94
+ let timer: ReturnType<typeof setTimeout> | undefined;
95
+ const deadline = new Promise<never>((_, reject) => {
96
+ timer = setTimeout(
97
+ () =>
98
+ reject(
99
+ new Error(
100
+ "[pgxsinkit] adoption gate unmet: the eager Consistency groups did not complete their initial " +
101
+ `catch-up within ${deadlineMs}ms (offline, unauthorized, or the server was unreachable). The idb ` +
102
+ "store stays authoritative.",
103
+ ),
104
+ ),
105
+ deadlineMs,
106
+ );
107
+ });
108
+ try {
109
+ await Promise.race([ready, deadline]);
110
+ } finally {
111
+ if (timer !== undefined) clearTimeout(timer);
112
+ }
113
+ }
114
+
115
+ /**
116
+ * Construct the stateful adoption effects around narrow IO callbacks. Candidate ownership, gate timing,
117
+ * data-before-authority publication, and failed-candidate cleanup live here rather than in the package entrypoint.
118
+ */
119
+ export function buildAdoptionEffects(options: AdoptionEffectBuilderOptions): AdoptionEffects {
120
+ let candidate: AdoptionCandidateHandle | undefined;
121
+ return {
122
+ bootIdbPreExpose: () => options.readIdbJournal(),
123
+ async strictSyncAndCloseIdb() {
124
+ // The callback's drain read closes its read-only strict IDB engine before returning.
125
+ },
126
+ setPhase: (phase) => options.setPhase(phase),
127
+ async buildCandidateThroughGate() {
128
+ candidate = await options.buildCandidate();
129
+ await awaitAdoptionGate(candidate.ready, options.gateDeadlineMs ?? DEFAULT_ADOPTION_GATE_DEADLINE_MS);
130
+ },
131
+ async commitCandidate() {
132
+ const active = candidate;
133
+ if (active === undefined) throw new Error("[pgxsinkit] adoption: commit called before the candidate was built");
134
+ await runCommitmentBarrier({
135
+ strictSyncReturns: () => active.strictSync(),
136
+ publishSentinel: () => options.publishSentinel(),
137
+ setPhase: (phase) => options.setPhase(phase),
138
+ });
139
+ await active.close().catch(() => undefined);
140
+ candidate = undefined;
141
+ },
142
+ deleteIdbPredecessor: () => options.deleteIdbPredecessor(),
143
+ async teardownCandidate() {
144
+ if (candidate !== undefined) {
145
+ await candidate.close().catch(() => undefined);
146
+ candidate = undefined;
147
+ }
148
+ await options.deleteSentinel();
149
+ await options.deleteStoreDirectory();
150
+ },
151
+ };
152
+ }
153
+
154
+ /**
155
+ * The outcome of an adoption transition. `adopted: true` means the opfs successor is committed and the idb
156
+ * predecessor is gone (or scheduled for cleanup — see `predecessorCleanupPending`). Every `adopted: false`
157
+ * outcome leaves the idb store AUTHORITATIVE and untouched:
158
+ * - `not-declared` — automatic adoption without the declaration (default off); nothing ran (invariant 4).
159
+ * - `journal-owed` — the drain predicate failed; adoption is DEFERRED (the caller exposes the idb engine
160
+ * normally). The orchestrator boots the idb engine to READ the journal but exposes nothing itself.
161
+ * - `gate-failed` — the Adoption-bootstrap gate rejected (offline/unauthorized/`syncEnabled: false`/bootstrap
162
+ * error). The candidate was torn down; idb stays authoritative. `error` carries the gate failure text.
163
+ * - `barrier-failed` — the commitment barrier threw (strict sync did not return / VFS health bad). Nothing
164
+ * published; candidate torn down; idb stays authoritative. `error` carries the barrier failure text.
165
+ */
166
+ export type AdoptionOutcome =
167
+ | {
168
+ adopted: true;
169
+ /**
170
+ * Set only when the predecessor deletion FAILED after a successful commit. Adoption still SUCCEEDED
171
+ * (the phase is `opfs-committed`); the boot classifier's lingering-idb row (adoption crash-row 3 →
172
+ * `opfs-committed` with an idb store present → `open-committed`, then `completeAdoption` finishes the
173
+ * deletion) completes the cleanup on the next boot. Carries the deletion failure text for diagnostics.
174
+ */
175
+ predecessorCleanupPending?: string;
176
+ }
177
+ | { adopted: false; reason: "not-declared" | "journal-owed" | "gate-failed" | "barrier-failed"; error?: string };
178
+
179
+ /** Extract a stable message from a thrown value (an `Error`'s message, else its string form). */
180
+ function errorText(error: unknown): string {
181
+ return error instanceof Error ? error.message : String(error);
182
+ }
183
+
184
+ /**
185
+ * The shared transition body — identical for the automatic and manual entry points (they differ ONLY in the
186
+ * declaration check, applied before this runs). Steps, in order (plan "Adoption sequence"):
187
+ *
188
+ * 1. Boot the idb engine pre-expose and read the journal. NOT drained → `journal-owed` (the orchestrator boots
189
+ * NOTHING further and exposes NOTHING itself — the caller then exposes the idb engine normally; adoption
190
+ * deferred). Drained → continue.
191
+ * 2. Strict-sync + close the never-exposed idb engine.
192
+ * 3. Phase → `adopting`.
193
+ * 4. Build the opfs candidate through the Adoption-bootstrap gate. On throw → tear the candidate down + set
194
+ * `idb-authoritative` (idb stays authoritative, plan gate-unmet row) → `gate-failed`.
195
+ * 5. Commit the candidate via the shared barrier. On throw → tear the candidate down + set `idb-authoritative`
196
+ * → `barrier-failed` (the barrier is all-or-nothing; nothing published).
197
+ * 6. Delete the idb predecessor → adopted. A deletion throw here does NOT unadopt: the phase is already
198
+ * `opfs-committed`, so the outcome is `adopted: true` with `predecessorCleanupPending` recorded and the
199
+ * classifier's lingering-idb row finishes the deletion next boot.
200
+ */
201
+ async function runTransition(effects: AdoptionEffects): Promise<AdoptionOutcome> {
202
+ const counts = await effects.bootIdbPreExpose();
203
+ if (!journalOwesNothing(counts)) return { adopted: false, reason: "journal-owed" };
204
+
205
+ await effects.strictSyncAndCloseIdb();
206
+ await effects.setPhase("adopting");
207
+
208
+ try {
209
+ await effects.buildCandidateThroughGate();
210
+ } catch (error) {
211
+ // Adoption-bootstrap gate unmet (offline/unauthorized/syncEnabled: false/bootstrap error): nothing
212
+ // published, so idb stays authoritative (plan "Adoption gate unmet" row).
213
+ await effects.teardownCandidate();
214
+ await effects.setPhase("idb-authoritative");
215
+ return { adopted: false, reason: "gate-failed", error: errorText(error) };
216
+ }
217
+
218
+ try {
219
+ await effects.commitCandidate();
220
+ } catch (error) {
221
+ // The barrier is all-or-nothing — a failure publishes NOTHING (invariant 3). Recover to idb-authoritative.
222
+ await effects.teardownCandidate();
223
+ await effects.setPhase("idb-authoritative");
224
+ return { adopted: false, reason: "barrier-failed", error: errorText(error) };
225
+ }
226
+
227
+ try {
228
+ await effects.deleteIdbPredecessor();
229
+ } catch (error) {
230
+ // Adoption already SUCCEEDED (phase `opfs-committed`); a failed predecessor deletion never unadopts. The
231
+ // boot classifier's lingering-idb row completes the deletion next boot (plan adoption crash-row 3).
232
+ return { adopted: true, predecessorCleanupPending: errorText(error) };
233
+ }
234
+ return { adopted: true };
235
+ }
236
+
237
+ /**
238
+ * The AUTOMATIC adoption transition, run at boot BEFORE any engine is exposed (the caller guarantees pre-expose
239
+ * exclusivity — invariant 3's no-race-by-construction). Consults the {@link AdoptionDeclaration} FIRST: without
240
+ * `"server-reconstructible"` it refuses with `not-declared` and runs ZERO effects (invariant 4 — default off,
241
+ * hook absence is never authority). With the declaration it runs the shared {@link runTransition}.
242
+ */
243
+ export function runAdoptionTransition(
244
+ declaration: AdoptionDeclaration,
245
+ effects: AdoptionEffects,
246
+ ): Promise<AdoptionOutcome> {
247
+ if (declaration !== "server-reconstructible") {
248
+ return Promise.resolve({ adopted: false, reason: "not-declared" });
249
+ }
250
+ return runTransition(effects);
251
+ }
252
+
253
+ /**
254
+ * The MANUAL adoption API's core: the identical transition, but WITHOUT the declaration check — the consumer's
255
+ * explicit call IS the authorization (they were told to export/migrate any local-only data first). The drain
256
+ * predicate still gates it (a store that owes the server work is not adoptable), and every failure recovery is
257
+ * identical to the automatic path.
258
+ */
259
+ export function runManualAdoption(effects: AdoptionEffects): Promise<AdoptionOutcome> {
260
+ return runTransition(effects);
261
+ }
262
+
263
+ /**
264
+ * The boot-wiring predicate (plan step 11b): is a boot eligible to START an automatic adoption? True IFF the
265
+ * consumer declared `"server-reconstructible"` AND opfs sync access is available in this scope AND the boot
266
+ * classifier landed on `boot-idb-authoritative` — adoption only ever starts from an idb-authoritative store
267
+ * with opfs available (there is nowhere to build the successor otherwise, and no other verdict is a candidate).
268
+ */
269
+ export function adoptionEligible(
270
+ declaration: AdoptionDeclaration,
271
+ verdict: StoreBootVerdict,
272
+ hasOpfsSyncAccess: boolean,
273
+ ): boolean {
274
+ return declaration === "server-reconstructible" && hasOpfsSyncAccess && verdict.action === "boot-idb-authoritative";
275
+ }
@@ -32,6 +32,31 @@ export interface BootReport {
32
32
  * which a boolean cannot express.
33
33
  */
34
34
  storeKind: "fresh" | "warm" | "restored";
35
+ /**
36
+ * The store backend this boot actually opened (ADR-0049 decision 12): `"opfs-repacked"` (the placement probe
37
+ * granted sync-access handles in the engine home), `"idbfs"` (browser/worker, handles denied — today's default),
38
+ * `"filesystem"` (Bun/Node), or `"memory"` (the sanctioned test/ephemeral lane). Derived from the minted dataDir
39
+ * scheme at the single client-owned mint seam; absent (omitted) on a BYO instance whose backend is underivable.
40
+ * Additive field; `reportVersion` stays `1`. Distinct from {@link BootReport.storeKind}, which is untouched.
41
+ */
42
+ storageBackend?: "opfs-repacked" | "idbfs" | "filesystem" | "memory";
43
+ /**
44
+ * Where the engine ran for this boot (ADR-0049 decision 12): `"in-process"` for the main-thread/Bun
45
+ * `createSyncClient`; inside `defineSyncWorker`, the placement-probe result — `"shared-worker"` (the engine boots
46
+ * in the SharedWorker itself, WebKit today) or `"elected-worker"` (a tab-spawned dedicated worker holds the
47
+ * handles, Chromium/Firefox). Absent (omitted) when the boot cannot derive it (e.g. a dedicated elected-engine
48
+ * worker that never ran the SharedWorker placement decision). Additive field; `reportVersion` stays `1`.
49
+ */
50
+ engineHome?: "shared-worker" | "elected-worker" | "in-process";
51
+ /**
52
+ * The verbatim reason an opfs-CAPABLE boot (the probe granted sync-access handles) nonetheless opened `idbfs`
53
+ * (ADR-0049 decision 12). Set ONLY when such a fallback actually occurred — never on a plain idb boot (the probe
54
+ * denied from the start), and never on a granted opfs boot that stayed on opfs. Today's set-sites are the
55
+ * granted-then-idb transitions the client owns: a declaration-gated adoption that deferred/failed (idb stays
56
+ * authoritative) and the recordless idb-store downgrade (invariant 14 — never a fresh opfs mint over an
57
+ * existing idb store's data). Additive field; `reportVersion` stays `1`.
58
+ */
59
+ storageFallbackReason?: string;
35
60
  /** Whether the ADR-0032 S4 fetch/schema overlap was active for this boot. */
36
61
  overlapPrefetch: boolean;
37
62
  /** The registry fingerprint the store is provisioned under — the same value store-version reconcile stamps. */
@@ -71,42 +96,39 @@ export interface BootReport {
71
96
  storeVersionReconcileMs: number;
72
97
  /**
73
98
  * `startConfiguredSync`: stream/group construction wall. On an overlap boot (ADR-0032 S4,
74
- * {@link BootReport.overlapPrefetch}) the early-started segment runs concurrently with schema/journal/
75
- * reconcile, so this includes that shared wall. Structurally 0 when the boot is ready inside the
99
+ * {@link BootReport.overlapPrefetch}) the early-started segment runs concurrently with schema, journal
100
+ * recovery, and registry reconciliation, so this includes that shared wall. Structurally 0 when the boot
101
+ * is ready inside the
76
102
  * sync-start call itself (zero eager groups / instant catch-up) — finalize runs before the phase closes.
77
103
  */
78
104
  syncStartMs: number;
79
105
  /** Sync-start done → last eager boot group ready. */
80
106
  catchupMs: number;
81
107
  /**
82
- * Cumulative time in configured prepare hooks (`prepareLocalDbBeforeSchema` + `prepareLocalDb`), present
108
+ * Cumulative time in configured prepare hooks (`prepareLocalDbBeforeSchema` + `prepareLocalDbAfterSchema`), present
83
109
  * only when at least one hook is configured. Not part of the required v1 shape (ADR-0034).
84
110
  */
85
111
  prepareMs?: number;
86
112
  };
87
113
  /**
88
- * Warm-persisted-store-startup observability (the schema-replay + journal-recovery fast-path lane). Every
89
- * field carries the honest CURRENT truth so the report never lies mid-lane: the durable-schema-fingerprint
90
- * slice sets the `schema*` flags and the recovery-marker slice the `journal*` flags as those optimizations
91
- * land. Grouped like {@link BootReport.phases} so the flags structured-clone across the worker bridge as one
92
- * unit.
114
+ * Warm-store observability for the durable-schema and journal-recovery fast paths. Grouped like
115
+ * {@link BootReport.phases} so the flags structured-clone across the worker bridge as one unit.
93
116
  */
94
117
  warmBoot: {
95
- /** Whether durable-schema replay was skipped this boot (a fingerprint match). `false` today — replay is unconditional. */
118
+ /** Whether durable-schema replay was skipped this boot because the stored fingerprint matched. */
96
119
  schemaSkipped: boolean;
97
- /** Whether the stored durable-schema fingerprint matched the generated schema. `false` today — not yet computed. */
120
+ /** Whether the stored durable-schema fingerprint matched the generated schema. */
98
121
  schemaFingerprintMatch: boolean;
99
- /** Whether the boot-time `recoverSending` journal pass was skipped this boot. `false` today — the pass is unconditional. */
122
+ /** Whether the boot-time `recoverSending` journal pass was skipped this boot. */
100
123
  journalRecoverySkipped: boolean;
101
124
  /**
102
- * Whether journal recovery was required this boot. `true` today under pre-marker legacy semantics: with no
103
- * durable recovery marker, recovery is ALWAYS treated as required. The recovery-marker slice will set this
104
- * from the durable marker instead (a clean shutdown clears the marker → `false`, skipping recovery).
125
+ * Whether the durable recovery marker required journal recovery this boot. A clean settle clears the marker,
126
+ * allowing the next boot to skip the recovery pass.
105
127
  */
106
128
  journalRecoveryRequired: boolean;
107
129
  /** How many writable table journals the boot-time `recoverSending` pass visited (the registry's writable-entry count). */
108
130
  journalTablesVisited: number;
109
- /** Rows lifted `sending → pending` by recovery. `null` = not yet instrumented; populated by the recovery-marker slice. */
131
+ /** Rows lifted `sending → pending` by recovery; `null` when the selected recovery path cannot count them. */
110
132
  journalRowsRecovered: number | null;
111
133
  };
112
134
  /**
@@ -235,6 +257,18 @@ export interface BootReportBuilder extends BootStampCollector {
235
257
  ) => Promise<T>;
236
258
  setPgliteCreateMs: (ms: number | null) => void;
237
259
  setProvision: (provision: BootReport["provision"]) => void;
260
+ /**
261
+ * Stamp `storageBackend` (ADR-0049 decision 12) at the client-owned mint seam, derived from the resolved dataDir
262
+ * scheme. Idempotent — the first stamp wins (the mint runs once per boot). Never called on a BYO instance whose
263
+ * backend is underivable, leaving the field absent.
264
+ */
265
+ setStorageBackend: (backend: NonNullable<BootReport["storageBackend"]>) => void;
266
+ /**
267
+ * Stamp `storageFallbackReason` (ADR-0049 decision 12) — the verbatim reason an opfs-capable boot opened `idbfs`.
268
+ * Called ONLY when such a fallback occurred; a boot that never falls back leaves the field absent. Idempotent —
269
+ * the first stamp wins.
270
+ */
271
+ setStorageFallbackReason: (reason: string) => void;
238
272
  /**
239
273
  * Record the durable-schema fast-path outcome (the durable-schema-fingerprint slice): whether replay was
240
274
  * skipped and whether the stored fingerprint matched. Both default to the current truth (`false`), so this
@@ -280,6 +314,11 @@ export interface BootReportInit {
280
314
  mode: BootReport["mode"];
281
315
  freshStore: boolean;
282
316
  storeKind: BootReport["storeKind"];
317
+ /**
318
+ * The engine home for this boot (ADR-0049 decision 12), known at boot start. Omitted (`undefined`) when it
319
+ * cannot be derived up front — the finalized report then carries no `engineHome`.
320
+ */
321
+ engineHome?: BootReport["engineHome"];
283
322
  overlapPrefetch: boolean;
284
323
  registryFingerprint: string;
285
324
  }
@@ -291,8 +330,7 @@ export function createBootReportBuilder(init: BootReportInit): BootReportBuilder
291
330
  let prepareMs: number | null = null;
292
331
  let pgliteCreateMs: number | null = null;
293
332
  let provision: BootReport["provision"] = null;
294
- // Current-truth defaults (this slice's honest baseline): durable schema replay + journal recovery are both
295
- // unconditional today, and recovery is always treated as required pre-marker. Later slices flip these via
333
+ // Conservative defaults used until the boot path reports its actual schema and recovery outcomes through
296
334
  // the setters below.
297
335
  let warmBoot: BootReport["warmBoot"] = {
298
336
  schemaSkipped: false,
@@ -305,6 +343,10 @@ export function createBootReportBuilder(init: BootReportInit): BootReportBuilder
305
343
  let syncStartDoneOffset: number | null = null;
306
344
  let localReadReadyMs: number | null = null;
307
345
  let writeReadyMs: number | null = null;
346
+ // ADR-0049 decision 12 diagnostics — both stamped during the boot (after this builder is created), so they are
347
+ // mutable locals, not `init` fields. Absent (undefined) until stamped; the finalize output omits them then.
348
+ let storageBackend: NonNullable<BootReport["storageBackend"]> | undefined;
349
+ let storageFallbackReason: string | undefined;
308
350
  const groups: GroupAccumulator[] = [];
309
351
  let built: BootReport | null = null;
310
352
 
@@ -331,6 +373,12 @@ export function createBootReportBuilder(init: BootReportInit): BootReportBuilder
331
373
  setProvision: (value) => {
332
374
  provision = value;
333
375
  },
376
+ setStorageBackend: (backend) => {
377
+ if (storageBackend == null) storageBackend = backend;
378
+ },
379
+ setStorageFallbackReason: (reason) => {
380
+ if (storageFallbackReason == null) storageFallbackReason = reason;
381
+ },
334
382
  setSchemaFastPath: (info) => {
335
383
  warmBoot = { ...warmBoot, schemaSkipped: info.skipped, schemaFingerprintMatch: info.fingerprintMatch };
336
384
  },
@@ -369,6 +417,11 @@ export function createBootReportBuilder(init: BootReportInit): BootReportBuilder
369
417
  mode: init.mode,
370
418
  freshStore: init.freshStore,
371
419
  storeKind: init.storeKind,
420
+ // ADR-0049 decision 12 diagnostics: additive and OMITTED when not derivable/stamped (so an unstamped boot
421
+ // — or a BYO instance with an underivable backend — carries none of them), keeping `reportVersion` at 1.
422
+ ...(init.engineHome != null ? { engineHome: init.engineHome } : {}),
423
+ ...(storageBackend != null ? { storageBackend } : {}),
424
+ ...(storageFallbackReason != null ? { storageFallbackReason } : {}),
372
425
  overlapPrefetch: init.overlapPrefetch,
373
426
  registryFingerprint: init.registryFingerprint,
374
427
  startedAt,
@@ -5,7 +5,8 @@
5
5
  * This driver is the *scheduling-policy seam*: the app decides WHEN to converge (online?
6
6
  * foregrounded? on power?) and how it learns those conditions, while the library owns the
7
7
  * convergence pass and the congestion policy (jittered backoff + attempt cap, already in the
8
- * mutation runtime). Pass nothing to `createSyncClient` → fully manual, today's behaviour.
8
+ * mutation runtime). The driver is opt-in: pass nothing to `createSyncClient` and no scheduling policy
9
+ * runs — convergence stays fully manual until the app installs one.
9
10
  *
10
11
  * A pass is `flush` → `reconcile`. It deliberately does NOT call `retryFailed`: `flush`
11
12
  * already re-attempts `failed` mutations whose `next_retry_at_us` backoff has elapsed, so a
@@ -0,0 +1,26 @@
1
+ /**
2
+ * Flatten an error's `cause` chain into one message. Driver wrappers (drizzle's "Failed query: …")
3
+ * carry the ACTUAL database error — SQLSTATE code, message, detail — on `.cause`, so surfacing only
4
+ * `error.message` reports the query text while hiding why it failed (observed in production as a
5
+ * degraded engine whose lastError ended at "params: [object Object]"). Every place that stringifies an
6
+ * error into `status.lastError` or a bridge broadcast goes through this instead.
7
+ */
8
+ export function describeErrorChain(error: unknown, maxDepth = 5): string {
9
+ const parts: string[] = [];
10
+ let current: unknown = error;
11
+ for (let depth = 0; depth < maxDepth && current != null; depth += 1) {
12
+ const message =
13
+ current instanceof Error ? current.message : typeof current === "string" ? current : JSON.stringify(current);
14
+ const code = typeof current === "object" && "code" in current ? (current as { code?: unknown }).code : undefined;
15
+ const detail =
16
+ typeof current === "object" && "detail" in current ? (current as { detail?: unknown }).detail : undefined;
17
+ const asText = (value: unknown): string => (typeof value === "string" ? value : JSON.stringify(value));
18
+ parts.push(
19
+ [message, code != null ? `[${asText(code)}]` : undefined, detail != null ? `(${asText(detail)})` : undefined]
20
+ .filter(Boolean)
21
+ .join(" "),
22
+ );
23
+ current = current instanceof Error ? current.cause : undefined;
24
+ }
25
+ return parts.join(" ← caused by: ");
26
+ }
@@ -148,7 +148,11 @@ export async function runThrowawayCloneDump(
148
148
  const cloneDataDir = resolveStoreDataDir(nextCloneStorePath(), "memory");
149
149
  const cloneBootStartedAtMs = nowMs() - startPerf;
150
150
  const cloneBootStartPerf = nowMs();
151
- const throwaway = await PGlite.create({ dataDir: cloneDataDir, loadDataDir: dumped });
151
+ // Relaxed durability (ADR-0047): this clone is a MEMORY-backed, read-only throwaway (dumped → `pg_dump`
152
+ // → discarded), so it has no idb flush to relax — the flag is a no-op on the memory backend and is set
153
+ // purely to state intent (a throwaway never needs synchronous durability) and stay correct if the clone's
154
+ // backend ever changes.
155
+ const throwaway = await PGlite.create({ dataDir: cloneDataDir, loadDataDir: dumped, relaxedDurability: true });
152
156
  const cloneBootMs = nowMs() - cloneBootStartPerf;
153
157
 
154
158
  let sqlBytes: Uint8Array<ArrayBuffer>;
@@ -175,7 +175,7 @@ export type ExportReport = StoreBackupReport | DiagnosticDumpReport | DataExport
175
175
 
176
176
  /** The artefact + its report — the resolved value of {@link SyncClient.exportStore}. */
177
177
  export interface StoreExportResult {
178
- /** The store-backup tarball as a named `File` (PGlite-restorable via `loadDataDir`, a later slice). */
178
+ /** The store-backup tarball as a named `File`, restorable by PGlite via `loadDataDir`. */
179
179
  file: File;
180
180
  /** The structured record of the export (ADR-0035). */
181
181
  report: StoreBackupReport;