xytara 3.1.13 → 3.1.15

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 (68) hide show
  1. package/.env.example +38 -4
  2. package/BSV_TERANODE_PLATFORM_DISCONTINUITY_RUNBOOK.md +126 -126
  3. package/REAL_PAYMENT_SETUP.md +14 -7
  4. package/RELEASE_NOTES.md +9 -4
  5. package/fixtures/catalog.js +22 -0
  6. package/lib/a2a_rpc.js +287 -280
  7. package/lib/account_auth.js +585 -585
  8. package/lib/agent_identity.js +162 -162
  9. package/lib/asyncapi_contract.js +3 -3
  10. package/lib/bolt_adapter.js +187 -187
  11. package/lib/bolt_payment_front.js +224 -224
  12. package/lib/buyer_event_log.js +215 -0
  13. package/lib/buyer_safety_policy.js +132 -0
  14. package/lib/checkout_processor_adapter.js +217 -217
  15. package/lib/command_flow.js +911 -722
  16. package/lib/commerce_artifacts.js +591 -591
  17. package/lib/commerce_bridge.js +274 -274
  18. package/lib/commerce_cases.js +399 -399
  19. package/lib/commerce_client.js +7694 -7694
  20. package/lib/commerce_quotes.js +29 -0
  21. package/lib/commerce_runtime.js +322 -322
  22. package/lib/execution_dedupe.js +86 -86
  23. package/lib/external_credit_bridge.js +142 -142
  24. package/lib/http_transport.js +99 -81
  25. package/lib/l402_adapter.js +241 -241
  26. package/lib/l402_payment_front.js +265 -265
  27. package/lib/mpp_adapter.js +237 -237
  28. package/lib/openapi_contract.js +4 -0
  29. package/lib/payment_config.js +257 -253
  30. package/lib/payment_verification.js +357 -357
  31. package/lib/provider_payout_execution.js +155 -155
  32. package/lib/provider_registry.js +852 -842
  33. package/lib/rate_limiter.js +81 -81
  34. package/lib/runtime_state_store.js +495 -369
  35. package/lib/settlement_bsv_live.js +600 -600
  36. package/lib/settlement_bsv_teranode.js +117 -117
  37. package/lib/stripe_mpp_payment_front.js +258 -258
  38. package/lib/x402_facilitator.js +198 -191
  39. package/lib/x402_lane_contract.js +5 -3
  40. package/lib/x402_settlement_recovery.js +175 -0
  41. package/package.json +9 -3
  42. package/scripts/buyer_events_daily_report.js +79 -0
  43. package/scripts/state_backup_offsite.js +196 -0
  44. package/scripts/verify_a2a_rpc.js +131 -105
  45. package/scripts/verify_agent_identity.js +153 -153
  46. package/scripts/verify_all.js +1 -1
  47. package/scripts/verify_bolt_adapter.js +128 -128
  48. package/scripts/verify_buyer_event_log.js +123 -0
  49. package/scripts/verify_buyer_safety.js +141 -0
  50. package/scripts/verify_cdp_facilitator.js +110 -110
  51. package/scripts/verify_checkout_processor.js +109 -109
  52. package/scripts/verify_commerce_bridge.js +177 -177
  53. package/scripts/verify_execution_dedupe.js +189 -189
  54. package/scripts/verify_execution_surfacing.js +76 -76
  55. package/scripts/verify_final_activation.js +191 -191
  56. package/scripts/verify_l402_adapter.js +86 -86
  57. package/scripts/verify_lifecycle_spend_binding.js +88 -0
  58. package/scripts/verify_mpp_adapter.js +128 -128
  59. package/scripts/verify_production_readiness.js +268 -268
  60. package/scripts/verify_rate_limiter.js +52 -52
  61. package/scripts/verify_refund_credit.js +106 -106
  62. package/scripts/verify_release_candidate.js +81 -81
  63. package/scripts/verify_runtime_state_guard.js +117 -0
  64. package/scripts/verify_service.js +15421 -15421
  65. package/scripts/verify_verify_execute_settle.js +209 -208
  66. package/scripts/verify_x402_facilitator.js +307 -286
  67. package/scripts/verify_x402_settlement_recovery.js +153 -0
  68. package/server.js +12242 -11974
@@ -1,369 +1,495 @@
1
- "use strict";
2
-
3
- const fs = require("fs");
4
- const path = require("path");
5
-
6
- function normalizeFilePath(filePath) {
7
- const raw = typeof filePath === "string" ? filePath.trim() : "";
8
- return raw ? path.resolve(raw) : "";
9
- }
10
-
11
- function normalizeUrl(url) {
12
- const raw = typeof url === "string" ? url.trim() : "";
13
- return raw ? raw.replace(/\/+$/, "") : "";
14
- }
15
-
16
- function normalizeString(value, fallback = "") {
17
- const raw = typeof value === "string" ? value.trim() : "";
18
- return raw || fallback;
19
- }
20
-
21
- // Top-level state keys that are PROCESS-LOCAL transient scratch, not durable facts, and
22
- // must never be snapshotted: persisting them risks restoring a stale entry that briefly
23
- // misbehaves after a restart. Kept out of the snapshot entirely (no write, no restore).
24
- const TRANSIENT_STATE_KEYS = new Set(["inFlightPaymentAuthorizations"]);
25
-
26
- function stateForSnapshot(state) {
27
- if (!state || typeof state !== "object" || Array.isArray(state)) return state;
28
- const snapshotSource = {};
29
- for (const [key, value] of Object.entries(state)) {
30
- if (TRANSIENT_STATE_KEYS.has(key)) continue;
31
- snapshotSource[key] = value;
32
- }
33
- return snapshotSource;
34
- }
35
-
36
- function serializeValue(value) {
37
- if (value instanceof Map) {
38
- return {
39
- __runtime_state_kind: "Map",
40
- value: Array.from(value.entries()).map(([key, entry]) => [key, serializeValue(entry)])
41
- };
42
- }
43
- if (value instanceof Set) {
44
- return {
45
- __runtime_state_kind: "Set",
46
- value: Array.from(value.values()).map((entry) => serializeValue(entry))
47
- };
48
- }
49
- if (Array.isArray(value)) {
50
- return value.map((entry) => serializeValue(entry));
51
- }
52
- if (value && typeof value === "object") {
53
- return Object.fromEntries(
54
- Object.entries(value).map(([key, entry]) => [key, serializeValue(entry)])
55
- );
56
- }
57
- return value;
58
- }
59
-
60
- function deserializeValue(value) {
61
- if (Array.isArray(value)) {
62
- return value.map((entry) => deserializeValue(entry));
63
- }
64
- if (!value || typeof value !== "object") {
65
- return value;
66
- }
67
- if (value.__runtime_state_kind === "Map" && Array.isArray(value.value)) {
68
- return new Map(value.value.map((entry) => [entry[0], deserializeValue(entry[1])]));
69
- }
70
- if (value.__runtime_state_kind === "Set" && Array.isArray(value.value)) {
71
- return new Set(value.value.map((entry) => deserializeValue(entry)));
72
- }
73
- return Object.fromEntries(
74
- Object.entries(value).map(([key, entry]) => [key, deserializeValue(entry)])
75
- );
76
- }
77
-
78
- function createRuntimeStateStore(config = {}) {
79
- const filePath = normalizeFilePath(config.filePath);
80
- const directoryPath = filePath ? path.dirname(filePath) : "";
81
- const intervalMs = Math.max(1000, Number.parseInt(String(config.intervalMs || 5000), 10) || 5000);
82
- const supabaseUrl = normalizeUrl(config.supabaseUrl);
83
- const supabaseServiceRoleKey = normalizeString(config.supabaseServiceRoleKey);
84
- const supabaseTable = normalizeString(config.supabaseTable, "xytara_runtime_state");
85
- const stateKey = normalizeString(config.stateKey, "default");
86
- const storageMode = supabaseUrl && supabaseServiceRoleKey ? "supabase" : filePath ? "file" : "memory";
87
- let dirty = false;
88
- let timer = null;
89
- let lastPersistedAtIso = null;
90
- let lastFlushSucceeded = false;
91
- let lastError = null;
92
- let snapshotExists = false;
93
- let snapshotUpdatedAtIso = null;
94
- let snapshotSizeBytes = 0;
95
- let remoteConfigured = storageMode === "supabase";
96
- let remoteReachable = storageMode !== "supabase";
97
- let remoteTableReady = storageMode !== "supabase";
98
-
99
- function enabled() {
100
- return storageMode !== "memory";
101
- }
102
-
103
- function markDirty() {
104
- if (!enabled()) return;
105
- dirty = true;
106
- }
107
-
108
- function applyRestoredState(state, restored) {
109
- if (!restored || typeof restored !== "object" || !state) return false;
110
- for (const key of Object.keys(state)) {
111
- if (Object.prototype.hasOwnProperty.call(restored, key)) {
112
- state[key] = restored[key];
113
- }
114
- }
115
- return true;
116
- }
117
-
118
- function inspectFileDirectory() {
119
- let exists = false;
120
- let writable = false;
121
- let error = null;
122
- if (storageMode !== "file") {
123
- return {
124
- exists: false,
125
- writable: false,
126
- error: null
127
- };
128
- }
129
- try {
130
- exists = fs.existsSync(directoryPath);
131
- if (exists) {
132
- fs.accessSync(directoryPath, fs.constants.W_OK);
133
- writable = true;
134
- }
135
- } catch (issue) {
136
- writable = false;
137
- error = issue;
138
- }
139
- return {
140
- exists,
141
- writable,
142
- error
143
- };
144
- }
145
-
146
- async function fetchSupabase(pathname, options = {}) {
147
- const response = await fetch(`${supabaseUrl}${pathname}`, {
148
- ...options,
149
- headers: {
150
- apikey: supabaseServiceRoleKey,
151
- authorization: `Bearer ${supabaseServiceRoleKey}`,
152
- ...(options.headers || {})
153
- }
154
- });
155
- remoteReachable = true;
156
- if (!response.ok) {
157
- const text = await response.text();
158
- const error = new Error(`supabase_runtime_state_${response.status}: ${text || response.statusText}`);
159
- error.status = response.status;
160
- throw error;
161
- }
162
- return response;
163
- }
164
-
165
- function updateSuccessSnapshotMetadata(persistedAtIso, serializedSnapshot) {
166
- lastPersistedAtIso = persistedAtIso;
167
- lastFlushSucceeded = true;
168
- lastError = null;
169
- snapshotExists = true;
170
- snapshotUpdatedAtIso = persistedAtIso;
171
- snapshotSizeBytes = Buffer.byteLength(JSON.stringify(serializedSnapshot), "utf8");
172
- }
173
-
174
- async function flushSupabase(state) {
175
- if (!dirty || !state) return false;
176
- const persistedAtIso = new Date().toISOString();
177
- const serializedSnapshot = serializeValue(stateForSnapshot(state));
178
- const payload = [{
179
- state_key: stateKey,
180
- snapshot: serializedSnapshot,
181
- persisted_at_iso: persistedAtIso
182
- }];
183
- try {
184
- await fetchSupabase(`/rest/v1/${encodeURIComponent(supabaseTable)}?on_conflict=state_key`, {
185
- method: "POST",
186
- headers: {
187
- "content-type": "application/json",
188
- prefer: "resolution=merge-duplicates,return=minimal"
189
- },
190
- body: JSON.stringify(payload)
191
- });
192
- remoteTableReady = true;
193
- dirty = false;
194
- updateSuccessSnapshotMetadata(persistedAtIso, serializedSnapshot);
195
- return true;
196
- } catch (error) {
197
- lastFlushSucceeded = false;
198
- lastError = error;
199
- remoteReachable = false;
200
- remoteTableReady = false;
201
- throw error;
202
- }
203
- }
204
-
205
- function flushFile(state) {
206
- if (!dirty || !state) return false;
207
- try {
208
- fs.mkdirSync(path.dirname(filePath), { recursive: true });
209
- const tempPath = `${filePath}.tmp`;
210
- const persistedAtIso = new Date().toISOString();
211
- const serializedSnapshot = serializeValue(stateForSnapshot(state));
212
- const snapshot = {
213
- persisted_at_iso: persistedAtIso,
214
- state: serializedSnapshot
215
- };
216
- fs.writeFileSync(tempPath, JSON.stringify(snapshot, null, 2), "utf8");
217
- fs.renameSync(tempPath, filePath);
218
- dirty = false;
219
- updateSuccessSnapshotMetadata(persistedAtIso, serializedSnapshot);
220
- return true;
221
- } catch (error) {
222
- lastFlushSucceeded = false;
223
- lastError = error;
224
- throw error;
225
- }
226
- }
227
-
228
- async function flush(state) {
229
- if (!enabled() || !dirty || !state) return false;
230
- if (storageMode === "supabase") {
231
- return flushSupabase(state);
232
- }
233
- if (storageMode === "file") {
234
- return flushFile(state);
235
- }
236
- return false;
237
- }
238
-
239
- async function loadSupabase(state) {
240
- try {
241
- const response = await fetchSupabase(
242
- `/rest/v1/${encodeURIComponent(supabaseTable)}?state_key=eq.${encodeURIComponent(stateKey)}&select=snapshot,persisted_at_iso&limit=1`
243
- );
244
- const rows = await response.json();
245
- const row = Array.isArray(rows) && rows[0] ? rows[0] : null;
246
- remoteTableReady = true;
247
- if (!row || !row.snapshot) {
248
- dirty = false;
249
- lastFlushSucceeded = true;
250
- lastError = null;
251
- snapshotExists = false;
252
- return false;
253
- }
254
- const restored = deserializeValue(row.snapshot);
255
- const applied = applyRestoredState(state, restored);
256
- dirty = false;
257
- lastPersistedAtIso = row.persisted_at_iso ? String(row.persisted_at_iso) : null;
258
- lastFlushSucceeded = true;
259
- lastError = null;
260
- snapshotExists = applied;
261
- snapshotUpdatedAtIso = lastPersistedAtIso;
262
- snapshotSizeBytes = Buffer.byteLength(JSON.stringify(row.snapshot), "utf8");
263
- return applied;
264
- } catch (error) {
265
- lastFlushSucceeded = false;
266
- lastError = error;
267
- remoteReachable = false;
268
- remoteTableReady = false;
269
- throw error;
270
- }
271
- }
272
-
273
- async function loadFile(state) {
274
- if (!state || !fs.existsSync(filePath)) return false;
275
- const raw = fs.readFileSync(filePath, "utf8");
276
- const parsed = JSON.parse(raw);
277
- const restored = deserializeValue(parsed && parsed.state ? parsed.state : parsed);
278
- const applied = applyRestoredState(state, restored);
279
- dirty = false;
280
- lastPersistedAtIso = parsed && parsed.persisted_at_iso ? String(parsed.persisted_at_iso) : null;
281
- lastFlushSucceeded = true;
282
- lastError = null;
283
- snapshotExists = applied;
284
- snapshotUpdatedAtIso = parsed && parsed.persisted_at_iso ? String(parsed.persisted_at_iso) : null;
285
- snapshotSizeBytes = Buffer.byteLength(raw, "utf8");
286
- return applied;
287
- }
288
-
289
- async function load(state) {
290
- if (!enabled() || !state) return false;
291
- if (storageMode === "supabase") {
292
- return loadSupabase(state);
293
- }
294
- if (storageMode === "file") {
295
- return loadFile(state);
296
- }
297
- return false;
298
- }
299
-
300
- function inspect() {
301
- const fileDirectory = inspectFileDirectory();
302
- const fileStats = storageMode === "file" && snapshotExists && fs.existsSync(filePath)
303
- ? fs.statSync(filePath)
304
- : null;
305
- return {
306
- enabled: enabled(),
307
- storage_mode: storageMode,
308
- file_path: filePath || null,
309
- directory_path: directoryPath || null,
310
- interval_ms: intervalMs,
311
- dirty,
312
- timer_active: Boolean(timer),
313
- directory_exists: storageMode === "file" ? fileDirectory.exists : false,
314
- directory_writable: storageMode === "file" ? fileDirectory.writable : false,
315
- directory_error: storageMode === "file" && fileDirectory.error ? fileDirectory.error.message : null,
316
- snapshot_exists: snapshotExists,
317
- snapshot_size_bytes: fileStats ? fileStats.size : snapshotSizeBytes,
318
- snapshot_updated_at_iso: fileStats ? fileStats.mtime.toISOString() : snapshotUpdatedAtIso,
319
- last_persisted_at_iso: lastPersistedAtIso,
320
- last_flush_succeeded: lastFlushSucceeded,
321
- last_error: lastError ? lastError.message : null,
322
- supabase_url: supabaseUrl || null,
323
- supabase_table: storageMode === "supabase" ? supabaseTable : null,
324
- supabase_state_key: storageMode === "supabase" ? stateKey : null,
325
- remote_configured: remoteConfigured,
326
- remote_reachable: remoteReachable,
327
- remote_table_ready: remoteTableReady
328
- };
329
- }
330
-
331
- function start(state) {
332
- if (!enabled() || timer) return;
333
- timer = setInterval(() => {
334
- Promise.resolve(flush(state)).catch((error) => {
335
- console.error("runtime state snapshot flush failed", error);
336
- });
337
- }, intervalMs);
338
- if (typeof timer.unref === "function") timer.unref();
339
- }
340
-
341
- async function stop(state) {
342
- if (timer) {
343
- clearInterval(timer);
344
- timer = null;
345
- }
346
- try {
347
- await flush(state);
348
- } catch (error) {
349
- console.error("runtime state snapshot final flush failed", error);
350
- }
351
- }
352
-
353
- return {
354
- enabled,
355
- storageMode,
356
- filePath,
357
- intervalMs,
358
- inspect,
359
- load,
360
- markDirty,
361
- flush,
362
- start,
363
- stop
364
- };
365
- }
366
-
367
- module.exports = {
368
- createRuntimeStateStore
369
- };
1
+ "use strict";
2
+
3
+ const crypto = require("crypto");
4
+ const fs = require("fs");
5
+ const path = require("path");
6
+
7
+ function normalizeFilePath(filePath) {
8
+ const raw = typeof filePath === "string" ? filePath.trim() : "";
9
+ return raw ? path.resolve(raw) : "";
10
+ }
11
+
12
+ function normalizeUrl(url) {
13
+ const raw = typeof url === "string" ? url.trim() : "";
14
+ return raw ? raw.replace(/\/+$/, "") : "";
15
+ }
16
+
17
+ function normalizeString(value, fallback = "") {
18
+ const raw = typeof value === "string" ? value.trim() : "";
19
+ return raw || fallback;
20
+ }
21
+
22
+ // Top-level state keys that are PROCESS-LOCAL transient scratch, not durable facts, and
23
+ // must never be snapshotted: persisting them risks restoring a stale entry that briefly
24
+ // misbehaves after a restart. Kept out of the snapshot entirely (no write, no restore).
25
+ const TRANSIENT_STATE_KEYS = new Set(["inFlightPaymentAuthorizations"]);
26
+
27
+ function stateForSnapshot(state) {
28
+ if (!state || typeof state !== "object" || Array.isArray(state)) return state;
29
+ const snapshotSource = {};
30
+ for (const [key, value] of Object.entries(state)) {
31
+ if (TRANSIENT_STATE_KEYS.has(key)) continue;
32
+ snapshotSource[key] = value;
33
+ }
34
+ return snapshotSource;
35
+ }
36
+
37
+ function serializeValue(value) {
38
+ if (value instanceof Map) {
39
+ return {
40
+ __runtime_state_kind: "Map",
41
+ value: Array.from(value.entries()).map(([key, entry]) => [key, serializeValue(entry)])
42
+ };
43
+ }
44
+ if (value instanceof Set) {
45
+ return {
46
+ __runtime_state_kind: "Set",
47
+ value: Array.from(value.values()).map((entry) => serializeValue(entry))
48
+ };
49
+ }
50
+ if (Array.isArray(value)) {
51
+ return value.map((entry) => serializeValue(entry));
52
+ }
53
+ if (value && typeof value === "object") {
54
+ return Object.fromEntries(
55
+ Object.entries(value).map(([key, entry]) => [key, serializeValue(entry)])
56
+ );
57
+ }
58
+ return value;
59
+ }
60
+
61
+ function deserializeValue(value) {
62
+ if (Array.isArray(value)) {
63
+ return value.map((entry) => deserializeValue(entry));
64
+ }
65
+ if (!value || typeof value !== "object") {
66
+ return value;
67
+ }
68
+ if (value.__runtime_state_kind === "Map" && Array.isArray(value.value)) {
69
+ return new Map(value.value.map((entry) => [entry[0], deserializeValue(entry[1])]));
70
+ }
71
+ if (value.__runtime_state_kind === "Set" && Array.isArray(value.value)) {
72
+ return new Set(value.value.map((entry) => deserializeValue(entry)));
73
+ }
74
+ return Object.fromEntries(
75
+ Object.entries(value).map(([key, entry]) => [key, deserializeValue(entry)])
76
+ );
77
+ }
78
+
79
+ function createRuntimeStateStore(config = {}) {
80
+ const filePath = normalizeFilePath(config.filePath);
81
+ const directoryPath = filePath ? path.dirname(filePath) : "";
82
+ const intervalMs = Math.max(1000, Number.parseInt(String(config.intervalMs || 15000), 10) || 15000);
83
+ // Rolling history (Supabase mode): every historyIntervalMs, the snapshot is ALSO written to one of
84
+ // historySlots rotating rows (`<stateKey>::history::<n>`) in the same table, so a bad write or a
85
+ // logical clobber of the main row can be rolled back. 0 disables. Off-site copies are separate
86
+ // (see scripts/state_backup_offsite.js).
87
+ const historyIntervalMs = config.historyIntervalMs === undefined || config.historyIntervalMs === null || config.historyIntervalMs === ""
88
+ ? 3600000
89
+ : Math.max(0, Number(config.historyIntervalMs) || 0);
90
+ const historySlots = Math.max(1, Math.min(168, Number.parseInt(String(config.historySlots || 24), 10) || 24));
91
+ const supabaseUrl = normalizeUrl(config.supabaseUrl);
92
+ const supabaseServiceRoleKey = normalizeString(config.supabaseServiceRoleKey);
93
+ const supabaseTable = normalizeString(config.supabaseTable, "xytara_runtime_state");
94
+ const stateKey = normalizeString(config.stateKey, "default");
95
+ const supabaseTimeoutMs = Math.max(1000, Number.parseInt(String(config.supabaseTimeoutMs || process.env.XYTARA_SUPABASE_TIMEOUT_MS || 10000), 10) || 10000);
96
+ const storageMode = supabaseUrl && supabaseServiceRoleKey ? "supabase" : filePath ? "file" : "memory";
97
+ let dirty = false;
98
+ let timer = null;
99
+ let lastPersistedAtIso = null;
100
+ let lastFlushSucceeded = false;
101
+ let lastError = null;
102
+ let snapshotExists = false;
103
+ let snapshotUpdatedAtIso = null;
104
+ let snapshotSizeBytes = 0;
105
+ let remoteConfigured = storageMode === "supabase";
106
+ let remoteReachable = storageMode !== "supabase";
107
+ let remoteTableReady = storageMode !== "supabase";
108
+ // WRITE GUARD: nothing is written until the durable snapshot has been read successfully (a
109
+ // restore, or a confirmed "no snapshot yet"). If the boot-time load fails (e.g. the backend
110
+ // times out), the process runs on empty state — and writing that would OVERWRITE the good
111
+ // snapshot. Instead flushes are refused and the load is retried; on success the snapshot is
112
+ // merged under whatever happened since boot, and only then do writes resume.
113
+ // Content digest of the last snapshot actually persisted: an unchanged snapshot is never rewritten.
114
+ let lastPersistedDigest = null;
115
+ let skippedUnchangedWrites = 0;
116
+ let lastHistoryAtMs = 0;
117
+ let lastHistorySlot = null;
118
+ let lastHistoryError = null;
119
+ let restoreConfirmed = false;
120
+ let restoreAttempts = 0;
121
+ let lastRestoreAttemptAtIso = null;
122
+ let restoreMergedAfterBoot = false;
123
+
124
+ function enabled() {
125
+ return storageMode !== "memory";
126
+ }
127
+
128
+ // Merge a restored snapshot UNDER the live in-memory state (used only when a restore succeeds
129
+ // after the process already started on empty state): collections are unioned with live entries
130
+ // winning; scalars/objects take the restored (durable) value.
131
+ function mergeRestoredState(state, restored) {
132
+ if (!restored || typeof restored !== "object" || !state) return false;
133
+ for (const key of Object.keys(state)) {
134
+ if (!Object.prototype.hasOwnProperty.call(restored, key)) continue;
135
+ const live = state[key];
136
+ const durable = restored[key];
137
+ if (live instanceof Map && durable instanceof Map) {
138
+ state[key] = new Map([...durable, ...live]);
139
+ } else if (live instanceof Set && durable instanceof Set) {
140
+ state[key] = new Set([...durable, ...live]);
141
+ } else if (Array.isArray(live) && Array.isArray(durable)) {
142
+ const seen = new Set(durable.map((entry) => JSON.stringify(entry)));
143
+ state[key] = durable.concat(live.filter((entry) => !seen.has(JSON.stringify(entry))));
144
+ } else {
145
+ state[key] = durable;
146
+ }
147
+ }
148
+ return true;
149
+ }
150
+
151
+ function markDirty() {
152
+ if (!enabled()) return;
153
+ dirty = true;
154
+ }
155
+
156
+ function applyRestoredState(state, restored) {
157
+ if (!restored || typeof restored !== "object" || !state) return false;
158
+ for (const key of Object.keys(state)) {
159
+ if (Object.prototype.hasOwnProperty.call(restored, key)) {
160
+ state[key] = restored[key];
161
+ }
162
+ }
163
+ return true;
164
+ }
165
+
166
+ function inspectFileDirectory() {
167
+ let exists = false;
168
+ let writable = false;
169
+ let error = null;
170
+ if (storageMode !== "file") {
171
+ return {
172
+ exists: false,
173
+ writable: false,
174
+ error: null
175
+ };
176
+ }
177
+ try {
178
+ exists = fs.existsSync(directoryPath);
179
+ if (exists) {
180
+ fs.accessSync(directoryPath, fs.constants.W_OK);
181
+ writable = true;
182
+ }
183
+ } catch (issue) {
184
+ writable = false;
185
+ error = issue;
186
+ }
187
+ return {
188
+ exists,
189
+ writable,
190
+ error
191
+ };
192
+ }
193
+
194
+ async function fetchSupabase(pathname, options = {}) {
195
+ // Bounded: a hung Supabase must never stall boot (the server waits for the restore before it
196
+ // listens) or a flush. A timeout is just a failed attempt; the write guard handles the rest.
197
+ const response = await fetch(`${supabaseUrl}${pathname}`, {
198
+ signal: options.signal || AbortSignal.timeout(supabaseTimeoutMs),
199
+ ...options,
200
+ headers: {
201
+ apikey: supabaseServiceRoleKey,
202
+ authorization: `Bearer ${supabaseServiceRoleKey}`,
203
+ ...(options.headers || {})
204
+ }
205
+ });
206
+ remoteReachable = true;
207
+ if (!response.ok) {
208
+ const text = await response.text();
209
+ const error = new Error(`supabase_runtime_state_${response.status}: ${text || response.statusText}`);
210
+ error.status = response.status;
211
+ throw error;
212
+ }
213
+ return response;
214
+ }
215
+
216
+ function updateSuccessSnapshotMetadata(persistedAtIso, snapshotJson) {
217
+ lastPersistedAtIso = persistedAtIso;
218
+ lastFlushSucceeded = true;
219
+ lastError = null;
220
+ snapshotExists = true;
221
+ snapshotUpdatedAtIso = persistedAtIso;
222
+ snapshotSizeBytes = Buffer.byteLength(snapshotJson, "utf8");
223
+ }
224
+
225
+ function digestOf(json) {
226
+ return crypto.createHash("sha256").update(json, "utf8").digest("hex");
227
+ }
228
+
229
+ function upsertRowBody(key, snapshotJson, persistedAtIso) {
230
+ return `[{"state_key":${JSON.stringify(key)},"snapshot":${snapshotJson},"persisted_at_iso":${JSON.stringify(persistedAtIso)}}]`;
231
+ }
232
+
233
+ async function upsertSupabaseRow(key, snapshotJson, persistedAtIso) {
234
+ await fetchSupabase(`/rest/v1/${encodeURIComponent(supabaseTable)}?on_conflict=state_key`, {
235
+ method: "POST",
236
+ headers: {
237
+ "content-type": "application/json",
238
+ prefer: "resolution=merge-duplicates,return=minimal"
239
+ },
240
+ body: upsertRowBody(key, snapshotJson, persistedAtIso)
241
+ });
242
+ }
243
+
244
+ // Best-effort rolling history copy; never fails the main flush.
245
+ async function maybeWriteHistory(snapshotJson, persistedAtIso) {
246
+ if (historyIntervalMs <= 0) return;
247
+ const nowMs = Date.parse(persistedAtIso);
248
+ if (lastHistoryAtMs && nowMs - lastHistoryAtMs < historyIntervalMs) return;
249
+ const slot = Math.floor(nowMs / historyIntervalMs) % historySlots;
250
+ try {
251
+ await upsertSupabaseRow(`${stateKey}::history::${slot}`, snapshotJson, persistedAtIso);
252
+ lastHistoryAtMs = nowMs;
253
+ lastHistorySlot = slot;
254
+ lastHistoryError = null;
255
+ } catch (error) {
256
+ lastHistoryError = error;
257
+ }
258
+ }
259
+
260
+ async function flushSupabase(state) {
261
+ if (!dirty || !state) return false;
262
+ const persistedAtIso = new Date().toISOString();
263
+ const snapshotJson = JSON.stringify(serializeValue(stateForSnapshot(state)));
264
+ const digest = digestOf(snapshotJson);
265
+ if (digest === lastPersistedDigest) {
266
+ // Nothing changed since the last successful write (e.g. a read-only POST): skip the rewrite.
267
+ dirty = false;
268
+ skippedUnchangedWrites += 1;
269
+ return false;
270
+ }
271
+ try {
272
+ await upsertSupabaseRow(stateKey, snapshotJson, persistedAtIso);
273
+ remoteTableReady = true;
274
+ dirty = false;
275
+ lastPersistedDigest = digest;
276
+ updateSuccessSnapshotMetadata(persistedAtIso, snapshotJson);
277
+ await maybeWriteHistory(snapshotJson, persistedAtIso);
278
+ return true;
279
+ } catch (error) {
280
+ lastFlushSucceeded = false;
281
+ lastError = error;
282
+ remoteReachable = false;
283
+ remoteTableReady = false;
284
+ throw error;
285
+ }
286
+ }
287
+
288
+ function flushFile(state) {
289
+ if (!dirty || !state) return false;
290
+ try {
291
+ fs.mkdirSync(path.dirname(filePath), { recursive: true });
292
+ const tempPath = `${filePath}.tmp`;
293
+ const persistedAtIso = new Date().toISOString();
294
+ const serializedSnapshot = serializeValue(stateForSnapshot(state));
295
+ const snapshotJson = JSON.stringify(serializedSnapshot);
296
+ const digest = digestOf(snapshotJson);
297
+ if (digest === lastPersistedDigest) {
298
+ dirty = false;
299
+ skippedUnchangedWrites += 1;
300
+ return false;
301
+ }
302
+ const snapshot = {
303
+ persisted_at_iso: persistedAtIso,
304
+ state: serializedSnapshot
305
+ };
306
+ fs.writeFileSync(tempPath, JSON.stringify(snapshot, null, 2), "utf8");
307
+ fs.renameSync(tempPath, filePath);
308
+ dirty = false;
309
+ lastPersistedDigest = digest;
310
+ updateSuccessSnapshotMetadata(persistedAtIso, snapshotJson);
311
+ return true;
312
+ } catch (error) {
313
+ lastFlushSucceeded = false;
314
+ lastError = error;
315
+ throw error;
316
+ }
317
+ }
318
+
319
+ async function flush(state) {
320
+ if (!enabled() || !dirty || !state) return false;
321
+ if (!restoreConfirmed) return false; // never overwrite a snapshot we have not read yet
322
+ if (storageMode === "supabase") {
323
+ return flushSupabase(state);
324
+ }
325
+ if (storageMode === "file") {
326
+ return flushFile(state);
327
+ }
328
+ return false;
329
+ }
330
+
331
+ async function loadSupabase(state, options = {}) {
332
+ try {
333
+ const response = await fetchSupabase(
334
+ `/rest/v1/${encodeURIComponent(supabaseTable)}?state_key=eq.${encodeURIComponent(stateKey)}&select=snapshot,persisted_at_iso&limit=1`
335
+ );
336
+ const rows = await response.json();
337
+ const row = Array.isArray(rows) && rows[0] ? rows[0] : null;
338
+ remoteTableReady = true;
339
+ if (!row || !row.snapshot) {
340
+ dirty = Boolean(options.merge && dirty);
341
+ lastFlushSucceeded = true;
342
+ lastError = null;
343
+ snapshotExists = false;
344
+ return false;
345
+ }
346
+ const restored = deserializeValue(row.snapshot);
347
+ const applied = options.merge ? mergeRestoredState(state, restored) : applyRestoredState(state, restored);
348
+ // After a late merge the live state now holds snapshot + post-boot changes: persist it.
349
+ dirty = Boolean(options.merge);
350
+ lastPersistedAtIso = row.persisted_at_iso ? String(row.persisted_at_iso) : null;
351
+ lastFlushSucceeded = true;
352
+ lastError = null;
353
+ snapshotExists = applied;
354
+ snapshotUpdatedAtIso = lastPersistedAtIso;
355
+ snapshotSizeBytes = Buffer.byteLength(JSON.stringify(row.snapshot), "utf8");
356
+ return applied;
357
+ } catch (error) {
358
+ lastFlushSucceeded = false;
359
+ lastError = error;
360
+ remoteReachable = false;
361
+ remoteTableReady = false;
362
+ throw error;
363
+ }
364
+ }
365
+
366
+ async function loadFile(state, options = {}) {
367
+ if (!state || !fs.existsSync(filePath)) return false;
368
+ const raw = fs.readFileSync(filePath, "utf8");
369
+ const parsed = JSON.parse(raw);
370
+ const restored = deserializeValue(parsed && parsed.state ? parsed.state : parsed);
371
+ const applied = options.merge ? mergeRestoredState(state, restored) : applyRestoredState(state, restored);
372
+ dirty = Boolean(options.merge);
373
+ lastPersistedAtIso = parsed && parsed.persisted_at_iso ? String(parsed.persisted_at_iso) : null;
374
+ lastFlushSucceeded = true;
375
+ lastError = null;
376
+ snapshotExists = applied;
377
+ snapshotUpdatedAtIso = parsed && parsed.persisted_at_iso ? String(parsed.persisted_at_iso) : null;
378
+ snapshotSizeBytes = Buffer.byteLength(raw, "utf8");
379
+ return applied;
380
+ }
381
+
382
+ // options.merge: the process already ran on empty state, so merge the snapshot under the live
383
+ // state instead of replacing it. Any successful read (restore OR confirmed-empty) unlocks writes;
384
+ // a failed read leaves writes locked and the error propagates to the caller.
385
+ async function load(state, options = {}) {
386
+ if (!enabled() || !state) return false;
387
+ restoreAttempts += 1;
388
+ lastRestoreAttemptAtIso = new Date().toISOString();
389
+ let result = false;
390
+ if (storageMode === "supabase") {
391
+ result = await loadSupabase(state, options);
392
+ } else if (storageMode === "file") {
393
+ result = await loadFile(state, options);
394
+ }
395
+ restoreConfirmed = true;
396
+ if (options.merge) restoreMergedAfterBoot = true;
397
+ return result;
398
+ }
399
+
400
+ function restoreConfirmedState() {
401
+ return restoreConfirmed;
402
+ }
403
+
404
+ function inspect() {
405
+ const fileDirectory = inspectFileDirectory();
406
+ const fileStats = storageMode === "file" && snapshotExists && fs.existsSync(filePath)
407
+ ? fs.statSync(filePath)
408
+ : null;
409
+ return {
410
+ enabled: enabled(),
411
+ storage_mode: storageMode,
412
+ file_path: filePath || null,
413
+ directory_path: directoryPath || null,
414
+ interval_ms: intervalMs,
415
+ dirty,
416
+ timer_active: Boolean(timer),
417
+ directory_exists: storageMode === "file" ? fileDirectory.exists : false,
418
+ directory_writable: storageMode === "file" ? fileDirectory.writable : false,
419
+ directory_error: storageMode === "file" && fileDirectory.error ? fileDirectory.error.message : null,
420
+ snapshot_exists: snapshotExists,
421
+ snapshot_size_bytes: fileStats ? fileStats.size : snapshotSizeBytes,
422
+ snapshot_updated_at_iso: fileStats ? fileStats.mtime.toISOString() : snapshotUpdatedAtIso,
423
+ last_persisted_at_iso: lastPersistedAtIso,
424
+ last_flush_succeeded: lastFlushSucceeded,
425
+ last_error: lastError ? lastError.message : null,
426
+ supabase_url: supabaseUrl || null,
427
+ supabase_table: storageMode === "supabase" ? supabaseTable : null,
428
+ supabase_state_key: storageMode === "supabase" ? stateKey : null,
429
+ remote_configured: remoteConfigured,
430
+ remote_reachable: remoteReachable,
431
+ remote_table_ready: remoteTableReady,
432
+ skipped_unchanged_writes: skippedUnchangedWrites,
433
+ history_interval_ms: storageMode === "supabase" ? historyIntervalMs : null,
434
+ history_slots: storageMode === "supabase" ? historySlots : null,
435
+ last_history_at_iso: lastHistoryAtMs ? new Date(lastHistoryAtMs).toISOString() : null,
436
+ last_history_slot: lastHistorySlot,
437
+ last_history_error: lastHistoryError ? lastHistoryError.message : null,
438
+ restore_confirmed: restoreConfirmed,
439
+ writes_locked_until_restore: enabled() && !restoreConfirmed,
440
+ restore_attempts: restoreAttempts,
441
+ last_restore_attempt_at_iso: lastRestoreAttemptAtIso,
442
+ restore_merged_after_boot: restoreMergedAfterBoot
443
+ };
444
+ }
445
+
446
+ // onRestored(restored): optional callback when a deferred restore finally succeeds.
447
+ function start(state, onRestored) {
448
+ if (!enabled() || timer) return;
449
+ let busy = false;
450
+ timer = setInterval(() => {
451
+ if (busy) return;
452
+ busy = true;
453
+ const step = restoreConfirmed
454
+ ? Promise.resolve(flush(state))
455
+ : Promise.resolve(load(state, { merge: true })).then((restored) => {
456
+ console.log("xytara runtime state restore succeeded after boot; writes unlocked");
457
+ if (typeof onRestored === "function") onRestored(restored);
458
+ });
459
+ step.catch((error) => {
460
+ console.error(restoreConfirmed ? "runtime state snapshot flush failed" : "runtime state restore retry failed (writes stay locked)", error && error.message ? error.message : error);
461
+ }).finally(() => { busy = false; });
462
+ }, intervalMs);
463
+ if (typeof timer.unref === "function") timer.unref();
464
+ }
465
+
466
+ async function stop(state) {
467
+ if (timer) {
468
+ clearInterval(timer);
469
+ timer = null;
470
+ }
471
+ try {
472
+ await flush(state);
473
+ } catch (error) {
474
+ console.error("runtime state snapshot final flush failed", error);
475
+ }
476
+ }
477
+
478
+ return {
479
+ enabled,
480
+ storageMode,
481
+ filePath,
482
+ intervalMs,
483
+ inspect,
484
+ load,
485
+ restoreConfirmed: restoreConfirmedState,
486
+ markDirty,
487
+ flush,
488
+ start,
489
+ stop
490
+ };
491
+ }
492
+
493
+ module.exports = {
494
+ createRuntimeStateStore
495
+ };