moflo 4.0.2 → 4.0.3

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 (89) hide show
  1. package/package.json +114 -110
  2. package/v3/@claude-flow/cli/dist/src/memory/memory-bridge.js +194 -81
  3. package/v3/@claude-flow/cli/dist/src/memory/memory-initializer.js +1892 -1841
  4. package/v3/@claude-flow/memory/README.md +587 -0
  5. package/v3/@claude-flow/memory/dist/agent-memory-scope.d.ts +131 -0
  6. package/v3/@claude-flow/memory/dist/agent-memory-scope.js +223 -0
  7. package/v3/@claude-flow/memory/dist/agent-memory-scope.test.d.ts +8 -0
  8. package/v3/@claude-flow/memory/dist/agent-memory-scope.test.js +463 -0
  9. package/v3/@claude-flow/memory/dist/agentdb-adapter.d.ts +165 -0
  10. package/v3/@claude-flow/memory/dist/agentdb-adapter.js +806 -0
  11. package/v3/@claude-flow/memory/dist/agentdb-backend.d.ts +214 -0
  12. package/v3/@claude-flow/memory/dist/agentdb-backend.js +844 -0
  13. package/v3/@claude-flow/memory/dist/agentdb-backend.test.d.ts +7 -0
  14. package/v3/@claude-flow/memory/dist/agentdb-backend.test.js +258 -0
  15. package/v3/@claude-flow/memory/dist/application/commands/delete-memory.command.d.ts +65 -0
  16. package/v3/@claude-flow/memory/dist/application/commands/delete-memory.command.js +129 -0
  17. package/v3/@claude-flow/memory/dist/application/commands/store-memory.command.d.ts +48 -0
  18. package/v3/@claude-flow/memory/dist/application/commands/store-memory.command.js +72 -0
  19. package/v3/@claude-flow/memory/dist/application/index.d.ts +12 -0
  20. package/v3/@claude-flow/memory/dist/application/index.js +15 -0
  21. package/v3/@claude-flow/memory/dist/application/queries/search-memory.query.d.ts +72 -0
  22. package/v3/@claude-flow/memory/dist/application/queries/search-memory.query.js +143 -0
  23. package/v3/@claude-flow/memory/dist/application/services/memory-application-service.d.ts +121 -0
  24. package/v3/@claude-flow/memory/dist/application/services/memory-application-service.js +190 -0
  25. package/v3/@claude-flow/memory/dist/auto-memory-bridge.d.ts +226 -0
  26. package/v3/@claude-flow/memory/dist/auto-memory-bridge.js +709 -0
  27. package/v3/@claude-flow/memory/dist/auto-memory-bridge.test.d.ts +8 -0
  28. package/v3/@claude-flow/memory/dist/auto-memory-bridge.test.js +754 -0
  29. package/v3/@claude-flow/memory/dist/benchmark.test.d.ts +2 -0
  30. package/v3/@claude-flow/memory/dist/benchmark.test.js +277 -0
  31. package/v3/@claude-flow/memory/dist/cache-manager.d.ts +134 -0
  32. package/v3/@claude-flow/memory/dist/cache-manager.js +407 -0
  33. package/v3/@claude-flow/memory/dist/controller-registry.d.ts +216 -0
  34. package/v3/@claude-flow/memory/dist/controller-registry.js +893 -0
  35. package/v3/@claude-flow/memory/dist/controller-registry.test.d.ts +14 -0
  36. package/v3/@claude-flow/memory/dist/controller-registry.test.js +636 -0
  37. package/v3/@claude-flow/memory/dist/database-provider.d.ts +87 -0
  38. package/v3/@claude-flow/memory/dist/database-provider.js +410 -0
  39. package/v3/@claude-flow/memory/dist/database-provider.test.d.ts +7 -0
  40. package/v3/@claude-flow/memory/dist/database-provider.test.js +285 -0
  41. package/v3/@claude-flow/memory/dist/domain/entities/memory-entry.d.ts +143 -0
  42. package/v3/@claude-flow/memory/dist/domain/entities/memory-entry.js +226 -0
  43. package/v3/@claude-flow/memory/dist/domain/index.d.ts +11 -0
  44. package/v3/@claude-flow/memory/dist/domain/index.js +12 -0
  45. package/v3/@claude-flow/memory/dist/domain/repositories/memory-repository.interface.d.ts +102 -0
  46. package/v3/@claude-flow/memory/dist/domain/repositories/memory-repository.interface.js +11 -0
  47. package/v3/@claude-flow/memory/dist/domain/services/memory-domain-service.d.ts +105 -0
  48. package/v3/@claude-flow/memory/dist/domain/services/memory-domain-service.js +297 -0
  49. package/v3/@claude-flow/memory/dist/hnsw-index.d.ts +111 -0
  50. package/v3/@claude-flow/memory/dist/hnsw-index.js +781 -0
  51. package/v3/@claude-flow/memory/dist/hnsw-lite.d.ts +23 -0
  52. package/v3/@claude-flow/memory/dist/hnsw-lite.js +168 -0
  53. package/v3/@claude-flow/memory/dist/hybrid-backend.d.ts +245 -0
  54. package/v3/@claude-flow/memory/dist/hybrid-backend.js +569 -0
  55. package/v3/@claude-flow/memory/dist/hybrid-backend.test.d.ts +8 -0
  56. package/v3/@claude-flow/memory/dist/hybrid-backend.test.js +320 -0
  57. package/v3/@claude-flow/memory/dist/index.d.ts +208 -0
  58. package/v3/@claude-flow/memory/dist/index.js +362 -0
  59. package/v3/@claude-flow/memory/dist/infrastructure/index.d.ts +17 -0
  60. package/v3/@claude-flow/memory/dist/infrastructure/index.js +16 -0
  61. package/v3/@claude-flow/memory/dist/infrastructure/repositories/hybrid-memory-repository.d.ts +66 -0
  62. package/v3/@claude-flow/memory/dist/infrastructure/repositories/hybrid-memory-repository.js +409 -0
  63. package/v3/@claude-flow/memory/dist/learning-bridge.d.ts +137 -0
  64. package/v3/@claude-flow/memory/dist/learning-bridge.js +335 -0
  65. package/v3/@claude-flow/memory/dist/learning-bridge.test.d.ts +8 -0
  66. package/v3/@claude-flow/memory/dist/learning-bridge.test.js +578 -0
  67. package/v3/@claude-flow/memory/dist/memory-graph.d.ts +100 -0
  68. package/v3/@claude-flow/memory/dist/memory-graph.js +333 -0
  69. package/v3/@claude-flow/memory/dist/memory-graph.test.d.ts +8 -0
  70. package/v3/@claude-flow/memory/dist/memory-graph.test.js +609 -0
  71. package/v3/@claude-flow/memory/dist/migration.d.ts +68 -0
  72. package/v3/@claude-flow/memory/dist/migration.js +513 -0
  73. package/v3/@claude-flow/memory/dist/persistent-sona.d.ts +144 -0
  74. package/v3/@claude-flow/memory/dist/persistent-sona.js +332 -0
  75. package/v3/@claude-flow/memory/dist/query-builder.d.ts +211 -0
  76. package/v3/@claude-flow/memory/dist/query-builder.js +438 -0
  77. package/v3/@claude-flow/memory/dist/rvf-backend.d.ts +51 -0
  78. package/v3/@claude-flow/memory/dist/rvf-backend.js +481 -0
  79. package/v3/@claude-flow/memory/dist/rvf-learning-store.d.ts +139 -0
  80. package/v3/@claude-flow/memory/dist/rvf-learning-store.js +295 -0
  81. package/v3/@claude-flow/memory/dist/rvf-migration.d.ts +45 -0
  82. package/v3/@claude-flow/memory/dist/rvf-migration.js +254 -0
  83. package/v3/@claude-flow/memory/dist/sqlite-backend.d.ts +121 -0
  84. package/v3/@claude-flow/memory/dist/sqlite-backend.js +564 -0
  85. package/v3/@claude-flow/memory/dist/sqljs-backend.d.ts +128 -0
  86. package/v3/@claude-flow/memory/dist/sqljs-backend.js +601 -0
  87. package/v3/@claude-flow/memory/dist/types.d.ts +484 -0
  88. package/v3/@claude-flow/memory/dist/types.js +58 -0
  89. package/v3/@claude-flow/memory/package.json +46 -0
@@ -0,0 +1,335 @@
1
+ /**
2
+ * LearningBridge - Connects AutoMemoryBridge to NeuralLearningSystem
3
+ *
4
+ * When insights are recorded via AutoMemoryBridge, this module triggers
5
+ * neural learning trajectories so the system continuously improves from
6
+ * its own discoveries. The NeuralLearningSystem dependency is optional:
7
+ * when unavailable, all operations degrade gracefully to no-ops.
8
+ *
9
+ * @module @claude-flow/memory/learning-bridge
10
+ */
11
+ import { EventEmitter } from 'node:events';
12
+ const DEFAULT_CONFIG = {
13
+ sonaMode: 'balanced',
14
+ confidenceDecayRate: 0.005,
15
+ accessBoostAmount: 0.03,
16
+ maxConfidence: 1.0,
17
+ minConfidence: 0.1,
18
+ ewcLambda: 2000,
19
+ consolidationThreshold: 10,
20
+ enabled: true,
21
+ };
22
+ const MS_PER_HOUR = 3_600_000;
23
+ // ===== LearningBridge =====
24
+ /**
25
+ * Connects AutoMemoryBridge insights to the NeuralLearningSystem.
26
+ *
27
+ * @example
28
+ * ```typescript
29
+ * const bridge = new LearningBridge(memoryBackend);
30
+ * await bridge.onInsightRecorded(insight, entryId);
31
+ * await bridge.onInsightAccessed(entryId);
32
+ * const result = await bridge.consolidate();
33
+ * ```
34
+ */
35
+ export class LearningBridge extends EventEmitter {
36
+ neural = null;
37
+ backend;
38
+ config;
39
+ activeTrajectories = new Map();
40
+ stats = {
41
+ totalTrajectories: 0,
42
+ completedTrajectories: 0,
43
+ totalConsolidations: 0,
44
+ totalDecays: 0,
45
+ confidenceBoosts: 0,
46
+ totalBoostAmount: 0,
47
+ };
48
+ destroyed = false;
49
+ neuralInitPromise = null;
50
+ constructor(backend, config) {
51
+ super();
52
+ this.backend = backend;
53
+ this.config = { ...DEFAULT_CONFIG, ...config };
54
+ }
55
+ // ===== Public API =====
56
+ /**
57
+ * Notify the bridge that an insight has been recorded in AgentDB.
58
+ * Creates a learning trajectory so the neural system can track the
59
+ * insight's lifecycle.
60
+ */
61
+ async onInsightRecorded(insight, entryId) {
62
+ if (!this.config.enabled || this.destroyed)
63
+ return;
64
+ await this.initNeural();
65
+ if (this.neural) {
66
+ try {
67
+ const trajectoryId = this.neural.beginTask(insight.summary, 'general');
68
+ this.activeTrajectories.set(entryId, trajectoryId);
69
+ this.stats.totalTrajectories++;
70
+ const embedding = this.createHashEmbedding(insight.summary);
71
+ this.neural.recordStep(trajectoryId, {
72
+ action: `record:${insight.category}`,
73
+ reward: insight.confidence,
74
+ stateEmbedding: embedding,
75
+ });
76
+ }
77
+ catch {
78
+ // Neural system failure is non-fatal
79
+ }
80
+ }
81
+ this.emit('insight:learning-started', { entryId, category: insight.category });
82
+ }
83
+ /**
84
+ * Notify the bridge that an insight entry was accessed.
85
+ * Boosts confidence in the backend and records a step in the
86
+ * trajectory if one exists.
87
+ */
88
+ async onInsightAccessed(entryId) {
89
+ if (!this.config.enabled || this.destroyed)
90
+ return;
91
+ const entry = await this.backend.get(entryId);
92
+ if (!entry)
93
+ return;
94
+ const currentConf = entry.metadata?.confidence ?? 0.5;
95
+ const newConf = Math.min(this.config.maxConfidence, currentConf + this.config.accessBoostAmount);
96
+ await this.backend.update(entryId, {
97
+ metadata: { ...entry.metadata, confidence: newConf },
98
+ });
99
+ this.stats.confidenceBoosts++;
100
+ this.stats.totalBoostAmount += this.config.accessBoostAmount;
101
+ if (this.neural && this.activeTrajectories.has(entryId)) {
102
+ try {
103
+ const trajectoryId = this.activeTrajectories.get(entryId);
104
+ this.neural.recordStep(trajectoryId, {
105
+ action: 'access',
106
+ reward: this.config.accessBoostAmount,
107
+ });
108
+ }
109
+ catch {
110
+ // Non-fatal
111
+ }
112
+ }
113
+ this.emit('insight:accessed', { entryId, newConfidence: newConf });
114
+ }
115
+ /**
116
+ * Consolidate active trajectories by completing them in the neural system.
117
+ * Only runs when there are enough active trajectories to justify the cost.
118
+ */
119
+ async consolidate() {
120
+ const startTime = Date.now();
121
+ const earlyResult = {
122
+ trajectoriesCompleted: 0,
123
+ patternsLearned: 0,
124
+ entriesUpdated: 0,
125
+ durationMs: 0,
126
+ };
127
+ if (!this.config.enabled || this.destroyed) {
128
+ return earlyResult;
129
+ }
130
+ if (!this.neural || this.activeTrajectories.size < this.config.consolidationThreshold) {
131
+ earlyResult.durationMs = Date.now() - startTime;
132
+ return earlyResult;
133
+ }
134
+ let completed = 0;
135
+ let patternsLearned = 0;
136
+ const toRemove = [];
137
+ const entries = Array.from(this.activeTrajectories.entries());
138
+ for (const [entryId, trajectoryId] of entries) {
139
+ try {
140
+ await this.neural.completeTask(trajectoryId, 1.0);
141
+ completed++;
142
+ patternsLearned++;
143
+ toRemove.push(entryId);
144
+ }
145
+ catch {
146
+ // Skip failed completions
147
+ }
148
+ }
149
+ for (const key of toRemove) {
150
+ this.activeTrajectories.delete(key);
151
+ }
152
+ this.stats.completedTrajectories += completed;
153
+ this.stats.totalConsolidations++;
154
+ const result = {
155
+ trajectoriesCompleted: completed,
156
+ patternsLearned,
157
+ entriesUpdated: completed,
158
+ durationMs: Date.now() - startTime,
159
+ };
160
+ this.emit('consolidation:completed', result);
161
+ return result;
162
+ }
163
+ /**
164
+ * Apply time-based confidence decay to entries in the given namespace.
165
+ * Entries not accessed for more than one hour see their confidence reduced
166
+ * proportionally to the hours elapsed, down to minConfidence.
167
+ *
168
+ * @returns number of entries whose confidence was lowered
169
+ */
170
+ async decayConfidences(namespace) {
171
+ if (!this.config.enabled || this.destroyed)
172
+ return 0;
173
+ let entries;
174
+ try {
175
+ entries = await this.backend.query({
176
+ type: 'hybrid',
177
+ namespace,
178
+ limit: 1000,
179
+ });
180
+ }
181
+ catch {
182
+ return 0;
183
+ }
184
+ const now = Date.now();
185
+ let decayed = 0;
186
+ for (const entry of entries) {
187
+ const hoursSinceUpdate = (now - entry.updatedAt) / MS_PER_HOUR;
188
+ if (hoursSinceUpdate < 1)
189
+ continue;
190
+ const currentConf = entry.metadata?.confidence ?? 0.5;
191
+ const newConf = Math.max(this.config.minConfidence, currentConf - this.config.confidenceDecayRate * hoursSinceUpdate);
192
+ if (newConf < currentConf) {
193
+ try {
194
+ await this.backend.update(entry.id, {
195
+ metadata: { ...entry.metadata, confidence: newConf },
196
+ });
197
+ decayed++;
198
+ }
199
+ catch {
200
+ // Skip failed updates
201
+ }
202
+ }
203
+ }
204
+ this.stats.totalDecays += decayed;
205
+ return decayed;
206
+ }
207
+ /**
208
+ * Find patterns similar to the given content using the neural system.
209
+ * Returns an empty array when the neural system is unavailable.
210
+ */
211
+ async findSimilarPatterns(content, k = 5) {
212
+ if (!this.config.enabled || this.destroyed)
213
+ return [];
214
+ await this.initNeural();
215
+ if (!this.neural)
216
+ return [];
217
+ try {
218
+ const embedding = this.createHashEmbedding(content);
219
+ const results = await this.neural.findPatterns(embedding, k);
220
+ if (!Array.isArray(results))
221
+ return [];
222
+ return results.map((r) => ({
223
+ content: r.content ?? r.data ?? '',
224
+ similarity: r.similarity ?? r.score ?? 0,
225
+ category: r.category ?? 'unknown',
226
+ confidence: r.confidence ?? r.reward ?? 0,
227
+ }));
228
+ }
229
+ catch {
230
+ return [];
231
+ }
232
+ }
233
+ /** Return aggregated learning statistics */
234
+ getStats() {
235
+ const avgBoost = this.stats.confidenceBoosts > 0
236
+ ? this.stats.totalBoostAmount / this.stats.confidenceBoosts
237
+ : 0;
238
+ return {
239
+ totalTrajectories: this.stats.totalTrajectories,
240
+ completedTrajectories: this.stats.completedTrajectories,
241
+ activeTrajectories: this.activeTrajectories.size,
242
+ totalConsolidations: this.stats.totalConsolidations,
243
+ totalDecays: this.stats.totalDecays,
244
+ avgConfidenceBoost: avgBoost,
245
+ neuralAvailable: this.neural !== null,
246
+ };
247
+ }
248
+ /** Tear down the bridge. Subsequent method calls become no-ops. */
249
+ destroy() {
250
+ this.destroyed = true;
251
+ this.activeTrajectories.clear();
252
+ if (this.neural && typeof this.neural.cleanup === 'function') {
253
+ try {
254
+ this.neural.cleanup();
255
+ }
256
+ catch {
257
+ // Best-effort cleanup
258
+ }
259
+ }
260
+ this.neural = null;
261
+ this.neuralInitPromise = null;
262
+ this.removeAllListeners();
263
+ }
264
+ // ===== Private =====
265
+ /**
266
+ * Lazily attempt to load and initialize the NeuralLearningSystem.
267
+ * The promise is cached so that repeated calls do not re-attempt
268
+ * after a failure.
269
+ */
270
+ async initNeural() {
271
+ if (this.neural)
272
+ return;
273
+ if (this.neuralInitPromise) {
274
+ await this.neuralInitPromise;
275
+ return;
276
+ }
277
+ this.neuralInitPromise = this.loadNeural();
278
+ await this.neuralInitPromise;
279
+ }
280
+ async loadNeural() {
281
+ try {
282
+ if (this.config.neuralLoader) {
283
+ // Use injected loader (test / custom integrations)
284
+ this.neural = await this.config.neuralLoader();
285
+ return;
286
+ }
287
+ const mod = await import('@claude-flow/neural');
288
+ const NeuralLearningSystem = mod.NeuralLearningSystem ?? mod.default;
289
+ if (!NeuralLearningSystem)
290
+ return;
291
+ const instance = new NeuralLearningSystem({
292
+ mode: this.config.sonaMode,
293
+ ewcLambda: this.config.ewcLambda,
294
+ });
295
+ if (typeof instance.initialize === 'function') {
296
+ await instance.initialize();
297
+ }
298
+ this.neural = instance;
299
+ }
300
+ catch {
301
+ // @claude-flow/neural not installed or failed to initialize.
302
+ // This is expected in many environments; degrade silently.
303
+ this.neural = null;
304
+ }
305
+ }
306
+ /**
307
+ * Create a deterministic hash-based embedding for content.
308
+ * This is a lightweight stand-in for a real embedding model,
309
+ * suitable for pattern matching within the neural trajectory system.
310
+ */
311
+ createHashEmbedding(text, dimensions = 768) {
312
+ const embedding = new Float32Array(dimensions);
313
+ const normalized = text.toLowerCase().trim();
314
+ for (let i = 0; i < dimensions; i++) {
315
+ let hash = 0;
316
+ for (let j = 0; j < normalized.length; j++) {
317
+ hash = ((hash << 5) - hash + normalized.charCodeAt(j) * (i + 1)) | 0;
318
+ }
319
+ embedding[i] = (Math.sin(hash) + 1) / 2;
320
+ }
321
+ let norm = 0;
322
+ for (let i = 0; i < dimensions; i++) {
323
+ norm += embedding[i] * embedding[i];
324
+ }
325
+ norm = Math.sqrt(norm);
326
+ if (norm > 0) {
327
+ for (let i = 0; i < dimensions; i++) {
328
+ embedding[i] /= norm;
329
+ }
330
+ }
331
+ return embedding;
332
+ }
333
+ }
334
+ export default LearningBridge;
335
+ //# sourceMappingURL=learning-bridge.js.map
@@ -0,0 +1,8 @@
1
+ /**
2
+ * Tests for LearningBridge
3
+ *
4
+ * TDD London School (mock-first) tests for the bridge that connects
5
+ * AutoMemoryBridge insights to the NeuralLearningSystem.
6
+ */
7
+ export {};
8
+ //# sourceMappingURL=learning-bridge.test.d.ts.map