xytara 3.1.13 → 3.1.14

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