enigma-memory 0.1.17 → 0.1.22

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 (290) hide show
  1. package/README.md +85 -27
  2. package/apps/cli/bin/enigma-desktop.mjs +140 -0
  3. package/apps/cli/bin/enigma-terminal.mjs +78 -0
  4. package/apps/cli/bin/enigma.mjs +4979 -3263
  5. package/apps/desktop/electron-main.cjs +217 -0
  6. package/apps/desktop/package.json +12 -0
  7. package/apps/desktop/src/app.js +264 -7
  8. package/apps/desktop/src/index.html +3514 -1373
  9. package/apps/desktop/src/launch-electron.mjs +51 -0
  10. package/apps/desktop/src/server.mjs +2914 -0
  11. package/apps/desktop/src/styles.css +2972 -260
  12. package/apps/desktop/src/zk-browser-prove.mjs +53 -0
  13. package/apps/desktop/src/zk-state.mjs +1789 -0
  14. package/apps/gateway/bin/enigma-gateway.mjs +102 -5
  15. package/apps/gateway/src/server.mjs +271 -8
  16. package/apps/ios/EnigmaCore/Package.swift +12 -0
  17. package/apps/ios/EnigmaCore/Sources/EnigmaCore/EnigmaAPIClient.swift +227 -0
  18. package/apps/ios/EnigmaCore/Sources/EnigmaCore/Models.swift +278 -0
  19. package/apps/ios/EnigmaCore/Sources/EnigmaCore/PKCE.swift +96 -0
  20. package/apps/ios/EnigmaCore/Sources/EnigmaCore/PrivacyMinimizer.swift +187 -0
  21. package/apps/ios/EnigmaCore/Sources/EnigmaCore/ToolModels.swift +129 -0
  22. package/apps/ios/EnigmaCore/Tests/EnigmaCoreTests/EnigmaCoreTests.swift +42 -0
  23. package/apps/ios/EnigmaIOS/Enigma/AppModel.swift +346 -0
  24. package/apps/ios/EnigmaIOS/Enigma/Assets.xcassets/AccentColor.colorset/Contents.json +12 -0
  25. package/apps/ios/EnigmaIOS/Enigma/Assets.xcassets/AppIcon.appiconset/Contents.json +11 -0
  26. package/apps/ios/EnigmaIOS/Enigma/Assets.xcassets/AppIcon.appiconset/EnigmaAppIcon.png +0 -0
  27. package/apps/ios/EnigmaIOS/Enigma/Assets.xcassets/Contents.json +3 -0
  28. package/apps/ios/EnigmaIOS/Enigma/Assets.xcassets/LaunchBackground.colorset/Contents.json +12 -0
  29. package/apps/ios/EnigmaIOS/Enigma/ChatView.swift +181 -0
  30. package/apps/ios/EnigmaIOS/Enigma/CouncilView.swift +78 -0
  31. package/apps/ios/EnigmaIOS/Enigma/CreateView.swift +152 -0
  32. package/apps/ios/EnigmaIOS/Enigma/EnigmaApp.swift +52 -0
  33. package/apps/ios/EnigmaIOS/Enigma/Info.plist +52 -0
  34. package/apps/ios/EnigmaIOS/Enigma/NaturalLanguagePrivacyTagger.swift +26 -0
  35. package/apps/ios/EnigmaIOS/Enigma/OAuthClient.swift +321 -0
  36. package/apps/ios/EnigmaIOS/Enigma/OnboardingView.swift +105 -0
  37. package/apps/ios/EnigmaIOS/Enigma/PrivateVaultView.swift +275 -0
  38. package/apps/ios/EnigmaIOS/Enigma/SecureStore.swift +76 -0
  39. package/apps/ios/EnigmaIOS/Enigma/SettingsView.swift +60 -0
  40. package/apps/ios/EnigmaIOS/Enigma/Theme.swift +80 -0
  41. package/apps/ios/EnigmaIOS/EnigmaIOS.xcodeproj/project.pbxproj +211 -0
  42. package/apps/ios/EnigmaIOS/EnigmaIOS.xcodeproj/xcshareddata/xcschemes/Enigma.xcscheme +23 -0
  43. package/apps/native-host/README.md +19 -8
  44. package/apps/native-host/bin/enigma-native-host.mjs +229 -13
  45. package/apps/relay/bin/enigma-relay.mjs +103 -5
  46. package/apps/relay/src/federation-runtime.mjs +618 -0
  47. package/apps/relay/src/server.mjs +310 -9
  48. package/apps/verifier/bin/enigma-verify.mjs +327 -11
  49. package/cortex-v3/circuits/build/intent_vk_bytes.json +35 -0
  50. package/cortex-v3/circuits/build/sale_vk_bytes.json +35 -0
  51. package/cortex-v3/circuits/build/vk_bytes.json +32 -0
  52. package/cortex-v3/proving-assets.json +64 -0
  53. package/cortex-v3/zk/BUILD-CONTRACT.md +87 -0
  54. package/cortex-v3/zk/action-transition-vk.json +119 -0
  55. package/cortex-v3/zk/alias-adversarial.test.mjs +220 -0
  56. package/cortex-v3/zk/groth16-verify-child.mjs +17 -0
  57. package/cortex-v3/zk/intent-witness.mjs +365 -0
  58. package/cortex-v3/zk/intent-witness.test.mjs +485 -0
  59. package/cortex-v3/zk/proving-assets.mjs +203 -0
  60. package/cortex-v3/zk/sale-witness.mjs +783 -0
  61. package/cortex-v3/zk/sale-witness.test.mjs +784 -0
  62. package/cortex-v3/zk/sealed-sale-release-vk.json +119 -0
  63. package/cortex-v3/zk/settlement-evidence.mjs +722 -0
  64. package/cortex-v3/zk/setup-intent.mjs +688 -0
  65. package/cortex-v3/zk/setup-sale.mjs +666 -0
  66. package/cortex-v3/zk/setup.mjs +594 -0
  67. package/cortex-v3/zk/witness.mjs +184 -0
  68. package/cortex-v3/zk/zk-codec.mjs +232 -0
  69. package/cortex-v3/zk/zk-codec.test.mjs +293 -0
  70. package/cortex-v3/zk/zk-settle.mjs +370 -0
  71. package/cortex-v3/zk/zk-tree.mjs +256 -0
  72. package/cortex-v3/zk/zk-tree.test.mjs +419 -0
  73. package/deploy/SIMULATION.md +14 -9
  74. package/deploy/docker-compose.local-production-simulation.yml +54 -12
  75. package/docs/benchmark-attestation-network.md +487 -487
  76. package/docs/benchmark-reproducibility.md +289 -289
  77. package/docs/blockchain-only-mechanisms.md +400 -400
  78. package/docs/browser-extension-install.md +8 -6
  79. package/docs/client-connectors.md +16 -12
  80. package/docs/demo-proof-network.md +275 -275
  81. package/docs/developer-ecosystem.md +15 -13
  82. package/docs/developer-proof-quickstart.md +325 -325
  83. package/docs/enigma-memory-ready-conformance.md +378 -376
  84. package/docs/install-anywhere.md +64 -30
  85. package/docs/installers-and-desktop.md +8 -7
  86. package/docs/memory-benchmarks.md +1 -1
  87. package/docs/memory-drive-health-model.md +690 -690
  88. package/docs/novelty-invention-candidates.md +161 -161
  89. package/docs/proof-network-build-notes.md +240 -240
  90. package/docs/proof-network-claim-boundaries.md +320 -318
  91. package/docs/proof-network.md +339 -339
  92. package/docs/sdk-api.md +324 -324
  93. package/docs/solana-proof-rail.md +453 -453
  94. package/examples/01-quickstart-agent/index.mjs +49 -0
  95. package/examples/01_agent_memory_quickstart.mjs +57 -0
  96. package/examples/02-multi-agent-swarm/index.mjs +57 -0
  97. package/examples/02_cross_model_passport.mjs +64 -0
  98. package/examples/03-langchain-memory/index.mjs +41 -0
  99. package/examples/03_poseidon_commitment_verification.mjs +71 -0
  100. package/examples/04-python-trading-agent/trader.py +49 -0
  101. package/examples/README.md +27 -0
  102. package/examples/ci/github-actions.yml +7 -2
  103. package/package.json +410 -278
  104. package/packages/adapters/PACKAGE_CONTRACT.md +1 -1
  105. package/packages/connectors/src/index.js +196 -4
  106. package/packages/connectors/swarm-router.mjs +168 -0
  107. package/packages/core/src/index.js +249 -2
  108. package/packages/core/src/version.mjs +7 -0
  109. package/packages/dev-tools/package.json +19 -0
  110. package/packages/dev-tools/src/index.js +4 -0
  111. package/packages/dev-tools/src/memory-benchmark-suite.js +112 -0
  112. package/packages/dev-tools/src/swarm-simulator.js +101 -0
  113. package/packages/dev-tools/src/vault-inspector.js +114 -0
  114. package/packages/dev-tools/src/vector-benchmark.js +100 -0
  115. package/packages/developer-platform/src/access-credentials.js +341 -0
  116. package/packages/developer-platform/src/http.js +132 -0
  117. package/packages/developer-platform/src/index.js +4 -0
  118. package/packages/developer-platform/src/usage-http.js +60 -0
  119. package/packages/developer-platform/src/usage.js +295 -0
  120. package/packages/enclave-runtime/attestation.mjs +159 -0
  121. package/packages/enclave-runtime/index.mjs +47 -0
  122. package/packages/enclave-runtime/session-manager.mjs +253 -0
  123. package/packages/enclave-runtime/zeroization-proof.mjs +227 -0
  124. package/packages/enigma-reflex/package.json +14 -0
  125. package/packages/enigma-reflex/src/index.js +204 -0
  126. package/packages/enigma-reflex/training/generate-dataset.mjs +40 -0
  127. package/packages/enigma-reflex/training/requirements.txt +8 -0
  128. package/packages/enigma-reflex/training/train.py +314 -0
  129. package/packages/enigma-weave/LICENSE +22 -0
  130. package/packages/enigma-weave/UPSTREAM.json +21 -0
  131. package/packages/enigma-weave/package.json +14 -0
  132. package/packages/enigma-weave/src/index.js +286 -0
  133. package/packages/hosted-cloud/src/index.js +80 -5
  134. package/packages/importers/src/index.js +432 -0
  135. package/packages/inference-runtime/src/browser.js +401 -0
  136. package/packages/inference-runtime/src/chat.js +265 -0
  137. package/packages/inference-runtime/src/code.js +407 -0
  138. package/packages/inference-runtime/src/contracts.js +162 -0
  139. package/packages/inference-runtime/src/http.js +232 -0
  140. package/packages/inference-runtime/src/image.js +186 -0
  141. package/packages/inference-runtime/src/index.js +10 -0
  142. package/packages/inference-runtime/src/model-router.js +320 -0
  143. package/packages/inference-runtime/src/platform.js +125 -0
  144. package/packages/inference-runtime/src/privacy.js +400 -0
  145. package/packages/inference-runtime/src/video.js +253 -0
  146. package/packages/mcp-server/README.md +22 -6
  147. package/packages/mcp-server/bin/enigma-mcp.mjs +2 -1
  148. package/packages/mcp-server/src/index.js +2498 -1185
  149. package/packages/mcp-server/src/oauth.js +561 -0
  150. package/packages/mcp-server/src/private-handoff.js +84 -0
  151. package/packages/mcp-server/src/remote-http.js +273 -0
  152. package/packages/mcp-server/src/remote-policy.js +72 -0
  153. package/packages/mcp-server/swarm-bridge.mjs +361 -0
  154. package/packages/mesh/index.d.ts +283 -0
  155. package/packages/mesh/package.json +23 -0
  156. package/packages/mesh/src/crypto.js +189 -0
  157. package/packages/mesh/src/federation-packets.js +353 -0
  158. package/packages/mesh/src/gossip.js +311 -0
  159. package/packages/mesh/src/index.js +6 -0
  160. package/packages/mesh/src/protocol.js +255 -0
  161. package/packages/mesh/src/router.js +279 -0
  162. package/packages/mesh/src/transport.js +306 -0
  163. package/packages/passport/src/index.js +436 -7
  164. package/packages/private-economy/src/credits-http.js +100 -0
  165. package/packages/private-economy/src/credits.js +447 -0
  166. package/packages/private-economy/src/index.js +5 -0
  167. package/packages/private-economy/src/payments-http.js +120 -0
  168. package/packages/private-economy/src/payments.js +509 -0
  169. package/packages/private-economy/src/x402.js +346 -0
  170. package/packages/proof-network/PACKAGE_CONTRACT.md +21 -0
  171. package/packages/rag/index.d.ts +182 -0
  172. package/packages/rag/models/Xenova/all-MiniLM-L6-v2/THIRD_PARTY_LICENSES.txt +207 -0
  173. package/packages/rag/models/Xenova/all-MiniLM-L6-v2/config.json +25 -0
  174. package/packages/rag/models/Xenova/all-MiniLM-L6-v2/onnx/model_quantized.onnx +0 -0
  175. package/packages/rag/models/Xenova/all-MiniLM-L6-v2/sha256-manifest.json +28 -0
  176. package/packages/rag/models/Xenova/all-MiniLM-L6-v2/tokenizer.json +30686 -0
  177. package/packages/rag/models/Xenova/all-MiniLM-L6-v2/tokenizer_config.json +15 -0
  178. package/packages/rag/package.json +27 -0
  179. package/packages/rag/src/blinded-search.js +109 -0
  180. package/packages/rag/src/bm25.js +169 -0
  181. package/packages/rag/src/embeddings.js +459 -0
  182. package/packages/rag/src/hybrid.js +76 -0
  183. package/packages/rag/src/index.js +38 -0
  184. package/packages/rag/src/reranker.js +61 -0
  185. package/packages/rag/src/research.js +107 -0
  186. package/packages/rag/src/vector-store.js +430 -0
  187. package/packages/rag/src/verify-model-artifacts.mjs +4 -0
  188. package/packages/sdk/index.d.ts +760 -0
  189. package/packages/sdk/package.json +33 -0
  190. package/packages/sdk/python/README.md +24 -0
  191. package/packages/sdk/python/enigma_sdk.py +250 -0
  192. package/packages/sdk/python/pyproject.toml +34 -0
  193. package/packages/sdk/python/requirements.txt +1 -0
  194. package/packages/sdk/python/setup.py +20 -0
  195. package/packages/sdk/src/federation/capability-grant.js +389 -0
  196. package/packages/sdk/src/federation/federation-router.js +360 -0
  197. package/packages/sdk/src/federation/ghostmesh-bridge.js +497 -0
  198. package/packages/sdk/src/federation/index.js +3 -0
  199. package/packages/sdk/src/index.js +1796 -0
  200. package/packages/sdk/src/intelligence/contradiction.js +337 -0
  201. package/packages/sdk/src/intelligence/decision-engine.js +155 -0
  202. package/packages/sdk/src/intelligence/index.js +4 -0
  203. package/packages/sdk/src/intelligence/ontology.js +122 -0
  204. package/packages/sdk/src/intelligence/temporal.js +123 -0
  205. package/packages/sdk/src/market-client.js +142 -0
  206. package/packages/sdk/src/mesh-client.js +110 -0
  207. package/packages/sdk/src/middleware/index.js +3 -0
  208. package/packages/sdk/src/middleware/langchain.js +159 -0
  209. package/packages/sdk/src/middleware/llamaindex.js +101 -0
  210. package/packages/sdk/src/middleware/vercel-ai.js +112 -0
  211. package/packages/sdk/src/rag-client.js +85 -0
  212. package/packages/sdk/src/swarm-orchestrator.js +260 -0
  213. package/packages/settlement/PACKAGE_CONTRACT.md +1 -1
  214. package/packages/snapcompact/THIRD_PARTY_LICENSES.txt +40 -0
  215. package/packages/snapcompact/assets/8x13-latin1.bdf +3837 -0
  216. package/packages/snapcompact/index.d.ts +284 -0
  217. package/packages/snapcompact/package.json +25 -0
  218. package/packages/snapcompact/src/index.js +716 -0
  219. package/packages/storage/PACKAGE_CONTRACT.md +1 -1
  220. package/packages/terminal-console/animations.mjs +240 -0
  221. package/packages/terminal-console/auto-anchor.mjs +220 -0
  222. package/packages/terminal-console/banner.mjs +91 -0
  223. package/packages/terminal-console/commands.mjs +459 -0
  224. package/packages/terminal-console/delegation.mjs +152 -0
  225. package/packages/terminal-console/index.mjs +5 -0
  226. package/packages/terminal-console/outbox.mjs +143 -0
  227. package/packages/terminal-console/phantom-bridge.mjs +637 -0
  228. package/packages/terminal-console/repl.mjs +136 -0
  229. package/packages/terminal-console/signer-store.mjs +130 -0
  230. package/packages/terminal-console/solana-rpc.mjs +214 -0
  231. package/packages/terminal-console/solana-transport.mjs +189 -0
  232. package/packages/terminal-tui/dashboard.mjs +214 -0
  233. package/packages/terminal-tui/index.mjs +28 -0
  234. package/packages/terminal-tui/merkle-tree-renderer.mjs +268 -0
  235. package/packages/terminal-tui/telemetry-hud.mjs +137 -0
  236. package/packages/vault/index.d.ts +449 -0
  237. package/packages/vault/package.json +27 -0
  238. package/packages/vault/src/e2ee.mjs +393 -0
  239. package/packages/vault/src/enclave.js +481 -0
  240. package/packages/vault/src/erasure.js +207 -0
  241. package/packages/vault/src/index.js +1150 -125
  242. package/packages/vault/src/persistence.js +307 -0
  243. package/packages/vault/src/poseidon.js +354 -0
  244. package/packages/vault/src/receipt.js +459 -0
  245. package/scripts/benchmark-optical-context.mjs +166 -0
  246. package/scripts/bootstrap-enigma.mjs +502 -0
  247. package/scripts/build-edge-backend-workers.mjs +20 -5
  248. package/scripts/build-goal-completion-audit.mjs +72 -25
  249. package/scripts/build-hosted-api-key-lifecycle.mjs +292 -274
  250. package/scripts/build-hosted-customer-lifecycle.mjs +493 -476
  251. package/scripts/build-hosted-probe-worker.mjs +19 -4
  252. package/scripts/build-installer-assets.mjs +409 -389
  253. package/scripts/build-operator-evidence-starter.mjs +59 -1
  254. package/scripts/build-production-backend-env-kit.mjs +2 -0
  255. package/scripts/build-production-unblocker.mjs +4 -1
  256. package/scripts/build-proof-network-packet.mjs +213 -213
  257. package/scripts/check.mjs +25 -4
  258. package/scripts/collect-hosted-backend-live-evidence.mjs +49 -12
  259. package/scripts/install-enigma-local.mjs +18 -5
  260. package/scripts/release-audit.mjs +74 -115
  261. package/scripts/release-provenance.mjs +12 -2
  262. package/scripts/run-backend-readiness-smoke.mjs +112 -10
  263. package/scripts/run-standard-memory-benchmarks.mjs +1354 -1352
  264. package/scripts/scan-secrets.mjs +178 -0
  265. package/scripts/simulate-production-env.mjs +71 -10
  266. package/scripts/validate-hosted-backend-live.mjs +112 -1
  267. package/specs/antibody-pack-v1.schema.json +95 -0
  268. package/specs/antigen-envelope-v1.schema.json +81 -0
  269. package/specs/boundary-manifest-v1.schema.json +35 -35
  270. package/specs/capsule-v1.schema.json +55 -55
  271. package/specs/claim-boundary-manifest-v1.schema.json +22 -22
  272. package/specs/claim-ledger-v1.schema.json +291 -0
  273. package/specs/context-passport-v1.schema.json +59 -0
  274. package/specs/deletion-tombstone-v1.schema.json +26 -26
  275. package/specs/evidence-packet-v1.schema.json +177 -0
  276. package/specs/hosted-backend-live-evidence-v1.schema.json +72 -3
  277. package/specs/immune-scan-report-v1.schema.json +112 -0
  278. package/specs/lifecycle-receipt-log-v1.schema.json +67 -0
  279. package/specs/memory-atom-v1.schema.json +59 -0
  280. package/specs/memory-event-v1.schema.json +42 -42
  281. package/specs/passport-v1.schema.json +50 -50
  282. package/specs/proof-of-non-use-v1.schema.json +65 -0
  283. package/specs/quarantine-record-v1.schema.json +126 -0
  284. package/specs/receipt-v1.schema.json +61 -61
  285. package/specs/state-checkpoint-v1.schema.json +37 -37
  286. package/specs/trust-bundle-v1.schema.json +56 -56
  287. package/specs/trust-card-v1.schema.json +119 -0
  288. package/docs/proof-network-launch-plan.md +0 -421
  289. package/packages/metering/PACKAGE_CONTRACT.md +0 -20
  290. package/scripts/build-ai-orchestration-plan.mjs +0 -248
@@ -0,0 +1,361 @@
1
+ import { createHash, randomUUID } from 'node:crypto';
2
+
3
+ export const SWARM_PERMISSIONS = Object.freeze({ READ: 1, WRITE: 2, SYNC: 4, GRAPH: 8, CLUSTER: 16, ADMIN: 32 });
4
+ const ALL_PERMISSIONS = Object.values(SWARM_PERMISSIONS).reduce((mask, value) => mask | value, 0);
5
+ const DEFAULT_PERMISSIONS = SWARM_PERMISSIONS.READ | SWARM_PERMISSIONS.WRITE | SWARM_PERMISSIONS.SYNC | SWARM_PERMISSIONS.GRAPH | SWARM_PERMISSIONS.CLUSTER;
6
+
7
+ function canonical(value) {
8
+ if (Array.isArray(value)) return `[${value.map(canonical).join(',')}]`;
9
+ if (value && typeof value === 'object') return `{${Object.keys(value).sort().map((key) => `${JSON.stringify(key)}:${canonical(value[key])}`).join(',')}}`;
10
+ return JSON.stringify(value);
11
+ }
12
+ function sha256(value) { return `sha256:${createHash('sha256').update(typeof value === 'string' ? value : canonical(value)).digest('hex')}`; }
13
+ function clone(value) { return value === undefined ? undefined : structuredClone(value); }
14
+ function requiredString(value, name) {
15
+ if (typeof value !== 'string' || !value.trim()) throw new Error(`${name} is required`);
16
+ return value.trim();
17
+ }
18
+ function normalizePermissionMask(value) {
19
+ if (value === undefined || value === null) return DEFAULT_PERMISSIONS;
20
+ if (Number.isInteger(value) && value >= 0 && value <= ALL_PERMISSIONS) return value;
21
+ const names = Array.isArray(value) ? value : String(value).split(/[|,\s]+/);
22
+ let mask = 0;
23
+ for (const rawName of names) {
24
+ const name = String(rawName).trim().toUpperCase();
25
+ if (!name) continue;
26
+ if (!(name in SWARM_PERMISSIONS)) throw new Error(`unknown swarm permission: ${rawName}`);
27
+ mask |= SWARM_PERMISSIONS[name];
28
+ }
29
+ return mask;
30
+ }
31
+ function permissionNames(mask) { return Object.entries(SWARM_PERMISSIONS).filter(([, bit]) => (mask & bit) === bit).map(([name]) => name.toLowerCase()); }
32
+ function atomId(atom) {
33
+ const value = atom?.memory_addr ?? atom?.memoryAddr ?? atom?.atom_id ?? atom?.atomId ?? atom?.id;
34
+ return requiredString(value, 'memory atom id');
35
+ }
36
+ function atomContent(atom) { return String(atom?.content ?? atom?.text ?? atom?.summary ?? atom?.metadata?.summary ?? ''); }
37
+ const TOKEN_STOPWORDS = new Set(['a', 'an', 'and', 'are', 'as', 'at', 'be', 'by', 'for', 'from', 'in', 'is', 'it', 'of', 'on', 'or', 'that', 'the', 'this', 'to', 'was', 'were', 'with']);
38
+ function tokens(value) { return new Set(String(value).toLowerCase().match(/[\p{L}\p{N}_-]{2,}/gu)?.filter((token) => !TOKEN_STOPWORDS.has(token)) ?? []); }
39
+ function similarity(left, right) {
40
+ if (left.size === 0 && right.size === 0) return 1;
41
+ let intersection = 0;
42
+ for (const token of left) if (right.has(token)) intersection += 1;
43
+ const union = left.size + right.size - intersection;
44
+ return union === 0 ? 0 : intersection / union;
45
+ }
46
+ function entityEntry(value) {
47
+ if (typeof value === 'string') return { id: value, label: value, type: 'entity' };
48
+ if (!value || typeof value !== 'object') return null;
49
+ const id = value.id ?? value.entity_id ?? value.entityId ?? value.name ?? value.label;
50
+ if (typeof id !== 'string' || !id.trim()) return null;
51
+ return { id: id.trim(), label: String(value.label ?? value.name ?? id), type: String(value.type ?? value.kind ?? 'entity') };
52
+ }
53
+ function relationEntry(value) {
54
+ if (!value || typeof value !== 'object') return null;
55
+ const from = value.from ?? value.source ?? value.subject ?? value.source_id;
56
+ const to = value.to ?? value.target ?? value.object ?? value.target_id;
57
+ if (typeof from !== 'string' || !from.trim() || typeof to !== 'string' || !to.trim()) return null;
58
+ return { from: from.trim(), to: to.trim(), type: String(value.type ?? value.relation ?? value.predicate ?? 'related_to'), directed: value.directed !== false };
59
+ }
60
+ function atomRelations(atom) {
61
+ return [...(Array.isArray(atom.relations) ? atom.relations : []), ...(Array.isArray(atom.metadata?.relations) ? atom.metadata.relations : [])].map(relationEntry).filter(Boolean);
62
+ }
63
+ function atomEntities(atom) {
64
+ const raw = [...(Array.isArray(atom.entities) ? atom.entities : []), ...(Array.isArray(atom.metadata?.entities) ? atom.metadata.entities : [])];
65
+ const entries = raw.map(entityEntry).filter(Boolean);
66
+ const seen = new Set(entries.map((entry) => entry.id));
67
+ for (const relation of atomRelations(atom)) for (const id of [relation.from, relation.to]) if (!seen.has(id)) { entries.push({ id, label: id, type: 'entity' }); seen.add(id); }
68
+ return entries;
69
+ }
70
+ function publicAtom(atom) {
71
+ const copy = clone(atom);
72
+ delete copy.plaintext;
73
+ delete copy._swarm_hash;
74
+ return copy;
75
+ }
76
+
77
+ const COMMITMENT_ATOM_STRING_FIELDS = Object.freeze([
78
+ 'schema',
79
+ 'memory_addr',
80
+ 'memory_id',
81
+ 'atom_id',
82
+ 'swarm_id',
83
+ 'namespace',
84
+ 'owner_agent_id',
85
+ 'source_addr',
86
+ 'successor_addr',
87
+ 'kind',
88
+ 'state',
89
+ 'status',
90
+ 'confidence',
91
+ 'sensitivity',
92
+ 'retention',
93
+ 'created_at',
94
+ 'updated_at',
95
+ 'tombstoned_at',
96
+ ]);
97
+ const COMMITMENT_HASH_FIELDS = Object.freeze(['content_hash', 'content_commitment']);
98
+ const COMMITMENT_ATOM_KEYS = new Set([...COMMITMENT_ATOM_STRING_FIELDS, ...COMMITMENT_HASH_FIELDS, 'entities', 'relations']);
99
+ const COMMITMENT_RELATION_KEYS = new Set(['from', 'to', 'type', 'directed']);
100
+ const SAFE_IDENTIFIER_PATTERN = /^[A-Za-z0-9][A-Za-z0-9._:/@+-]{0,255}$/;
101
+ const SHA256_VALUE_PATTERN = /^sha256:[a-f0-9]{64}$/i;
102
+ const COMMITMENT_VALUE_PATTERN = /^(?:sha256|hmac-sha256):[a-f0-9]{64}$/i;
103
+
104
+ function safeIdentifier(value) {
105
+ return typeof value === 'string' && SAFE_IDENTIFIER_PATTERN.test(value);
106
+ }
107
+
108
+ export function projectSwarmCommitmentAtom(atom) {
109
+ const projected = {};
110
+ for (const key of COMMITMENT_ATOM_STRING_FIELDS) {
111
+ if (safeIdentifier(atom?.[key])) projected[key] = atom[key];
112
+ }
113
+ const memoryAddr = atomId(atom);
114
+ if (!safeIdentifier(memoryAddr)) throw new Error('memory atom id is not a safe stable identifier');
115
+ projected.memory_addr = memoryAddr;
116
+ if (SHA256_VALUE_PATTERN.test(atom?.content_hash ?? '')) projected.content_hash = atom.content_hash;
117
+ if (COMMITMENT_VALUE_PATTERN.test(atom?.content_commitment ?? '')) projected.content_commitment = atom.content_commitment;
118
+ const entities = atomEntities(atom).map((entity) => entity.id).filter(safeIdentifier);
119
+ if (entities.length > 0) projected.entities = [...new Set(entities)].sort();
120
+ const relations = atomRelations(atom)
121
+ .filter(({ from, to, type }) => safeIdentifier(from) && safeIdentifier(to) && safeIdentifier(type))
122
+ .map(({ from, to, type, directed }) => ({ from, to, type, directed }));
123
+ if (relations.length > 0) projected.relations = relations;
124
+ return projected;
125
+ }
126
+
127
+ export function validateSwarmCommitmentAtom(atom) {
128
+ if (!atom || typeof atom !== 'object' || Array.isArray(atom)) throw new Error('commitment-only snapshot atom must be an object');
129
+ for (const key of Object.keys(atom)) {
130
+ if (!COMMITMENT_ATOM_KEYS.has(key)) throw new Error(`commitment-only snapshot atom contains unsafe field: ${key}`);
131
+ }
132
+ for (const key of COMMITMENT_ATOM_STRING_FIELDS) {
133
+ if (atom[key] !== undefined && !safeIdentifier(atom[key])) throw new Error(`commitment-only snapshot atom ${key} is not a safe stable identifier`);
134
+ }
135
+ if (atom.content_hash !== undefined && !SHA256_VALUE_PATTERN.test(atom.content_hash)) throw new Error('commitment-only snapshot atom content_hash is invalid');
136
+ if (atom.content_commitment !== undefined && !COMMITMENT_VALUE_PATTERN.test(atom.content_commitment)) throw new Error('commitment-only snapshot atom content_commitment is invalid');
137
+ const memoryAddr = atomId(atom);
138
+ if (!safeIdentifier(memoryAddr)) throw new Error('commitment-only snapshot atom memory_addr is not a safe stable identifier');
139
+ if (atom.entities !== undefined && (!Array.isArray(atom.entities) || atom.entities.some((entity) => !safeIdentifier(entity)))) {
140
+ throw new Error('commitment-only snapshot atom entities must be an array of safe string identifiers');
141
+ }
142
+ if (atom.relations !== undefined) {
143
+ if (!Array.isArray(atom.relations)) throw new Error('commitment-only snapshot atom relations must be an array');
144
+ for (const relation of atom.relations) {
145
+ if (!relation || typeof relation !== 'object' || Array.isArray(relation)) throw new Error('commitment-only snapshot relation must be an object');
146
+ for (const key of Object.keys(relation)) {
147
+ if (!COMMITMENT_RELATION_KEYS.has(key)) throw new Error(`commitment-only snapshot relation contains unsafe field: ${key}`);
148
+ }
149
+ if (!safeIdentifier(relation.from) || !safeIdentifier(relation.to) || !safeIdentifier(relation.type) || typeof relation.directed !== 'boolean') {
150
+ throw new Error('commitment-only snapshot relation has invalid identifiers');
151
+ }
152
+ }
153
+ }
154
+ return atom;
155
+ }
156
+
157
+ function replicationAtom(atom, includeContent) {
158
+ return includeContent ? publicAtom(atom) : projectSwarmCommitmentAtom(atom);
159
+ }
160
+ function atomLeaf(atom) { const copy = publicAtom(atom); delete copy._swarm_hash; return sha256(copy); }
161
+ function merkleRootFromLeaves(leaves) {
162
+ if (leaves.length === 0) return sha256('');
163
+ let level = [...leaves].sort();
164
+ while (level.length > 1) {
165
+ const next = [];
166
+ for (let index = 0; index < level.length; index += 2) next.push(sha256(`${level[index]}|${level[index + 1] ?? level[index]}`));
167
+ level = next;
168
+ }
169
+ return level[0];
170
+ }
171
+ export function computeSwarmMerkleRoot(atoms = []) { return merkleRootFromLeaves(atoms.map(atomLeaf)); }
172
+
173
+ export class SwarmMemoryBridge {
174
+ constructor(state = {}) {
175
+ this.swarmId = String(state.swarm_id ?? state.swarmId ?? `swarm_${randomUUID()}`);
176
+ this.agents = new Map();
177
+ this.namespaces = new Map();
178
+ for (const agent of state.agents ?? []) this.registerAgent(agent, { restoring: true });
179
+ for (const [namespace, atoms] of Object.entries(state.namespaces ?? {})) {
180
+ const store = new Map();
181
+ for (const rawAtom of atoms ?? []) {
182
+ const atom = clone(rawAtom);
183
+ atom._swarm_hash = atomLeaf(atom);
184
+ store.set(atomId(atom), atom);
185
+ }
186
+ this.namespaces.set(namespace, store);
187
+ }
188
+ }
189
+
190
+ registerAgent(input = {}, options = {}) {
191
+ const agentId = requiredString(input.agent_id ?? input.agentId, 'agent_id');
192
+ const domain = requiredString(input.swarm_id ?? input.swarmId ?? input.domain ?? this.swarmId, 'swarm_id');
193
+ if (domain !== this.swarmId) throw new Error(`agent swarm domain mismatch: ${domain}`);
194
+ const namespace = requiredString(input.namespace ?? agentId, 'namespace');
195
+ const permissionMask = normalizePermissionMask(input.permission_mask ?? input.permissionMask ?? input.permissions);
196
+ const existing = this.agents.get(agentId);
197
+ if (existing && existing.namespace !== namespace && !options.restoring) throw new Error(`agent ${agentId} is already fenced to namespace ${existing.namespace}`);
198
+ const agent = { agent_id: agentId, swarm_id: this.swarmId, namespace, permission_mask: permissionMask, permissions: permissionNames(permissionMask), registered_at: existing?.registered_at ?? input.registered_at ?? new Date().toISOString() };
199
+ this.agents.set(agentId, agent);
200
+ if (!this.namespaces.has(namespace)) this.namespaces.set(namespace, new Map());
201
+ return clone(agent);
202
+ }
203
+
204
+ requireAgent(agentId, permission, namespace) {
205
+ const agent = this.agents.get(requiredString(agentId, 'agent_id'));
206
+ if (!agent) throw new Error(`unregistered swarm agent: ${agentId}`);
207
+ if ((agent.permission_mask & SWARM_PERMISSIONS.ADMIN) !== SWARM_PERMISSIONS.ADMIN && (agent.permission_mask & permission) !== permission) throw new Error(`agent ${agent.agent_id} lacks ${permissionNames(permission)[0]} permission`);
208
+ const requestedNamespace = namespace ?? agent.namespace;
209
+ if ((agent.permission_mask & SWARM_PERMISSIONS.ADMIN) !== SWARM_PERMISSIONS.ADMIN && requestedNamespace !== agent.namespace) throw new Error(`namespace fence violation for agent ${agent.agent_id}`);
210
+ return { agent, namespace: requestedNamespace };
211
+ }
212
+
213
+ writeMemory(input = {}) {
214
+ const { agent, namespace } = this.requireAgent(input.agent_id ?? input.agentId, SWARM_PERMISSIONS.WRITE, input.namespace);
215
+ const atom = clone(input.atom ?? input.memory ?? input); delete atom.agent_id; delete atom.agentId;
216
+ const id = atomId(atom);
217
+ const fenced = { ...atom, memory_addr: id, swarm_id: this.swarmId, namespace, owner_agent_id: atom.owner_agent_id ?? agent.agent_id };
218
+ fenced._swarm_hash = atomLeaf(fenced);
219
+ this.namespaces.get(namespace).set(id, fenced);
220
+ return publicAtom(fenced);
221
+ }
222
+
223
+ ingestMemories(input = {}) {
224
+ const { agent, namespace } = this.requireAgent(input.agent_id ?? input.agentId, SWARM_PERMISSIONS.WRITE, input.namespace);
225
+ const store = this.namespaces.get(namespace); let added = 0; let unchanged = 0;
226
+ for (const rawAtom of input.atoms ?? input.memories ?? []) {
227
+ const id = atomId(rawAtom);
228
+ const atom = { ...clone(rawAtom), memory_addr: id, swarm_id: this.swarmId, namespace, owner_agent_id: rawAtom.owner_agent_id ?? agent.agent_id };
229
+ atom._swarm_hash = atomLeaf(atom);
230
+ if (store.get(id)?._swarm_hash === atom._swarm_hash) unchanged += 1; else { store.set(id, atom); added += 1; }
231
+ }
232
+ return { added, unchanged, namespace, merkle_root: computeSwarmMerkleRoot([...store.values()]) };
233
+ }
234
+
235
+ hydrateCanonicalMemories(namespace, atoms = []) {
236
+ const store = this.namespaces.get(requiredString(namespace, 'namespace'));
237
+ if (!store) throw new Error(`unknown swarm namespace: ${namespace}`);
238
+ for (const rawAtom of atoms) {
239
+ const id = atomId(rawAtom);
240
+ const atom = { ...clone(rawAtom), memory_addr: id, swarm_id: this.swarmId, namespace };
241
+ atom._swarm_hash = atomLeaf(atom);
242
+ store.set(id, atom);
243
+ }
244
+ }
245
+
246
+ readMemory(input = {}) {
247
+ const { namespace } = this.requireAgent(input.agent_id ?? input.agentId, SWARM_PERMISSIONS.READ, input.namespace);
248
+ const atom = this.namespaces.get(namespace).get(requiredString(input.memory_addr ?? input.memoryAddr ?? input.id, 'memory_addr'));
249
+ return atom ? publicAtom(atom) : null;
250
+ }
251
+ listMemories(input = {}) {
252
+ const { namespace } = this.requireAgent(input.agent_id ?? input.agentId, SWARM_PERMISSIONS.READ, input.namespace);
253
+ return [...this.namespaces.get(namespace).values()].map(publicAtom).sort((a, b) => atomId(a).localeCompare(atomId(b)));
254
+ }
255
+
256
+ graphQuery(input = {}) {
257
+ const { namespace } = this.requireAgent(input.agent_id ?? input.agentId, SWARM_PERMISSIONS.GRAPH, input.namespace);
258
+ const atoms = [...this.namespaces.get(namespace).values()]; const entities = new Map(); const edges = []; const entityAtoms = new Map();
259
+ for (const atom of atoms) {
260
+ const id = atomId(atom);
261
+ for (const entity of atomEntities(atom)) { entities.set(entity.id, entity); if (!entityAtoms.has(entity.id)) entityAtoms.set(entity.id, new Set()); entityAtoms.get(entity.id).add(id); }
262
+ for (const relation of atomRelations(atom)) edges.push({ ...relation, memory_addr: id, associative: false });
263
+ }
264
+ for (const [entityId, addresses] of entityAtoms) {
265
+ const sorted = [...addresses].sort();
266
+ for (let left = 0; left < sorted.length; left += 1) for (let right = left + 1; right < sorted.length; right += 1) edges.push({ from: sorted[left], to: sorted[right], type: 'shares_entity', entity_id: entityId, directed: false, associative: true });
267
+ }
268
+ const start = input.start ?? input.entity_id ?? input.entityId ?? input.query;
269
+ const maxDepth = Math.max(0, Math.min(12, Number(input.max_depth ?? input.maxDepth ?? 3)));
270
+ const limit = Math.max(1, Math.min(500, Number(input.limit ?? 100)));
271
+ const adjacency = new Map(); const link = (from, edge, to) => { if (!adjacency.has(from)) adjacency.set(from, []); adjacency.get(from).push({ edge, to }); };
272
+ for (const edge of edges) { link(edge.from, edge, edge.to); if (!edge.directed || input.direction !== 'out') link(edge.to, edge, edge.from); }
273
+ for (const [entityId, addresses] of entityAtoms) for (const address of addresses) { const edge = { from: entityId, to: address, type: 'mentioned_in', directed: false, associative: true }; link(entityId, edge, address); link(address, edge, entityId); }
274
+ const starts = start ? [String(start)] : [...entities.keys()].sort().slice(0, 1);
275
+ const queue = starts.map((node) => ({ node, depth: 0 })); const visited = new Map(); const traversedEdges = [];
276
+ while (queue.length && visited.size < limit) {
277
+ const current = queue.shift();
278
+ if (visited.has(current.node) && visited.get(current.node).depth <= current.depth) continue;
279
+ visited.set(current.node, current); if (current.depth >= maxDepth) continue;
280
+ for (const next of adjacency.get(current.node) ?? []) { traversedEdges.push(next.edge); queue.push({ node: next.to, depth: current.depth + 1 }); }
281
+ }
282
+ const memoryById = new Map(atoms.map((atom) => [atomId(atom), atom]));
283
+ return { schema: 'enigma.swarm_graph_query.v1', swarm_id: this.swarmId, namespace, start: start ?? null, max_depth: maxDepth,
284
+ nodes: [...visited].map(([id, visit]) => ({ id, kind: memoryById.has(id) ? 'memory' : 'entity', depth: visit.depth, ...(entities.get(id) ?? {}) })), edges: [...new Map(traversedEdges.map((edge) => [canonical(edge), edge])).values()], memories: [...visited.keys()].filter((id) => memoryById.has(id)).map((id) => publicAtom(memoryById.get(id))) };
285
+ }
286
+
287
+ clusterMemories(input = {}) {
288
+ const { namespace } = this.requireAgent(input.agent_id ?? input.agentId, SWARM_PERMISSIONS.CLUSTER, input.namespace);
289
+ const threshold = Math.max(0, Math.min(1, Number(input.threshold ?? 0.22))); const maxClusters = Math.max(1, Math.min(100, Number(input.max_clusters ?? input.maxClusters ?? 20)));
290
+ const atoms = [...this.namespaces.get(namespace).values()].sort((a, b) => atomId(a).localeCompare(atomId(b))); const clusters = [];
291
+ for (const atom of atoms) {
292
+ const atomTokens = tokens(`${atomContent(atom)} ${(atom.purpose_tags ?? atom.tags ?? []).join(' ')} ${atomEntities(atom).map((entity) => entity.label).join(' ')}`);
293
+ let best = null; for (const cluster of clusters) { const score = similarity(atomTokens, cluster.centroidTokens); if (!best || score > best.score) best = { cluster, score }; }
294
+ if (!best || (best.score < threshold && clusters.length < maxClusters)) clusters.push({ members: [atom], tokenSets: [atomTokens], centroidTokens: new Set(atomTokens) });
295
+ else {
296
+ best.cluster.members.push(atom); best.cluster.tokenSets.push(atomTokens); const counts = new Map();
297
+ for (const set of best.cluster.tokenSets) for (const token of set) counts.set(token, (counts.get(token) ?? 0) + 1);
298
+ best.cluster.centroidTokens = new Set([...counts].filter(([, count]) => count * 2 >= best.cluster.tokenSets.length).map(([token]) => token));
299
+ }
300
+ }
301
+ return { schema: 'enigma.swarm_clusters.v1', swarm_id: this.swarmId, namespace, threshold, clusters: clusters.map((cluster, index) => {
302
+ const centroidTerms = [...cluster.centroidTokens].sort(); const addresses = cluster.members.map(atomId).sort();
303
+ return { cluster_id: `cluster_${index + 1}_${sha256(addresses).slice(7, 15)}`, size: addresses.length, memory_addresses: addresses, centroid_terms: centroidTerms, centroid_fingerprint: sha256({ centroid_terms: centroidTerms, memory_addresses: addresses }) };
304
+ }) };
305
+ }
306
+
307
+ createSnapshot(input = {}) {
308
+ const { agent, namespace } = this.requireAgent(input.agent_id ?? input.agentId, SWARM_PERMISSIONS.SYNC, input.namespace);
309
+ const contentIncluded = input.include_content === true;
310
+ const atoms = [...this.namespaces.get(namespace).values()].map((atom) => replicationAtom(atom, contentIncluded)).sort((a, b) => atomId(a).localeCompare(atomId(b)));
311
+ return { schema: 'enigma.swarm_snapshot.v1', swarm_id: this.swarmId, namespace, source_agent_id: agent.agent_id, sequence: Number(input.sequence ?? 0), generated_at: input.generated_at ?? new Date().toISOString(), local_simulator: true, network_transmission: false, content_included: contentIncluded, atoms, atom_hashes: Object.fromEntries(atoms.map((atom) => [atomId(atom), atomLeaf(atom)])), merkle_root: computeSwarmMerkleRoot(atoms) };
312
+ }
313
+
314
+ sync(input = {}) {
315
+ const { namespace } = this.requireAgent(input.agent_id ?? input.agentId, SWARM_PERMISSIONS.SYNC, input.namespace);
316
+ const snapshot = input.snapshot ?? input.peer_snapshot ?? input.peerSnapshot;
317
+ if (!snapshot || snapshot.schema !== 'enigma.swarm_snapshot.v1') throw new Error('sync requires an enigma.swarm_snapshot.v1 snapshot');
318
+ if (snapshot.swarm_id !== this.swarmId) throw new Error('snapshot swarm domain mismatch');
319
+ if (snapshot.namespace !== namespace) throw new Error('snapshot namespace fence mismatch');
320
+ if (typeof snapshot.content_included !== 'boolean') throw new Error('snapshot content_included must be a boolean');
321
+ if (snapshot.content_included === true && input.allow_content !== true) throw new Error('content-bearing snapshot requires explicit allow_content authorization');
322
+ if (!Array.isArray(snapshot.atoms)) throw new Error('snapshot atoms must be an array');
323
+ const remoteAtoms = snapshot.atoms;
324
+ const contentIncluded = snapshot.content_included;
325
+ if (!contentIncluded) remoteAtoms.forEach(validateSwarmCommitmentAtom);
326
+ const remoteRoot = computeSwarmMerkleRoot(remoteAtoms);
327
+ if (remoteRoot !== snapshot.merkle_root) throw new Error('snapshot Merkle root validation failed');
328
+ const local = this.namespaces.get(namespace);
329
+ const localProjection = () => [...local.values()].map((atom) => replicationAtom(atom, contentIncluded));
330
+ const beforeRoot = computeSwarmMerkleRoot(localProjection());
331
+ const added = []; const updated = []; const unchanged = [];
332
+ for (const remoteAtom of remoteAtoms) {
333
+ const id = atomId(remoteAtom); const remoteHash = atomLeaf(remoteAtom);
334
+ if (!local.has(id)) added.push(id);
335
+ else if (atomLeaf(replicationAtom(local.get(id), contentIncluded)) !== remoteHash) updated.push(id);
336
+ else unchanged.push(id);
337
+ if (input.apply === true && !unchanged.includes(id)) {
338
+ const next = contentIncluded ? clone(remoteAtom) : { ...(local.get(id) ?? {}), ...clone(remoteAtom) };
339
+ local.set(id, { ...next, _swarm_hash: atomLeaf(next) });
340
+ }
341
+ }
342
+ const afterRoot = input.apply === true ? computeSwarmMerkleRoot(localProjection()) : beforeRoot;
343
+ return { schema: 'enigma.swarm_sync_result.v1', swarm_id: this.swarmId, namespace, local_simulator: true, network_transmission: false, validated: true, applied: input.apply === true, content_included: snapshot.content_included === true, before_merkle_root: beforeRoot, peer_merkle_root: remoteRoot, after_merkle_root: afterRoot,
344
+ diff: { added, updated, unchanged, local_only: [...local.keys()].filter((id) => !remoteAtoms.some((atom) => atomId(atom) === id)).sort() } };
345
+ }
346
+
347
+ status() {
348
+ const namespaces = [...this.namespaces].map(([namespace, atoms]) => ({ namespace, agent_count: [...this.agents.values()].filter((agent) => agent.namespace === namespace).length, memory_count: atoms.size, merkle_root: computeSwarmMerkleRoot([...atoms.values()]) })).sort((a, b) => a.namespace.localeCompare(b.namespace));
349
+ return { schema: 'enigma.swarm_status.v1', swarm_id: this.swarmId, local_simulator: true, network_transmission: false, agent_count: this.agents.size, namespace_count: namespaces.length, namespaces };
350
+ }
351
+ exportState() {
352
+ return { schema: 'enigma.swarm_bridge_state.v1', swarm_id: this.swarmId, agents: [...this.agents.values()].map(clone).sort((a, b) => a.agent_id.localeCompare(b.agent_id)), namespaces: Object.fromEntries([...this.namespaces].sort(([a], [b]) => a.localeCompare(b)).map(([namespace, atoms]) => [namespace, [...atoms.values()].map(publicAtom).sort((a, b) => atomId(a).localeCompare(atomId(b)))])) };
353
+ }
354
+ }
355
+
356
+ export function createSwarmBridge(state = {}) { return new SwarmMemoryBridge(state); }
357
+ export function enigma_graph_search(bridge, input = {}) {
358
+ if (!(bridge instanceof SwarmMemoryBridge)) throw new Error('enigma_graph_search requires a SwarmMemoryBridge');
359
+ return bridge.graphQuery(input);
360
+ }
361
+ export const enigma_graph_query = enigma_graph_search;
@@ -0,0 +1,283 @@
1
+ /// <reference types="node" />
2
+ import { EventEmitter } from 'events';
3
+
4
+ export interface MeshIdentity {
5
+ publicKey: Buffer;
6
+ secretKey: Buffer;
7
+ encryptionPublicKey: Buffer;
8
+ encryptionSecretKey: Buffer;
9
+ destination: Buffer;
10
+ destinationHex: string;
11
+ scope: string;
12
+ }
13
+
14
+ export declare function generateMeshIdentity(scope?: string): MeshIdentity;
15
+
16
+ export interface SealedPayload {
17
+ ciphertext: Buffer;
18
+ authTag: Buffer;
19
+ ephemeralPubkey: Buffer;
20
+ }
21
+
22
+ export declare function sealPayload(
23
+ plaintext: string | Buffer,
24
+ recipientX25519PubBytes: Buffer | string,
25
+ opts?: { aad?: Buffer | string; [key: string]: unknown }
26
+ ): SealedPayload;
27
+
28
+ export declare function unsealPayload(
29
+ ciphertext: Buffer,
30
+ authTag: Buffer,
31
+ ephemeralPubkey: Buffer,
32
+ recipientX25519PrivBytes: Buffer | string,
33
+ opts?: { aad?: Buffer | string; [key: string]: unknown }
34
+ ): Buffer;
35
+
36
+ export declare function signPacket(packetBuffer: Buffer, secretKey: Buffer): Buffer;
37
+ export declare function verifyPacketSignature(signedPacketBuffer: Buffer): boolean;
38
+
39
+ export declare class InMemoryBus {
40
+ nodes: Map<string, InMemoryTransport>;
41
+ constructor();
42
+ register(nodeId: string, transport: InMemoryTransport): void;
43
+ unregister(nodeId: string): void;
44
+ deliver(fromNodeId: string, toNodeId: string, packetBuffer: Buffer): void;
45
+ broadcast(fromNodeId: string, packetBuffer: Buffer): void;
46
+ }
47
+
48
+ export declare class InMemoryTransport extends EventEmitter {
49
+ id: string;
50
+ nodeId: string;
51
+ bus: InMemoryBus;
52
+ running: boolean;
53
+ constructor(nodeId: string, bus: InMemoryBus, id?: string);
54
+ start(): Promise<void>;
55
+ stop(): Promise<void>;
56
+ send(rawPacketBuffer: Buffer, peerId?: string): Promise<boolean>;
57
+ broadcast(rawPacketBuffer: Buffer): Promise<boolean>;
58
+ }
59
+
60
+ export declare class WebSocketTransport extends EventEmitter {
61
+ id: string;
62
+ port?: number;
63
+ host?: string;
64
+ running: boolean;
65
+ constructor(options?: { port?: number; host?: string; id?: string; peers?: string[] });
66
+ start(): Promise<void>;
67
+ stop(): Promise<void>;
68
+ connectToPeer(address: string): Promise<string>;
69
+ send(rawPacketBuffer: Buffer, peerId?: string): Promise<boolean>;
70
+ broadcast(rawPacketBuffer: Buffer): Promise<boolean>;
71
+ }
72
+
73
+ export declare class MeshGossipNode extends EventEmitter {
74
+ scope: string;
75
+ identity: MeshIdentity;
76
+ nodeId: string;
77
+ router: unknown;
78
+ transports: Map<string, unknown>;
79
+ discoveredPeers: Map<string, unknown>;
80
+
81
+ constructor(options?: {
82
+ identity?: MeshIdentity;
83
+ nodeId?: string;
84
+ scope?: string;
85
+ transports?: unknown[];
86
+ });
87
+
88
+ addTransport(transport: unknown): void;
89
+ start(): Promise<void>;
90
+ stop(): Promise<void>;
91
+ announce(metadata?: Record<string, unknown>): Promise<Buffer>;
92
+ sendEncryptedCapsule(
93
+ destination: Buffer | string,
94
+ recipientX25519Pub: Buffer | string,
95
+ memoryContent: string | Record<string, unknown>,
96
+ opts?: Record<string, unknown>
97
+ ): Promise<{ packetId: string; deliveredLocally: boolean; routed: boolean }>;
98
+ getPeers(): Array<Record<string, unknown>>;
99
+ broadcastZkProof(proofPayload: Record<string, unknown> | Buffer): Promise<Buffer>;
100
+ broadcastSealedSaleOffer(saleListing: Record<string, unknown> | Buffer): Promise<Buffer>;
101
+ getStatus(): Record<string, unknown>;
102
+ }
103
+
104
+ export declare const PROTOCOL_MAGIC: number;
105
+ export declare const PROTOCOL_VERSION: number;
106
+ export declare const HEADER_SIZE: number;
107
+ export declare const MAX_PACKET_SIZE: number;
108
+ export declare const DEFAULT_HOP_TTL: number;
109
+ export declare const PACKET_TYPES: Readonly<{
110
+ ANNOUNCE: number;
111
+ MEMORY_CAPSULE: number;
112
+ ZK_PROOF_GOSSIP: number;
113
+ SEALED_SALE_OFFER: number;
114
+ TREE_SYNC_REQ: number;
115
+ TREE_SYNC_RESP: number;
116
+ STORE_FORWARD_CHUNK: number;
117
+ ACK: number;
118
+ CAPABILITY_GRANT: number;
119
+ FEDERATED_QUERY_REQUEST: number;
120
+ FEDERATED_QUERY_RESPONSE: number;
121
+ CAPABILITY_REVOCATION: number;
122
+ }>;
123
+
124
+ export interface MeshPacket {
125
+ magic: number;
126
+ version: number;
127
+ type: number;
128
+ typeName: string;
129
+ flags: number;
130
+ hopTtl: number;
131
+ seqId: number;
132
+ destination: Buffer;
133
+ destinationHex: string;
134
+ senderPubkey: Buffer;
135
+ senderPubkeyHex: string;
136
+ ephemeralPubkey: Buffer;
137
+ ephemeralPubkeyHex: string;
138
+ payloadLength: number;
139
+ chunkIndex: number;
140
+ chunkTotal: number;
141
+ payload: Buffer;
142
+ authTag: Buffer;
143
+ signature: Buffer;
144
+ rawBytes: Buffer;
145
+ }
146
+
147
+ export declare function deriveDestination(
148
+ ed25519PublicKey: Buffer | Uint8Array | string,
149
+ encryptionPublicKey?: Buffer | Uint8Array | string | { x: string | bigint; y: string | bigint } | null,
150
+ scope?: string
151
+ ): Buffer;
152
+ export declare function encodePacket(packet: {
153
+ type: number;
154
+ destination: Buffer | Uint8Array;
155
+ senderPubkey: Buffer | Uint8Array;
156
+ ephemeralPubkey?: Buffer | Uint8Array;
157
+ payload: Buffer | Uint8Array;
158
+ authTag?: Buffer | Uint8Array;
159
+ signature?: Buffer | Uint8Array;
160
+ hopTtl?: number;
161
+ seqId?: number;
162
+ chunkIndex?: number;
163
+ chunkTotal?: number;
164
+ flags?: number;
165
+ }): Buffer;
166
+ export declare function decodePacket(packetBuffer: Buffer | Uint8Array): MeshPacket;
167
+ export declare function getSignableBytes(packetBuffer: Buffer): Buffer;
168
+ export declare function getPacketReplayIdentity(packetBuffer: Buffer): string;
169
+
170
+ export type FederationPacketKind =
171
+ | 'capability_grant'
172
+ | 'query_request'
173
+ | 'query_response'
174
+ | 'capability_revocation';
175
+
176
+ export interface CapabilityGrantPacketBody {
177
+ grant: Record<string, unknown>;
178
+ }
179
+
180
+ export interface FederatedQueryRequestPacketBody {
181
+ request: Record<string, unknown>;
182
+ top_k: number;
183
+ }
184
+
185
+ export interface FederatedQueryResponsePacketBody {
186
+ ok: boolean;
187
+ result: Record<string, unknown> | null;
188
+ error: string | null;
189
+ request_hash: string;
190
+ }
191
+
192
+ export interface CapabilityRevocationPacketBody {
193
+ grant_id: string;
194
+ revoked_at: string;
195
+ }
196
+
197
+ export type FederationPacketBody =
198
+ | CapabilityGrantPacketBody
199
+ | FederatedQueryRequestPacketBody
200
+ | FederatedQueryResponsePacketBody
201
+ | CapabilityRevocationPacketBody;
202
+
203
+ export interface MeshEndpoint {
204
+ publicKey: Buffer | Uint8Array | string;
205
+ encryptionPublicKey: Buffer | Uint8Array | string;
206
+ destination?: Buffer | Uint8Array | string;
207
+ destinationHex?: string;
208
+ scope: string;
209
+ }
210
+
211
+ export interface FederationPacketCreation {
212
+ packetId: string;
213
+ kind: FederationPacketKind;
214
+ correlationId: string | null;
215
+ destinationHex: string;
216
+ packetBuffer: Buffer;
217
+ }
218
+
219
+ export interface OpenFederationPacket<T = Record<string, unknown>> {
220
+ packetId: string;
221
+ correlationId: string | null;
222
+ kind: FederationPacketKind;
223
+ body: T;
224
+ createdAt: string;
225
+ sender: {
226
+ publicKey: Buffer;
227
+ encryptionPublicKey: Buffer;
228
+ destination: Buffer;
229
+ destinationHex: string;
230
+ scope: string;
231
+ };
232
+ recipientDestinationHex: string;
233
+ replayIdentity: string;
234
+ decoded: MeshPacket;
235
+ }
236
+
237
+ export declare const GHOSTMESH_FEDERATION_PACKET_SCHEMA: string;
238
+ export declare const FEDERATION_PACKET_KINDS: Readonly<{
239
+ CAPABILITY_GRANT: 'capability_grant';
240
+ QUERY_REQUEST: 'query_request';
241
+ QUERY_RESPONSE: 'query_response';
242
+ CAPABILITY_REVOCATION: 'capability_revocation';
243
+ }>;
244
+ export declare function hashFederationValue(value: unknown): string;
245
+ export declare function createFederationPacket(options: {
246
+ kind: FederationPacketKind;
247
+ body: FederationPacketBody;
248
+ senderIdentity: MeshIdentity;
249
+ senderScope?: string;
250
+ recipient: MeshEndpoint;
251
+ packetId?: string;
252
+ correlationId?: string | null;
253
+ createdAt?: string;
254
+ hopTtl?: number;
255
+ seqId?: number;
256
+ }): FederationPacketCreation;
257
+ export declare function openFederationPacket<T = Record<string, unknown>>(
258
+ packetBuffer: Buffer,
259
+ options: {
260
+ recipientIdentity: MeshIdentity;
261
+ recipientScope?: string;
262
+ expectedKind?: FederationPacketKind;
263
+ expectedCorrelationId?: string | null;
264
+ expectedSenderPublicKey?: Buffer | Uint8Array | string;
265
+ }
266
+ ): OpenFederationPacket<T>;
267
+
268
+ export declare class PacketRouter {
269
+ constructor(options?: { nodeIdentity?: MeshIdentity; nodeId?: string });
270
+ handleIncomingPacket(
271
+ rawPacket: Buffer,
272
+ fromPeerId?: string,
273
+ transportId?: string
274
+ ): Promise<{
275
+ action: 'DELIVERED' | 'ROUTED' | 'DROPPED' | 'QUEUED' | 'ANNOUNCED';
276
+ packet?: MeshPacket;
277
+ reason?: string;
278
+ nextHopPeerId?: string;
279
+ transportId?: string;
280
+ forwardBuffer?: Buffer;
281
+ }>;
282
+ getRoutingStats(): Record<string, unknown>;
283
+ }
@@ -0,0 +1,23 @@
1
+ {
2
+ "name": "@enigma/mesh",
3
+ "version": "0.1.22",
4
+ "description": "GhostMesh: Encrypted P2P Relay Layer with X25519 ECDH and Ed25519 Envelope Signatures",
5
+ "type": "module",
6
+ "main": "src/index.js",
7
+ "types": "./index.d.ts",
8
+ "files": [
9
+ "src/",
10
+ "index.d.ts"
11
+ ],
12
+ "exports": {
13
+ ".": {
14
+ "types": "./index.d.ts",
15
+ "import": "./src/index.js",
16
+ "default": "./src/index.js"
17
+ }
18
+ },
19
+ "dependencies": {
20
+ "@enigma/core": "workspace:*",
21
+ "ws": "^8.21.0"
22
+ }
23
+ }