claude-flow-novice 2.0.3 → 2.0.4

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 (272) hide show
  1. package/dist/src/cli/commands/guidance.js +487 -668
  2. package/dist/src/cli/commands/index-validate.js +18 -29
  3. package/dist/src/cli/commands/mcp-troubleshoot.js +230 -282
  4. package/dist/src/cli/commands/neural-goal-init.js +92 -125
  5. package/dist/src/cli/commands/swarm-exec.js +317 -393
  6. package/dist/src/cli/commands/swarm.js +1 -1
  7. package/dist/src/cli/commands/validate-framework.js +983 -1100
  8. package/dist/src/cli/commands/validate.js +144 -223
  9. package/dist/src/cli/simple-commands/__tests__/agent.test.js +265 -277
  10. package/dist/src/cli/simple-commands/__tests__/memory.test.js +6 -7
  11. package/dist/src/cli/simple-commands/__tests__/swarm.test.js +373 -356
  12. package/dist/src/cli/simple-commands/__tests__/task.test.js +6 -7
  13. package/dist/src/cli/simple-commands/agent.js +157 -193
  14. package/dist/src/cli/simple-commands/analysis.js +336 -446
  15. package/dist/src/cli/simple-commands/automation-executor.js +1095 -1339
  16. package/dist/src/cli/simple-commands/automation.js +481 -469
  17. package/dist/src/cli/simple-commands/batch-manager.js +261 -313
  18. package/dist/src/cli/simple-commands/claude-telemetry.js +241 -267
  19. package/dist/src/cli/simple-commands/claude-track.js +68 -90
  20. package/dist/src/cli/simple-commands/concurrent-display.js +266 -320
  21. package/dist/src/cli/simple-commands/config.js +245 -290
  22. package/dist/src/cli/simple-commands/coordination.js +182 -234
  23. package/dist/src/cli/simple-commands/enhanced-ui-views.js +812 -615
  24. package/dist/src/cli/simple-commands/enhanced-webui-complete.js +922 -981
  25. package/dist/src/cli/simple-commands/fix-hook-variables.js +274 -294
  26. package/dist/src/cli/simple-commands/github/gh-coordinator.js +378 -457
  27. package/dist/src/cli/simple-commands/github/github-api.js +535 -574
  28. package/dist/src/cli/simple-commands/github/init.js +276 -303
  29. package/dist/src/cli/simple-commands/github.js +222 -247
  30. package/dist/src/cli/simple-commands/goal.js +51 -63
  31. package/dist/src/cli/simple-commands/hive-mind/auto-save-middleware.js +208 -278
  32. package/dist/src/cli/simple-commands/hive-mind/communication.js +601 -696
  33. package/dist/src/cli/simple-commands/hive-mind/core.js +907 -979
  34. package/dist/src/cli/simple-commands/hive-mind/db-optimizer.js +406 -655
  35. package/dist/src/cli/simple-commands/hive-mind/mcp-wrapper.js +1125 -1245
  36. package/dist/src/cli/simple-commands/hive-mind/memory.js +854 -1090
  37. package/dist/src/cli/simple-commands/hive-mind/performance-optimizer.js +459 -574
  38. package/dist/src/cli/simple-commands/hive-mind/performance-test.js +263 -347
  39. package/dist/src/cli/simple-commands/hive-mind/queen.js +727 -768
  40. package/dist/src/cli/simple-commands/hive-mind/session-manager.js +745 -1049
  41. package/dist/src/cli/simple-commands/hive-mind-optimize.js +227 -283
  42. package/dist/src/cli/simple-commands/hive-mind-wizard.js +174 -217
  43. package/dist/src/cli/simple-commands/hive-mind.js +1842 -2283
  44. package/dist/src/cli/simple-commands/hive.js +90 -79
  45. package/dist/src/cli/simple-commands/hook-safety.js +431 -521
  46. package/dist/src/cli/simple-commands/hooks/session-start-soul.js +203 -254
  47. package/dist/src/cli/simple-commands/hooks.js +1064 -1204
  48. package/dist/src/cli/simple-commands/init/agent-copier.js +294 -319
  49. package/dist/src/cli/simple-commands/init/batch-init.js +496 -562
  50. package/dist/src/cli/simple-commands/init/claude-commands/claude-flow-commands.js +13 -19
  51. package/dist/src/cli/simple-commands/init/claude-commands/optimized-claude-flow-commands.js +13 -19
  52. package/dist/src/cli/simple-commands/init/claude-commands/optimized-slash-commands.js +61 -88
  53. package/dist/src/cli/simple-commands/init/claude-commands/optimized-sparc-commands.js +125 -150
  54. package/dist/src/cli/simple-commands/init/claude-commands/slash-commands.js +42 -49
  55. package/dist/src/cli/simple-commands/init/claude-commands/sparc-commands.js +43 -61
  56. package/dist/src/cli/simple-commands/init/copy-revised-templates.js +141 -147
  57. package/dist/src/cli/simple-commands/init/executable-wrapper.js +31 -44
  58. package/dist/src/cli/simple-commands/init/gitignore-updater.js +64 -90
  59. package/dist/src/cli/simple-commands/init/help.js +104 -107
  60. package/dist/src/cli/simple-commands/init/hive-mind-init.js +509 -528
  61. package/dist/src/cli/simple-commands/init/index.js +1510 -1759
  62. package/dist/src/cli/simple-commands/init/performance-monitor.js +234 -317
  63. package/dist/src/cli/simple-commands/init/rollback/backup-manager.js +441 -504
  64. package/dist/src/cli/simple-commands/init/rollback/index.js +289 -364
  65. package/dist/src/cli/simple-commands/init/rollback/recovery-manager.js +652 -728
  66. package/dist/src/cli/simple-commands/init/rollback/rollback-executor.js +416 -481
  67. package/dist/src/cli/simple-commands/init/rollback/state-tracker.js +369 -448
  68. package/dist/src/cli/simple-commands/init/sparc/roo-readme.js +1 -2
  69. package/dist/src/cli/simple-commands/init/sparc/roomodes-config.js +122 -99
  70. package/dist/src/cli/simple-commands/init/sparc/workflows.js +32 -37
  71. package/dist/src/cli/simple-commands/init/sparc-structure.js +55 -62
  72. package/dist/src/cli/simple-commands/init/template-copier.js +421 -533
  73. package/dist/src/cli/simple-commands/init/templates/coordination-md.js +3 -6
  74. package/dist/src/cli/simple-commands/init/templates/enhanced-templates.js +344 -318
  75. package/dist/src/cli/simple-commands/init/templates/github-safe-enhanced.js +173 -218
  76. package/dist/src/cli/simple-commands/init/templates/github-safe.js +65 -75
  77. package/dist/src/cli/simple-commands/init/templates/memory-bank-md.js +3 -6
  78. package/dist/src/cli/simple-commands/init/templates/readme-files.js +2 -4
  79. package/dist/src/cli/simple-commands/init/templates/safe-hook-patterns.js +187 -230
  80. package/dist/src/cli/simple-commands/init/templates/sparc-modes.js +53 -80
  81. package/dist/src/cli/simple-commands/init/templates/verification-claude-md.js +101 -85
  82. package/dist/src/cli/simple-commands/init/validation/config-validator.js +283 -330
  83. package/dist/src/cli/simple-commands/init/validation/health-checker.js +495 -561
  84. package/dist/src/cli/simple-commands/init/validation/index.js +302 -358
  85. package/dist/src/cli/simple-commands/init/validation/mode-validator.js +308 -359
  86. package/dist/src/cli/simple-commands/init/validation/post-init-validator.js +389 -366
  87. package/dist/src/cli/simple-commands/init/validation/pre-init-validator.js +270 -268
  88. package/dist/src/cli/simple-commands/init/validation/test-runner.js +427 -447
  89. package/dist/src/cli/simple-commands/init.js +1 -2
  90. package/dist/src/cli/simple-commands/mcp-health.js +131 -158
  91. package/dist/src/cli/simple-commands/mcp-integration-layer.js +533 -634
  92. package/dist/src/cli/simple-commands/mcp.js +345 -400
  93. package/dist/src/cli/simple-commands/memory-consolidation.js +426 -537
  94. package/dist/src/cli/simple-commands/memory.js +247 -311
  95. package/dist/src/cli/simple-commands/migrate-hooks.js +39 -46
  96. package/dist/src/cli/simple-commands/monitor.js +294 -363
  97. package/dist/src/cli/simple-commands/neural.js +51 -65
  98. package/dist/src/cli/simple-commands/pair-autofix-only.js +538 -662
  99. package/dist/src/cli/simple-commands/pair-basic.js +528 -656
  100. package/dist/src/cli/simple-commands/pair-old.js +430 -543
  101. package/dist/src/cli/simple-commands/pair-working.js +615 -751
  102. package/dist/src/cli/simple-commands/pair.js +615 -751
  103. package/dist/src/cli/simple-commands/performance-hooks.js +83 -111
  104. package/dist/src/cli/simple-commands/performance-metrics.js +348 -433
  105. package/dist/src/cli/simple-commands/process-ui-enhanced.js +708 -787
  106. package/dist/src/cli/simple-commands/process-ui.js +230 -254
  107. package/dist/src/cli/simple-commands/realtime-update-system.js +525 -611
  108. package/dist/src/cli/simple-commands/sparc/architecture.js +1704 -1530
  109. package/dist/src/cli/simple-commands/sparc/commands.js +438 -516
  110. package/dist/src/cli/simple-commands/sparc/completion.js +1224 -1481
  111. package/dist/src/cli/simple-commands/sparc/coordinator.js +913 -978
  112. package/dist/src/cli/simple-commands/sparc/index.js +241 -298
  113. package/dist/src/cli/simple-commands/sparc/phase-base.js +314 -390
  114. package/dist/src/cli/simple-commands/sparc/pseudocode.js +965 -869
  115. package/dist/src/cli/simple-commands/sparc/refinement.js +980 -1273
  116. package/dist/src/cli/simple-commands/sparc/specification.js +559 -645
  117. package/dist/src/cli/simple-commands/sparc-modes/architect.js +1 -1
  118. package/dist/src/cli/simple-commands/sparc-modes/ask.js +1 -1
  119. package/dist/src/cli/simple-commands/sparc-modes/code.js +1 -1
  120. package/dist/src/cli/simple-commands/sparc-modes/debug.js +1 -1
  121. package/dist/src/cli/simple-commands/sparc-modes/devops.js +1 -1
  122. package/dist/src/cli/simple-commands/sparc-modes/docs-writer.js +1 -1
  123. package/dist/src/cli/simple-commands/sparc-modes/generic.js +1 -1
  124. package/dist/src/cli/simple-commands/sparc-modes/index.js +47 -55
  125. package/dist/src/cli/simple-commands/sparc-modes/integration.js +1 -1
  126. package/dist/src/cli/simple-commands/sparc-modes/mcp.js +1 -1
  127. package/dist/src/cli/simple-commands/sparc-modes/monitoring.js +1 -1
  128. package/dist/src/cli/simple-commands/sparc-modes/optimization.js +1 -1
  129. package/dist/src/cli/simple-commands/sparc-modes/security-review.js +1 -1
  130. package/dist/src/cli/simple-commands/sparc-modes/sparc-orchestrator.js +1 -1
  131. package/dist/src/cli/simple-commands/sparc-modes/spec-pseudocode.js +1 -1
  132. package/dist/src/cli/simple-commands/sparc-modes/supabase-admin.js +1 -1
  133. package/dist/src/cli/simple-commands/sparc-modes/swarm.js +101 -87
  134. package/dist/src/cli/simple-commands/sparc-modes/tdd.js +1 -1
  135. package/dist/src/cli/simple-commands/sparc-modes/tutorial.js +1 -1
  136. package/dist/src/cli/simple-commands/sparc.js +465 -493
  137. package/dist/src/cli/simple-commands/start-ui.js +108 -132
  138. package/dist/src/cli/simple-commands/start-wrapper.js +240 -268
  139. package/dist/src/cli/simple-commands/start.js +1 -1
  140. package/dist/src/cli/simple-commands/status.js +254 -275
  141. package/dist/src/cli/simple-commands/stream-chain-clean.js +128 -171
  142. package/dist/src/cli/simple-commands/stream-chain-fixed.js +61 -82
  143. package/dist/src/cli/simple-commands/stream-chain-real.js +267 -331
  144. package/dist/src/cli/simple-commands/stream-chain-working.js +211 -263
  145. package/dist/src/cli/simple-commands/stream-chain.js +260 -318
  146. package/dist/src/cli/simple-commands/stream-processor.js +290 -315
  147. package/dist/src/cli/simple-commands/swarm-executor.js +189 -222
  148. package/dist/src/cli/simple-commands/swarm-metrics-integration.js +208 -300
  149. package/dist/src/cli/simple-commands/swarm-ui.js +623 -703
  150. package/dist/src/cli/simple-commands/swarm-webui-integration.js +258 -286
  151. package/dist/src/cli/simple-commands/swarm.js +887 -1082
  152. package/dist/src/cli/simple-commands/task.js +161 -206
  153. package/dist/src/cli/simple-commands/timestamp-fix.js +59 -89
  154. package/dist/src/cli/simple-commands/token-tracker.js +258 -316
  155. package/dist/src/cli/simple-commands/tool-execution-framework.js +433 -519
  156. package/dist/src/cli/simple-commands/train-and-stream.js +275 -331
  157. package/dist/src/cli/simple-commands/training-pipeline.js +619 -725
  158. package/dist/src/cli/simple-commands/training.js +170 -227
  159. package/dist/src/cli/simple-commands/verification-hooks.js +261 -284
  160. package/dist/src/cli/simple-commands/verification-integration.js +389 -417
  161. package/dist/src/cli/simple-commands/verification-training-integration.js +486 -606
  162. package/dist/src/cli/simple-commands/verification.js +493 -513
  163. package/dist/src/cli/simple-commands/web-server.js +766 -836
  164. package/dist/src/cli/simple-commands/webui-validator.js +106 -124
  165. package/dist/src/coordination/event-bus/demo-wasm-integration.js +212 -251
  166. package/dist/src/coordination/event-bus/qe-event-bus.js +608 -748
  167. package/dist/src/coordination/event-bus/qe-event-bus.test.js +379 -454
  168. package/dist/src/coordination/iteration-tracker.js +363 -454
  169. package/dist/src/enterprise/analytics-manager.js +1135 -0
  170. package/dist/src/enterprise/audit-manager.js +1115 -0
  171. package/dist/src/enterprise/cloud-manager.js +891 -0
  172. package/dist/src/enterprise/deployment-manager.js +966 -0
  173. package/dist/src/enterprise/index.js +6 -0
  174. package/dist/src/enterprise/project-manager.js +584 -0
  175. package/dist/src/enterprise/security-manager.js +991 -0
  176. package/dist/src/index.js +1 -1
  177. package/dist/src/mcp/DEPRECATED.js +46 -60
  178. package/dist/src/mcp/fixes/mcp-error-fixes.js +115 -134
  179. package/dist/src/mcp/implementations/agent-tracker.js +114 -128
  180. package/dist/src/mcp/implementations/daa-tools.js +292 -350
  181. package/dist/src/mcp/implementations/workflow-tools.js +329 -361
  182. package/dist/src/mcp/mcp-config-manager.js +1183 -1331
  183. package/dist/src/mcp/mcp-server-novice-simplified.js +11 -17
  184. package/dist/src/mcp/mcp-server-novice.js +11 -17
  185. package/dist/src/mcp/mcp-server-sdk.js +11 -17
  186. package/dist/src/mcp/mcp-server.js +1620 -1484
  187. package/dist/src/mcp/ruv-swarm-wrapper.js +209 -239
  188. package/dist/src/memory/advanced-serializer.js +609 -589
  189. package/dist/src/memory/enhanced-examples.js +220 -305
  190. package/dist/src/memory/enhanced-memory.js +295 -336
  191. package/dist/src/memory/enhanced-session-serializer.js +408 -492
  192. package/dist/src/memory/fallback-memory-system.js +900 -1021
  193. package/dist/src/memory/fallback-store.js +93 -131
  194. package/dist/src/memory/high-performance-serialization.js +592 -730
  195. package/dist/src/memory/in-memory-store.js +161 -213
  196. package/dist/src/memory/index.js +123 -157
  197. package/dist/src/memory/lock-free-structures.js +578 -764
  198. package/dist/src/memory/memory-mapped-persistence.js +585 -766
  199. package/dist/src/memory/memory-pressure-manager.js +569 -707
  200. package/dist/src/memory/migration.js +358 -445
  201. package/dist/src/memory/shared-memory.js +641 -768
  202. package/dist/src/memory/sqlite-store.js +245 -325
  203. package/dist/src/memory/sqlite-wrapper.js +122 -151
  204. package/dist/src/memory/swarm-memory.js +470 -603
  205. package/dist/src/memory/test-example.js +126 -134
  206. package/dist/src/memory/ultra-fast-memory-store.js +622 -821
  207. package/dist/src/memory/unified-memory-manager.js +356 -437
  208. package/dist/src/migration/index.js +92 -0
  209. package/dist/src/migration/logger.js +121 -0
  210. package/dist/src/migration/migration-analyzer.js +268 -0
  211. package/dist/src/migration/migration-runner.js +522 -0
  212. package/dist/src/migration/migration-validator.js +285 -0
  213. package/dist/src/migration/progress-reporter.js +150 -0
  214. package/dist/src/migration/rollback-manager.js +321 -0
  215. package/dist/src/migration/tests/migration-system.test.js +7 -0
  216. package/dist/src/migration/types.js +3 -0
  217. package/dist/src/swarm/CodeRefactoringSwarm.js +777 -952
  218. package/dist/src/swarm/__tests__/integration.test.js +227 -0
  219. package/dist/src/swarm/__tests__/prompt-copier.test.js +344 -0
  220. package/dist/src/swarm/advanced-orchestrator.js +1095 -0
  221. package/dist/src/swarm/claude-code-interface.js +961 -0
  222. package/dist/src/swarm/claude-flow-executor.js +229 -0
  223. package/dist/src/swarm/consensus-coordinator.js +475 -0
  224. package/dist/src/swarm/coordinator.js +2993 -0
  225. package/dist/src/swarm/direct-executor.js +1180 -0
  226. package/dist/src/swarm/error-recovery/advanced-error-detection.js +691 -0
  227. package/dist/src/swarm/error-recovery/automated-recovery-workflows.js +998 -0
  228. package/dist/src/swarm/error-recovery/error-recovery-coordinator.js +1197 -0
  229. package/dist/src/swarm/error-recovery/recovery-monitoring.js +772 -0
  230. package/dist/src/swarm/error-recovery/resilience-architecture.js +714 -0
  231. package/dist/src/swarm/error-recovery/self-healing-mechanisms.js +1319 -0
  232. package/dist/src/swarm/error-recovery/test-error-recovery-effectiveness.js +808 -0
  233. package/dist/src/swarm/executor-v2.js +322 -0
  234. package/dist/src/swarm/executor.js +815 -0
  235. package/dist/src/swarm/hive-mind-integration.js +703 -0
  236. package/dist/src/swarm/index.js +41 -0
  237. package/dist/src/swarm/json-output-aggregator.js +267 -0
  238. package/dist/src/swarm/large-scale-coordinator.js +542 -0
  239. package/dist/src/swarm/mcp-integration-wrapper.js +628 -0
  240. package/dist/src/swarm/memory.js +1117 -0
  241. package/dist/src/swarm/optimizations/__tests__/optimization.test.js +348 -0
  242. package/dist/src/swarm/optimizations/async-file-manager.js +285 -0
  243. package/dist/src/swarm/optimizations/circular-buffer.js +162 -0
  244. package/dist/src/swarm/optimizations/connection-pool.js +244 -0
  245. package/dist/src/swarm/optimizations/index.js +28 -0
  246. package/dist/src/swarm/optimizations/optimized-executor.js +320 -0
  247. package/dist/src/swarm/optimizations/ttl-map.js +234 -0
  248. package/dist/src/swarm/prompt-cli.js +200 -0
  249. package/dist/src/swarm/prompt-copier-enhanced.js +202 -0
  250. package/dist/src/swarm/prompt-copier.js +381 -0
  251. package/dist/src/swarm/prompt-manager.js +295 -0
  252. package/dist/src/swarm/prompt-utils.js +310 -0
  253. package/dist/src/swarm/result-aggregator.js +718 -0
  254. package/dist/src/swarm/sparc-executor.js +1568 -0
  255. package/dist/src/swarm/strategies/auto.js +758 -0
  256. package/dist/src/swarm/strategies/base.js +128 -0
  257. package/dist/src/swarm/strategies/research.js +914 -0
  258. package/dist/src/swarm/strategies/strategy-metrics-patch.js +2 -0
  259. package/dist/src/swarm/types.js +52 -0
  260. package/dist/src/swarm/workers/copy-worker.js +56 -0
  261. package/dist/src/utils/__tests__/github-cli-safety-wrapper.test.js +332 -400
  262. package/dist/src/utils/github-cli-safe.js +56 -64
  263. package/dist/src/utils/github-cli-safety-wrapper.js +451 -546
  264. package/dist/src/utils/npx-isolated-cache.js +104 -119
  265. package/dist/src/utils/preference-manager.js +622 -652
  266. package/dist/src/utils/timezone-utils.js +86 -105
  267. package/dist/src/validators/epic-config-schema.js +214 -0
  268. package/dist/src/validators/index.js +10 -0
  269. package/dist/src/validators/swarm-init-validator.js +259 -0
  270. package/dist/src/validators/todowrite-batching-validator.js +215 -0
  271. package/dist/src/validators/todowrite-integration.js +187 -0
  272. package/package.json +2 -2
@@ -0,0 +1,1117 @@
1
+ /**
2
+ * Distributed Memory System with Cross-Agent Sharing
3
+ */ function _define_property(obj, key, value) {
4
+ if (key in obj) {
5
+ Object.defineProperty(obj, key, {
6
+ value: value,
7
+ enumerable: true,
8
+ configurable: true,
9
+ writable: true
10
+ });
11
+ } else {
12
+ obj[key] = value;
13
+ }
14
+ return obj;
15
+ }
16
+ import { EventEmitter } from "node:events";
17
+ import * as fs from "node:fs/promises";
18
+ import * as path from "node:path";
19
+ import * as crypto from "node:crypto";
20
+ import { Logger } from "../core/logger.js";
21
+ import { generateId } from "../utils/helpers.js";
22
+ export class SwarmMemoryManager extends EventEmitter {
23
+ async initialize() {
24
+ if (this.isInitialized) {
25
+ return;
26
+ }
27
+ this.logger.info('Initializing swarm memory manager...');
28
+ try {
29
+ // Initialize subsystems
30
+ await this.persistence.initialize();
31
+ await this.encryption.initialize();
32
+ await this.replication.initialize();
33
+ await this.index.initialize();
34
+ // Load existing data
35
+ await this.loadMemoryState();
36
+ // Create default partitions
37
+ await this.createDefaultPartitions();
38
+ // Start background processes
39
+ this.startBackgroundProcesses();
40
+ this.isInitialized = true;
41
+ this.emit('memory:initialized', {
42
+ namespace: this.config.namespace,
43
+ entriesLoaded: this.entries.size,
44
+ partitionsLoaded: this.partitions.size
45
+ });
46
+ this.logger.info('Swarm memory manager initialized', {
47
+ namespace: this.config.namespace,
48
+ entries: this.entries.size,
49
+ partitions: this.partitions.size
50
+ });
51
+ } catch (error) {
52
+ this.logger.error('Failed to initialize memory manager', {
53
+ error
54
+ });
55
+ throw error;
56
+ }
57
+ }
58
+ async shutdown() {
59
+ if (!this.isInitialized) {
60
+ return;
61
+ }
62
+ this.logger.info('Shutting down swarm memory manager...');
63
+ try {
64
+ // Stop background processes
65
+ this.stopBackgroundProcesses();
66
+ // Save final state
67
+ await this.saveMemoryState();
68
+ // Shutdown subsystems
69
+ await this.replication.shutdown();
70
+ await this.persistence.shutdown();
71
+ await this.encryption.shutdown();
72
+ this.isInitialized = false;
73
+ this.emit('memory:shutdown');
74
+ this.logger.info('Swarm memory manager shut down');
75
+ } catch (error) {
76
+ this.logger.error('Error during memory manager shutdown', {
77
+ error
78
+ });
79
+ }
80
+ }
81
+ // ===== MEMORY OPERATIONS =====
82
+ async store(key, value, options = {}) {
83
+ this.ensureInitialized();
84
+ const entryId = generateId('mem');
85
+ const now = new Date();
86
+ // Validate access permissions
87
+ if (options.owner) {
88
+ await this.validateAccess(options.owner, 'write', options.partition);
89
+ }
90
+ // Determine partition
91
+ const partitionName = options.partition || 'default';
92
+ const partition = await this.getOrCreatePartition(partitionName);
93
+ // Create memory entry
94
+ const entry = {
95
+ id: entryId,
96
+ key,
97
+ value: await this.serializeValue(value),
98
+ type: options.type || 'knowledge',
99
+ tags: options.tags || [],
100
+ owner: options.owner || {
101
+ id: 'system',
102
+ swarmId: '',
103
+ type: 'coordinator',
104
+ instance: 0
105
+ },
106
+ accessLevel: options.accessLevel || 'team',
107
+ createdAt: now,
108
+ updatedAt: now,
109
+ expiresAt: options.ttl ? new Date(now.getTime() + options.ttl) : undefined,
110
+ version: 1,
111
+ references: [],
112
+ dependencies: []
113
+ };
114
+ // Validate entry size
115
+ const entrySize = this.calculateEntrySize(entry);
116
+ if (entrySize > this.config.maxEntrySize) {
117
+ throw new Error(`Entry size ${entrySize} exceeds maximum ${this.config.maxEntrySize}`);
118
+ }
119
+ // Check memory limits
120
+ await this.enforceMemoryLimits(entrySize);
121
+ // Store entry
122
+ this.entries.set(entryId, entry);
123
+ partition.entries.push(entry);
124
+ // Update index
125
+ await this.index.addEntry(entry);
126
+ // Update cache
127
+ if (this.config.enableCaching) {
128
+ this.cache.set(key, entry);
129
+ }
130
+ // Replicate if enabled
131
+ if (this.config.enableDistribution) {
132
+ await this.replication.replicate(entry);
133
+ }
134
+ // Emit event
135
+ this.emit('memory:stored', {
136
+ entryId,
137
+ key,
138
+ partition: partitionName,
139
+ type: entry.type,
140
+ size: entrySize
141
+ });
142
+ this.logger.debug('Stored memory entry', {
143
+ entryId,
144
+ key,
145
+ partition: partitionName,
146
+ type: entry.type,
147
+ size: entrySize
148
+ });
149
+ return entryId;
150
+ }
151
+ async retrieve(key, options = {}) {
152
+ this.ensureInitialized();
153
+ // Try cache first
154
+ if (this.config.enableCaching) {
155
+ const cached = this.cache.get(key);
156
+ if (cached && !this.isExpired(cached)) {
157
+ if (options.requester) {
158
+ await this.validateAccess(options.requester, 'read', options.partition);
159
+ }
160
+ return options.includeMetadata ? cached : await this.deserializeValue(cached.value);
161
+ }
162
+ }
163
+ // Find entry
164
+ const entry = await this.findEntry(key, options.partition);
165
+ if (!entry) {
166
+ return null;
167
+ }
168
+ // Check expiration
169
+ if (this.isExpired(entry)) {
170
+ await this.deleteEntry(entry.id);
171
+ return null;
172
+ }
173
+ // Validate access
174
+ if (options.requester) {
175
+ await this.validateAccess(options.requester, 'read', options.partition);
176
+ }
177
+ // Update cache
178
+ if (this.config.enableCaching) {
179
+ this.cache.set(key, entry);
180
+ }
181
+ // Emit event
182
+ this.emit('memory:retrieved', {
183
+ entryId: entry.id,
184
+ key,
185
+ requester: options.requester?.id
186
+ });
187
+ return options.includeMetadata ? entry : await this.deserializeValue(entry.value);
188
+ }
189
+ async update(key, value, options = {}) {
190
+ this.ensureInitialized();
191
+ const entry = await this.findEntry(key, options.partition);
192
+ if (!entry) {
193
+ return false;
194
+ }
195
+ // Validate access
196
+ if (options.updater) {
197
+ await this.validateAccess(options.updater, 'write', options.partition);
198
+ }
199
+ // Create backup of old version
200
+ if (options.incrementVersion !== false) {
201
+ entry.previousVersions = entry.previousVersions || [];
202
+ entry.previousVersions.push({
203
+ ...entry
204
+ });
205
+ // Limit version history
206
+ if (entry.previousVersions.length > 10) {
207
+ entry.previousVersions = entry.previousVersions.slice(-10);
208
+ }
209
+ }
210
+ // Update entry
211
+ entry.value = await this.serializeValue(value);
212
+ entry.updatedAt = new Date();
213
+ if (options.incrementVersion !== false) {
214
+ entry.version++;
215
+ }
216
+ // Update index
217
+ await this.index.updateEntry(entry);
218
+ // Update cache
219
+ if (this.config.enableCaching) {
220
+ this.cache.set(key, entry);
221
+ }
222
+ // Replicate if enabled
223
+ if (this.config.enableDistribution) {
224
+ await this.replication.replicate(entry);
225
+ }
226
+ this.emit('memory:updated', {
227
+ entryId: entry.id,
228
+ key,
229
+ version: entry.version,
230
+ updater: options.updater?.id
231
+ });
232
+ return true;
233
+ }
234
+ async delete(key, options = {}) {
235
+ this.ensureInitialized();
236
+ const entry = await this.findEntry(key, options.partition);
237
+ if (!entry) {
238
+ return false;
239
+ }
240
+ // Validate access
241
+ if (options.deleter && !options.force) {
242
+ await this.validateAccess(options.deleter, 'delete', options.partition);
243
+ }
244
+ return await this.deleteEntry(entry.id);
245
+ }
246
+ async query(query) {
247
+ this.ensureInitialized();
248
+ let results = Array.from(this.entries.values());
249
+ // Apply filters
250
+ if (query.partition) {
251
+ const partition = this.partitions.get(query.partition);
252
+ if (partition) {
253
+ const entryIds = new Set(partition.entries.map((e)=>e.id));
254
+ results = results.filter((e)=>entryIds.has(e.id));
255
+ } else {
256
+ return [];
257
+ }
258
+ }
259
+ if (query.key) {
260
+ results = results.filter((e)=>e.key === query.key);
261
+ }
262
+ if (query.type) {
263
+ results = results.filter((e)=>e.type === query.type);
264
+ }
265
+ if (query.owner) {
266
+ results = results.filter((e)=>e.owner.id === query.owner.id);
267
+ }
268
+ if (query.accessLevel) {
269
+ results = results.filter((e)=>e.accessLevel === query.accessLevel);
270
+ }
271
+ if (query.tags && query.tags.length > 0) {
272
+ results = results.filter((e)=>query.tags.some((tag)=>e.tags.includes(tag)));
273
+ }
274
+ if (query.createdAfter) {
275
+ results = results.filter((e)=>e.createdAt >= query.createdAfter);
276
+ }
277
+ if (query.createdBefore) {
278
+ results = results.filter((e)=>e.createdAt <= query.createdBefore);
279
+ }
280
+ if (query.expiresAfter) {
281
+ results = results.filter((e)=>e.expiresAt && e.expiresAt >= query.expiresAfter);
282
+ }
283
+ // Filter out expired entries
284
+ results = results.filter((e)=>!this.isExpired(e));
285
+ // Sort results
286
+ if (query.sortBy) {
287
+ results.sort((a, b)=>{
288
+ let compareValue = 0;
289
+ switch(query.sortBy){
290
+ case 'createdAt':
291
+ compareValue = a.createdAt.getTime() - b.createdAt.getTime();
292
+ break;
293
+ case 'updatedAt':
294
+ compareValue = a.updatedAt.getTime() - b.updatedAt.getTime();
295
+ break;
296
+ case 'key':
297
+ compareValue = a.key.localeCompare(b.key);
298
+ break;
299
+ default:
300
+ compareValue = 0;
301
+ }
302
+ return query.sortOrder === 'desc' ? -compareValue : compareValue;
303
+ });
304
+ }
305
+ // Apply pagination
306
+ const offset = query.offset || 0;
307
+ const limit = query.limit || results.length;
308
+ results = results.slice(offset, offset + limit);
309
+ return results;
310
+ }
311
+ async search(options) {
312
+ this.ensureInitialized();
313
+ return await this.index.search(options);
314
+ }
315
+ // ===== SHARING AND COLLABORATION =====
316
+ async shareMemory(key, targetAgent, options = {}) {
317
+ this.ensureInitialized();
318
+ const entry = await this.findEntry(key, options.partition);
319
+ if (!entry) {
320
+ throw new Error(`Memory entry not found: ${key}`);
321
+ }
322
+ // Validate sharing permissions
323
+ if (options.sharer) {
324
+ await this.validateAccess(options.sharer, 'share', options.partition);
325
+ }
326
+ // Create shared copy
327
+ const sharedEntryId = generateId('shared-mem');
328
+ const sharedEntry = {
329
+ ...entry,
330
+ id: sharedEntryId,
331
+ owner: targetAgent,
332
+ accessLevel: options.accessLevel || entry.accessLevel,
333
+ createdAt: new Date(),
334
+ updatedAt: new Date(),
335
+ expiresAt: options.expiresAt,
336
+ references: [
337
+ ...entry.references,
338
+ entry.id
339
+ ]
340
+ };
341
+ // Store shared entry
342
+ this.entries.set(sharedEntryId, sharedEntry);
343
+ await this.index.addEntry(sharedEntry);
344
+ // Add to target agent's partition
345
+ const targetPartition = await this.getOrCreatePartition(`agent_${targetAgent.id}`);
346
+ targetPartition.entries.push(sharedEntry);
347
+ this.emit('memory:shared', {
348
+ originalId: entry.id,
349
+ sharedId: sharedEntryId,
350
+ key,
351
+ sharer: options.sharer?.id,
352
+ target: targetAgent.id
353
+ });
354
+ this.logger.info('Shared memory entry', {
355
+ key,
356
+ from: options.sharer?.id,
357
+ to: targetAgent.id,
358
+ sharedId: sharedEntryId
359
+ });
360
+ return sharedEntryId;
361
+ }
362
+ async broadcastMemory(key, targetAgents, options = {}) {
363
+ this.ensureInitialized();
364
+ const sharedIds = [];
365
+ for (const targetAgent of targetAgents){
366
+ try {
367
+ const sharedId = await this.shareMemory(key, targetAgent, {
368
+ ...options,
369
+ sharer: options.broadcaster
370
+ });
371
+ sharedIds.push(sharedId);
372
+ } catch (error) {
373
+ this.logger.warn('Failed to share memory with agent', {
374
+ key,
375
+ targetAgent: targetAgent.id,
376
+ error: error instanceof Error ? error.message : String(error)
377
+ });
378
+ }
379
+ }
380
+ this.emit('memory:broadcasted', {
381
+ key,
382
+ broadcaster: options.broadcaster?.id,
383
+ targets: targetAgents.map((a)=>a.id),
384
+ sharedCount: sharedIds.length
385
+ });
386
+ return sharedIds;
387
+ }
388
+ async synchronizeWith(targetNode, options = {}) {
389
+ this.ensureInitialized();
390
+ if (!this.config.enableDistribution) {
391
+ throw new Error('Distribution not enabled');
392
+ }
393
+ await this.replication.synchronizeWith(targetNode, options);
394
+ this.emit('memory:synchronized', {
395
+ targetNode,
396
+ direction: options.direction || 'bidirectional',
397
+ partition: options.partition
398
+ });
399
+ }
400
+ // ===== PARTITION MANAGEMENT =====
401
+ async createPartition(name, options = {}, skipInitCheck = false) {
402
+ if (!skipInitCheck) {
403
+ this.ensureInitialized();
404
+ }
405
+ if (this.partitions.has(name)) {
406
+ throw new Error(`Partition already exists: ${name}`);
407
+ }
408
+ const partition = {
409
+ id: generateId('partition'),
410
+ name,
411
+ type: options.type || 'knowledge',
412
+ entries: [],
413
+ maxSize: options.maxSize || this.config.maxMemorySize,
414
+ ttl: options.ttl,
415
+ readOnly: options.readOnly || false,
416
+ shared: options.shared || true,
417
+ indexed: options.indexed !== false,
418
+ compressed: options.compressed || this.config.enableCompression
419
+ };
420
+ this.partitions.set(name, partition);
421
+ this.memory.partitions.push(partition);
422
+ this.emit('memory:partition-created', {
423
+ partitionId: partition.id,
424
+ name,
425
+ type: partition.type
426
+ });
427
+ this.logger.info('Created memory partition', {
428
+ name,
429
+ type: partition.type,
430
+ maxSize: partition.maxSize
431
+ });
432
+ return partition.id;
433
+ }
434
+ async deletePartition(name, force = false) {
435
+ this.ensureInitialized();
436
+ const partition = this.partitions.get(name);
437
+ if (!partition) {
438
+ return false;
439
+ }
440
+ if (partition.entries.length > 0 && !force) {
441
+ throw new Error(`Partition ${name} contains entries. Use force=true to delete.`);
442
+ }
443
+ // Delete all entries in partition
444
+ for (const entry of partition.entries){
445
+ await this.deleteEntry(entry.id);
446
+ }
447
+ this.partitions.delete(name);
448
+ this.memory.partitions = this.memory.partitions.filter((p)=>p.id !== partition.id);
449
+ this.emit('memory:partition-deleted', {
450
+ partitionId: partition.id,
451
+ name
452
+ });
453
+ return true;
454
+ }
455
+ getPartition(name) {
456
+ return this.partitions.get(name);
457
+ }
458
+ getPartitions() {
459
+ return Array.from(this.partitions.values());
460
+ }
461
+ // ===== BACKUP AND RECOVERY =====
462
+ async createBackup() {
463
+ this.ensureInitialized();
464
+ const backup = {
465
+ timestamp: new Date(),
466
+ version: '1.0.0',
467
+ checksum: '',
468
+ metadata: {
469
+ namespace: this.config.namespace,
470
+ entryCount: this.entries.size,
471
+ partitionCount: this.partitions.size
472
+ },
473
+ entries: Array.from(this.entries.values()),
474
+ partitions: Array.from(this.partitions.values())
475
+ };
476
+ // Calculate checksum
477
+ backup.checksum = this.calculateChecksum(backup);
478
+ const backupId = generateId('backup');
479
+ await this.persistence.saveBackup(backupId, backup);
480
+ this.emit('memory:backup-created', {
481
+ backupId,
482
+ entryCount: backup.entries.length,
483
+ size: JSON.stringify(backup).length
484
+ });
485
+ return backupId;
486
+ }
487
+ async restoreFromBackup(backupId) {
488
+ this.ensureInitialized();
489
+ const backup = await this.persistence.loadBackup(backupId);
490
+ if (!backup) {
491
+ throw new Error(`Backup not found: ${backupId}`);
492
+ }
493
+ // Verify checksum
494
+ const calculatedChecksum = this.calculateChecksum(backup);
495
+ if (calculatedChecksum !== backup.checksum) {
496
+ throw new Error('Backup checksum verification failed');
497
+ }
498
+ // Clear current state
499
+ this.entries.clear();
500
+ this.partitions.clear();
501
+ await this.index.clear();
502
+ // Restore entries
503
+ for (const entry of backup.entries){
504
+ this.entries.set(entry.id, entry);
505
+ await this.index.addEntry(entry);
506
+ }
507
+ // Restore partitions
508
+ for (const partition of backup.partitions){
509
+ this.partitions.set(partition.name, partition);
510
+ }
511
+ this.memory.partitions = backup.partitions;
512
+ this.emit('memory:backup-restored', {
513
+ backupId,
514
+ entryCount: backup.entries.length,
515
+ partitionCount: backup.partitions.length
516
+ });
517
+ this.logger.info('Restored from backup', {
518
+ backupId,
519
+ entries: backup.entries.length,
520
+ partitions: backup.partitions.length
521
+ });
522
+ }
523
+ // ===== STATISTICS AND MONITORING =====
524
+ getStatistics() {
525
+ const entries = Array.from(this.entries.values());
526
+ const validEntries = entries.filter((e)=>!this.isExpired(e));
527
+ const entriesByType = {
528
+ knowledge: 0,
529
+ state: 0,
530
+ cache: 0,
531
+ logs: 0,
532
+ results: 0,
533
+ communication: 0,
534
+ configuration: 0,
535
+ metrics: 0
536
+ };
537
+ const entriesByAccess = {
538
+ private: 0,
539
+ team: 0,
540
+ swarm: 0,
541
+ public: 0,
542
+ system: 0
543
+ };
544
+ let totalSize = 0;
545
+ let oldestEntry = new Date();
546
+ let newestEntry = new Date(0);
547
+ let expiringEntries = 0;
548
+ for (const entry of validEntries){
549
+ entriesByType[entry.type]++;
550
+ entriesByAccess[entry.accessLevel]++;
551
+ const entrySize = this.calculateEntrySize(entry);
552
+ totalSize += entrySize;
553
+ if (entry.createdAt < oldestEntry) {
554
+ oldestEntry = entry.createdAt;
555
+ }
556
+ if (entry.createdAt > newestEntry) {
557
+ newestEntry = entry.createdAt;
558
+ }
559
+ if (entry.expiresAt && entry.expiresAt.getTime() - Date.now() < 24 * 60 * 60 * 1000) {
560
+ expiringEntries++;
561
+ }
562
+ }
563
+ return {
564
+ totalEntries: validEntries.length,
565
+ totalSize,
566
+ partitionCount: this.partitions.size,
567
+ entriesByType,
568
+ entriesByAccess,
569
+ averageSize: validEntries.length > 0 ? totalSize / validEntries.length : 0,
570
+ oldestEntry,
571
+ newestEntry,
572
+ expiringEntries
573
+ };
574
+ }
575
+ async exportMemory(options = {}) {
576
+ this.ensureInitialized();
577
+ let entries = Array.from(this.entries.values());
578
+ if (!options.includeExpired) {
579
+ entries = entries.filter((e)=>!this.isExpired(e));
580
+ }
581
+ if (options.filter) {
582
+ const filteredResults = await this.query(options.filter);
583
+ const filteredIds = new Set(filteredResults.map((e)=>e.id));
584
+ entries = entries.filter((e)=>filteredIds.has(e.id));
585
+ }
586
+ if (options.format === 'csv') {
587
+ return this.entriesToCSV(entries);
588
+ } else {
589
+ return JSON.stringify({
590
+ exported: new Date().toISOString(),
591
+ namespace: this.config.namespace,
592
+ entryCount: entries.length,
593
+ entries: entries.map((e)=>({
594
+ ...e,
595
+ value: e.value
596
+ }))
597
+ }, null, 2);
598
+ }
599
+ }
600
+ // ===== PRIVATE METHODS =====
601
+ ensureInitialized() {
602
+ if (!this.isInitialized) {
603
+ throw new Error('Memory manager not initialized');
604
+ }
605
+ }
606
+ async findEntry(key, partition) {
607
+ for (const entry of this.entries.values()){
608
+ if (entry.key === key) {
609
+ if (partition) {
610
+ const part = this.partitions.get(partition);
611
+ if (part && part.entries.find((e)=>e.id === entry.id)) {
612
+ return entry;
613
+ }
614
+ } else {
615
+ return entry;
616
+ }
617
+ }
618
+ }
619
+ return null;
620
+ }
621
+ async deleteEntry(entryId) {
622
+ const entry = this.entries.get(entryId);
623
+ if (!entry) {
624
+ return false;
625
+ }
626
+ // Remove from entries
627
+ this.entries.delete(entryId);
628
+ // Remove from partitions
629
+ for (const partition of this.partitions.values()){
630
+ partition.entries = partition.entries.filter((e)=>e.id !== entryId);
631
+ }
632
+ // Remove from index
633
+ await this.index.removeEntry(entryId);
634
+ // Remove from cache
635
+ if (this.config.enableCaching) {
636
+ this.cache.delete(entry.key);
637
+ }
638
+ this.emit('memory:deleted', {
639
+ entryId,
640
+ key: entry.key
641
+ });
642
+ return true;
643
+ }
644
+ isExpired(entry) {
645
+ return entry.expiresAt ? entry.expiresAt <= new Date() : false;
646
+ }
647
+ async validateAccess(agent, operation, partition) {
648
+ // Implement access control logic here
649
+ // For now, allow all operations
650
+ return;
651
+ }
652
+ async getOrCreatePartition(name) {
653
+ let partition = this.partitions.get(name);
654
+ if (!partition) {
655
+ await this.createPartition(name, {}, !this.isInitialized);
656
+ partition = this.partitions.get(name);
657
+ }
658
+ return partition;
659
+ }
660
+ async serializeValue(value) {
661
+ // Apply compression and encryption if enabled
662
+ let serialized = JSON.stringify(value);
663
+ if (this.config.enableCompression) {
664
+ // Compression would be implemented here
665
+ // For now, just return the serialized value
666
+ }
667
+ if (this.config.enableEncryption) {
668
+ serialized = await this.encryption.encrypt(serialized);
669
+ }
670
+ return serialized;
671
+ }
672
+ async deserializeValue(value) {
673
+ let deserialized = value;
674
+ if (this.config.enableEncryption) {
675
+ deserialized = await this.encryption.decrypt(deserialized);
676
+ }
677
+ if (this.config.enableCompression) {
678
+ // Decompression would be implemented here
679
+ // For now, just use the deserialized value
680
+ }
681
+ return JSON.parse(deserialized);
682
+ }
683
+ calculateEntrySize(entry) {
684
+ return JSON.stringify(entry).length;
685
+ }
686
+ async enforceMemoryLimits(newEntrySize) {
687
+ const stats = this.getStatistics();
688
+ const projectedSize = stats.totalSize + newEntrySize;
689
+ if (projectedSize > this.config.maxMemorySize) {
690
+ // Remove expired entries first
691
+ await this.cleanupExpiredEntries();
692
+ // If still over limit, remove oldest entries
693
+ const updatedStats = this.getStatistics();
694
+ if (updatedStats.totalSize + newEntrySize > this.config.maxMemorySize) {
695
+ await this.evictOldEntries(newEntrySize);
696
+ }
697
+ }
698
+ }
699
+ async cleanupExpiredEntries() {
700
+ const expiredEntries = Array.from(this.entries.values()).filter((e)=>this.isExpired(e));
701
+ for (const entry of expiredEntries){
702
+ await this.deleteEntry(entry.id);
703
+ }
704
+ if (expiredEntries.length > 0) {
705
+ this.logger.info('Cleaned up expired entries', {
706
+ count: expiredEntries.length
707
+ });
708
+ }
709
+ }
710
+ async evictOldEntries(requiredSpace) {
711
+ const entries = Array.from(this.entries.values()).filter((e)=>!this.isExpired(e)).sort((a, b)=>a.createdAt.getTime() - b.createdAt.getTime());
712
+ let freedSpace = 0;
713
+ let evictedCount = 0;
714
+ for (const entry of entries){
715
+ if (freedSpace >= requiredSpace) {
716
+ break;
717
+ }
718
+ if (entry.accessLevel !== 'system') {
719
+ // Don't evict system entries
720
+ const entrySize = this.calculateEntrySize(entry);
721
+ await this.deleteEntry(entry.id);
722
+ freedSpace += entrySize;
723
+ evictedCount++;
724
+ }
725
+ }
726
+ this.logger.warn('Evicted old entries for space', {
727
+ evictedCount,
728
+ freedSpace,
729
+ requiredSpace
730
+ });
731
+ }
732
+ calculateChecksum(backup) {
733
+ const content = JSON.stringify({
734
+ entries: backup.entries,
735
+ partitions: backup.partitions
736
+ });
737
+ return crypto.createHash('sha256').update(content).digest('hex');
738
+ }
739
+ entriesToCSV(entries) {
740
+ const headers = [
741
+ 'id',
742
+ 'key',
743
+ 'type',
744
+ 'accessLevel',
745
+ 'createdAt',
746
+ 'updatedAt',
747
+ 'owner',
748
+ 'tags'
749
+ ];
750
+ const rows = entries.map((entry)=>[
751
+ entry.id,
752
+ entry.key,
753
+ entry.type,
754
+ entry.accessLevel,
755
+ entry.createdAt.toISOString(),
756
+ entry.updatedAt.toISOString(),
757
+ entry.owner.id,
758
+ entry.tags.join(';')
759
+ ]);
760
+ return [
761
+ headers,
762
+ ...rows
763
+ ].map((row)=>row.join(',')).join('\n');
764
+ }
765
+ async loadMemoryState() {
766
+ try {
767
+ const state = await this.persistence.loadState();
768
+ if (state) {
769
+ // Load entries
770
+ for (const entry of state.entries || []){
771
+ this.entries.set(entry.id, entry);
772
+ await this.index.addEntry(entry);
773
+ }
774
+ // Load partitions
775
+ for (const partition of state.partitions || []){
776
+ this.partitions.set(partition.name, partition);
777
+ }
778
+ this.memory.partitions = state.partitions || [];
779
+ this.logger.info('Loaded memory state', {
780
+ entries: this.entries.size,
781
+ partitions: this.partitions.size
782
+ });
783
+ }
784
+ } catch (error) {
785
+ this.logger.warn('Failed to load memory state', {
786
+ error
787
+ });
788
+ }
789
+ }
790
+ async saveMemoryState() {
791
+ try {
792
+ const state = {
793
+ namespace: this.config.namespace,
794
+ timestamp: new Date(),
795
+ entries: Array.from(this.entries.values()),
796
+ partitions: Array.from(this.partitions.values())
797
+ };
798
+ await this.persistence.saveState(state);
799
+ } catch (error) {
800
+ this.logger.error('Failed to save memory state', {
801
+ error
802
+ });
803
+ }
804
+ }
805
+ async createDefaultPartitions() {
806
+ const defaultPartitions = [
807
+ {
808
+ name: 'default',
809
+ type: 'knowledge'
810
+ },
811
+ {
812
+ name: 'system',
813
+ type: 'configuration'
814
+ },
815
+ {
816
+ name: 'cache',
817
+ type: 'cache'
818
+ },
819
+ {
820
+ name: 'logs',
821
+ type: 'logs'
822
+ }
823
+ ];
824
+ for (const partition of defaultPartitions){
825
+ if (!this.partitions.has(partition.name)) {
826
+ await this.createPartition(partition.name, {
827
+ type: partition.type
828
+ }, true);
829
+ }
830
+ }
831
+ }
832
+ mergeWithDefaults(config) {
833
+ return {
834
+ namespace: 'default',
835
+ persistencePath: './swarm-memory',
836
+ maxMemorySize: 100 * 1024 * 1024,
837
+ maxEntrySize: 10 * 1024 * 1024,
838
+ defaultTtl: 24 * 60 * 60 * 1000,
839
+ enableCompression: false,
840
+ enableEncryption: false,
841
+ consistencyLevel: 'eventual',
842
+ syncInterval: 60000,
843
+ backupInterval: 3600000,
844
+ maxBackups: 24,
845
+ enableDistribution: false,
846
+ distributionNodes: [],
847
+ replicationFactor: 1,
848
+ enableCaching: true,
849
+ cacheSize: 1000,
850
+ cacheTtl: 300000,
851
+ ...config
852
+ };
853
+ }
854
+ startBackgroundProcesses() {
855
+ // Sync process
856
+ if (this.config.syncInterval > 0) {
857
+ this.syncTimer = setInterval(()=>{
858
+ this.performSync();
859
+ }, this.config.syncInterval);
860
+ }
861
+ // Backup process
862
+ if (this.config.backupInterval > 0) {
863
+ this.backupTimer = setInterval(()=>{
864
+ this.createBackup().catch((error)=>{
865
+ this.logger.error('Background backup failed', {
866
+ error
867
+ });
868
+ });
869
+ }, this.config.backupInterval);
870
+ }
871
+ // Cleanup process
872
+ this.cleanupTimer = setInterval(()=>{
873
+ this.cleanupExpiredEntries();
874
+ }, 60000); // Every minute
875
+ }
876
+ stopBackgroundProcesses() {
877
+ if (this.syncTimer) {
878
+ clearInterval(this.syncTimer);
879
+ this.syncTimer = undefined;
880
+ }
881
+ if (this.backupTimer) {
882
+ clearInterval(this.backupTimer);
883
+ this.backupTimer = undefined;
884
+ }
885
+ if (this.cleanupTimer) {
886
+ clearInterval(this.cleanupTimer);
887
+ this.cleanupTimer = undefined;
888
+ }
889
+ }
890
+ async performSync() {
891
+ try {
892
+ await this.saveMemoryState();
893
+ if (this.config.enableDistribution) {
894
+ await this.replication.sync();
895
+ }
896
+ } catch (error) {
897
+ this.logger.error('Background sync failed', {
898
+ error
899
+ });
900
+ }
901
+ }
902
+ setupEventHandlers() {
903
+ // Handle replication events
904
+ this.replication.on('entry-received', async (data)=>{
905
+ const entry = data.entry;
906
+ this.entries.set(entry.id, entry);
907
+ await this.index.addEntry(entry);
908
+ this.emit('memory:replicated', {
909
+ entryId: entry.id,
910
+ key: entry.key,
911
+ source: data.source
912
+ });
913
+ });
914
+ }
915
+ constructor(config = {}){
916
+ super(), _define_property(this, "logger", void 0), _define_property(this, "config", void 0), _define_property(this, "memory", void 0), _define_property(this, "partitions", new Map()), _define_property(this, "entries", new Map()), _define_property(this, "index", void 0), _define_property(this, "cache", void 0), _define_property(this, "replication", void 0), _define_property(this, "persistence", void 0), _define_property(this, "encryption", void 0), _define_property(this, "isInitialized", false), // Background processes
917
+ _define_property(this, "syncTimer", void 0), _define_property(this, "backupTimer", void 0), _define_property(this, "cleanupTimer", void 0);
918
+ // Configure logger based on config or default to quiet mode
919
+ const logLevel = config.logging?.level || 'error';
920
+ const logFormat = config.logging?.format || 'text';
921
+ const logDestination = config.logging?.destination || 'console';
922
+ this.logger = new Logger({
923
+ level: logLevel,
924
+ format: logFormat,
925
+ destination: logDestination
926
+ }, {
927
+ component: 'SwarmMemoryManager'
928
+ });
929
+ this.config = this.mergeWithDefaults(config);
930
+ // Initialize memory structure
931
+ this.memory = {
932
+ namespace: this.config.namespace,
933
+ partitions: [],
934
+ permissions: {
935
+ read: 'swarm',
936
+ write: 'team',
937
+ delete: 'private',
938
+ share: 'team'
939
+ },
940
+ persistent: true,
941
+ backupEnabled: true,
942
+ distributed: this.config.enableDistribution,
943
+ consistency: this.config.consistencyLevel,
944
+ cacheEnabled: this.config.enableCaching,
945
+ compressionEnabled: this.config.enableCompression
946
+ };
947
+ // Initialize subsystems
948
+ this.index = new MemoryIndex();
949
+ this.cache = new MemoryCache(this.config.cacheSize, this.config.cacheTtl);
950
+ this.replication = new MemoryReplication(this.config);
951
+ this.persistence = new MemoryPersistence(this.config);
952
+ this.encryption = new MemoryEncryption(this.config);
953
+ this.setupEventHandlers();
954
+ }
955
+ }
956
+ // ===== SUPPORTING CLASSES =====
957
+ let MemoryIndex = class MemoryIndex {
958
+ async initialize() {
959
+ // Initialize search index
960
+ }
961
+ async addEntry(entry) {
962
+ // Add entry to search index
963
+ this.indexTerms(entry.id, [
964
+ entry.key,
965
+ ...entry.tags,
966
+ entry.type
967
+ ]);
968
+ }
969
+ async updateEntry(entry) {
970
+ await this.removeEntry(entry.id);
971
+ await this.addEntry(entry);
972
+ }
973
+ async removeEntry(entryId) {
974
+ // Remove from all index terms
975
+ for (const termSet of this.index.values()){
976
+ termSet.delete(entryId);
977
+ }
978
+ }
979
+ async search(options) {
980
+ // Implement search logic
981
+ return [];
982
+ }
983
+ async clear() {
984
+ this.index.clear();
985
+ }
986
+ indexTerms(entryId, terms) {
987
+ for (const term of terms){
988
+ const normalizedTerm = term.toLowerCase();
989
+ if (!this.index.has(normalizedTerm)) {
990
+ this.index.set(normalizedTerm, new Set());
991
+ }
992
+ this.index.get(normalizedTerm).add(entryId);
993
+ }
994
+ }
995
+ constructor(){
996
+ _define_property(this, "index", new Map());
997
+ }
998
+ };
999
+ let MemoryCache = class MemoryCache {
1000
+ set(key, entry) {
1001
+ // Evict if at capacity
1002
+ if (this.cache.size >= this.maxSize) {
1003
+ const oldestKey = this.cache.keys().next().value;
1004
+ this.cache.delete(oldestKey);
1005
+ }
1006
+ this.cache.set(key, {
1007
+ entry,
1008
+ expiry: Date.now() + this.ttl
1009
+ });
1010
+ }
1011
+ get(key) {
1012
+ const cached = this.cache.get(key);
1013
+ if (!cached) {
1014
+ return null;
1015
+ }
1016
+ if (Date.now() > cached.expiry) {
1017
+ this.cache.delete(key);
1018
+ return null;
1019
+ }
1020
+ return cached.entry;
1021
+ }
1022
+ delete(key) {
1023
+ this.cache.delete(key);
1024
+ }
1025
+ constructor(maxSize, ttl){
1026
+ _define_property(this, "cache", new Map());
1027
+ _define_property(this, "maxSize", void 0);
1028
+ _define_property(this, "ttl", void 0);
1029
+ this.maxSize = maxSize;
1030
+ this.ttl = ttl;
1031
+ }
1032
+ };
1033
+ let MemoryReplication = class MemoryReplication extends EventEmitter {
1034
+ async initialize() {
1035
+ // Initialize replication
1036
+ }
1037
+ async shutdown() {
1038
+ // Shutdown replication
1039
+ }
1040
+ async replicate(entry) {
1041
+ // Replicate entry to other nodes
1042
+ }
1043
+ async synchronizeWith(targetNode, options) {
1044
+ // Synchronize with target node
1045
+ }
1046
+ async sync() {
1047
+ // Perform background sync
1048
+ }
1049
+ constructor(config){
1050
+ super(), _define_property(this, "config", void 0);
1051
+ this.config = config;
1052
+ }
1053
+ };
1054
+ let MemoryPersistence = class MemoryPersistence {
1055
+ async initialize() {
1056
+ await fs.mkdir(this.config.persistencePath, {
1057
+ recursive: true
1058
+ });
1059
+ }
1060
+ async shutdown() {
1061
+ // Shutdown persistence
1062
+ }
1063
+ async saveState(state) {
1064
+ const statePath = path.join(this.config.persistencePath, 'state.json');
1065
+ await fs.writeFile(statePath, JSON.stringify(state, null, 2));
1066
+ }
1067
+ async loadState() {
1068
+ try {
1069
+ const statePath = path.join(this.config.persistencePath, 'state.json');
1070
+ const content = await fs.readFile(statePath, 'utf-8');
1071
+ return JSON.parse(content);
1072
+ } catch (error) {
1073
+ return null;
1074
+ }
1075
+ }
1076
+ async saveBackup(backupId, backup) {
1077
+ const backupPath = path.join(this.config.persistencePath, 'backups', `${backupId}.json`);
1078
+ await fs.mkdir(path.dirname(backupPath), {
1079
+ recursive: true
1080
+ });
1081
+ await fs.writeFile(backupPath, JSON.stringify(backup, null, 2));
1082
+ }
1083
+ async loadBackup(backupId) {
1084
+ try {
1085
+ const backupPath = path.join(this.config.persistencePath, 'backups', `${backupId}.json`);
1086
+ const content = await fs.readFile(backupPath, 'utf-8');
1087
+ return JSON.parse(content);
1088
+ } catch (error) {
1089
+ return null;
1090
+ }
1091
+ }
1092
+ constructor(config){
1093
+ _define_property(this, "config", void 0);
1094
+ this.config = config;
1095
+ }
1096
+ };
1097
+ let MemoryEncryption = class MemoryEncryption {
1098
+ async initialize() {
1099
+ // Initialize encryption
1100
+ }
1101
+ async shutdown() {
1102
+ // Shutdown encryption
1103
+ }
1104
+ async encrypt(data) {
1105
+ // Implement encryption
1106
+ return data;
1107
+ }
1108
+ async decrypt(data) {
1109
+ // Implement decryption
1110
+ return data;
1111
+ }
1112
+ constructor(config){
1113
+ _define_property(this, "config", void 0);
1114
+ this.config = config;
1115
+ }
1116
+ };
1117
+ export default SwarmMemoryManager;