enigma-memory 0.1.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 (105) hide show
  1. package/LICENSE +55 -0
  2. package/README.md +379 -0
  3. package/apps/cli/bin/enigma.mjs +1117 -0
  4. package/apps/desktop/src/app.js +1327 -0
  5. package/apps/desktop/src/index.html +1373 -0
  6. package/apps/desktop/src/styles.css +386 -0
  7. package/apps/gateway/bin/enigma-gateway.mjs +52 -0
  8. package/apps/gateway/src/server.mjs +1403 -0
  9. package/apps/native-host/README.md +265 -0
  10. package/apps/native-host/bin/enigma-native-host.mjs +499 -0
  11. package/apps/native-host/manifests/com.enigma.native_host.chrome.json +9 -0
  12. package/apps/native-host/manifests/com.enigma.native_host.edge.json +9 -0
  13. package/apps/native-host/manifests/com.enigma.native_host.firefox.json +9 -0
  14. package/apps/relay/bin/enigma-relay.mjs +52 -0
  15. package/apps/relay/src/server.mjs +1571 -0
  16. package/apps/verifier/bin/enigma-verify.mjs +240 -0
  17. package/deploy/docker-compose.production.example.yml +150 -0
  18. package/deploy/kubernetes/enigma-backend.example.yaml +580 -0
  19. package/package.json +196 -0
  20. package/packages/adapters/PACKAGE_CONTRACT.md +47 -0
  21. package/packages/adapters/src/index.js +183 -0
  22. package/packages/boundary/src/index.js +468 -0
  23. package/packages/connectors/src/index.js +533 -0
  24. package/packages/core/src/index.js +766 -0
  25. package/packages/enterprise/src/index.js +505 -0
  26. package/packages/importers/src/index.js +1083 -0
  27. package/packages/mcp-server/bin/enigma-mcp.mjs +19 -0
  28. package/packages/mcp-server/src/index.js +1185 -0
  29. package/packages/mesh/src/index.js +531 -0
  30. package/packages/metering/PACKAGE_CONTRACT.md +20 -0
  31. package/packages/metering/src/index.js +246 -0
  32. package/packages/optimizer/src/index.js +707 -0
  33. package/packages/passport/src/index.js +651 -0
  34. package/packages/settlement/PACKAGE_CONTRACT.md +28 -0
  35. package/packages/settlement/src/index.js +369 -0
  36. package/packages/storage/PACKAGE_CONTRACT.md +23 -0
  37. package/packages/storage/src/index.js +392 -0
  38. package/packages/vault/src/index.js +904 -0
  39. package/scripts/build-ai-orchestration-plan.mjs +248 -0
  40. package/scripts/build-cloudflare-pages-release-packet.mjs +287 -0
  41. package/scripts/build-cloudflare-token-policy.mjs +239 -0
  42. package/scripts/build-cloudflare-token-request.mjs +314 -0
  43. package/scripts/build-demo-assets.mjs +263 -0
  44. package/scripts/build-edge-backend-workers.mjs +353 -0
  45. package/scripts/build-goal-completion-audit.mjs +398 -0
  46. package/scripts/build-hosted-probe-worker.mjs +191 -0
  47. package/scripts/build-operator-acceptance-packet.mjs +254 -0
  48. package/scripts/build-operator-evidence-starter.mjs +525 -0
  49. package/scripts/build-production-backend-env-kit.mjs +384 -0
  50. package/scripts/build-production-dependency-report.mjs +369 -0
  51. package/scripts/build-production-handoff-packet.mjs +475 -0
  52. package/scripts/build-production-readiness-manifest.mjs +209 -0
  53. package/scripts/build-production-status-board.mjs +297 -0
  54. package/scripts/build-production-storage-migration.mjs +86 -0
  55. package/scripts/build-production-workplan.mjs +371 -0
  56. package/scripts/build-review-packet.mjs +594 -0
  57. package/scripts/check.mjs +419 -0
  58. package/scripts/cloudflare-ops.mjs +1672 -0
  59. package/scripts/cloudflare-secret-env.mjs +128 -0
  60. package/scripts/collect-hosted-backend-live-evidence.mjs +263 -0
  61. package/scripts/infrastructure-readiness.mjs +944 -0
  62. package/scripts/install-enigma-local.mjs +270 -0
  63. package/scripts/memory-optimization-benchmark.mjs +242 -0
  64. package/scripts/monitor-live-endpoints.mjs +358 -0
  65. package/scripts/release-audit.mjs +5588 -0
  66. package/scripts/release-provenance.mjs +250 -0
  67. package/scripts/run-backend-readiness-smoke.mjs +220 -0
  68. package/scripts/validate-backup-restore-drill.mjs +166 -0
  69. package/scripts/validate-cloudflare-credentials.mjs +112 -0
  70. package/scripts/validate-cloudflare-worker-inspect.mjs +179 -0
  71. package/scripts/validate-domain-tls.mjs +248 -0
  72. package/scripts/validate-hosted-backend-live.mjs +319 -0
  73. package/scripts/validate-incident-drill.mjs +221 -0
  74. package/scripts/validate-kms-custody.mjs +235 -0
  75. package/scripts/validate-legal-compliance-approval.mjs +274 -0
  76. package/scripts/validate-monitoring-alerting.mjs +263 -0
  77. package/scripts/validate-network-access-policy.mjs +285 -0
  78. package/scripts/validate-operator-acceptance.mjs +298 -0
  79. package/scripts/validate-production-manifests.mjs +325 -0
  80. package/scripts/validate-public-site-security.mjs +252 -0
  81. package/scripts/validate-security-threat-model.mjs +285 -0
  82. package/scripts/validate-service-settlement.mjs +256 -0
  83. package/scripts/validate-support-sla.mjs +190 -0
  84. package/scripts/validate-tenant-policy-approval.mjs +228 -0
  85. package/scripts/validate-usage-metering.mjs +224 -0
  86. package/scripts/validate-whitepaper-claims.mjs +166 -0
  87. package/specs/boundary-manifest-v1.schema.json +35 -0
  88. package/specs/capsule-v1.schema.json +55 -0
  89. package/specs/claim-boundary-manifest-v1.schema.json +22 -0
  90. package/specs/connector-profile-v1.schema.json +62 -0
  91. package/specs/deletion-tombstone-v1.schema.json +26 -0
  92. package/specs/enterprise-policy-v1.schema.json +59 -0
  93. package/specs/gateway-request-v1.schema.json +32 -0
  94. package/specs/goal-completion-audit-v1.schema.json +70 -0
  95. package/specs/hosted-backend-live-evidence-v1.schema.json +147 -0
  96. package/specs/import-report-v1.schema.json +214 -0
  97. package/specs/infrastructure-readiness-manifest-v1.schema.json +130 -0
  98. package/specs/memory-event-v1.schema.json +42 -0
  99. package/specs/mesh-node-v1.schema.json +126 -0
  100. package/specs/passport-v1.schema.json +50 -0
  101. package/specs/production-handoff-packet-v1.schema.json +149 -0
  102. package/specs/receipt-v1.schema.json +61 -0
  103. package/specs/relay-record-v1.schema.json +43 -0
  104. package/specs/state-checkpoint-v1.schema.json +37 -0
  105. package/specs/trust-bundle-v1.schema.json +56 -0
@@ -0,0 +1,392 @@
1
+ export const PRODUCTION_STORAGE_SCHEMA = 'enigma.production_storage_contract.v1';
2
+ export const POSTGRES_MIGRATION_SCHEMA = 'enigma.postgres_migration.v1';
3
+ export const PRODUCTION_STORAGE_OPERATION_SCHEMA = 'enigma.production_storage_sql_operation.v1';
4
+
5
+ export const PRODUCTION_STORAGE_TABLES = Object.freeze([
6
+ 'enigma_schema_migrations',
7
+ 'relay_records',
8
+ 'relay_witness_checkpoints',
9
+ 'relay_pairings',
10
+ 'gateway_policy_versions',
11
+ 'gateway_decisions',
12
+ 'gateway_siem_events',
13
+ 'readiness_evidence_refs',
14
+ ]);
15
+
16
+ const FORBIDDEN_STORAGE_SQL_RE = /\b(prompt|completion|transcript|plaintext|raw_memory|memory_text|decrypted|embedding_vector|provider_response_body|api_key|token|password|private_key)\b/i;
17
+ const FORBIDDEN_PUBLIC_VALUE_RE = /(?:Bearer\s+[A-Za-z0-9._~+/=-]{12,}|Basic\s+[A-Za-z0-9+/=-]{12,}|-----BEGIN [A-Z ]*PRIVATE KEY-----|https?:\/\/[^\s/@]+:[^\s/@]+@|raw memory|private prompt|full transcript|decrypted capsule)/iu;
18
+
19
+ function assertNoForbiddenPublicValue(value, path = 'storage') {
20
+ if (typeof value === 'string') {
21
+ if (FORBIDDEN_PUBLIC_VALUE_RE.test(value)) throw new Error(`${path} contains secret or plaintext-looking material`);
22
+ return;
23
+ }
24
+ if (Array.isArray(value)) {
25
+ value.forEach((item, index) => assertNoForbiddenPublicValue(item, `${path}[${index}]`));
26
+ return;
27
+ }
28
+ if (value !== null && typeof value === 'object') {
29
+ for (const [key, child] of Object.entries(value)) {
30
+ if (/prompt|completion|transcript|plaintext|raw[_-]?memory|memory[_-]?text|decrypted|embedding|provider[_-]?response|api[_-]?key|token|password|private[_-]?key/i.test(key)) {
31
+ throw new Error(`${path}.${key} uses a forbidden storage evidence field`);
32
+ }
33
+ assertNoForbiddenPublicValue(child, `${path}.${key}`);
34
+ }
35
+ }
36
+ }
37
+
38
+ function sql(strings, ...values) {
39
+ let out = '';
40
+ for (let index = 0; index < strings.length; index += 1) {
41
+ out += strings[index];
42
+ if (index < values.length) out += values[index];
43
+ }
44
+ return out.trim();
45
+ }
46
+
47
+ export function postgresProductionSchemaSql(options = {}) {
48
+ const schemaName = options.schema ?? options.schemaName ?? 'enigma';
49
+ if (!/^[a-z_][a-z0-9_]{0,62}$/i.test(schemaName)) throw new Error('schema name must be a safe SQL identifier');
50
+ const q = (name) => `"${schemaName}"."${name}"`;
51
+ const text = sql`
52
+ CREATE SCHEMA IF NOT EXISTS "${schemaName}";
53
+
54
+ CREATE TABLE IF NOT EXISTS ${q('enigma_schema_migrations')} (
55
+ migration_id text PRIMARY KEY,
56
+ applied_at timestamptz NOT NULL DEFAULT now(),
57
+ checksum text NOT NULL CHECK (checksum ~ '^sha256:[a-f0-9]{64}$')
58
+ );
59
+
60
+ CREATE TABLE IF NOT EXISTS ${q('relay_records')} (
61
+ record_id text PRIMARY KEY,
62
+ store_id text NOT NULL,
63
+ capsule_id text NOT NULL,
64
+ encrypted_payload_hash text NOT NULL CHECK (encrypted_payload_hash ~ '^sha256:[a-f0-9]{64}$'),
65
+ payload_storage jsonb NOT NULL,
66
+ received_at timestamptz NOT NULL,
67
+ expires_at timestamptz,
68
+ signature jsonb NOT NULL,
69
+ inserted_at timestamptz NOT NULL DEFAULT now(),
70
+ CHECK (jsonb_typeof(payload_storage) = 'object'),
71
+ CHECK (jsonb_typeof(signature) = 'object')
72
+ );
73
+ CREATE INDEX IF NOT EXISTS relay_records_store_received_idx ON ${q('relay_records')} (store_id, received_at DESC);
74
+ CREATE INDEX IF NOT EXISTS relay_records_capsule_idx ON ${q('relay_records')} (capsule_id);
75
+
76
+ CREATE TABLE IF NOT EXISTS ${q('relay_witness_checkpoints')} (
77
+ checkpoint_id text PRIMARY KEY,
78
+ root text NOT NULL CHECK (root ~ '^sha256:[a-f0-9]{64}$'),
79
+ previous_root text CHECK (previous_root ~ '^sha256:[a-f0-9]{64}$'),
80
+ record_count bigint NOT NULL CHECK (record_count >= 0),
81
+ checkpointed_at timestamptz NOT NULL,
82
+ signature jsonb NOT NULL,
83
+ inserted_at timestamptz NOT NULL DEFAULT now(),
84
+ CHECK (jsonb_typeof(signature) = 'object')
85
+ );
86
+
87
+ CREATE TABLE IF NOT EXISTS ${q('relay_pairings')} (
88
+ pairing_id text PRIMARY KEY,
89
+ challenge_id text NOT NULL,
90
+ relay_node_id text NOT NULL,
91
+ client_public_key_hash text NOT NULL CHECK (client_public_key_hash ~ '^sha256:[a-f0-9]{64}$'),
92
+ issued_at timestamptz NOT NULL,
93
+ signature jsonb NOT NULL,
94
+ inserted_at timestamptz NOT NULL DEFAULT now(),
95
+ CHECK (jsonb_typeof(signature) = 'object')
96
+ );
97
+
98
+ CREATE TABLE IF NOT EXISTS ${q('gateway_policy_versions')} (
99
+ policy_hash text PRIMARY KEY CHECK (policy_hash ~ '^sha256:[a-f0-9]{64}$'),
100
+ policy jsonb NOT NULL,
101
+ active_from timestamptz NOT NULL DEFAULT now(),
102
+ retired_at timestamptz,
103
+ CHECK (jsonb_typeof(policy) = 'object')
104
+ );
105
+
106
+ CREATE TABLE IF NOT EXISTS ${q('gateway_decisions')} (
107
+ decision_id text PRIMARY KEY,
108
+ policy_hash text NOT NULL CHECK (policy_hash ~ '^sha256:[a-f0-9]{64}$'),
109
+ decision_hash text NOT NULL CHECK (decision_hash ~ '^sha256:[a-f0-9]{64}$'),
110
+ decision jsonb NOT NULL,
111
+ created_at timestamptz NOT NULL DEFAULT now(),
112
+ CHECK (jsonb_typeof(decision) = 'object')
113
+ );
114
+ CREATE INDEX IF NOT EXISTS gateway_decisions_policy_idx ON ${q('gateway_decisions')} (policy_hash, created_at DESC);
115
+
116
+ CREATE TABLE IF NOT EXISTS ${q('gateway_siem_events')} (
117
+ event_id text PRIMARY KEY,
118
+ event_hash text NOT NULL CHECK (event_hash ~ '^sha256:[a-f0-9]{64}$'),
119
+ event jsonb NOT NULL,
120
+ created_at timestamptz NOT NULL DEFAULT now(),
121
+ CHECK (jsonb_typeof(event) = 'object')
122
+ );
123
+
124
+ CREATE TABLE IF NOT EXISTS ${q('readiness_evidence_refs')} (
125
+ evidence_key text PRIMARY KEY,
126
+ provider text NOT NULL,
127
+ ref text NOT NULL,
128
+ status text NOT NULL CHECK (status IN ('declared', 'observed', 'verified', 'go')),
129
+ observed_at timestamptz NOT NULL,
130
+ metadata jsonb NOT NULL DEFAULT '{}'::jsonb,
131
+ CHECK (jsonb_typeof(metadata) = 'object')
132
+ );
133
+ `;
134
+ if (FORBIDDEN_STORAGE_SQL_RE.test(text)) throw new Error('Postgres production schema contains forbidden plaintext/secret column names');
135
+ return text;
136
+ }
137
+
138
+ export function buildPostgresMigration(options = {}) {
139
+ const sqlText = postgresProductionSchemaSql(options);
140
+ const migration = {
141
+ schema: POSTGRES_MIGRATION_SCHEMA,
142
+ migration_id: options.migration_id ?? options.migrationId ?? '001_enigma_production_storage',
143
+ engine: 'postgres',
144
+ reversible: false,
145
+ claim_boundary: [
146
+ 'This migration defines durable production storage tables only; it does not provision a database or prove hosted readiness.',
147
+ 'Tables store hashes, opaque encrypted payload references, minimized decisions, SIEM events, and public-safe readiness refs; raw prompts, transcripts, decrypted memory, provider responses, and secrets are forbidden.',
148
+ ],
149
+ tables: [...PRODUCTION_STORAGE_TABLES],
150
+ sql: sqlText,
151
+ };
152
+ assertNoForbiddenPublicValue(migration, 'migration');
153
+ return migration;
154
+ }
155
+
156
+ export function assertProductionStorageSqlSafe(sqlText) {
157
+ if (typeof sqlText !== 'string' || sqlText.trim().length === 0) throw new Error('SQL text is required');
158
+ if (FORBIDDEN_STORAGE_SQL_RE.test(sqlText)) throw new Error('SQL text contains forbidden plaintext/secret storage fields');
159
+ for (const table of PRODUCTION_STORAGE_TABLES) {
160
+ if (!new RegExp(`CREATE TABLE IF NOT EXISTS [\\s\\S]*${table}`, 'i').test(sqlText)) {
161
+ throw new Error(`SQL text missing table ${table}`);
162
+ }
163
+ }
164
+ if (!/encrypted_payload_hash/i.test(sqlText)) throw new Error('relay storage must use encrypted_payload_hash');
165
+ if (!/client_public_key_hash/i.test(sqlText)) throw new Error('pairing storage must hash client public keys');
166
+ if (!/decision_hash/i.test(sqlText) || !/event_hash/i.test(sqlText)) throw new Error('gateway storage must hash decisions and SIEM events');
167
+ return true;
168
+ }
169
+
170
+ export function productionStorageContract(options = {}) {
171
+ const migration = buildPostgresMigration(options);
172
+ assertProductionStorageSqlSafe(migration.sql);
173
+ return Object.freeze({
174
+ schema: PRODUCTION_STORAGE_SCHEMA,
175
+ engine: 'postgres',
176
+ migration_schema: migration.schema,
177
+ migration_id: migration.migration_id,
178
+ tables: Object.freeze([...migration.tables]),
179
+ required_refs: Object.freeze([
180
+ 'backend_host',
181
+ 'dns_tls',
182
+ 'durable_storage',
183
+ 'kms_or_secret_custody',
184
+ 'backup_restore',
185
+ 'monitoring',
186
+ 'siem_or_log_sink',
187
+ 'operator_acceptance',
188
+ 'runtime_auth',
189
+ 'admin_auth',
190
+ 'data_plane_auth',
191
+ ]),
192
+ claim_boundary: Object.freeze([
193
+ 'Storage contract is schema/readiness preparation only, not a live database.',
194
+ 'Operators must provision Postgres, KMS/secret custody, backups, monitoring, SIEM/log routing, and auth before hosted_live_ready can be true.',
195
+ ]),
196
+ });
197
+ }
198
+
199
+ function safeSqlIdentifier(value, label = 'identifier') {
200
+ if (typeof value !== 'string' || !/^[a-z_][a-z0-9_]{0,62}$/i.test(value)) {
201
+ throw new Error(`${label} must be a safe SQL identifier`);
202
+ }
203
+ return value;
204
+ }
205
+
206
+ function storageTable(schema, table) {
207
+ safeSqlIdentifier(schema, 'schema');
208
+ if (!PRODUCTION_STORAGE_TABLES.includes(table)) throw new Error(`unknown production storage table: ${table}`);
209
+ return `"${schema}"."${table}"`;
210
+ }
211
+
212
+ function requireNonEmptyString(value, path) {
213
+ if (typeof value !== 'string' || value.trim().length === 0) throw new Error(`${path} must be a non-empty string`);
214
+ assertNoForbiddenPublicValue(value, path);
215
+ return value;
216
+ }
217
+
218
+ function optionalIsoString(value, path) {
219
+ if (value === undefined || value === null || value === '') return null;
220
+ const text = requireNonEmptyString(value, path);
221
+ if (Number.isNaN(Date.parse(text))) throw new Error(`${path} must be an ISO timestamp`);
222
+ return text;
223
+ }
224
+
225
+ function requireSha256(value, path) {
226
+ const text = requireNonEmptyString(value, path);
227
+ if (!/^sha256:[a-f0-9]{64}$/i.test(text)) throw new Error(`${path} must be a sha256-prefixed digest`);
228
+ return text.toLowerCase();
229
+ }
230
+
231
+ function jsonValue(value, path) {
232
+ if (value === null || typeof value !== 'object' || Array.isArray(value)) throw new Error(`${path} must be an object`);
233
+ assertNoForbiddenPublicValue(value, path);
234
+ return JSON.stringify(value);
235
+ }
236
+
237
+ function storageOperation(name, text, values) {
238
+ assertNoForbiddenPublicValue(values, `${name}.values`);
239
+ if (FORBIDDEN_STORAGE_SQL_RE.test(text)) throw new Error(`${name} SQL contains forbidden plaintext/secret fields`);
240
+ return Object.freeze({
241
+ schema: PRODUCTION_STORAGE_OPERATION_SCHEMA,
242
+ engine: 'postgres',
243
+ name,
244
+ text,
245
+ values: Object.freeze([...values]),
246
+ claim_boundary: Object.freeze([
247
+ 'This operation is parameterized SQL material only; it does not connect to or mutate a database by itself.',
248
+ 'Values must contain hashes, opaque encrypted payload refs, minimized decisions/events, or public-safe refs only.',
249
+ ]),
250
+ });
251
+ }
252
+
253
+ export function buildRelayRecordUpsert(record, options = {}) {
254
+ assertNoForbiddenPublicValue(record, 'relay_record');
255
+ const schema = options.schema ?? options.schemaName ?? 'enigma';
256
+ return storageOperation('relay_records.upsert', `INSERT INTO ${storageTable(schema, 'relay_records')} (
257
+ record_id, store_id, capsule_id, encrypted_payload_hash, payload_storage, received_at, expires_at, signature
258
+ ) VALUES ($1, $2, $3, $4, $5::jsonb, $6, $7, $8::jsonb)
259
+ ON CONFLICT (record_id) DO UPDATE SET
260
+ encrypted_payload_hash = EXCLUDED.encrypted_payload_hash,
261
+ payload_storage = EXCLUDED.payload_storage,
262
+ received_at = EXCLUDED.received_at,
263
+ expires_at = EXCLUDED.expires_at,
264
+ signature = EXCLUDED.signature
265
+ RETURNING record_id`, [
266
+ requireNonEmptyString(record?.record_id, 'relay_record.record_id'),
267
+ requireNonEmptyString(record?.store_id, 'relay_record.store_id'),
268
+ requireNonEmptyString(record?.capsule_id, 'relay_record.capsule_id'),
269
+ requireSha256(record?.encrypted_payload_hash, 'relay_record.encrypted_payload_hash'),
270
+ jsonValue(record?.payload_storage, 'relay_record.payload_storage'),
271
+ optionalIsoString(record?.received_at, 'relay_record.received_at') ?? new Date(0).toISOString(),
272
+ optionalIsoString(record?.expires_at, 'relay_record.expires_at'),
273
+ jsonValue(record?.signature, 'relay_record.signature'),
274
+ ]);
275
+ }
276
+
277
+ export function buildWitnessCheckpointUpsert(checkpoint, options = {}) {
278
+ assertNoForbiddenPublicValue(checkpoint, 'witness_checkpoint');
279
+ const schema = options.schema ?? options.schemaName ?? 'enigma';
280
+ return storageOperation('relay_witness_checkpoints.upsert', `INSERT INTO ${storageTable(schema, 'relay_witness_checkpoints')} (
281
+ checkpoint_id, root, previous_root, record_count, checkpointed_at, signature
282
+ ) VALUES ($1, $2, $3, $4, $5, $6::jsonb)
283
+ ON CONFLICT (checkpoint_id) DO UPDATE SET
284
+ root = EXCLUDED.root,
285
+ previous_root = EXCLUDED.previous_root,
286
+ record_count = EXCLUDED.record_count,
287
+ checkpointed_at = EXCLUDED.checkpointed_at,
288
+ signature = EXCLUDED.signature
289
+ RETURNING checkpoint_id`, [
290
+ requireNonEmptyString(checkpoint?.checkpoint_id, 'witness_checkpoint.checkpoint_id'),
291
+ requireSha256(checkpoint?.root, 'witness_checkpoint.root'),
292
+ checkpoint?.previous_root === undefined || checkpoint?.previous_root === null ? null : requireSha256(checkpoint.previous_root, 'witness_checkpoint.previous_root'),
293
+ Number.isInteger(checkpoint?.record_count) && checkpoint.record_count >= 0 ? checkpoint.record_count : (() => { throw new Error('witness_checkpoint.record_count must be a non-negative integer'); })(),
294
+ optionalIsoString(checkpoint?.checkpointed_at, 'witness_checkpoint.checkpointed_at') ?? new Date(0).toISOString(),
295
+ jsonValue(checkpoint?.signature, 'witness_checkpoint.signature'),
296
+ ]);
297
+ }
298
+
299
+ export function buildRelayPairingUpsert(pairing, options = {}) {
300
+ assertNoForbiddenPublicValue(pairing, 'relay_pairing');
301
+ const schema = options.schema ?? options.schemaName ?? 'enigma';
302
+ return storageOperation('relay_pairings.upsert', `INSERT INTO ${storageTable(schema, 'relay_pairings')} (
303
+ pairing_id, challenge_id, relay_node_id, client_public_key_hash, issued_at, signature
304
+ ) VALUES ($1, $2, $3, $4, $5, $6::jsonb)
305
+ ON CONFLICT (pairing_id) DO UPDATE SET
306
+ challenge_id = EXCLUDED.challenge_id,
307
+ relay_node_id = EXCLUDED.relay_node_id,
308
+ client_public_key_hash = EXCLUDED.client_public_key_hash,
309
+ issued_at = EXCLUDED.issued_at,
310
+ signature = EXCLUDED.signature
311
+ RETURNING pairing_id`, [
312
+ requireNonEmptyString(pairing?.pairing_id, 'relay_pairing.pairing_id'),
313
+ requireNonEmptyString(pairing?.challenge_id, 'relay_pairing.challenge_id'),
314
+ requireNonEmptyString(pairing?.relay_node_id, 'relay_pairing.relay_node_id'),
315
+ requireSha256(pairing?.client_public_key_hash, 'relay_pairing.client_public_key_hash'),
316
+ optionalIsoString(pairing?.issued_at, 'relay_pairing.issued_at') ?? new Date(0).toISOString(),
317
+ jsonValue(pairing?.signature, 'relay_pairing.signature'),
318
+ ]);
319
+ }
320
+
321
+ export function buildGatewayPolicyVersionUpsert(policyVersion, options = {}) {
322
+ assertNoForbiddenPublicValue(policyVersion, 'gateway_policy_version');
323
+ const schema = options.schema ?? options.schemaName ?? 'enigma';
324
+ return storageOperation('gateway_policy_versions.upsert', `INSERT INTO ${storageTable(schema, 'gateway_policy_versions')} (
325
+ policy_hash, policy, active_from, retired_at
326
+ ) VALUES ($1, $2::jsonb, $3, $4)
327
+ ON CONFLICT (policy_hash) DO UPDATE SET
328
+ policy = EXCLUDED.policy,
329
+ active_from = EXCLUDED.active_from,
330
+ retired_at = EXCLUDED.retired_at
331
+ RETURNING policy_hash`, [
332
+ requireSha256(policyVersion?.policy_hash, 'gateway_policy_version.policy_hash'),
333
+ jsonValue(policyVersion?.policy, 'gateway_policy_version.policy'),
334
+ optionalIsoString(policyVersion?.active_from, 'gateway_policy_version.active_from') ?? new Date(0).toISOString(),
335
+ optionalIsoString(policyVersion?.retired_at, 'gateway_policy_version.retired_at'),
336
+ ]);
337
+ }
338
+
339
+ export function buildGatewayDecisionInsert(decisionRecord, options = {}) {
340
+ assertNoForbiddenPublicValue(decisionRecord, 'gateway_decision');
341
+ const schema = options.schema ?? options.schemaName ?? 'enigma';
342
+ return storageOperation('gateway_decisions.insert', `INSERT INTO ${storageTable(schema, 'gateway_decisions')} (
343
+ decision_id, policy_hash, decision_hash, decision, created_at
344
+ ) VALUES ($1, $2, $3, $4::jsonb, $5)
345
+ ON CONFLICT (decision_id) DO NOTHING
346
+ RETURNING decision_id`, [
347
+ requireNonEmptyString(decisionRecord?.decision_id, 'gateway_decision.decision_id'),
348
+ requireSha256(decisionRecord?.policy_hash, 'gateway_decision.policy_hash'),
349
+ requireSha256(decisionRecord?.decision_hash, 'gateway_decision.decision_hash'),
350
+ jsonValue(decisionRecord?.decision, 'gateway_decision.decision'),
351
+ optionalIsoString(decisionRecord?.created_at, 'gateway_decision.created_at') ?? new Date(0).toISOString(),
352
+ ]);
353
+ }
354
+
355
+ export function buildGatewaySiemEventInsert(eventRecord, options = {}) {
356
+ assertNoForbiddenPublicValue(eventRecord, 'gateway_siem_event');
357
+ const schema = options.schema ?? options.schemaName ?? 'enigma';
358
+ return storageOperation('gateway_siem_events.insert', `INSERT INTO ${storageTable(schema, 'gateway_siem_events')} (
359
+ event_id, event_hash, event, created_at
360
+ ) VALUES ($1, $2, $3::jsonb, $4)
361
+ ON CONFLICT (event_id) DO NOTHING
362
+ RETURNING event_id`, [
363
+ requireNonEmptyString(eventRecord?.event_id, 'gateway_siem_event.event_id'),
364
+ requireSha256(eventRecord?.event_hash, 'gateway_siem_event.event_hash'),
365
+ jsonValue(eventRecord?.event, 'gateway_siem_event.event'),
366
+ optionalIsoString(eventRecord?.created_at, 'gateway_siem_event.created_at') ?? new Date(0).toISOString(),
367
+ ]);
368
+ }
369
+
370
+ export function buildReadinessEvidenceRefUpsert(evidenceRef, options = {}) {
371
+ assertNoForbiddenPublicValue(evidenceRef, 'readiness_evidence_ref');
372
+ const schema = options.schema ?? options.schemaName ?? 'enigma';
373
+ const status = requireNonEmptyString(evidenceRef?.status, 'readiness_evidence_ref.status');
374
+ if (!['declared', 'observed', 'verified', 'go'].includes(status)) throw new Error('readiness_evidence_ref.status is unsupported');
375
+ return storageOperation('readiness_evidence_refs.upsert', `INSERT INTO ${storageTable(schema, 'readiness_evidence_refs')} (
376
+ evidence_key, provider, ref, status, observed_at, metadata
377
+ ) VALUES ($1, $2, $3, $4, $5, $6::jsonb)
378
+ ON CONFLICT (evidence_key) DO UPDATE SET
379
+ provider = EXCLUDED.provider,
380
+ ref = EXCLUDED.ref,
381
+ status = EXCLUDED.status,
382
+ observed_at = EXCLUDED.observed_at,
383
+ metadata = EXCLUDED.metadata
384
+ RETURNING evidence_key`, [
385
+ requireNonEmptyString(evidenceRef?.evidence_key, 'readiness_evidence_ref.evidence_key'),
386
+ requireNonEmptyString(evidenceRef?.provider, 'readiness_evidence_ref.provider'),
387
+ requireNonEmptyString(evidenceRef?.ref, 'readiness_evidence_ref.ref'),
388
+ status,
389
+ optionalIsoString(evidenceRef?.observed_at, 'readiness_evidence_ref.observed_at') ?? new Date(0).toISOString(),
390
+ jsonValue(evidenceRef?.metadata ?? {}, 'readiness_evidence_ref.metadata'),
391
+ ]);
392
+ }