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,270 @@
1
+ #!/usr/bin/env node
2
+ import { execFile } from 'node:child_process';
3
+ import { mkdir } from 'node:fs/promises';
4
+ import { dirname, isAbsolute, resolve as resolvePath } from 'node:path';
5
+ import { promisify } from 'node:util';
6
+ import { fileURLToPath } from 'node:url';
7
+
8
+ export const INSTALLER_SCHEMA = 'enigma.local_installer.v1';
9
+ export const REQUIRED_NODE_MAJOR = 24;
10
+ export const DEFAULT_BUNDLE_PATH = '.enigma/bundle.json';
11
+
12
+ const execFileAsync = promisify(execFile);
13
+ const SCRIPT_PATH = fileURLToPath(import.meta.url);
14
+ const DEFAULT_PACKAGE_DIR = resolvePath(dirname(SCRIPT_PATH), '..');
15
+ const SAFE_COMMAND_RE = /^[A-Za-z0-9._-]+$/u;
16
+
17
+ function readRequiredValue(argv, index, flag) {
18
+ const value = argv[index + 1];
19
+ if (value === undefined || value.startsWith('--')) throw new Error(`Missing value for ${flag}.`);
20
+ return value;
21
+ }
22
+
23
+ export function usage() {
24
+ return `Usage: node scripts/install-enigma-local.mjs [--dry-run|--execute] [--init-vault] [--bundle <path>]\n\nDry-run is the default. Execute mode runs npm install -g . from the local checkout.\nNo network download command is generated, and vault initialization runs only when --init-vault is present.\n`;
25
+ }
26
+
27
+ export function parseInstallerArgs(argv = process.argv.slice(2)) {
28
+ const options = {
29
+ dryRun: true,
30
+ execute: false,
31
+ initVault: false,
32
+ bundlePath: DEFAULT_BUNDLE_PATH,
33
+ packageDir: DEFAULT_PACKAGE_DIR,
34
+ subject: 'local-user',
35
+ displayName: 'Local user',
36
+ };
37
+ let sawDryRun = false;
38
+ let sawExecute = false;
39
+
40
+ for (let index = 0; index < argv.length; index += 1) {
41
+ const arg = argv[index];
42
+ if (arg === '--help' || arg === '-h') {
43
+ options.help = true;
44
+ } else if (arg === '--dry-run') {
45
+ sawDryRun = true;
46
+ options.dryRun = true;
47
+ options.execute = false;
48
+ } else if (arg === '--execute') {
49
+ sawExecute = true;
50
+ options.dryRun = false;
51
+ options.execute = true;
52
+ } else if (arg === '--init-vault') {
53
+ options.initVault = true;
54
+ } else if (arg === '--no-init-vault') {
55
+ options.initVault = false;
56
+ } else if (arg === '--bundle') {
57
+ options.bundlePath = readRequiredValue(argv, index, arg);
58
+ index += 1;
59
+ } else if (arg === '--package-dir') {
60
+ options.packageDir = readRequiredValue(argv, index, arg);
61
+ index += 1;
62
+ } else if (arg === '--subject') {
63
+ options.subject = readRequiredValue(argv, index, arg);
64
+ index += 1;
65
+ } else if (arg === '--display-name') {
66
+ options.displayName = readRequiredValue(argv, index, arg);
67
+ index += 1;
68
+ } else {
69
+ throw new Error('Unknown argument.');
70
+ }
71
+ }
72
+
73
+ if (sawDryRun && sawExecute) throw new Error('Use either --dry-run or --execute, not both.');
74
+ return options;
75
+ }
76
+
77
+ export function nodeMajor(version) {
78
+ const match = String(version ?? '').trim().match(/^v?(\d+)(?:\.\d+){0,2}(?:[-+].*)?$/u);
79
+ if (!match) throw new Error('Invalid Node version override.');
80
+ return Number(match[1]);
81
+ }
82
+
83
+ export function validateNodeVersion(version = process.versions.node, requiredMajor = REQUIRED_NODE_MAJOR) {
84
+ const major = nodeMajor(version);
85
+ if (!Number.isSafeInteger(major) || major < requiredMajor) {
86
+ throw new Error(`Node >=${requiredMajor} is required for the local Enigma installer.`);
87
+ }
88
+ return { ok: true, required: `>=${requiredMajor}`, current_major: major };
89
+ }
90
+
91
+ function commandForPlatform(base, platform) {
92
+ return platform === 'win32' ? `${base}.cmd` : base;
93
+ }
94
+
95
+ function rejectUnsafeArg(arg, label) {
96
+ const value = String(arg ?? '');
97
+ if (value.length === 0) throw new Error(`${label} must not be empty.`);
98
+ if (value.includes('\0') || value.includes('\n') || value.includes('\r')) throw new Error(`${label} contains an invalid control character.`);
99
+ }
100
+
101
+ export function validateCommandSpec(spec) {
102
+ if (!spec || typeof spec !== 'object' || Array.isArray(spec)) throw new Error('Installer command spec must be an object.');
103
+ const command = String(spec.command ?? '');
104
+ if (!SAFE_COMMAND_RE.test(command)) throw new Error('Installer command name is not safe.');
105
+ const args = Array.isArray(spec.args) ? spec.args.map(String) : [];
106
+ for (const [index, arg] of args.entries()) rejectUnsafeArg(arg, `Installer command argument ${index}`);
107
+
108
+ if (command === 'npm' || command === 'npm.cmd') {
109
+ if (args.length !== 3 || args[0] !== 'install' || args[1] !== '-g' || args[2] !== '.') {
110
+ throw new Error('Installer npm command must be exactly npm install -g .');
111
+ }
112
+ return true;
113
+ }
114
+
115
+ if (command === 'enigma' || command === 'enigma.cmd') {
116
+ const bundleIndex = args.indexOf('--bundle');
117
+ if (args[0] !== 'init' || bundleIndex === -1 || bundleIndex + 1 >= args.length) {
118
+ throw new Error('Installer Enigma command must initialize a bundle with --bundle.');
119
+ }
120
+ return true;
121
+ }
122
+
123
+ throw new Error('Installer command is not allowlisted.');
124
+ }
125
+
126
+ function publicCommand(command) {
127
+ if (command.step === 'install_package') return { command: 'npm', args: ['install', '-g', '.'] };
128
+ return { command: 'enigma', args: ['init', '--bundle', '<bundle-path>', '--subject', '<subject>', '--display-name', '<display-name>'] };
129
+ }
130
+
131
+ export function buildInstallerPlan(options = {}, runtime = {}) {
132
+ const platform = runtime.platform ?? process.platform;
133
+ const cwd = runtime.cwd ?? process.cwd();
134
+ const requestedPackageDir = String(options.packageDir ?? DEFAULT_PACKAGE_DIR);
135
+ rejectUnsafeArg(requestedPackageDir, 'Package directory');
136
+ const packageDir = resolvePath(requestedPackageDir);
137
+ const requestedBundlePath = String(options.bundlePath ?? DEFAULT_BUNDLE_PATH);
138
+ rejectUnsafeArg(requestedBundlePath, 'Bundle path');
139
+ const bundlePath = isAbsolute(requestedBundlePath) ? resolvePath(requestedBundlePath) : resolvePath(cwd, requestedBundlePath);
140
+
141
+ const commands = [
142
+ {
143
+ step: 'install_package',
144
+ command: commandForPlatform('npm', platform),
145
+ args: ['install', '-g', '.'],
146
+ cwd: packageDir,
147
+ mutates_global_state: true,
148
+ },
149
+ ];
150
+
151
+ if (options.initVault === true) {
152
+ commands.push({
153
+ step: 'initialize_vault',
154
+ command: commandForPlatform('enigma', platform),
155
+ args: ['init', '--bundle', bundlePath, '--subject', String(options.subject ?? 'local-user'), '--display-name', String(options.displayName ?? 'Local user')],
156
+ cwd: packageDir,
157
+ mutates_local_filesystem: true,
158
+ });
159
+ }
160
+
161
+ for (const command of commands) validateCommandSpec(command);
162
+
163
+ return {
164
+ dryRun: options.execute === true ? false : true,
165
+ execute: options.execute === true,
166
+ packageDir,
167
+ bundlePath,
168
+ bundlePathKind: requestedBundlePath === DEFAULT_BUNDLE_PATH ? 'default' : (isAbsolute(requestedBundlePath) ? 'absolute' : 'relative'),
169
+ initVault: options.initVault === true,
170
+ commands,
171
+ };
172
+ }
173
+
174
+ function publicCommandRecords(plan, resultByStep = new Map()) {
175
+ return plan.commands.map((command) => {
176
+ const publicSpec = publicCommand(command);
177
+ const runResult = resultByStep.get(command.step);
178
+ return {
179
+ step: command.step,
180
+ command: publicSpec.command,
181
+ args: publicSpec.args,
182
+ status: plan.execute ? (runResult?.ok ? 'executed' : 'pending') : 'preview',
183
+ mutates: command.mutates_global_state === true ? 'global_npm_install' : 'local_bundle_file',
184
+ };
185
+ });
186
+ }
187
+
188
+ function publicOutput(plan, node, commandResults = []) {
189
+ const resultByStep = new Map(commandResults.map((result) => [result.step, result]));
190
+ const commands = publicCommandRecords(plan, resultByStep);
191
+ return {
192
+ schema: INSTALLER_SCHEMA,
193
+ ok: commandResults.every((result) => result.ok !== false),
194
+ mode: plan.execute ? 'execute' : 'dry-run',
195
+ dry_run: plan.dryRun,
196
+ execute: plan.execute,
197
+ public_safe: true,
198
+ node,
199
+ package_source: {
200
+ kind: 'local_checkout',
201
+ install_boundary: 'Runs npm install -g . against the checked-out package only; it does not download Enigma from a registry.',
202
+ },
203
+ bundle: {
204
+ path: '<bundle-path>',
205
+ path_kind: plan.bundlePathKind,
206
+ initialize_requested: plan.initVault,
207
+ initialized: plan.execute && plan.initVault && resultByStep.get('initialize_vault')?.ok === true,
208
+ },
209
+ commands,
210
+ preview: {
211
+ commands,
212
+ },
213
+ safety: {
214
+ default_dry_run: true,
215
+ requires_execute_for_mutation: true,
216
+ shell: false,
217
+ network_download_command: false,
218
+ prints_local_absolute_paths: false,
219
+ prints_secrets: false,
220
+ },
221
+ };
222
+ }
223
+
224
+ async function runCommand(command, execFileImpl) {
225
+ try {
226
+ await execFileImpl(command.command, command.args, { cwd: command.cwd, windowsHide: true });
227
+ return { step: command.step, ok: true };
228
+ } catch {
229
+ throw new Error(`Installer command failed at ${command.step}.`);
230
+ }
231
+ }
232
+
233
+ export async function runInstallEnigmaLocal(argv = process.argv.slice(2), runtime = {}) {
234
+ const options = Array.isArray(argv) ? parseInstallerArgs(argv) : { ...argv };
235
+ const node = validateNodeVersion(options.nodeVersion ?? runtime.nodeVersion ?? process.versions.node);
236
+ const plan = buildInstallerPlan(options, runtime);
237
+ if (plan.dryRun) return publicOutput(plan, node);
238
+
239
+ const mkdirImpl = runtime.mkdirImpl ?? mkdir;
240
+ if (options.initVault === true) await mkdirImpl(dirname(plan.bundlePath), { recursive: true });
241
+ const execFileImpl = runtime.execFileImpl ?? execFileAsync;
242
+ const commandResults = [];
243
+ for (const command of plan.commands) {
244
+ commandResults.push(await runCommand(command, execFileImpl));
245
+ }
246
+ return publicOutput(plan, node, commandResults);
247
+ }
248
+
249
+ function safeErrorMessage(error) {
250
+ const message = String(error?.message ?? error);
251
+ if (/^(Missing value|Unknown argument|Use either|Invalid Node version|Node >=|Installer command)/u.test(message)) return message;
252
+ return 'Local Enigma installer failed.';
253
+ }
254
+
255
+ async function main() {
256
+ const args = parseInstallerArgs();
257
+ if (args.help) {
258
+ process.stdout.write(usage());
259
+ return;
260
+ }
261
+ const output = await runInstallEnigmaLocal(args);
262
+ process.stdout.write(`${JSON.stringify(output, null, 2)}\n`);
263
+ }
264
+
265
+ if (process.argv[1] && fileURLToPath(import.meta.url) === resolvePath(process.argv[1])) {
266
+ main().catch((error) => {
267
+ process.stdout.write(`${JSON.stringify({ schema: INSTALLER_SCHEMA, ok: false, public_safe: true, error: { code: 'LOCAL_INSTALLER_FAILED', message: safeErrorMessage(error) } }, null, 2)}\n`);
268
+ process.exitCode = 1;
269
+ });
270
+ }
@@ -0,0 +1,242 @@
1
+ #!/usr/bin/env node
2
+ import { writeFile } from 'node:fs/promises';
3
+ import { dirname, resolve } from 'node:path';
4
+ import { fileURLToPath } from 'node:url';
5
+ import { mkdir } from 'node:fs/promises';
6
+ import {
7
+ createMemoryAccessReceipt,
8
+ createMemoryOptimizationPlan,
9
+ estimateTextTokens,
10
+ } from '../packages/optimizer/src/index.js';
11
+
12
+ export const MEMORY_OPTIMIZATION_BENCHMARK_SCHEMA = 'enigma.memory_optimization_benchmark.v1';
13
+
14
+ const DEFAULT_PRICE_PER_MILLION_TOKENS = 2.5;
15
+
16
+ function parseArgs(argv = process.argv.slice(2)) {
17
+ const flags = new Map();
18
+ for (let index = 0; index < argv.length; index += 1) {
19
+ const arg = argv[index];
20
+ if (!arg.startsWith('--')) continue;
21
+ const eq = arg.indexOf('=');
22
+ if (eq !== -1) {
23
+ flags.set(arg.slice(2, eq), arg.slice(eq + 1));
24
+ } else if (!argv[index + 1] || argv[index + 1].startsWith('--')) {
25
+ flags.set(arg.slice(2), true);
26
+ } else {
27
+ flags.set(arg.slice(2), argv[index + 1]);
28
+ index += 1;
29
+ }
30
+ }
31
+ return flags;
32
+ }
33
+
34
+ function getFlag(flags, names, fallback = undefined) {
35
+ for (const name of names) if (flags.has(name)) return flags.get(name);
36
+ return fallback;
37
+ }
38
+
39
+ function sha256Like(label) {
40
+ let hash = 0;
41
+ for (let index = 0; index < label.length; index += 1) hash = (hash * 31 + label.charCodeAt(index)) >>> 0;
42
+ return `sha256:${String(hash.toString(16)).padStart(64, '0').slice(0, 64)}`;
43
+ }
44
+
45
+ function fixtureCandidates() {
46
+ const rows = [
47
+ ['mem_auth_policy', 'Project policy: admin routes stay private; public routes expose only readyz and livez.', 0.92],
48
+ ['mem_auth_policy_duplicate', 'Project policy: admin routes stay private; public routes expose only readyz and livez.', 0.7],
49
+ ['mem_cost_boundary', 'Cost claims must be estimate-bound: no universal discount, benchmark lead, or invoice claim without commands and results.', 0.86],
50
+ ['mem_chain_boundary', 'Blockchain is for access, settlement, and proof anchoring only; raw memory never goes on-chain.', 0.82],
51
+ ['mem_support_note', 'Support escalation uses observed facts only and does not claim provider deletion or model forgetting.', 0.58],
52
+ ['mem_old_context', 'Old context can stay proof-only when the task does not need full text.', 0.18],
53
+ ];
54
+ return rows.map(([address, content, importance], index) => ({
55
+ address,
56
+ content,
57
+ importance,
58
+ last_accessed_at: `2026-06-23T12:0${Math.min(index, 5)}:00.000Z`,
59
+ metadata: {
60
+ fixture: 'optimizer-benchmark',
61
+ order: index,
62
+ content_commitment: sha256Like(`${address}:${content.length}`),
63
+ },
64
+ }));
65
+ }
66
+
67
+ function publicItem(item) {
68
+ const out = { ...item };
69
+ if (out.content_hash !== undefined) {
70
+ delete out.content_hash;
71
+ out.content_hash_redacted = true;
72
+ }
73
+ return out;
74
+ }
75
+
76
+ function publicPlan(plan) {
77
+ const tiers = {};
78
+ for (const [tier, items] of Object.entries(plan.tiers ?? {})) tiers[tier] = items.map(publicItem);
79
+ return {
80
+ ...plan,
81
+ tiers,
82
+ items: plan.items.map(publicItem),
83
+ };
84
+ }
85
+
86
+ function publicReceipt(receipt) {
87
+ const out = { ...receipt };
88
+ if (out.content_hash !== undefined) {
89
+ delete out.content_hash;
90
+ out.content_hash_redacted = true;
91
+ }
92
+ return out;
93
+ }
94
+
95
+
96
+ function comparativeBaselines(plan, candidates, pricing) {
97
+ const seen = new Set();
98
+ let dedupedFullContextTokens = 0;
99
+ let duplicateCandidatesRemoved = 0;
100
+ for (const candidate of candidates) {
101
+ const content = String(candidate.content ?? '');
102
+ if (seen.has(content)) {
103
+ duplicateCandidatesRemoved += 1;
104
+ continue;
105
+ }
106
+ seen.add(content);
107
+ dedupedFullContextTokens += estimateTextTokens(content);
108
+ }
109
+ const optimizedTokens = plan.optimized_prompt_tokens;
110
+ const baselineTokens = plan.baseline_prompt_tokens;
111
+ return {
112
+ schema: 'enigma.memory_strategy_comparison.v1',
113
+ strategies: [
114
+ {
115
+ id: 'full_context_unverified',
116
+ prompt_tokens: baselineTokens,
117
+ estimated_cost: (baselineTokens / 1_000_000) * pricing.price_per_million_tokens,
118
+ duplicate_candidates_removed: 0,
119
+ access_receipts: false,
120
+ proof_boundary: false,
121
+ public_candidate_text_included: false,
122
+ },
123
+ {
124
+ id: 'deduped_full_context_unreceipted',
125
+ prompt_tokens: dedupedFullContextTokens,
126
+ estimated_cost: (dedupedFullContextTokens / 1_000_000) * pricing.price_per_million_tokens,
127
+ duplicate_candidates_removed: duplicateCandidatesRemoved,
128
+ access_receipts: false,
129
+ proof_boundary: false,
130
+ public_candidate_text_included: false,
131
+ },
132
+ {
133
+ id: 'enigma_receipted_plan',
134
+ prompt_tokens: optimizedTokens,
135
+ estimated_cost: (optimizedTokens / 1_000_000) * pricing.price_per_million_tokens,
136
+ duplicate_candidates_removed: plan.totals.duplicates_removed,
137
+ access_receipts: true,
138
+ proof_boundary: true,
139
+ public_candidate_text_included: false,
140
+ },
141
+ ],
142
+ enigma_vs_full_context: {
143
+ prompt_token_delta: baselineTokens - optimizedTokens,
144
+ prompt_token_reduction_pct: baselineTokens === 0 ? 0 : Number((((baselineTokens - optimizedTokens) / baselineTokens) * 100).toFixed(6)),
145
+ access_receipts_added: true,
146
+ raw_text_publication_removed: true,
147
+ provider_invoice_savings_claim: false,
148
+ universal_discount_claim: false,
149
+ },
150
+ claim_boundary: [
151
+ 'Strategy comparison is computed on a repository fixture only.',
152
+ 'Lower prompt_tokens is a local estimator result, not a provider invoice or universal discount claim.',
153
+ 'Unreceipted strategies may use fewer tokens but do not provide Enigma receipt/proof boundaries.',
154
+ ],
155
+ };
156
+ }
157
+ export function runMemoryOptimizationBenchmark(options = {}) {
158
+ const generatedAt = options.generated_at ?? options.generatedAt ?? new Date().toISOString();
159
+ const pricing = {
160
+ currency: options.currency ?? 'USD',
161
+ price_per_million_tokens: Number(options.price_per_million_tokens ?? options.pricePerMillionTokens ?? DEFAULT_PRICE_PER_MILLION_TOKENS),
162
+ };
163
+ if (!Number.isFinite(pricing.price_per_million_tokens) || pricing.price_per_million_tokens < 0) {
164
+ throw new Error('price_per_million_tokens must be a non-negative number');
165
+ }
166
+ const plan = createMemoryOptimizationPlan({
167
+ candidates: fixtureCandidates(),
168
+ prompt: 'Prepare the production memory-layer launch answer with security and claim boundaries.',
169
+ pricing,
170
+ now: '2026-06-23T12:06:00.000Z',
171
+ });
172
+ const receipts = plan.items.map((item, index) => createMemoryAccessReceipt({
173
+ item,
174
+ plan,
175
+ timestamp: generatedAt,
176
+ sequence: index,
177
+ pricing,
178
+ }));
179
+ const report = {
180
+ schema: MEMORY_OPTIMIZATION_BENCHMARK_SCHEMA,
181
+ generated_at: generatedAt,
182
+ corpus: {
183
+ name: 'enigma.optimizer.fixture.v1',
184
+ private_candidate_count: fixtureCandidates().length,
185
+ public_candidate_text_included: false,
186
+ },
187
+ strategy_comparison: comparativeBaselines(plan, fixtureCandidates(), pricing),
188
+ method: {
189
+ tokenizer: 'estimateTextTokens deterministic local estimator',
190
+ planner: 'createMemoryOptimizationPlan',
191
+ pricing_input: pricing,
192
+ claim_boundary: [
193
+ 'This is a fixture benchmark for repository behavior only.',
194
+ 'savings_pct is estimated prompt-token reduction for these inputs, not provider invoice savings.',
195
+ 'No external-deletion, external-forgetting, crypto-return, compliance, or universal-discount claim is made.',
196
+ ],
197
+ },
198
+ result: {
199
+ baseline_prompt_tokens: plan.baseline_prompt_tokens,
200
+ optimized_prompt_tokens: plan.optimized_prompt_tokens,
201
+ savings_pct: plan.savings_pct,
202
+ baseline_cost: plan.baseline_cost,
203
+ optimized_cost: plan.optimized_cost,
204
+ duplicate_candidates_removed: plan.totals.duplicates_removed,
205
+ deduped_candidates: plan.totals.deduped_candidates,
206
+ tiers: Object.fromEntries(Object.entries(plan.tiers).map(([tier, items]) => [tier, items.length])),
207
+ },
208
+ optimization_plan: publicPlan(plan),
209
+ optimization_receipts: receipts.map(publicReceipt),
210
+ };
211
+ const serialized = JSON.stringify(report);
212
+ if (/Project policy|Cost claims|Blockchain is|Support escalation|Old context/i.test(serialized)) {
213
+ throw new Error('benchmark report leaked private fixture text');
214
+ }
215
+ return report;
216
+ }
217
+
218
+ async function main() {
219
+ const flags = parseArgs();
220
+ const report = runMemoryOptimizationBenchmark({
221
+ price_per_million_tokens: getFlag(flags, ['price-per-million-tokens', 'pricePerMillionTokens'], DEFAULT_PRICE_PER_MILLION_TOKENS),
222
+ currency: getFlag(flags, ['currency'], 'USD'),
223
+ });
224
+ const out = getFlag(flags, ['out']);
225
+ if (out && out !== true) {
226
+ const path = resolve(String(out));
227
+ await mkdir(dirname(path), { recursive: true });
228
+ await writeFile(path, `${JSON.stringify(report, null, 2)}\n`, 'utf8');
229
+ process.stdout.write(`${JSON.stringify({ ok: true, schema: report.schema, out: path, result: report.result }, null, 2)}\n`);
230
+ return;
231
+ }
232
+ process.stdout.write(`${JSON.stringify(report, null, 2)}\n`);
233
+ }
234
+
235
+ const invokedPath = process.argv[1] ? resolve(process.argv[1]) : '';
236
+ const modulePath = fileURLToPath(import.meta.url);
237
+ if (invokedPath === modulePath) {
238
+ main().catch((error) => {
239
+ process.stderr.write(`${error.message}\n`);
240
+ process.exitCode = 1;
241
+ });
242
+ }