@claude-flow/memory 3.0.0-alpha.2 → 3.0.0-alpha.21

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 (253) hide show
  1. package/README.md +651 -42
  2. package/dist/agent-memory-scope.d.ts +131 -0
  3. package/dist/agent-memory-scope.d.ts.map +1 -0
  4. package/dist/agent-memory-scope.js +223 -0
  5. package/dist/agent-memory-scope.js.map +1 -0
  6. package/dist/agent-memory-scope.test.d.ts +8 -0
  7. package/dist/agent-memory-scope.test.d.ts.map +1 -0
  8. package/dist/agent-memory-scope.test.js +463 -0
  9. package/dist/agent-memory-scope.test.js.map +1 -0
  10. package/dist/agentdb-adapter.d.ts +82 -4
  11. package/dist/agentdb-adapter.d.ts.map +1 -1
  12. package/dist/agentdb-adapter.js +388 -17
  13. package/dist/agentdb-adapter.js.map +1 -1
  14. package/dist/agentdb-backend.d.ts +6 -0
  15. package/dist/agentdb-backend.d.ts.map +1 -1
  16. package/dist/agentdb-backend.js +89 -25
  17. package/dist/agentdb-backend.js.map +1 -1
  18. package/dist/auto-memory-bridge.d.ts +237 -0
  19. package/dist/auto-memory-bridge.d.ts.map +1 -0
  20. package/dist/auto-memory-bridge.js +758 -0
  21. package/dist/auto-memory-bridge.js.map +1 -0
  22. package/dist/auto-memory-bridge.test.d.ts +8 -0
  23. package/dist/auto-memory-bridge.test.d.ts.map +1 -0
  24. package/dist/auto-memory-bridge.test.js +849 -0
  25. package/dist/auto-memory-bridge.test.js.map +1 -0
  26. package/dist/benchmark.test.d.ts +2 -0
  27. package/dist/benchmark.test.d.ts.map +1 -0
  28. package/dist/benchmark.test.js +277 -0
  29. package/dist/benchmark.test.js.map +1 -0
  30. package/dist/consolidator.d.ts +96 -0
  31. package/dist/consolidator.d.ts.map +1 -0
  32. package/dist/consolidator.js +209 -0
  33. package/dist/consolidator.js.map +1 -0
  34. package/dist/consolidator.test.d.ts +17 -0
  35. package/dist/consolidator.test.d.ts.map +1 -0
  36. package/dist/consolidator.test.js +239 -0
  37. package/dist/consolidator.test.js.map +1 -0
  38. package/dist/controller-registry.d.ts +248 -0
  39. package/dist/controller-registry.d.ts.map +1 -0
  40. package/dist/controller-registry.js +1086 -0
  41. package/dist/controller-registry.js.map +1 -0
  42. package/dist/controller-registry.test.d.ts +14 -0
  43. package/dist/controller-registry.test.d.ts.map +1 -0
  44. package/dist/controller-registry.test.js +691 -0
  45. package/dist/controller-registry.test.js.map +1 -0
  46. package/dist/database-provider.d.ts +14 -2
  47. package/dist/database-provider.d.ts.map +1 -1
  48. package/dist/database-provider.js +63 -3
  49. package/dist/database-provider.js.map +1 -1
  50. package/dist/database-provider.test.js +56 -3
  51. package/dist/database-provider.test.js.map +1 -1
  52. package/dist/entity-tagger.d.ts +31 -0
  53. package/dist/entity-tagger.d.ts.map +1 -0
  54. package/dist/entity-tagger.js +80 -0
  55. package/dist/entity-tagger.js.map +1 -0
  56. package/dist/entity-tagger.test.d.ts +12 -0
  57. package/dist/entity-tagger.test.d.ts.map +1 -0
  58. package/dist/entity-tagger.test.js +70 -0
  59. package/dist/entity-tagger.test.js.map +1 -0
  60. package/dist/fts5.test.d.ts +13 -0
  61. package/dist/fts5.test.d.ts.map +1 -0
  62. package/dist/fts5.test.js +144 -0
  63. package/dist/fts5.test.js.map +1 -0
  64. package/dist/graceful-retrieval.test.d.ts +14 -0
  65. package/dist/graceful-retrieval.test.d.ts.map +1 -0
  66. package/dist/graceful-retrieval.test.js +192 -0
  67. package/dist/graceful-retrieval.test.js.map +1 -0
  68. package/dist/hnsw-index.d.ts +51 -0
  69. package/dist/hnsw-index.d.ts.map +1 -1
  70. package/dist/hnsw-index.js +396 -12
  71. package/dist/hnsw-index.js.map +1 -1
  72. package/dist/hnsw-persistence.test.d.ts +13 -0
  73. package/dist/hnsw-persistence.test.d.ts.map +1 -0
  74. package/dist/hnsw-persistence.test.js +208 -0
  75. package/dist/hnsw-persistence.test.js.map +1 -0
  76. package/dist/hybrid-backend.d.ts +28 -0
  77. package/dist/hybrid-backend.d.ts.map +1 -1
  78. package/dist/hybrid-backend.js +82 -4
  79. package/dist/hybrid-backend.js.map +1 -1
  80. package/dist/hybrid-backend.test.js +6 -5
  81. package/dist/hybrid-backend.test.js.map +1 -1
  82. package/dist/index.d.ts +167 -9
  83. package/dist/index.d.ts.map +1 -1
  84. package/dist/index.js +277 -30
  85. package/dist/index.js.map +1 -1
  86. package/dist/index.test.d.ts +10 -0
  87. package/dist/index.test.d.ts.map +1 -0
  88. package/dist/index.test.js +71 -0
  89. package/dist/index.test.js.map +1 -0
  90. package/dist/json-security.d.ts +12 -0
  91. package/dist/json-security.d.ts.map +1 -0
  92. package/dist/json-security.js +20 -0
  93. package/dist/json-security.js.map +1 -0
  94. package/dist/learning-bridge.d.ts +137 -0
  95. package/dist/learning-bridge.d.ts.map +1 -0
  96. package/dist/learning-bridge.js +335 -0
  97. package/dist/learning-bridge.js.map +1 -0
  98. package/dist/learning-bridge.test.d.ts +8 -0
  99. package/dist/learning-bridge.test.d.ts.map +1 -0
  100. package/dist/learning-bridge.test.js +578 -0
  101. package/dist/learning-bridge.test.js.map +1 -0
  102. package/dist/memory-graph.d.ts +100 -0
  103. package/dist/memory-graph.d.ts.map +1 -0
  104. package/dist/memory-graph.js +333 -0
  105. package/dist/memory-graph.js.map +1 -0
  106. package/dist/memory-graph.test.d.ts +8 -0
  107. package/dist/memory-graph.test.d.ts.map +1 -0
  108. package/dist/memory-graph.test.js +609 -0
  109. package/dist/memory-graph.test.js.map +1 -0
  110. package/dist/persistent-sona.d.ts +144 -0
  111. package/dist/persistent-sona.d.ts.map +1 -0
  112. package/dist/persistent-sona.js +332 -0
  113. package/dist/persistent-sona.js.map +1 -0
  114. package/dist/rvf-backend.d.ts +53 -0
  115. package/dist/rvf-backend.d.ts.map +1 -0
  116. package/dist/rvf-backend.js +643 -0
  117. package/dist/rvf-backend.js.map +1 -0
  118. package/dist/rvf-learning-store.d.ts +139 -0
  119. package/dist/rvf-learning-store.d.ts.map +1 -0
  120. package/dist/rvf-learning-store.js +295 -0
  121. package/dist/rvf-learning-store.js.map +1 -0
  122. package/dist/rvf-migration.d.ts +45 -0
  123. package/dist/rvf-migration.d.ts.map +1 -0
  124. package/dist/rvf-migration.js +254 -0
  125. package/dist/rvf-migration.js.map +1 -0
  126. package/dist/smart-retrieval.d.ts +118 -0
  127. package/dist/smart-retrieval.d.ts.map +1 -0
  128. package/dist/smart-retrieval.js +322 -0
  129. package/dist/smart-retrieval.js.map +1 -0
  130. package/dist/smart-retrieval.test.d.ts +2 -0
  131. package/dist/smart-retrieval.test.d.ts.map +1 -0
  132. package/dist/smart-retrieval.test.js +238 -0
  133. package/dist/smart-retrieval.test.js.map +1 -0
  134. package/dist/sqlite-backend.d.ts +10 -0
  135. package/dist/sqlite-backend.d.ts.map +1 -1
  136. package/dist/sqlite-backend.js +104 -8
  137. package/dist/sqlite-backend.js.map +1 -1
  138. package/dist/sqljs-backend.d.ts +9 -0
  139. package/dist/sqljs-backend.d.ts.map +1 -1
  140. package/dist/sqljs-backend.js +96 -5
  141. package/dist/sqljs-backend.js.map +1 -1
  142. package/dist/types.d.ts +3 -0
  143. package/dist/types.d.ts.map +1 -1
  144. package/package.json +21 -8
  145. package/.agentic-flow/intelligence.json +0 -16
  146. package/__tests__/coverage/base.css +0 -224
  147. package/__tests__/coverage/block-navigation.js +0 -87
  148. package/__tests__/coverage/coverage-final.json +0 -19
  149. package/__tests__/coverage/favicon.png +0 -0
  150. package/__tests__/coverage/index.html +0 -206
  151. package/__tests__/coverage/lcov-report/base.css +0 -224
  152. package/__tests__/coverage/lcov-report/block-navigation.js +0 -87
  153. package/__tests__/coverage/lcov-report/favicon.png +0 -0
  154. package/__tests__/coverage/lcov-report/index.html +0 -206
  155. package/__tests__/coverage/lcov-report/prettify.css +0 -1
  156. package/__tests__/coverage/lcov-report/prettify.js +0 -2
  157. package/__tests__/coverage/lcov-report/sort-arrow-sprite.png +0 -0
  158. package/__tests__/coverage/lcov-report/sorter.js +0 -210
  159. package/__tests__/coverage/lcov-report/src/agentdb-adapter.ts.html +0 -2737
  160. package/__tests__/coverage/lcov-report/src/agentdb-backend.ts.html +0 -3130
  161. package/__tests__/coverage/lcov-report/src/application/commands/delete-memory.command.ts.html +0 -601
  162. package/__tests__/coverage/lcov-report/src/application/commands/index.html +0 -131
  163. package/__tests__/coverage/lcov-report/src/application/commands/store-memory.command.ts.html +0 -394
  164. package/__tests__/coverage/lcov-report/src/application/queries/index.html +0 -116
  165. package/__tests__/coverage/lcov-report/src/application/queries/search-memory.query.ts.html +0 -796
  166. package/__tests__/coverage/lcov-report/src/application/services/index.html +0 -116
  167. package/__tests__/coverage/lcov-report/src/application/services/memory-application-service.ts.html +0 -793
  168. package/__tests__/coverage/lcov-report/src/cache-manager.ts.html +0 -1633
  169. package/__tests__/coverage/lcov-report/src/database-provider.ts.html +0 -1618
  170. package/__tests__/coverage/lcov-report/src/domain/entities/index.html +0 -116
  171. package/__tests__/coverage/lcov-report/src/domain/entities/memory-entry.ts.html +0 -952
  172. package/__tests__/coverage/lcov-report/src/domain/services/index.html +0 -116
  173. package/__tests__/coverage/lcov-report/src/domain/services/memory-domain-service.ts.html +0 -1294
  174. package/__tests__/coverage/lcov-report/src/hnsw-index.ts.html +0 -3124
  175. package/__tests__/coverage/lcov-report/src/hybrid-backend.ts.html +0 -2167
  176. package/__tests__/coverage/lcov-report/src/index.html +0 -266
  177. package/__tests__/coverage/lcov-report/src/infrastructure/repositories/hybrid-memory-repository.ts.html +0 -1633
  178. package/__tests__/coverage/lcov-report/src/infrastructure/repositories/index.html +0 -116
  179. package/__tests__/coverage/lcov-report/src/migration.ts.html +0 -2092
  180. package/__tests__/coverage/lcov-report/src/query-builder.ts.html +0 -1711
  181. package/__tests__/coverage/lcov-report/src/sqlite-backend.ts.html +0 -2281
  182. package/__tests__/coverage/lcov-report/src/sqljs-backend.ts.html +0 -2374
  183. package/__tests__/coverage/lcov-report/src/types.ts.html +0 -2266
  184. package/__tests__/coverage/lcov.info +0 -10238
  185. package/__tests__/coverage/prettify.css +0 -1
  186. package/__tests__/coverage/prettify.js +0 -2
  187. package/__tests__/coverage/sort-arrow-sprite.png +0 -0
  188. package/__tests__/coverage/sorter.js +0 -210
  189. package/__tests__/coverage/src/agentdb-adapter.ts.html +0 -2737
  190. package/__tests__/coverage/src/agentdb-backend.ts.html +0 -3130
  191. package/__tests__/coverage/src/application/commands/delete-memory.command.ts.html +0 -601
  192. package/__tests__/coverage/src/application/commands/index.html +0 -131
  193. package/__tests__/coverage/src/application/commands/store-memory.command.ts.html +0 -394
  194. package/__tests__/coverage/src/application/queries/index.html +0 -116
  195. package/__tests__/coverage/src/application/queries/search-memory.query.ts.html +0 -796
  196. package/__tests__/coverage/src/application/services/index.html +0 -116
  197. package/__tests__/coverage/src/application/services/memory-application-service.ts.html +0 -793
  198. package/__tests__/coverage/src/cache-manager.ts.html +0 -1633
  199. package/__tests__/coverage/src/database-provider.ts.html +0 -1618
  200. package/__tests__/coverage/src/domain/entities/index.html +0 -116
  201. package/__tests__/coverage/src/domain/entities/memory-entry.ts.html +0 -952
  202. package/__tests__/coverage/src/domain/services/index.html +0 -116
  203. package/__tests__/coverage/src/domain/services/memory-domain-service.ts.html +0 -1294
  204. package/__tests__/coverage/src/hnsw-index.ts.html +0 -3124
  205. package/__tests__/coverage/src/hybrid-backend.ts.html +0 -2167
  206. package/__tests__/coverage/src/index.html +0 -266
  207. package/__tests__/coverage/src/infrastructure/repositories/hybrid-memory-repository.ts.html +0 -1633
  208. package/__tests__/coverage/src/infrastructure/repositories/index.html +0 -116
  209. package/__tests__/coverage/src/migration.ts.html +0 -2092
  210. package/__tests__/coverage/src/query-builder.ts.html +0 -1711
  211. package/__tests__/coverage/src/sqlite-backend.ts.html +0 -2281
  212. package/__tests__/coverage/src/sqljs-backend.ts.html +0 -2374
  213. package/__tests__/coverage/src/types.ts.html +0 -2266
  214. package/benchmarks/cache-hit-rate.bench.ts +0 -535
  215. package/benchmarks/hnsw-indexing.bench.ts +0 -552
  216. package/benchmarks/memory-write.bench.ts +0 -469
  217. package/benchmarks/vector-search.bench.ts +0 -449
  218. package/docs/AGENTDB-INTEGRATION.md +0 -388
  219. package/docs/CROSS_PLATFORM.md +0 -505
  220. package/docs/WINDOWS_SUPPORT.md +0 -422
  221. package/examples/agentdb-example.ts +0 -345
  222. package/examples/cross-platform-usage.ts +0 -326
  223. package/framework/benchmark.ts +0 -112
  224. package/src/agentdb-adapter.ts +0 -884
  225. package/src/agentdb-backend.test.ts +0 -339
  226. package/src/agentdb-backend.ts +0 -1016
  227. package/src/application/commands/delete-memory.command.ts +0 -172
  228. package/src/application/commands/store-memory.command.ts +0 -103
  229. package/src/application/index.ts +0 -36
  230. package/src/application/queries/search-memory.query.ts +0 -237
  231. package/src/application/services/memory-application-service.ts +0 -236
  232. package/src/cache-manager.ts +0 -516
  233. package/src/database-provider.test.ts +0 -364
  234. package/src/database-provider.ts +0 -511
  235. package/src/domain/entities/memory-entry.ts +0 -289
  236. package/src/domain/index.ts +0 -35
  237. package/src/domain/repositories/memory-repository.interface.ts +0 -120
  238. package/src/domain/services/memory-domain-service.ts +0 -403
  239. package/src/hnsw-index.ts +0 -1013
  240. package/src/hybrid-backend.test.ts +0 -399
  241. package/src/hybrid-backend.ts +0 -694
  242. package/src/index.ts +0 -515
  243. package/src/infrastructure/index.ts +0 -23
  244. package/src/infrastructure/repositories/hybrid-memory-repository.ts +0 -516
  245. package/src/migration.ts +0 -669
  246. package/src/query-builder.ts +0 -542
  247. package/src/sqlite-backend.ts +0 -732
  248. package/src/sqljs-backend.ts +0 -763
  249. package/src/types.ts +0 -727
  250. package/tmp.json +0 -0
  251. package/tsconfig.json +0 -9
  252. package/tsconfig.tsbuildinfo +0 -1
  253. package/verify-cross-platform.ts +0 -170
@@ -0,0 +1,758 @@
1
+ /**
2
+ * AutoMemoryBridge - Bidirectional sync between Claude Code Auto Memory and AgentDB
3
+ *
4
+ * Per ADR-048: Bridges Claude Code's auto memory (markdown files at
5
+ * ~/.claude/projects/<project>/memory/) with claude-flow's unified memory
6
+ * system (AgentDB + HNSW).
7
+ *
8
+ * Auto memory files are human-readable markdown that Claude loads into its
9
+ * system prompt. MEMORY.md (first 200 lines) is the entrypoint; topic files
10
+ * store detailed notes and are read on demand.
11
+ *
12
+ * @module @claude-flow/memory/auto-memory-bridge
13
+ */
14
+ import { createHash } from 'node:crypto';
15
+ import { EventEmitter } from 'node:events';
16
+ import * as fs from 'node:fs/promises';
17
+ import { existsSync, readFileSync, readdirSync } from 'node:fs';
18
+ import * as path from 'node:path';
19
+ import { createDefaultEntry, } from './types.js';
20
+ import { LearningBridge } from './learning-bridge.js';
21
+ import { MemoryGraph } from './memory-graph.js';
22
+ // ===== Constants =====
23
+ const DEFAULT_TOPIC_MAPPING = {
24
+ 'project-patterns': 'patterns.md',
25
+ 'debugging': 'debugging.md',
26
+ 'architecture': 'architecture.md',
27
+ 'performance': 'performance.md',
28
+ 'security': 'security.md',
29
+ 'preferences': 'preferences.md',
30
+ 'swarm-results': 'swarm-results.md',
31
+ };
32
+ const CATEGORY_LABELS = {
33
+ 'project-patterns': 'Project Patterns',
34
+ 'debugging': 'Debugging',
35
+ 'architecture': 'Architecture',
36
+ 'performance': 'Performance',
37
+ 'security': 'Security',
38
+ 'preferences': 'Preferences',
39
+ 'swarm-results': 'Swarm Results',
40
+ };
41
+ const DEFAULT_CONFIG = {
42
+ memoryDir: '',
43
+ workingDir: process.env.CLAUDE_FLOW_CWD || process.cwd(),
44
+ maxIndexLines: 180,
45
+ topicMapping: DEFAULT_TOPIC_MAPPING,
46
+ syncMode: 'on-session-end',
47
+ syncIntervalMs: 60_000,
48
+ minConfidence: 0.7,
49
+ maxTopicFileLines: 500,
50
+ pruneStrategy: 'confidence-weighted',
51
+ };
52
+ // ===== AutoMemoryBridge =====
53
+ /**
54
+ * Bidirectional bridge between Claude Code auto memory and AgentDB.
55
+ *
56
+ * @example
57
+ * ```typescript
58
+ * const bridge = new AutoMemoryBridge(memoryBackend, {
59
+ * workingDir: '/workspaces/my-project',
60
+ * });
61
+ *
62
+ * // Record an insight
63
+ * await bridge.recordInsight({
64
+ * category: 'debugging',
65
+ * summary: 'HNSW index requires initialization before search',
66
+ * source: 'agent:tester',
67
+ * confidence: 0.95,
68
+ * });
69
+ *
70
+ * // Sync to auto memory files
71
+ * await bridge.syncToAutoMemory();
72
+ *
73
+ * // Import auto memory into AgentDB
74
+ * await bridge.importFromAutoMemory();
75
+ * ```
76
+ */
77
+ export class AutoMemoryBridge extends EventEmitter {
78
+ config;
79
+ backend;
80
+ lastSyncTime = 0;
81
+ syncTimer = null;
82
+ insights = [];
83
+ /** Track AgentDB keys of insights already written to files during this session */
84
+ syncedInsightKeys = new Set();
85
+ /** Monotonic counter to prevent key collisions within the same ms */
86
+ insightCounter = 0;
87
+ /** Optional learning bridge (ADR-049) */
88
+ learningBridge;
89
+ /** Optional knowledge graph (ADR-049) */
90
+ memoryGraph;
91
+ constructor(backend, config = {}) {
92
+ super();
93
+ this.backend = backend;
94
+ this.config = {
95
+ ...DEFAULT_CONFIG,
96
+ ...config,
97
+ topicMapping: {
98
+ ...DEFAULT_TOPIC_MAPPING,
99
+ ...(config.topicMapping || {}),
100
+ },
101
+ };
102
+ if (!this.config.memoryDir) {
103
+ this.config.memoryDir = resolveAutoMemoryDir(this.config.workingDir);
104
+ }
105
+ if (this.config.syncMode === 'periodic' && this.config.syncIntervalMs > 0) {
106
+ this.startPeriodicSync();
107
+ }
108
+ // ADR-049: Initialize optional learning bridge and knowledge graph
109
+ if (config.learning) {
110
+ this.learningBridge = new LearningBridge(backend, config.learning);
111
+ }
112
+ if (config.graph) {
113
+ this.memoryGraph = new MemoryGraph(config.graph);
114
+ }
115
+ }
116
+ /** Get the resolved auto memory directory path */
117
+ getMemoryDir() {
118
+ return this.config.memoryDir;
119
+ }
120
+ /** Get the path to MEMORY.md */
121
+ getIndexPath() {
122
+ return path.join(this.config.memoryDir, 'MEMORY.md');
123
+ }
124
+ /** Get the path to a topic file */
125
+ getTopicPath(category) {
126
+ const filename = this.config.topicMapping[category] || `${category}.md`;
127
+ return path.join(this.config.memoryDir, filename);
128
+ }
129
+ /**
130
+ * Record a memory insight.
131
+ * Stores in the in-memory buffer and optionally writes immediately.
132
+ */
133
+ async recordInsight(insight) {
134
+ this.insights.push(insight);
135
+ // Store in AgentDB
136
+ const key = await this.storeInsightInAgentDB(insight);
137
+ this.syncedInsightKeys.add(key);
138
+ // If sync-on-write, write immediately to files
139
+ if (this.config.syncMode === 'on-write') {
140
+ await this.writeInsightToFiles(insight);
141
+ }
142
+ // ADR-049: Notify learning bridge
143
+ if (this.learningBridge) {
144
+ await this.learningBridge.onInsightRecorded(insight, key);
145
+ }
146
+ this.emit('insight:recorded', insight);
147
+ }
148
+ /**
149
+ * Sync high-confidence AgentDB entries to auto memory files.
150
+ * Called on session-end or periodically.
151
+ */
152
+ async syncToAutoMemory() {
153
+ const startTime = Date.now();
154
+ const errors = [];
155
+ const updatedCategories = new Set();
156
+ try {
157
+ // ADR-049: Consolidate learning trajectories before syncing
158
+ if (this.learningBridge) {
159
+ await this.learningBridge.consolidate();
160
+ }
161
+ // Ensure directory exists
162
+ await this.ensureMemoryDir();
163
+ // Snapshot and clear the buffer atomically to avoid race conditions
164
+ const buffered = this.insights.splice(0, this.insights.length);
165
+ // Flush buffered insights to files
166
+ for (const insight of buffered) {
167
+ try {
168
+ await this.writeInsightToFiles(insight);
169
+ updatedCategories.add(insight.category);
170
+ }
171
+ catch (err) {
172
+ errors.push(`Failed to write insight: ${err.message}`);
173
+ }
174
+ }
175
+ // Query AgentDB for high-confidence entries since last sync,
176
+ // skipping entries we already wrote from the buffer above
177
+ const entries = await this.queryRecentInsights();
178
+ for (const entry of entries) {
179
+ const entryKey = entry.key;
180
+ if (this.syncedInsightKeys.has(entryKey))
181
+ continue;
182
+ try {
183
+ const category = this.classifyEntry(entry);
184
+ await this.appendToTopicFile(category, entry);
185
+ updatedCategories.add(category);
186
+ this.syncedInsightKeys.add(entryKey);
187
+ }
188
+ catch (err) {
189
+ errors.push(`Failed to sync entry ${entry.id}: ${err.message}`);
190
+ }
191
+ }
192
+ // Curate MEMORY.md index
193
+ await this.curateIndex();
194
+ const synced = buffered.length + entries.length;
195
+ this.lastSyncTime = Date.now();
196
+ // Prevent unbounded growth of syncedInsightKeys
197
+ if (this.syncedInsightKeys.size > 10_000) {
198
+ const keys = [...this.syncedInsightKeys];
199
+ this.syncedInsightKeys = new Set(keys.slice(keys.length - 5_000));
200
+ }
201
+ const result = {
202
+ synced,
203
+ categories: [...updatedCategories],
204
+ durationMs: Date.now() - startTime,
205
+ errors,
206
+ };
207
+ this.emit('sync:completed', result);
208
+ return result;
209
+ }
210
+ catch (err) {
211
+ errors.push(`Sync failed: ${err.message}`);
212
+ this.emit('sync:failed', { error: err });
213
+ return {
214
+ synced: 0,
215
+ categories: [],
216
+ durationMs: Date.now() - startTime,
217
+ errors,
218
+ };
219
+ }
220
+ }
221
+ /**
222
+ * Import auto memory files into AgentDB.
223
+ * Called on session-start to hydrate AgentDB with previous learnings.
224
+ * Uses bulk insert for efficiency.
225
+ */
226
+ async importFromAutoMemory() {
227
+ const startTime = Date.now();
228
+ const memoryDir = this.config.memoryDir;
229
+ if (!existsSync(memoryDir)) {
230
+ return { imported: 0, skipped: 0, files: [], durationMs: 0 };
231
+ }
232
+ let imported = 0;
233
+ let skipped = 0;
234
+ const processedFiles = [];
235
+ const files = readdirSync(memoryDir).filter(f => f.endsWith('.md'));
236
+ // Pre-fetch existing content hashes to avoid N queries
237
+ const existingHashes = await this.fetchExistingContentHashes();
238
+ // Batch entries for bulk insert
239
+ const batch = [];
240
+ for (const file of files) {
241
+ const filePath = path.join(memoryDir, file);
242
+ const content = await fs.readFile(filePath, 'utf-8');
243
+ const entries = parseMarkdownEntries(content);
244
+ for (const entry of entries) {
245
+ const contentHash = hashContent(entry.content);
246
+ if (existingHashes.has(contentHash)) {
247
+ skipped++;
248
+ continue;
249
+ }
250
+ const input = {
251
+ key: `auto-memory:${file}:${entry.heading}`,
252
+ content: entry.content,
253
+ namespace: 'auto-memory',
254
+ type: 'semantic',
255
+ tags: ['auto-memory', file.replace('.md', '')],
256
+ metadata: {
257
+ sourceFile: file,
258
+ heading: entry.heading,
259
+ importedAt: new Date().toISOString(),
260
+ contentHash,
261
+ },
262
+ };
263
+ batch.push(createDefaultEntry(input));
264
+ existingHashes.add(contentHash);
265
+ imported++;
266
+ }
267
+ processedFiles.push(file);
268
+ }
269
+ // Bulk insert all at once
270
+ if (batch.length > 0) {
271
+ await this.backend.bulkInsert(batch);
272
+ }
273
+ // ADR-049: Build knowledge graph from imported entries
274
+ if (this.memoryGraph && batch.length > 0) {
275
+ await this.memoryGraph.buildFromBackend(this.backend, 'auto-memory');
276
+ }
277
+ const result = {
278
+ imported,
279
+ skipped,
280
+ files: processedFiles,
281
+ durationMs: Date.now() - startTime,
282
+ };
283
+ this.emit('import:completed', result);
284
+ return result;
285
+ }
286
+ /**
287
+ * Curate MEMORY.md to stay under the line limit.
288
+ * Groups entries by category and prunes low-confidence items.
289
+ */
290
+ async curateIndex() {
291
+ await this.ensureMemoryDir();
292
+ // Collect summaries from all topic files
293
+ const sections = {};
294
+ for (const [category, filename] of Object.entries(this.config.topicMapping)) {
295
+ const topicPath = path.join(this.config.memoryDir, filename);
296
+ if (existsSync(topicPath)) {
297
+ const content = await fs.readFile(topicPath, 'utf-8');
298
+ const summaries = extractSummaries(content);
299
+ if (summaries.length > 0) {
300
+ sections[category] = summaries;
301
+ }
302
+ }
303
+ }
304
+ // Fix for #1556: if no topic files matched (e.g. the memory folder uses
305
+ // Claude Code's native `<type>_<topic>.md` convention rather than the
306
+ // hardcoded DEFAULT_TOPIC_MAPPING filenames), do NOT overwrite the
307
+ // existing MEMORY.md with a one-line stub. A `curate` operation must be
308
+ // non-destructive when there is nothing to curate.
309
+ if (Object.keys(sections).length === 0) {
310
+ this.emit('index:skipped', { reason: 'no-matching-topic-files' });
311
+ return;
312
+ }
313
+ // ADR-049: Use graph PageRank to prioritize sections
314
+ let sectionOrder;
315
+ if (this.memoryGraph) {
316
+ const topNodes = this.memoryGraph.getTopNodes(20);
317
+ const categoryCounts = new Map();
318
+ for (const node of topNodes) {
319
+ const cat = node.community || 'general';
320
+ categoryCounts.set(cat, (categoryCounts.get(cat) || 0) + 1);
321
+ }
322
+ sectionOrder = [...categoryCounts.entries()]
323
+ .sort((a, b) => b[1] - a[1])
324
+ .map(([cat]) => cat)
325
+ .filter((cat) => sections[cat]);
326
+ }
327
+ // Prune sections before building the index to avoid O(n^2) rebuild loop
328
+ const budget = this.config.maxIndexLines;
329
+ pruneSectionsToFit(sections, budget, this.config.pruneStrategy);
330
+ // Build the final index (with optional graph-aware ordering)
331
+ const lines = buildIndexLines(sections, this.config.topicMapping, sectionOrder);
332
+ await fs.writeFile(this.getIndexPath(), lines.join('\n'), 'utf-8');
333
+ this.emit('index:curated', { lines: lines.length });
334
+ }
335
+ /**
336
+ * Get auto memory status: directory info, file count, line counts.
337
+ */
338
+ getStatus() {
339
+ const memoryDir = this.config.memoryDir;
340
+ if (!existsSync(memoryDir)) {
341
+ return {
342
+ memoryDir,
343
+ exists: false,
344
+ files: [],
345
+ totalLines: 0,
346
+ indexLines: 0,
347
+ lastSyncTime: this.lastSyncTime,
348
+ bufferedInsights: this.insights.length,
349
+ };
350
+ }
351
+ const fileStats = [];
352
+ let totalLines = 0;
353
+ let indexLines = 0;
354
+ let mdFiles;
355
+ try {
356
+ mdFiles = readdirSync(memoryDir).filter(f => f.endsWith('.md'));
357
+ }
358
+ catch {
359
+ return {
360
+ memoryDir,
361
+ exists: true,
362
+ files: [],
363
+ totalLines: 0,
364
+ indexLines: 0,
365
+ lastSyncTime: this.lastSyncTime,
366
+ bufferedInsights: this.insights.length,
367
+ };
368
+ }
369
+ for (const file of mdFiles) {
370
+ try {
371
+ const content = readFileSync(path.join(memoryDir, file), 'utf-8');
372
+ const lineCount = content.split('\n').length;
373
+ fileStats.push({ name: file, lines: lineCount });
374
+ totalLines += lineCount;
375
+ if (file === 'MEMORY.md') {
376
+ indexLines = lineCount;
377
+ }
378
+ }
379
+ catch {
380
+ // Skip unreadable files
381
+ }
382
+ }
383
+ return {
384
+ memoryDir,
385
+ exists: true,
386
+ files: fileStats,
387
+ totalLines,
388
+ indexLines,
389
+ lastSyncTime: this.lastSyncTime,
390
+ bufferedInsights: this.insights.length,
391
+ };
392
+ }
393
+ /** Stop periodic sync and clean up */
394
+ destroy() {
395
+ if (this.syncTimer) {
396
+ clearInterval(this.syncTimer);
397
+ this.syncTimer = null;
398
+ }
399
+ // ADR-049: Clean up learning bridge
400
+ if (this.learningBridge) {
401
+ this.learningBridge.destroy();
402
+ }
403
+ this.removeAllListeners();
404
+ }
405
+ // ===== Private Methods =====
406
+ async ensureMemoryDir() {
407
+ const dir = this.config.memoryDir;
408
+ if (!existsSync(dir)) {
409
+ await fs.mkdir(dir, { recursive: true });
410
+ }
411
+ }
412
+ async storeInsightInAgentDB(insight) {
413
+ const content = insight.detail
414
+ ? `${insight.summary}\n\n${insight.detail}`
415
+ : insight.summary;
416
+ const key = `insight:${insight.category}:${Date.now()}:${this.insightCounter++}`;
417
+ const input = {
418
+ key,
419
+ content,
420
+ namespace: 'learnings',
421
+ type: 'semantic',
422
+ tags: ['insight', insight.category, `source:${insight.source}`],
423
+ metadata: {
424
+ category: insight.category,
425
+ summary: insight.summary,
426
+ source: insight.source,
427
+ confidence: insight.confidence,
428
+ contentHash: hashContent(content),
429
+ ...(insight.agentDbId ? { linkedEntryId: insight.agentDbId } : {}),
430
+ },
431
+ };
432
+ const entry = createDefaultEntry(input);
433
+ await this.backend.store(entry);
434
+ return key;
435
+ }
436
+ async writeInsightToFiles(insight) {
437
+ await this.ensureMemoryDir();
438
+ const topicPath = this.getTopicPath(insight.category);
439
+ const line = formatInsightLine(insight);
440
+ if (existsSync(topicPath)) {
441
+ const existing = await fs.readFile(topicPath, 'utf-8');
442
+ // Exact line-based dedup: check if the summary already appears as a bullet
443
+ if (hasSummaryLine(existing, insight.summary))
444
+ return;
445
+ const lineCount = existing.split('\n').length;
446
+ if (lineCount >= this.config.maxTopicFileLines) {
447
+ const pruned = pruneTopicFile(existing, this.config.maxTopicFileLines - 10);
448
+ await fs.writeFile(topicPath, pruned + '\n' + line, 'utf-8');
449
+ }
450
+ else {
451
+ await fs.appendFile(topicPath, '\n' + line, 'utf-8');
452
+ }
453
+ }
454
+ else {
455
+ const label = CATEGORY_LABELS[insight.category] || insight.category;
456
+ const header = `# ${label}\n\n`;
457
+ await fs.writeFile(topicPath, header + line, 'utf-8');
458
+ }
459
+ }
460
+ async queryRecentInsights() {
461
+ const query = {
462
+ type: 'hybrid',
463
+ namespace: 'learnings',
464
+ tags: ['insight'],
465
+ updatedAfter: this.lastSyncTime || 0,
466
+ limit: 50,
467
+ };
468
+ try {
469
+ const entries = await this.backend.query(query);
470
+ return entries.filter(e => {
471
+ const confidence = e.metadata?.confidence || 0;
472
+ return confidence >= this.config.minConfidence;
473
+ });
474
+ }
475
+ catch {
476
+ return [];
477
+ }
478
+ }
479
+ classifyEntry(entry) {
480
+ const category = entry.metadata?.category;
481
+ if (category && category in DEFAULT_TOPIC_MAPPING) {
482
+ return category;
483
+ }
484
+ const tags = entry.tags || [];
485
+ if (tags.includes('debugging') || tags.includes('bug') || tags.includes('fix')) {
486
+ return 'debugging';
487
+ }
488
+ if (tags.includes('architecture') || tags.includes('design')) {
489
+ return 'architecture';
490
+ }
491
+ if (tags.includes('performance') || tags.includes('benchmark')) {
492
+ return 'performance';
493
+ }
494
+ if (tags.includes('security') || tags.includes('cve')) {
495
+ return 'security';
496
+ }
497
+ if (tags.includes('swarm') || tags.includes('agent')) {
498
+ return 'swarm-results';
499
+ }
500
+ return 'project-patterns';
501
+ }
502
+ async appendToTopicFile(category, entry) {
503
+ const insight = {
504
+ category,
505
+ summary: entry.metadata?.summary || entry.content.split('\n')[0],
506
+ detail: entry.content,
507
+ source: entry.metadata?.source || 'agentdb',
508
+ confidence: entry.metadata?.confidence || 0.5,
509
+ agentDbId: entry.id,
510
+ };
511
+ await this.writeInsightToFiles(insight);
512
+ }
513
+ /** Fetch all existing content hashes from the auto-memory namespace in one query */
514
+ async fetchExistingContentHashes() {
515
+ try {
516
+ const entries = await this.backend.query({
517
+ type: 'hybrid',
518
+ namespace: 'auto-memory',
519
+ limit: 10_000,
520
+ });
521
+ const hashes = new Set();
522
+ for (const entry of entries) {
523
+ const hash = entry.metadata?.contentHash;
524
+ if (hash)
525
+ hashes.add(hash);
526
+ }
527
+ return hashes;
528
+ }
529
+ catch {
530
+ return new Set();
531
+ }
532
+ }
533
+ startPeriodicSync() {
534
+ this.syncTimer = setInterval(async () => {
535
+ try {
536
+ await this.syncToAutoMemory();
537
+ }
538
+ catch (err) {
539
+ this.emit('sync:error', err);
540
+ }
541
+ }, this.config.syncIntervalMs);
542
+ if (this.syncTimer.unref) {
543
+ this.syncTimer.unref();
544
+ }
545
+ }
546
+ }
547
+ // ===== Utility Functions =====
548
+ /**
549
+ * Resolve the auto memory directory for a given working directory.
550
+ * Mirrors Claude Code's path derivation from git root.
551
+ */
552
+ export function resolveAutoMemoryDir(workingDir) {
553
+ const gitRoot = findGitRoot(workingDir);
554
+ const basePath = gitRoot || workingDir;
555
+ // Claude Code normalizes to forward slashes then replaces both `/` and `_`
556
+ // with dashes (e.g. /workspaces/RX_ERP -> -workspaces-RX-ERP). The leading
557
+ // dash IS preserved.
558
+ const normalized = basePath.split(path.sep).join('/');
559
+ const projectKey = normalized.replace(/[\/_]/g, '-');
560
+ return path.join(process.env.HOME || process.env.USERPROFILE || '~', '.claude', 'projects', projectKey, 'memory');
561
+ }
562
+ /**
563
+ * Find the git root directory by walking up from workingDir.
564
+ */
565
+ export function findGitRoot(dir) {
566
+ let current = path.resolve(dir);
567
+ const root = path.parse(current).root;
568
+ while (current !== root) {
569
+ if (existsSync(path.join(current, '.git'))) {
570
+ return current;
571
+ }
572
+ current = path.dirname(current);
573
+ }
574
+ return null;
575
+ }
576
+ /**
577
+ * Parse markdown content into structured entries.
578
+ *
579
+ * Three-tier strategy to handle both legacy topic files and Claude Code's
580
+ * native auto-memory format:
581
+ * 1. Strip YAML frontmatter if present and capture name/description/type.
582
+ * 2. Split body on `## ` headings (legacy MEMORY.md-style topic files).
583
+ * 3. If no `## ` headings were found, fall back to a single entry per file
584
+ * using frontmatter.name as the heading (or `(untitled)`), the
585
+ * post-frontmatter body as content, and frontmatter fields as metadata.
586
+ *
587
+ * Without (3), files like Claude Code's `~/.claude/projects/<key>/memory/*.md`
588
+ * (frontmatter + free-text body, no `## ` sub-headings) parse to zero entries
589
+ * and silently drop on import. See issue #2283.
590
+ */
591
+ export function parseMarkdownEntries(content) {
592
+ const entries = [];
593
+ // Strip YAML frontmatter and capture key fields.
594
+ const frontmatter = {};
595
+ let body = content;
596
+ const fmMatch = content.match(/^---\r?\n([\s\S]*?)\r?\n---\r?\n?([\s\S]*)$/);
597
+ if (fmMatch) {
598
+ body = fmMatch[2];
599
+ for (const fmLine of fmMatch[1].split(/\r?\n/)) {
600
+ const kv = fmLine.match(/^([A-Za-z0-9_-]+):\s*(.*)$/);
601
+ if (kv)
602
+ frontmatter[kv[1]] = kv[2].trim().replace(/^["']|["']$/g, '');
603
+ }
604
+ }
605
+ const lines = body.split('\n');
606
+ let currentHeading = '';
607
+ let currentLines = [];
608
+ let sawHeading = false;
609
+ for (const line of lines) {
610
+ const headingMatch = line.match(/^##\s+(.+)/);
611
+ if (headingMatch) {
612
+ sawHeading = true;
613
+ if (currentHeading && currentLines.length > 0) {
614
+ entries.push({
615
+ heading: currentHeading,
616
+ content: currentLines.join('\n').trim(),
617
+ metadata: {},
618
+ });
619
+ }
620
+ currentHeading = headingMatch[1];
621
+ currentLines = [];
622
+ }
623
+ else if (currentHeading) {
624
+ currentLines.push(line);
625
+ }
626
+ }
627
+ if (currentHeading && currentLines.length > 0) {
628
+ entries.push({
629
+ heading: currentHeading,
630
+ content: currentLines.join('\n').trim(),
631
+ metadata: {},
632
+ });
633
+ }
634
+ if (!sawHeading) {
635
+ const trimmedBody = body.trim();
636
+ if (trimmedBody) {
637
+ const heading = frontmatter.name || frontmatter.description || '(untitled)';
638
+ const metadata = {};
639
+ if (frontmatter.type)
640
+ metadata.type = frontmatter.type;
641
+ if (frontmatter.description)
642
+ metadata.description = frontmatter.description;
643
+ if (frontmatter.originSessionId)
644
+ metadata.originSessionId = frontmatter.originSessionId;
645
+ entries.push({ heading, content: trimmedBody, metadata });
646
+ }
647
+ }
648
+ return entries;
649
+ }
650
+ /**
651
+ * Extract clean one-line summaries from a topic file.
652
+ * Returns bullet-point items (lines starting with '- '), stripping
653
+ * metadata annotations like _(source, date, conf: 0.95)_.
654
+ */
655
+ export function extractSummaries(content) {
656
+ return content
657
+ .split('\n')
658
+ .filter(line => line.startsWith('- '))
659
+ .map(line => line.slice(2).trim())
660
+ .filter(line => !line.startsWith('See `'))
661
+ .map(line => line.replace(/\s*_\(.*?\)_\s*$/, '').trim())
662
+ .filter(Boolean);
663
+ }
664
+ /**
665
+ * Format an insight as a markdown line for topic files.
666
+ */
667
+ export function formatInsightLine(insight) {
668
+ const timestamp = new Date().toISOString().split('T')[0];
669
+ const prefix = `- ${insight.summary}`;
670
+ const suffix = ` _(${insight.source}, ${timestamp}, conf: ${insight.confidence.toFixed(2)})_`;
671
+ if (insight.detail && insight.detail.split('\n').length > 2) {
672
+ return `${prefix}${suffix}\n ${insight.detail.split('\n').join('\n ')}`;
673
+ }
674
+ return `${prefix}${suffix}`;
675
+ }
676
+ /**
677
+ * Hash content for deduplication.
678
+ */
679
+ export function hashContent(content) {
680
+ return createHash('sha256').update(content).digest('hex').slice(0, 16);
681
+ }
682
+ /**
683
+ * Prune a topic file to stay under the line limit.
684
+ * Removes oldest entries (those closest to the top after the header).
685
+ */
686
+ export function pruneTopicFile(content, maxLines) {
687
+ const lines = content.split('\n');
688
+ if (lines.length <= maxLines)
689
+ return content;
690
+ const header = lines.slice(0, 3);
691
+ const entries = lines.slice(3);
692
+ const kept = entries.slice(entries.length - (maxLines - 3));
693
+ return [...header, ...kept].join('\n');
694
+ }
695
+ /**
696
+ * Check if a summary already exists as a bullet line in topic file content.
697
+ * Uses exact bullet prefix matching (not substring) to avoid false positives.
698
+ */
699
+ export function hasSummaryLine(content, summary) {
700
+ // Match lines that start with "- <summary>" (possibly followed by metadata)
701
+ return content.split('\n').some(line => line.startsWith(`- ${summary}`));
702
+ }
703
+ /**
704
+ * Prune sections to fit within a line budget.
705
+ * Removes entries from the largest sections first.
706
+ */
707
+ function pruneSectionsToFit(sections, budget, strategy) {
708
+ // Pre-compute total line count: title(1) + blank(1) + per-section(heading + items + "See..." + blank)
709
+ let totalLines = 2;
710
+ for (const summaries of Object.values(sections)) {
711
+ totalLines += 1 + summaries.length + 1 + 1;
712
+ }
713
+ while (totalLines > budget) {
714
+ const sorted = Object.entries(sections)
715
+ .filter(([, items]) => items.length > 1)
716
+ .sort((a, b) => b[1].length - a[1].length);
717
+ if (sorted.length === 0)
718
+ break;
719
+ const [targetCat, targetItems] = sorted[0];
720
+ if (strategy === 'lru' || strategy === 'fifo') {
721
+ targetItems.shift();
722
+ }
723
+ else {
724
+ targetItems.pop();
725
+ }
726
+ totalLines--; // one fewer bullet line
727
+ if (targetItems.length === 0) {
728
+ delete sections[targetCat];
729
+ totalLines -= 3; // heading + "See..." + blank removed
730
+ }
731
+ }
732
+ }
733
+ /**
734
+ * Build MEMORY.md index lines from curated sections.
735
+ */
736
+ function buildIndexLines(sections, topicMapping, sectionOrder) {
737
+ const lines = ['# Claude Flow V3 Project Memory', ''];
738
+ // Use provided order, then append any remaining sections
739
+ const orderedCategories = sectionOrder
740
+ ? [...sectionOrder, ...Object.keys(sections).filter((k) => !sectionOrder.includes(k))]
741
+ : Object.keys(sections);
742
+ for (const category of orderedCategories) {
743
+ const summaries = sections[category];
744
+ if (!summaries || summaries.length === 0)
745
+ continue;
746
+ const label = CATEGORY_LABELS[category] || category;
747
+ const filename = topicMapping[category] || `${category}.md`;
748
+ lines.push(`## ${label}`);
749
+ for (const summary of summaries) {
750
+ lines.push(`- ${summary}`);
751
+ }
752
+ lines.push(`- See \`${filename}\` for details`);
753
+ lines.push('');
754
+ }
755
+ return lines;
756
+ }
757
+ export default AutoMemoryBridge;
758
+ //# sourceMappingURL=auto-memory-bridge.js.map