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,398 @@
1
+ #!/usr/bin/env node
2
+ import { mkdir, readFile, writeFile } from 'node:fs/promises';
3
+ import { dirname, resolve } from 'node:path';
4
+ import { pathToFileURL } from 'node:url';
5
+ import { buildProductionHandoffPacket } from './build-production-handoff-packet.mjs';
6
+ import { buildCloudflareTokenPolicy } from './build-cloudflare-token-policy.mjs';
7
+ import { runBackendReadinessSmoke } from './run-backend-readiness-smoke.mjs';
8
+ import { HOSTED_BACKEND_LIVE_EVIDENCE_SCHEMA, HOSTED_BACKEND_LIVE_RESULT_SCHEMA, REQUIRED_REF_KEYS } from './validate-hosted-backend-live.mjs';
9
+ import { validateProductionManifestFiles } from './validate-production-manifests.mjs';
10
+ import { applyCloudflareSecretEnvFile } from './cloudflare-secret-env.mjs';
11
+
12
+ export const GOAL_COMPLETION_AUDIT_SCHEMA = 'enigma.goal_completion_audit.v1';
13
+
14
+ const SECRET_OUTPUT_RE = /(?:Bearer\s+[A-Za-z0-9._~+/=-]{12,}|Basic\s+[A-Za-z0-9+/=-]{12,}|-----BEGIN [A-Z ]*PRIVATE KEY-----|sk-[A-Za-z0-9_-]{16,}|AKIA[0-9A-Z]{16}|cf-[A-Za-z0-9_-]{12,})/iu;
15
+ const RAW_OUTPUT_RE = /(?:raw[\s_-]*memory|private[\s_-]*prompt|full[\s_-]*transcript|decrypted[\s_-]*(?:capsule|content)|provider[\s_-]*response|plain[\s_-]*text)/iu;
16
+
17
+ function assertNoUnsafeOutput(name, value, path = name) {
18
+ if (typeof value === 'string') {
19
+ if (SECRET_OUTPUT_RE.test(value)) throw new Error(`${path} appears to contain secret material`);
20
+ if (!/\.claim_boundary\[\d+\]$/.test(path) && RAW_OUTPUT_RE.test(value)) throw new Error(`${path} appears to contain raw-memory material`);
21
+ return;
22
+ }
23
+ if (Array.isArray(value)) {
24
+ value.forEach((item, index) => assertNoUnsafeOutput(name, item, `${path}[${index}]`));
25
+ return;
26
+ }
27
+ if (value !== null && typeof value === 'object') {
28
+ for (const [key, item] of Object.entries(value)) assertNoUnsafeOutput(name, item, `${path}.${key}`);
29
+ }
30
+ }
31
+
32
+ const DEFAULT_OBJECTIVE = 'Build Enigma Memory into a production-grade project with backend infrastructure, tests, professional math/diagram whitepaper, secure public site, deployment/handoff plan, GPT-5.5 architecture/review ownership, and Kimi Code implementation support without unsupported claims.';
33
+
34
+ class UsageError extends Error {
35
+ constructor(message) {
36
+ super(message);
37
+ this.name = 'UsageError';
38
+ }
39
+ }
40
+
41
+ function requireText(name, value) {
42
+ if (typeof value !== 'string' || value.trim().length === 0) throw new UsageError(`${name} is required`);
43
+ return value.trim();
44
+ }
45
+
46
+ function optionalText(value, fallback = null) {
47
+ return typeof value === 'string' && value.trim().length > 0 ? value.trim() : fallback;
48
+ }
49
+
50
+ function expandHostedBackendBlockers(infra) {
51
+ const externalBlockers = Array.isArray(infra?.external_blockers) ? infra.external_blockers : [];
52
+ const blockers = [
53
+ `hosted_live_ready is ${infra?.hosted_live_ready}`,
54
+ `hosted missing refs: ${infra?.hosted_required_ref_missing_count}`,
55
+ ...externalBlockers,
56
+ ];
57
+ const listedRefs = new Set();
58
+ for (const blocker of externalBlockers) {
59
+ const match = typeof blocker === 'string' ? /^missing refs\.([A-Za-z0-9_]+)$/.exec(blocker) : null;
60
+ if (match) listedRefs.add(match[1]);
61
+ }
62
+ const missingCount = Number(infra?.hosted_required_ref_missing_count ?? 0);
63
+ if (missingCount > listedRefs.size) {
64
+ for (const key of REQUIRED_REF_KEYS) {
65
+ if (!listedRefs.has(key)) blockers.push(`missing refs.${key}`);
66
+ }
67
+ }
68
+ return blockers;
69
+ }
70
+
71
+ function parseArgs(argv) {
72
+ const out = {
73
+ site: null,
74
+ projectName: 'enigma-memory',
75
+ domain: 'enigmamemory.com',
76
+ liveUrl: 'https://enigmamemory.com/',
77
+ expectTitle: 'Enigma',
78
+ accountId: '<cloudflare-account-id>',
79
+ objective: DEFAULT_OBJECTIVE,
80
+ out: null,
81
+ envFile: null,
82
+ operatorAcceptancePacket: null,
83
+ infrastructureReadiness: null,
84
+ releaseAudit: null,
85
+ workerInspect: null,
86
+ };
87
+ for (let index = 0; index < argv.length;) {
88
+ const token = argv[index];
89
+ if (token === '--help') return { help: true };
90
+ const readValue = (name) => {
91
+ if (index + 1 >= argv.length || argv[index + 1].startsWith('--')) throw new UsageError(`${name} requires a value`);
92
+ const value = argv[index + 1];
93
+ index += 2;
94
+ return value;
95
+ };
96
+ if (token === '--site') out.site = readValue(token);
97
+ else if (token === '--project-name') out.projectName = readValue(token);
98
+ else if (token === '--domain') out.domain = readValue(token);
99
+ else if (token === '--live-url') out.liveUrl = readValue(token);
100
+ else if (token === '--expect-title') out.expectTitle = readValue(token);
101
+ else if (token === '--account-id') out.accountId = readValue(token);
102
+ else if (token === '--objective') out.objective = readValue(token);
103
+ else if (token === '--cloudflare-env-file') out.envFile = readValue(token);
104
+ else if (token === '--operator-acceptance-packet' || token === '--operatorAcceptancePacket') out.operatorAcceptancePacket = readValue(token);
105
+ else if (token === '--infrastructure-readiness' || token === '--infrastructureReadiness') out.infrastructureReadiness = readValue(token);
106
+ else if (token === '--release-audit' || token === '--releaseAudit') out.releaseAudit = readValue(token);
107
+ else if (token === '--worker-inspect' || token === '--workerInspect') out.workerInspect = readValue(token);
108
+ else if (token === '--out') out.out = readValue(token);
109
+ else throw new UsageError(`unknown option ${token}`);
110
+ }
111
+ return out;
112
+ }
113
+
114
+ function usage() {
115
+ return `Usage: node scripts/build-goal-completion-audit.mjs --site <dir> [options]\n\nOptions:\n --project-name <name> Cloudflare Pages project. Default: enigma-memory.\n --domain <host> Public domain. Default: enigmamemory.com.\n --live-url <url> Current public URL to observe. Default: https://enigmamemory.com/.\n --expect-title <text> Expected live title fragment. Default: Enigma.\n --account-id <id> Cloudflare account id or placeholder for token-policy evidence.\n --infrastructure-readiness <file> Completed infrastructure readiness JSON to summarize.\n --operator-acceptance-packet <file> Completed operator packet JSON to validate and summarize.\n --release-audit <file> Current release audit JSON to summarize.\n --worker-inspect <file> Optional Worker inspection result; ready evidence suppresses the standalone probe action.\n --cloudflare-env-file <file> Load local Cloudflare env values without printing the path or values.\n --objective <text> Override objective text.\n --out <file> Write audit JSON.\n --help Show this help.\n`;
116
+ }
117
+
118
+ async function readText(path) {
119
+ return await readFile(path, 'utf8');
120
+ }
121
+
122
+ async function readJsonPath(path) {
123
+ if (!path) return null;
124
+ return JSON.parse(await readFile(resolve(path), 'utf8'));
125
+ }
126
+
127
+ function nextActionsForGoalAudit(nextActions, workerInspect) {
128
+ const actions = Array.isArray(nextActions) ? nextActions : [];
129
+ if (workerInspect?.worker_permission_ready === true) return actions.filter((item) => item?.id !== 'optional-standalone-worker-probe');
130
+ return actions;
131
+ }
132
+
133
+ function boolEvidence(ok, evidence, blockers = []) {
134
+ const accepted = ok === true;
135
+ return { ok: accepted, evidence, blockers: accepted ? [] : blockers.filter(Boolean) };
136
+ }
137
+
138
+ function blockerBreakdownLines(prefix, breakdown) {
139
+ if (breakdown === null || typeof breakdown !== 'object' || Array.isArray(breakdown)) return [];
140
+ return Object.entries(breakdown)
141
+ .filter(([, count]) => Number.isFinite(count) && count > 0)
142
+ .map(([name, count]) => `${prefix} ${name}: ${count}`);
143
+ }
144
+
145
+ async function inspectDocs() {
146
+ const masterPlan = await readText(resolve('docs/overnight-build-master-plan.md'));
147
+ const whitepaper = await readText(resolve('docs/enigma-memory-technical-whitepaper.md'));
148
+ const evidence = await readText(resolve('docs/release-evidence-2026-06-23.md'));
149
+ return {
150
+ masterPlan,
151
+ whitepaper,
152
+ evidence,
153
+ };
154
+ }
155
+
156
+ function deliverablesFromEvidence({ docs, handoff, tokenPolicy, backendSmoke, productionManifests }) {
157
+ const pages = handoff.pages ?? {};
158
+ const infra = handoff.infrastructure ?? {};
159
+ const operator = handoff.operator_acceptance ?? {};
160
+ const releaseAudit = handoff.release_audit ?? {};
161
+ const releaseGateNames = new Set(Array.isArray(releaseAudit.gate_names) ? releaseAudit.gate_names : []);
162
+ const deliverables = [];
163
+ deliverables.push({
164
+ id: 'orchestration-master-plan',
165
+ requirement: 'Architecture/review owner and implementation-owner plan exists with claim boundaries and handoff cadence.',
166
+ ...boolEvidence(
167
+ /GPT-5\.5 owns architecture, design, and review/.test(docs.masterPlan) && /Kimi Code owns implementation/.test(docs.masterPlan),
168
+ ['docs/overnight-build-master-plan.md'],
169
+ ),
170
+ });
171
+ deliverables.push({
172
+ id: 'whitepaper-math-diagrams',
173
+ requirement: 'Professional whitepaper contains math and diagrams for the memory layer and its evidence-bounded comparison framework.',
174
+ ...boolEvidence(
175
+ /Memory-layer evaluation framework/.test(docs.whitepaper)
176
+ && /D_E\(X\)/.test(docs.whitepaper)
177
+ && /not a theorem of universal superiority/.test(docs.whitepaper)
178
+ && /```mermaid/.test(docs.whitepaper)
179
+ && (releaseAudit.provided_audit !== true || releaseGateNames.has('whitepaper-claims-validator')),
180
+ ['docs/enigma-memory-technical-whitepaper.md', 'npm run production:whitepaper', 'release audit gate whitepaper-claims-validator'],
181
+ ['whitepaper missing evaluation math, diagram, claim boundary, or current validator evidence'],
182
+ ),
183
+ });
184
+ deliverables.push({
185
+ id: 'local-tests-release-gates',
186
+ requirement: 'Local package/test/release gates are green and documented as current local/package evidence.',
187
+ ...boolEvidence(
188
+ /release audit `ok:true`|release audit `ok: true`|`ok: true`/.test(docs.evidence) && /Full test suite \| PASS/.test(docs.evidence),
189
+ ['docs/release-evidence-2026-06-23.md', 'npm run check && npm test && npm run release:audit'],
190
+ ['release evidence row missing current green gate statement'],
191
+ ),
192
+ });
193
+ deliverables.push({
194
+ id: 'release-audit-current',
195
+ requirement: 'Current release audit evidence is supplied, accepted, and has zero required gate failures.',
196
+ ...boolEvidence(
197
+ releaseAudit.ok === true && releaseAudit.required_failed_count === 0 && Number(releaseAudit.gate_count ?? 0) > 0,
198
+ ['npm run check && npm test && npm run release:audit'],
199
+ ['accepted release audit evidence was not supplied to the handoff packet'],
200
+ ),
201
+ });
202
+ deliverables.push({
203
+ id: 'local-backend-readiness-smoke',
204
+ requirement: 'Relay and gateway loopback HTTP runtime verifies /livez, /readyz fail-closed production defaults, and fully referenced production fixtures.',
205
+ ...boolEvidence(
206
+ backendSmoke.ok === true
207
+ && backendSmoke.check_count === 4
208
+ && backendSmoke.checks?.filter((check) => check.mode === 'production-fail-closed' && check.readyz_status === 503).length === 2
209
+ && backendSmoke.checks?.filter((check) => check.mode === 'production-referenced-fixture' && check.readyz_status === 200 && check.readyz_missing_evidence_ref_count === 0).length === 2,
210
+ ['npm run production:backend-smoke', `${backendSmoke.check_count} checks`],
211
+ ['backend readiness smoke did not prove fail-closed and fully referenced local runtime fixtures'],
212
+ ),
213
+ });
214
+ deliverables.push({
215
+ id: 'production-manifest-validator',
216
+ requirement: 'Production Compose and Kubernetes backend manifests have standalone static validation for fail-closed hosted readiness shape.',
217
+ ...boolEvidence(
218
+ productionManifests.ok === true
219
+ && productionManifests.compose?.public_ports_loopback_only === true
220
+ && productionManifests.kubernetes?.public_readyz_paths === 2
221
+ && productionManifests.kubernetes?.public_livez_paths === 2
222
+ && productionManifests.kubernetes?.private_admin_ingress_class === true,
223
+ ['npm run production:manifests', productionManifests.schema],
224
+ ['production manifests were not accepted by standalone fail-closed validator'],
225
+ ),
226
+ });
227
+ deliverables.push({
228
+ id: 'hosted-live-evidence-contract',
229
+ requirement: 'Hosted backend live evidence has a formal validator/schema requiring public HTTPS relay/gateway probes, all hosted refs, and operator acceptance go.',
230
+ ...boolEvidence(
231
+ HOSTED_BACKEND_LIVE_EVIDENCE_SCHEMA === 'enigma.hosted_backend_live_evidence.v1'
232
+ && HOSTED_BACKEND_LIVE_RESULT_SCHEMA === 'enigma.hosted_backend_live_result.v1'
233
+ && REQUIRED_REF_KEYS.length === 25,
234
+ ['npm run production:hosted-live', 'specs/hosted-backend-live-evidence-v1.schema.json', `${REQUIRED_REF_KEYS.length} refs`],
235
+ ['hosted backend live validator/schema contract missing or incomplete'],
236
+ ),
237
+ });
238
+ deliverables.push({
239
+ id: 'secure-static-site-artifact',
240
+ requirement: 'Current local Enigma public-site artifact is preflighted and security-clean without personal data or secrets.',
241
+ ...boolEvidence(
242
+ pages.local_artifact_ready === true && Number(pages.security_blocker_count ?? 0) === 0,
243
+ ['npm run cloudflare:pages:packet', pages.artifact_root_hash].filter(Boolean),
244
+ ['local static artifact is not ready or has public-site security blockers'],
245
+ ),
246
+ });
247
+ deliverables.push({
248
+ id: 'live-domain-current-site',
249
+ requirement: 'enigmamemory.com serves the current Enigma artifact, not legacy Engram.',
250
+ ...boolEvidence(
251
+ pages.live_observation?.ok === true && pages.live_observation?.title_matched === true,
252
+ [pages.live_observation?.live_url, pages.live_observation?.title].filter(Boolean),
253
+ pages.live_observation?.blockers?.length ? pages.live_observation.blockers : ['live site has not been observed serving the expected Enigma title'],
254
+ ),
255
+ });
256
+ deliverables.push({
257
+ id: 'cloudflare-token-policy',
258
+ requirement: 'Cloudflare API token scope is specified without exposing a token.',
259
+ ...boolEvidence(
260
+ tokenPolicy.permission_groups?.some((item) => item.permission_name === 'Cloudflare Pages Edit')
261
+ && tokenPolicy.permission_groups?.some((item) => item.permission_name === 'Registrar Edit')
262
+ && tokenPolicy.mutation_boundaries?.token_value_printed === false,
263
+ ['npm run cloudflare:token-policy', `${tokenPolicy.permission_groups?.length ?? 0} permissions`],
264
+ ['Cloudflare token policy missing Pages/Registrar scope or token secrecy boundary'],
265
+ ),
266
+ });
267
+ deliverables.push({
268
+ id: 'cloudflare-credentials-present',
269
+ requirement: 'A current Cloudflare API token/account id exists in the execution environment for deploy/verify operations.',
270
+ ...boolEvidence(
271
+ handoff.credentials_present?.cloudflare_api_token === true && handoff.credentials_present?.cloudflare_account_id === true,
272
+ ['CLOUDFLARE_API_TOKEN', 'CLOUDFLARE_ACCOUNT_ID'],
273
+ ['CLOUDFLARE_API_TOKEN and/or CLOUDFLARE_ACCOUNT_ID absent from current environment'],
274
+ ),
275
+ });
276
+ deliverables.push({
277
+ id: 'hosted-backend-live',
278
+ requirement: 'Hosted relay/gateway/storage/KMS/SIEM/backup/operator infrastructure is live and directly verified.',
279
+ ...boolEvidence(
280
+ infra.hosted_live_ready === true,
281
+ ['npm run infrastructure:readiness -- --manifest <completed> --live --cloudflare-live required'],
282
+ expandHostedBackendBlockers(infra),
283
+ ),
284
+ });
285
+ deliverables.push({
286
+ id: 'operator-acceptance-go',
287
+ requirement: 'Operator acceptance packet is go with zero blockers for the target environment.',
288
+ ...boolEvidence(
289
+ operator.ok === true && operator.decision === 'go' && operator.blocker_count === 0,
290
+ ['npm run production:acceptance -- --packet <completed-packet.json>'],
291
+ [`operator acceptance decision ${operator.decision}`, `${operator.blocker_count} operator blockers`, ...blockerBreakdownLines('operator blockers', operator.blocker_breakdown)],
292
+ ),
293
+ });
294
+ deliverables.push({
295
+ id: 'unsupported-claims-blocked',
296
+ requirement: '$100B/best-in-world ambition is treated as ambition; collateral does not convert it into unsupported proof, ROI, compliance, or hosted-live claims.',
297
+ ...boolEvidence(
298
+ /unsupported_market_superlative/.test(docs.evidence) || /unsupported superlatives/.test(docs.evidence) || /unsupported launch claim/i.test(docs.masterPlan),
299
+ ['docs/overnight-build-master-plan.md', 'docs/release-evidence-2026-06-23.md'],
300
+ ['claim-boundary evidence missing unsupported-superlative controls'],
301
+ ),
302
+ });
303
+ return deliverables;
304
+ }
305
+
306
+ export async function buildGoalCompletionAudit(input = {}, options = {}) {
307
+ const env = options.env ?? process.env;
308
+ const generatedAt = options.generated_at ?? options.generatedAt ?? new Date().toISOString();
309
+ const site = resolve(requireText('--site', input.site));
310
+ const projectName = requireText('--project-name', input.projectName ?? 'enigma-memory');
311
+ const domain = optionalText(input.domain, 'enigmamemory.com');
312
+ const liveUrl = optionalText(input.liveUrl, domain ? `https://${domain}/` : null);
313
+ const expectTitle = optionalText(input.expectTitle, 'Enigma');
314
+ const accountId = optionalText(input.accountId, '<cloudflare-account-id>');
315
+ const docs = await inspectDocs();
316
+ const handoff = await buildProductionHandoffPacket({ site, projectName, domain, liveUrl, expectTitle, infrastructureReadiness: input.infrastructureReadiness, operatorAcceptancePacket: input.operatorAcceptancePacket, releaseAudit: input.releaseAudit }, {
317
+ env,
318
+ generated_at: generatedAt,
319
+ fetchImpl: options.fetchImpl ?? globalThis.fetch,
320
+ });
321
+ const workerInspect = await readJsonPath(input.workerInspect);
322
+ const tokenPolicy = buildCloudflareTokenPolicy({
323
+ mode: 'all',
324
+ accountId,
325
+ projectName,
326
+ domain,
327
+ generated_at: generatedAt,
328
+ });
329
+ const backendSmoke = await runBackendReadinessSmoke({
330
+ generated_at: generatedAt,
331
+ });
332
+ const productionManifests = await validateProductionManifestFiles({ generated_at: generatedAt });
333
+ const deliverables = deliverablesFromEvidence({ docs, handoff, tokenPolicy, backendSmoke, productionManifests });
334
+ const blockers = deliverables.flatMap((item) => item.ok ? [] : item.blockers.map((blocker) => `${item.id}: ${blocker}`));
335
+ const deliverableById = new Map(deliverables.map((item) => [item.id, item]));
336
+ const staticSiteLive = deliverableById.get('secure-static-site-artifact')?.ok === true
337
+ && deliverableById.get('live-domain-current-site')?.ok === true
338
+ && deliverableById.get('cloudflare-credentials-present')?.ok === true;
339
+ const releasePosture = blockers.length === 0
340
+ ? 'complete'
341
+ : (staticSiteLive ? 'static_site_live_with_blocked_hosted_backend' : 'local_package_artifact_ready_with_blocked_live_infrastructure');
342
+ const audit = {
343
+ schema: GOAL_COMPLETION_AUDIT_SCHEMA,
344
+ generated_at: generatedAt,
345
+ objective: optionalText(input.objective, DEFAULT_OBJECTIVE),
346
+ complete: blockers.length === 0,
347
+ release_posture: releasePosture,
348
+ go_live_ready: handoff.go_live_ready === true,
349
+ local_static_artifact_ready: handoff.local_static_artifact_ready === true,
350
+ backend_readiness_smoke: {
351
+ ok: backendSmoke.ok,
352
+ check_count: backendSmoke.check_count,
353
+ loopback_only: backendSmoke.loopback_only,
354
+ },
355
+ production_manifest_validation: {
356
+ ok: productionManifests.ok,
357
+ status: productionManifests.status,
358
+ blocker_count: productionManifests.blockers.length,
359
+ },
360
+ deliverables,
361
+ blockers,
362
+ next_actions: nextActionsForGoalAudit(handoff.next_actions, workerInspect),
363
+ claim_boundary: [
364
+ 'This audit preserves the original objective and maps it to current direct evidence.',
365
+ 'complete:false remains expected until hosted backend, operator acceptance, and provider evidence exist; static Cloudflare Pages deploy alone is not enough.',
366
+ 'Ambition language is not treated as proof of market value, ROI, compliance status, benchmark leadership, hosted-live readiness, provider deletion, or model forgetting.',
367
+ ],
368
+ };
369
+ assertNoUnsafeOutput('goal completion audit', audit);
370
+ return audit;
371
+ }
372
+
373
+ export async function runCli(argv = process.argv.slice(2), options = {}) {
374
+ const parsed = parseArgs(argv);
375
+ if (parsed.help) return { text: usage() };
376
+ const secretEnv = await applyCloudflareSecretEnvFile(options.env ?? process.env, { path: parsed.envFile ?? undefined, includePath: false });
377
+ const packet = await buildGoalCompletionAudit(parsed, { ...options, env: secretEnv.env });
378
+ const json = `${JSON.stringify(packet, null, 2)}\n`;
379
+ if (SECRET_OUTPUT_RE.test(json)) throw new Error('goal completion audit output appears to contain a secret');
380
+ if (parsed.out) {
381
+ const outPath = resolve(parsed.out);
382
+ await mkdir(dirname(outPath), { recursive: true });
383
+ await writeFile(outPath, json, 'utf8');
384
+ }
385
+ return { json: packet };
386
+ }
387
+
388
+ if (process.argv[1] && import.meta.url === pathToFileURL(process.argv[1]).href) {
389
+ try {
390
+ const result = await runCli();
391
+ if (result.text) process.stdout.write(result.text);
392
+ else process.stdout.write(`${JSON.stringify(result.json, null, 2)}\n`);
393
+ } catch (error) {
394
+ const message = error instanceof Error ? error.message : String(error);
395
+ process.stdout.write(`${JSON.stringify({ schema: GOAL_COMPLETION_AUDIT_SCHEMA, ok: false, error: { code: error instanceof UsageError ? 'USAGE_ERROR' : 'GOAL_COMPLETION_AUDIT_ERROR', message } }, null, 2)}\n`);
396
+ process.exitCode = error instanceof UsageError ? 2 : 1;
397
+ }
398
+ }
@@ -0,0 +1,191 @@
1
+ #!/usr/bin/env node
2
+ import { createHash } from 'node:crypto';
3
+ import { mkdir, writeFile } from 'node:fs/promises';
4
+ import { dirname, join, resolve } from 'node:path';
5
+ import { fileURLToPath } from 'node:url';
6
+
7
+ export const HOSTED_PROBE_WORKER_BUNDLE_SCHEMA = 'enigma.hosted_probe_worker_bundle.v1';
8
+
9
+ export const REQUIRED_WORKER_ENV_REFS = Object.freeze([
10
+ 'ENIGMA_BACKEND_HOST_REF',
11
+ 'ENIGMA_DNS_TLS_REF',
12
+ 'ENIGMA_DURABLE_STORAGE_REF',
13
+ 'ENIGMA_KMS_CUSTODY_REF',
14
+ 'ENIGMA_BACKUP_RESTORE_REF',
15
+ 'ENIGMA_MONITORING_ALERTING_REF',
16
+ 'ENIGMA_SIEM_LOG_SINK_REF',
17
+ 'ENIGMA_OPERATOR_ACCEPTANCE_REF',
18
+ 'ENIGMA_NETWORK_ACCESS_POLICY_REF',
19
+ 'ENIGMA_TENANT_POLICY_APPROVAL_REF',
20
+ 'ENIGMA_USAGE_METERING_REF',
21
+ 'ENIGMA_SERVICE_SETTLEMENT_REF',
22
+ 'ENIGMA_SECURITY_THREAT_MODEL_REF',
23
+ 'ENIGMA_LEGAL_COMPLIANCE_APPROVAL_REF',
24
+ 'ENIGMA_SUPPORT_SLA_REF',
25
+ 'ENIGMA_INCIDENT_DRILL_REF',
26
+ 'ENIGMA_PUBLIC_SITE_SECURITY_REF',
27
+ ]);
28
+
29
+ const WORKER_CLAIM_BOUNDARY = Object.freeze([
30
+ 'This Worker is a hosted public HTTPS probe harness, not the relay/gateway data plane.',
31
+ 'It proves only that the edge route can fail closed and expose /livez and /readyz shape without secrets.',
32
+ 'It must not be used as hosted backend live evidence unless real relay/gateway/storage/KMS/SIEM/backup/operator refs and probes are supplied separately.',
33
+ ]);
34
+
35
+ const SECRET_VALUE_RE = /(?:Bearer\s+[A-Za-z0-9._~+/=-]{12,}|Basic\s+[A-Za-z0-9+/=-]{12,}|-----BEGIN [A-Z ]*PRIVATE KEY-----|https?:\/\/[^\s/@]+:[^\s/@]+@|sk-[A-Za-z0-9_-]{16,}|AKIA[0-9A-Z]{16}|raw memory|private prompt|full transcript|decrypted capsule)/iu;
36
+
37
+ function sha256(text) {
38
+ return `sha256:${createHash('sha256').update(text).digest('hex')}`;
39
+ }
40
+
41
+ export function hostedProbeWorkerSource(options = {}) {
42
+ const serviceName = options.serviceName ?? 'enigma-hosted-probe';
43
+ const requiredRefs = JSON.stringify(REQUIRED_WORKER_ENV_REFS, null, 2);
44
+ const boundary = JSON.stringify(WORKER_CLAIM_BOUNDARY, null, 2);
45
+ return `const SERVICE_NAME = ${JSON.stringify(serviceName)};
46
+ const REQUIRED_REFS = ${requiredRefs};
47
+ const CLAIM_BOUNDARY = ${boundary};
48
+
49
+ function json(body, status = 200) {
50
+ return new Response(JSON.stringify(body, null, 2), {
51
+ status,
52
+ headers: {
53
+ 'content-type': 'application/json; charset=utf-8',
54
+ 'cache-control': 'no-store',
55
+ 'x-content-type-options': 'nosniff',
56
+ 'referrer-policy': 'no-referrer',
57
+ },
58
+ });
59
+ }
60
+
61
+ function hasValue(env, key) {
62
+ return typeof env?.[key] === 'string' && env[key].trim().length > 0;
63
+ }
64
+
65
+ function readiness(env) {
66
+ const missing = REQUIRED_REFS.filter((key) => !hasValue(env, key));
67
+ const decision = typeof env?.ENIGMA_OPERATOR_ACCEPTANCE_DECISION === 'string' ? env.ENIGMA_OPERATOR_ACCEPTANCE_DECISION.trim().toLowerCase() : '';
68
+ const decisionOk = decision === 'go';
69
+ return {
70
+ ok: missing.length === 0 && decisionOk,
71
+ service: SERVICE_NAME,
72
+ hosted_probe_only: true,
73
+ missing_evidence_refs: missing,
74
+ checks: [
75
+ { id: 'required_refs', ok: missing.length === 0, missing_count: missing.length, required_count: REQUIRED_REFS.length },
76
+ { id: 'operator_acceptance_decision', ok: decisionOk, expected: 'go', observed: decisionOk ? 'go' : 'missing_or_not_go' },
77
+ ],
78
+ claim_boundary: CLAIM_BOUNDARY,
79
+ };
80
+ }
81
+
82
+ export default {
83
+ async fetch(request, env) {
84
+ const url = new URL(request.url);
85
+ if (request.method !== 'GET' && request.method !== 'HEAD') return json({ ok: false, error: 'method_not_allowed' }, 405);
86
+ if (url.pathname === '/livez') {
87
+ return json({ ok: true, service: SERVICE_NAME, hosted_probe_only: true, claim_boundary: CLAIM_BOUNDARY });
88
+ }
89
+ if (url.pathname === '/readyz') {
90
+ const body = readiness(env);
91
+ return json(body, body.ok ? 200 : 503);
92
+ }
93
+ return json({ ok: false, error: 'not_found', allowed_paths: ['/livez', '/readyz'] }, 404);
94
+ },
95
+ };
96
+ `;
97
+ }
98
+
99
+ export function validateHostedProbeWorkerSource(source) {
100
+ const blockers = [];
101
+ const text = String(source ?? '');
102
+ if (!text.includes("url.pathname === '/livez'")) blockers.push({ path: 'source', message: 'worker must route /livez' });
103
+ if (!text.includes("url.pathname === '/readyz'")) blockers.push({ path: 'source', message: 'worker must route /readyz' });
104
+ if (!text.includes('missing_evidence_refs')) blockers.push({ path: 'source', message: 'worker must expose missing evidence refs on /readyz' });
105
+ if (!text.includes('hosted_probe_only: true')) blockers.push({ path: 'source', message: 'worker must mark hosted_probe_only true' });
106
+ if (!text.includes('status,') || !text.includes('body.ok ? 200 : 503')) blockers.push({ path: 'source', message: 'worker readyz must fail closed with 503 until complete' });
107
+ if (SECRET_VALUE_RE.test(text)) blockers.push({ path: 'source', message: 'worker source contains secret-looking literal' });
108
+ for (const ref of REQUIRED_WORKER_ENV_REFS) if (!text.includes(ref)) blockers.push({ path: `source.${ref}`, message: `worker missing required ref ${ref}` });
109
+ return {
110
+ ok: blockers.length === 0,
111
+ blockers,
112
+ required_ref_count: REQUIRED_WORKER_ENV_REFS.length,
113
+ source_hash: sha256(text),
114
+ };
115
+ }
116
+
117
+ export function buildHostedProbeWorkerBundle(options = {}) {
118
+ const source = hostedProbeWorkerSource(options);
119
+ const validation = validateHostedProbeWorkerSource(source);
120
+ return {
121
+ schema: HOSTED_PROBE_WORKER_BUNDLE_SCHEMA,
122
+ generated_at: options.generated_at ?? options.generatedAt ?? new Date().toISOString(),
123
+ ok: validation.ok,
124
+ worker_name: options.workerName ?? 'enigma-hosted-probe',
125
+ entrypoint: 'worker.mjs',
126
+ required_env_refs: [...REQUIRED_WORKER_ENV_REFS],
127
+ validation,
128
+ deployment_plan: {
129
+ runtime: 'cloudflare-workers',
130
+ entrypoint: 'worker.mjs',
131
+ default_routes: ['/livez', '/readyz'],
132
+ mutates_cloudflare: false,
133
+ command_hint: 'wrangler deploy worker.mjs --name enigma-hosted-probe',
134
+ },
135
+ claim_boundary: [...WORKER_CLAIM_BOUNDARY],
136
+ files: {
137
+ 'worker.mjs': source,
138
+ 'README.md': `# Enigma hosted probe Worker\n\nThis package is a Cloudflare Workers public HTTPS probe harness for Enigma backend readiness. It is not the relay/gateway data plane. It exposes /livez and /readyz, fails closed until required refs and operator acceptance are configured, and never returns secret values.\n`,
139
+ },
140
+ };
141
+ }
142
+
143
+ function parseArgs(argv) {
144
+ const out = { outDir: null, generated_at: null };
145
+ for (let index = 0; index < argv.length; index += 1) {
146
+ const token = argv[index];
147
+ if (token === '--out-dir') out.outDir = argv[++index];
148
+ else if (token === '--generated-at') out.generated_at = argv[++index];
149
+ else if (token === '--help' || token === '-h') out.help = true;
150
+ else throw new Error(`Unknown argument: ${token}`);
151
+ }
152
+ return out;
153
+ }
154
+
155
+ function help() {
156
+ return `Usage: node scripts/build-hosted-probe-worker.mjs [--out-dir <dir>]\n\nBuilds a public-safe Cloudflare Worker probe artifact for /livez and fail-closed /readyz.\nThis does not deploy Cloudflare resources or prove hosted backend readiness.\n`;
157
+ }
158
+
159
+ async function main() {
160
+ const options = parseArgs(process.argv.slice(2));
161
+ if (options.help) {
162
+ process.stdout.write(help());
163
+ return 0;
164
+ }
165
+ const bundle = buildHostedProbeWorkerBundle(options);
166
+ if (options.outDir) {
167
+ const outDir = resolve(options.outDir);
168
+ await mkdir(outDir, { recursive: true });
169
+ await Promise.all(Object.entries(bundle.files).map(async ([rel, body]) => {
170
+ const outPath = join(outDir, rel);
171
+ await mkdir(dirname(outPath), { recursive: true });
172
+ await writeFile(outPath, body, 'utf8');
173
+ }));
174
+ const manifest = { ...bundle, files: Object.fromEntries(Object.entries(bundle.files).map(([rel, body]) => [rel, { bytes: Buffer.byteLength(body), sha256: sha256(body) }])) };
175
+ await writeFile(join(outDir, 'HOSTED_PROBE_WORKER_MANIFEST.json'), `${JSON.stringify(manifest, null, 2)}\n`, 'utf8');
176
+ process.stdout.write(`${JSON.stringify(manifest, null, 2)}\n`);
177
+ return bundle.ok ? 0 : 1;
178
+ }
179
+ const publicBundle = { ...bundle, files: Object.fromEntries(Object.entries(bundle.files).map(([rel, body]) => [rel, { bytes: Buffer.byteLength(body), sha256: sha256(body) }])) };
180
+ process.stdout.write(`${JSON.stringify(publicBundle, null, 2)}\n`);
181
+ return bundle.ok ? 0 : 1;
182
+ }
183
+
184
+ if (process.argv[1] && fileURLToPath(import.meta.url) === resolve(process.argv[1])) {
185
+ main().then((code) => {
186
+ process.exitCode = code;
187
+ }).catch((error) => {
188
+ process.stderr.write(`${error.stack ?? error.message}\n`);
189
+ process.exitCode = 1;
190
+ });
191
+ }