@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,849 @@
1
+ /**
2
+ * Tests for AutoMemoryBridge
3
+ *
4
+ * TDD London School (mock-first) tests for the bidirectional bridge
5
+ * between Claude Code auto memory and AgentDB.
6
+ */
7
+ import { describe, it, expect, beforeEach, afterEach, vi } from 'vitest';
8
+ import * as fsSync from 'node:fs';
9
+ import * as path from 'node:path';
10
+ import { AutoMemoryBridge, resolveAutoMemoryDir, findGitRoot, parseMarkdownEntries, extractSummaries, formatInsightLine, hashContent, pruneTopicFile, hasSummaryLine, } from './auto-memory-bridge.js';
11
+ // ===== Mock Backend =====
12
+ function createMockBackend() {
13
+ const storedEntries = [];
14
+ return {
15
+ storedEntries,
16
+ initialize: vi.fn().mockResolvedValue(undefined),
17
+ shutdown: vi.fn().mockResolvedValue(undefined),
18
+ store: vi.fn().mockImplementation(async (entry) => {
19
+ storedEntries.push(entry);
20
+ }),
21
+ get: vi.fn().mockResolvedValue(null),
22
+ getByKey: vi.fn().mockResolvedValue(null),
23
+ update: vi.fn().mockResolvedValue(null),
24
+ delete: vi.fn().mockResolvedValue(true),
25
+ query: vi.fn().mockResolvedValue([]),
26
+ search: vi.fn().mockResolvedValue([]),
27
+ bulkInsert: vi.fn().mockResolvedValue(undefined),
28
+ bulkDelete: vi.fn().mockResolvedValue(0),
29
+ count: vi.fn().mockResolvedValue(0),
30
+ listNamespaces: vi.fn().mockResolvedValue([]),
31
+ clearNamespace: vi.fn().mockResolvedValue(0),
32
+ getStats: vi.fn().mockResolvedValue({
33
+ totalEntries: 0,
34
+ entriesByNamespace: {},
35
+ entriesByType: {},
36
+ memoryUsage: 0,
37
+ avgQueryTime: 0,
38
+ avgSearchTime: 0,
39
+ }),
40
+ healthCheck: vi.fn().mockResolvedValue({
41
+ status: 'healthy',
42
+ components: {
43
+ storage: { status: 'healthy', latency: 0 },
44
+ index: { status: 'healthy', latency: 0 },
45
+ cache: { status: 'healthy', latency: 0 },
46
+ },
47
+ timestamp: Date.now(),
48
+ issues: [],
49
+ recommendations: [],
50
+ }),
51
+ };
52
+ }
53
+ // ===== Test Fixtures =====
54
+ function createTestInsight(overrides = {}) {
55
+ return {
56
+ category: 'debugging',
57
+ summary: 'HNSW index requires initialization before search',
58
+ source: 'agent:tester',
59
+ confidence: 0.95,
60
+ ...overrides,
61
+ };
62
+ }
63
+ // ===== Utility Function Tests =====
64
+ describe('resolveAutoMemoryDir', () => {
65
+ it('should derive path from working directory', () => {
66
+ const result = resolveAutoMemoryDir('/workspaces/my-project');
67
+ expect(result).toContain('.claude/projects/');
68
+ expect(result).toContain('memory');
69
+ expect(result).not.toContain('//');
70
+ });
71
+ it('should replace slashes with dashes', () => {
72
+ const result = resolveAutoMemoryDir('/workspaces/my-project');
73
+ expect(result).toContain('workspaces-my-project');
74
+ });
75
+ it('should normalize underscores to dashes (issue #2282)', () => {
76
+ // Claude Code normalizes both `/` and `_` to `-` when computing the
77
+ // project key, so paths like /home/phil/A-Project/RX_ERP/ map to
78
+ // -home-phil-A-Project-RX-ERP, not -home-phil-A-Project-RX_ERP.
79
+ const result = resolveAutoMemoryDir('/home/phil/A-Project/RX_ERP');
80
+ expect(result).toContain('A-Project-RX-ERP');
81
+ expect(result).not.toContain('RX_ERP');
82
+ });
83
+ it('should produce consistent paths for same input', () => {
84
+ const a = resolveAutoMemoryDir('/workspaces/my-project');
85
+ const b = resolveAutoMemoryDir('/workspaces/my-project');
86
+ expect(a).toBe(b);
87
+ });
88
+ });
89
+ describe('findGitRoot', () => {
90
+ it('should find git root for a directory inside a repo', () => {
91
+ // Use the actual repo path (works regardless of workspace name)
92
+ const thisDir = path.resolve(__dirname);
93
+ const root = findGitRoot(thisDir);
94
+ expect(root).not.toBeNull();
95
+ // The root should contain a .git directory
96
+ expect(fsSync.existsSync(path.join(root, '.git'))).toBe(true);
97
+ });
98
+ it('should return the directory itself if it is the git root', () => {
99
+ // Find the actual git root first, then verify idempotence
100
+ const thisDir = path.resolve(__dirname);
101
+ const gitRoot = findGitRoot(thisDir);
102
+ expect(gitRoot).not.toBeNull();
103
+ const root = findGitRoot(gitRoot);
104
+ expect(root).toBe(gitRoot);
105
+ });
106
+ it('should return null for root filesystem', () => {
107
+ // /proc is almost certainly not in a git repo
108
+ const result = findGitRoot('/proc');
109
+ expect(result).toBeNull();
110
+ });
111
+ });
112
+ describe('parseMarkdownEntries', () => {
113
+ it('should parse markdown with ## headings into entries', () => {
114
+ const content = `# Main Title
115
+
116
+ ## Section One
117
+ Content of section one.
118
+ More content here.
119
+
120
+ ## Section Two
121
+ Content of section two.
122
+ `;
123
+ const entries = parseMarkdownEntries(content);
124
+ expect(entries).toHaveLength(2);
125
+ expect(entries[0].heading).toBe('Section One');
126
+ expect(entries[0].content).toContain('Content of section one');
127
+ expect(entries[1].heading).toBe('Section Two');
128
+ });
129
+ it('should fall back to single untitled entry when no ## headings or frontmatter (issue #2283)', () => {
130
+ // Pre-fix behavior was to return [] — we now emit one entry with the
131
+ // body as content so files without ## subheadings still import.
132
+ const content = '# Only h1 heading\nSome text\n';
133
+ const entries = parseMarkdownEntries(content);
134
+ expect(entries).toHaveLength(1);
135
+ expect(entries[0].heading).toBe('(untitled)');
136
+ expect(entries[0].content).toContain('# Only h1 heading');
137
+ expect(entries[0].content).toContain('Some text');
138
+ });
139
+ it('should parse YAML frontmatter + body as a single entry (issue #2283)', () => {
140
+ // Claude Code's auto-memory format: YAML frontmatter + free-text body,
141
+ // no ## sub-headings. Pre-fix this returned [] silently.
142
+ const content = `---
143
+ name: GitHub identity for RX Platform
144
+ description: Phil uses PrimitiveOne / one@primitive1.com for...
145
+ type: user
146
+ originSessionId: 753b313d-3414-abcd
147
+ ---
148
+ For the RX Platform / RX_ERP project specifically:
149
+
150
+ - **GitHub login**: \`PrimitiveOne\`
151
+ - **GitHub email**: \`one@primitive1.com\`
152
+ `;
153
+ const entries = parseMarkdownEntries(content);
154
+ expect(entries).toHaveLength(1);
155
+ expect(entries[0].heading).toBe('GitHub identity for RX Platform');
156
+ expect(entries[0].content).toContain('GitHub login');
157
+ expect(entries[0].content).toContain('PrimitiveOne');
158
+ expect(entries[0].metadata.type).toBe('user');
159
+ expect(entries[0].metadata.description).toContain('Phil uses PrimitiveOne');
160
+ expect(entries[0].metadata.originSessionId).toBe('753b313d-3414-abcd');
161
+ });
162
+ it('should prefer ## headings over frontmatter fallback when both present', () => {
163
+ const content = `---
164
+ name: Should be ignored when ## headings exist
165
+ type: user
166
+ ---
167
+ ## Real Section
168
+ Section content
169
+ `;
170
+ const entries = parseMarkdownEntries(content);
171
+ expect(entries).toHaveLength(1);
172
+ expect(entries[0].heading).toBe('Real Section');
173
+ expect(entries[0].content).toContain('Section content');
174
+ });
175
+ it('should return empty array for empty content', () => {
176
+ expect(parseMarkdownEntries('')).toHaveLength(0);
177
+ });
178
+ it('should return empty array when frontmatter has no body', () => {
179
+ const content = `---
180
+ name: Frontmatter only
181
+ ---
182
+ `;
183
+ const entries = parseMarkdownEntries(content);
184
+ expect(entries).toHaveLength(0);
185
+ });
186
+ it('should handle multiple lines under a heading', () => {
187
+ const content = `## Heading
188
+ Line 1
189
+ Line 2
190
+ Line 3
191
+ `;
192
+ const entries = parseMarkdownEntries(content);
193
+ expect(entries).toHaveLength(1);
194
+ expect(entries[0].content).toContain('Line 1');
195
+ expect(entries[0].content).toContain('Line 3');
196
+ });
197
+ it('should trim whitespace from section content', () => {
198
+ const content = '## Padded\n\n Text here \n\n';
199
+ const entries = parseMarkdownEntries(content);
200
+ expect(entries[0].content).toBe('Text here');
201
+ });
202
+ });
203
+ describe('extractSummaries', () => {
204
+ it('should extract bullet points from content', () => {
205
+ const content = `# Topic
206
+
207
+ - First summary
208
+ - Second summary
209
+ - See \`details.md\` for more
210
+ Some other text
211
+ `;
212
+ const summaries = extractSummaries(content);
213
+ expect(summaries).toHaveLength(2);
214
+ expect(summaries[0]).toBe('First summary');
215
+ expect(summaries[1]).toBe('Second summary');
216
+ });
217
+ it('should skip "See" references', () => {
218
+ const content = '- Good item\n- See `file.md` for details\n';
219
+ const summaries = extractSummaries(content);
220
+ expect(summaries).toHaveLength(1);
221
+ expect(summaries[0]).toBe('Good item');
222
+ });
223
+ it('should return empty array for content without bullets', () => {
224
+ const content = 'No bullets here\n';
225
+ const summaries = extractSummaries(content);
226
+ expect(summaries).toHaveLength(0);
227
+ });
228
+ it('should strip metadata annotations from summaries', () => {
229
+ const content = '- Use Int8 quantization _(agent:tester, 2026-02-08, conf: 0.95)_\n';
230
+ const summaries = extractSummaries(content);
231
+ expect(summaries).toHaveLength(1);
232
+ expect(summaries[0]).toBe('Use Int8 quantization');
233
+ });
234
+ it('should handle summaries without annotations', () => {
235
+ const content = '- Clean summary without annotation\n';
236
+ const summaries = extractSummaries(content);
237
+ expect(summaries[0]).toBe('Clean summary without annotation');
238
+ });
239
+ });
240
+ describe('formatInsightLine', () => {
241
+ it('should format insight as a markdown bullet', () => {
242
+ const insight = createTestInsight();
243
+ const line = formatInsightLine(insight);
244
+ expect(line.startsWith('- HNSW index requires initialization before search')).toBe(true);
245
+ expect(line).toContain('agent:tester');
246
+ expect(line).toContain('0.95');
247
+ });
248
+ it('should include detail as indented content for multi-line details', () => {
249
+ const insight = createTestInsight({
250
+ detail: 'Line 1\nLine 2\nLine 3',
251
+ });
252
+ const line = formatInsightLine(insight);
253
+ expect(line).toContain(' Line 1');
254
+ expect(line).toContain(' Line 2');
255
+ });
256
+ it('should not add indented detail for single-line details', () => {
257
+ const insight = createTestInsight({ detail: 'Short detail' });
258
+ const line = formatInsightLine(insight);
259
+ // Single-line detail should not produce indented lines
260
+ expect(line.split('\n')).toHaveLength(1);
261
+ });
262
+ });
263
+ describe('hashContent', () => {
264
+ it('should produce consistent hashes', () => {
265
+ const hash1 = hashContent('test content');
266
+ const hash2 = hashContent('test content');
267
+ expect(hash1).toBe(hash2);
268
+ });
269
+ it('should produce different hashes for different content', () => {
270
+ const hash1 = hashContent('content A');
271
+ const hash2 = hashContent('content B');
272
+ expect(hash1).not.toBe(hash2);
273
+ });
274
+ it('should return a 16-character hex string', () => {
275
+ const hash = hashContent('test');
276
+ expect(hash).toMatch(/^[0-9a-f]{16}$/);
277
+ });
278
+ });
279
+ describe('pruneTopicFile', () => {
280
+ it('should not prune if under limit', () => {
281
+ const content = '# Header\n\nSubheader\n- Item 1\n- Item 2\n';
282
+ const result = pruneTopicFile(content, 100);
283
+ expect(result).toBe(content);
284
+ });
285
+ it('should keep header and newest entries when pruning', () => {
286
+ const lines = ['# Header', '', 'Description'];
287
+ for (let i = 0; i < 20; i++) {
288
+ lines.push(`- Entry ${i}`);
289
+ }
290
+ const content = lines.join('\n');
291
+ const result = pruneTopicFile(content, 13);
292
+ const resultLines = result.split('\n');
293
+ expect(resultLines[0]).toBe('# Header');
294
+ expect(resultLines).toHaveLength(13);
295
+ expect(resultLines[resultLines.length - 1]).toBe('- Entry 19');
296
+ });
297
+ });
298
+ describe('hasSummaryLine', () => {
299
+ it('should find exact summary at start of bullet line', () => {
300
+ const content = '- Use Int8 quantization _(source, date)_\n- Other item\n';
301
+ expect(hasSummaryLine(content, 'Use Int8 quantization')).toBe(true);
302
+ });
303
+ it('should not match substrings inside other bullets', () => {
304
+ const content = '- Do not use Int8 for this case\n';
305
+ // "Use Int8" should NOT match because the line starts with "- Do not use..."
306
+ expect(hasSummaryLine(content, 'Use Int8')).toBe(false);
307
+ });
308
+ it('should return false when summary is absent', () => {
309
+ const content = '- Something else\n';
310
+ expect(hasSummaryLine(content, 'Missing summary')).toBe(false);
311
+ });
312
+ it('should handle empty content', () => {
313
+ expect(hasSummaryLine('', 'anything')).toBe(false);
314
+ });
315
+ });
316
+ // ===== AutoMemoryBridge Tests =====
317
+ describe('AutoMemoryBridge', () => {
318
+ let bridge;
319
+ let backend;
320
+ let testDir;
321
+ beforeEach(() => {
322
+ testDir = path.join('/tmp', `auto-memory-test-${Date.now()}-${Math.random().toString(36).slice(2, 8)}`);
323
+ fsSync.mkdirSync(testDir, { recursive: true });
324
+ backend = createMockBackend();
325
+ bridge = new AutoMemoryBridge(backend, {
326
+ memoryDir: testDir,
327
+ syncMode: 'on-session-end',
328
+ });
329
+ });
330
+ afterEach(() => {
331
+ bridge.destroy();
332
+ if (fsSync.existsSync(testDir)) {
333
+ fsSync.rmSync(testDir, { recursive: true, force: true });
334
+ }
335
+ });
336
+ describe('constructor', () => {
337
+ it('should initialize with default config', () => {
338
+ const b = new AutoMemoryBridge(backend);
339
+ expect(b.getMemoryDir()).toBeTruthy();
340
+ b.destroy();
341
+ });
342
+ it('should use provided memory directory', () => {
343
+ expect(bridge.getMemoryDir()).toBe(testDir);
344
+ });
345
+ });
346
+ describe('getIndexPath', () => {
347
+ it('should return path to MEMORY.md', () => {
348
+ expect(bridge.getIndexPath()).toBe(path.join(testDir, 'MEMORY.md'));
349
+ });
350
+ });
351
+ describe('getTopicPath', () => {
352
+ it('should return path to topic file based on category', () => {
353
+ const p = bridge.getTopicPath('debugging');
354
+ expect(p).toBe(path.join(testDir, 'debugging.md'));
355
+ });
356
+ it('should use custom topic mapping', () => {
357
+ const custom = new AutoMemoryBridge(backend, {
358
+ memoryDir: testDir,
359
+ topicMapping: { debugging: 'bugs.md' },
360
+ });
361
+ const p = custom.getTopicPath('debugging');
362
+ expect(p).toBe(path.join(testDir, 'bugs.md'));
363
+ custom.destroy();
364
+ });
365
+ });
366
+ describe('recordInsight', () => {
367
+ it('should store insight in AgentDB', async () => {
368
+ const insight = createTestInsight();
369
+ await bridge.recordInsight(insight);
370
+ expect(backend.store).toHaveBeenCalledTimes(1);
371
+ const storedEntry = backend.storedEntries[0];
372
+ expect(storedEntry.namespace).toBe('learnings');
373
+ expect(storedEntry.tags).toContain('insight');
374
+ expect(storedEntry.tags).toContain('debugging');
375
+ });
376
+ it('should emit insight:recorded event', async () => {
377
+ const handler = vi.fn();
378
+ bridge.on('insight:recorded', handler);
379
+ const insight = createTestInsight();
380
+ await bridge.recordInsight(insight);
381
+ expect(handler).toHaveBeenCalledWith(insight);
382
+ });
383
+ it('should write to files immediately in on-write mode', async () => {
384
+ bridge.destroy();
385
+ bridge = new AutoMemoryBridge(backend, {
386
+ memoryDir: testDir,
387
+ syncMode: 'on-write',
388
+ });
389
+ const insight = createTestInsight();
390
+ await bridge.recordInsight(insight);
391
+ const topicPath = bridge.getTopicPath('debugging');
392
+ expect(fsSync.existsSync(topicPath)).toBe(true);
393
+ const content = fsSync.readFileSync(topicPath, 'utf-8');
394
+ expect(content).toContain(insight.summary);
395
+ });
396
+ it('should not write to files immediately in on-session-end mode', async () => {
397
+ const insight = createTestInsight();
398
+ await bridge.recordInsight(insight);
399
+ const topicPath = bridge.getTopicPath('debugging');
400
+ expect(fsSync.existsSync(topicPath)).toBe(false);
401
+ });
402
+ it('should store confidence in metadata', async () => {
403
+ await bridge.recordInsight(createTestInsight({ confidence: 0.42 }));
404
+ const stored = backend.storedEntries[0];
405
+ expect(stored.metadata.confidence).toBe(0.42);
406
+ });
407
+ });
408
+ describe('syncToAutoMemory', () => {
409
+ it('should flush buffered insights to files', async () => {
410
+ await bridge.recordInsight(createTestInsight());
411
+ await bridge.recordInsight(createTestInsight({
412
+ category: 'performance',
413
+ summary: 'Use Int8 quantization for 3.92x memory reduction',
414
+ }));
415
+ const result = await bridge.syncToAutoMemory();
416
+ expect(result.synced).toBeGreaterThan(0);
417
+ expect(result.categories).toContain('debugging');
418
+ expect(result.categories).toContain('performance');
419
+ expect(result.errors).toHaveLength(0);
420
+ expect(fsSync.existsSync(bridge.getTopicPath('debugging'))).toBe(true);
421
+ expect(fsSync.existsSync(bridge.getTopicPath('performance'))).toBe(true);
422
+ });
423
+ it('should create MEMORY.md index', async () => {
424
+ await bridge.recordInsight(createTestInsight());
425
+ await bridge.syncToAutoMemory();
426
+ expect(fsSync.existsSync(bridge.getIndexPath())).toBe(true);
427
+ });
428
+ it('should emit sync:completed event', async () => {
429
+ const handler = vi.fn();
430
+ bridge.on('sync:completed', handler);
431
+ await bridge.syncToAutoMemory();
432
+ expect(handler).toHaveBeenCalledWith(expect.objectContaining({
433
+ durationMs: expect.any(Number),
434
+ }));
435
+ });
436
+ it('should not duplicate insights on repeated sync', async () => {
437
+ await bridge.recordInsight(createTestInsight());
438
+ await bridge.syncToAutoMemory();
439
+ await bridge.syncToAutoMemory();
440
+ const topicPath = bridge.getTopicPath('debugging');
441
+ const content = fsSync.readFileSync(topicPath, 'utf-8');
442
+ const matches = content.match(/HNSW index requires/g);
443
+ expect(matches).toHaveLength(1);
444
+ });
445
+ it('should clear the insight buffer after sync', async () => {
446
+ await bridge.recordInsight(createTestInsight());
447
+ expect(bridge.getStatus().bufferedInsights).toBe(1);
448
+ await bridge.syncToAutoMemory();
449
+ expect(bridge.getStatus().bufferedInsights).toBe(0);
450
+ });
451
+ it('should skip AgentDB entries already synced from the buffer', async () => {
452
+ // Record an insight (stored in buffer AND AgentDB)
453
+ await bridge.recordInsight(createTestInsight());
454
+ // Mock backend.query to return the same insight from AgentDB
455
+ const mockEntry = {
456
+ id: 'test-1',
457
+ key: 'insight:debugging:12345',
458
+ content: 'HNSW index requires initialization before search',
459
+ tags: ['insight', 'debugging'],
460
+ metadata: {
461
+ category: 'debugging',
462
+ summary: 'HNSW index requires initialization before search',
463
+ confidence: 0.95,
464
+ },
465
+ };
466
+ backend.query.mockResolvedValueOnce([mockEntry]);
467
+ await bridge.syncToAutoMemory();
468
+ // Should only appear once
469
+ const content = fsSync.readFileSync(bridge.getTopicPath('debugging'), 'utf-8');
470
+ const matches = content.match(/HNSW index requires/g);
471
+ expect(matches).toHaveLength(1);
472
+ });
473
+ });
474
+ describe('importFromAutoMemory', () => {
475
+ it('should import entries from existing markdown files', async () => {
476
+ const topicContent = `# Debugging Insights
477
+
478
+ ## Known Issues
479
+ - Always init HNSW before search
480
+ - SQLite WASM needs sql.js
481
+ `;
482
+ fsSync.writeFileSync(path.join(testDir, 'debugging.md'), topicContent, 'utf-8');
483
+ const result = await bridge.importFromAutoMemory();
484
+ expect(result.imported).toBeGreaterThan(0);
485
+ expect(result.files).toContain('debugging.md');
486
+ // Should use bulkInsert, not individual store calls
487
+ expect(backend.bulkInsert).toHaveBeenCalled();
488
+ });
489
+ it('should skip entries already in AgentDB', async () => {
490
+ const topicContent = `# Test
491
+
492
+ ## Existing
493
+ Already in DB
494
+ `;
495
+ fsSync.writeFileSync(path.join(testDir, 'test.md'), topicContent, 'utf-8');
496
+ // Mock backend to return existing entry with matching content hash
497
+ backend.query.mockResolvedValue([{
498
+ id: 'existing-1',
499
+ metadata: { contentHash: hashContent('Already in DB') },
500
+ }]);
501
+ const result = await bridge.importFromAutoMemory();
502
+ expect(result.skipped).toBeGreaterThan(0);
503
+ });
504
+ it('should return zero imported for non-existent directory', async () => {
505
+ bridge.destroy();
506
+ bridge = new AutoMemoryBridge(backend, {
507
+ memoryDir: '/tmp/nonexistent-auto-memory-dir-xyz',
508
+ });
509
+ const result = await bridge.importFromAutoMemory();
510
+ expect(result.imported).toBe(0);
511
+ expect(result.files).toHaveLength(0);
512
+ });
513
+ it('should batch imports with bulkInsert', async () => {
514
+ // Create multiple files with multiple sections
515
+ fsSync.writeFileSync(path.join(testDir, 'file1.md'), '## A\nContent A\n## B\nContent B\n', 'utf-8');
516
+ fsSync.writeFileSync(path.join(testDir, 'file2.md'), '## C\nContent C\n', 'utf-8');
517
+ await bridge.importFromAutoMemory();
518
+ // bulkInsert should be called once with all entries
519
+ expect(backend.bulkInsert).toHaveBeenCalledTimes(1);
520
+ const batchArg = backend.bulkInsert.mock.calls[0][0];
521
+ expect(batchArg).toHaveLength(3);
522
+ });
523
+ });
524
+ describe('curateIndex', () => {
525
+ it('should generate MEMORY.md from topic files', async () => {
526
+ fsSync.writeFileSync(path.join(testDir, 'debugging.md'), '# Debugging\n\n- Init HNSW before search\n- Check embeddings dimension\n', 'utf-8');
527
+ fsSync.writeFileSync(path.join(testDir, 'performance.md'), '# Performance\n\n- Use Int8 quantization\n', 'utf-8');
528
+ await bridge.curateIndex();
529
+ const indexContent = fsSync.readFileSync(bridge.getIndexPath(), 'utf-8');
530
+ expect(indexContent).toContain('# Claude Flow V3 Project Memory');
531
+ expect(indexContent).toContain('Init HNSW before search');
532
+ expect(indexContent).toContain('Use Int8 quantization');
533
+ });
534
+ it('should stay under maxIndexLines', async () => {
535
+ const lines = ['# Debugging', ''];
536
+ for (let i = 0; i < 200; i++) {
537
+ lines.push(`- Item ${i} is a debugging insight`);
538
+ }
539
+ fsSync.writeFileSync(path.join(testDir, 'debugging.md'), lines.join('\n'), 'utf-8');
540
+ bridge.destroy();
541
+ bridge = new AutoMemoryBridge(backend, {
542
+ memoryDir: testDir,
543
+ maxIndexLines: 20,
544
+ });
545
+ await bridge.curateIndex();
546
+ const indexContent = fsSync.readFileSync(bridge.getIndexPath(), 'utf-8');
547
+ const indexLines = indexContent.split('\n');
548
+ expect(indexLines.length).toBeLessThanOrEqual(20);
549
+ });
550
+ it('should strip metadata from summaries in the index', async () => {
551
+ fsSync.writeFileSync(path.join(testDir, 'debugging.md'), '# Debugging\n\n- Fixed a bug _(agent:tester, 2026-02-08, conf: 0.90)_\n', 'utf-8');
552
+ await bridge.curateIndex();
553
+ const indexContent = fsSync.readFileSync(bridge.getIndexPath(), 'utf-8');
554
+ expect(indexContent).toContain('- Fixed a bug');
555
+ expect(indexContent).not.toContain('_(agent:tester');
556
+ });
557
+ it('should handle pruneStrategy=fifo by removing oldest entries', async () => {
558
+ const lines = ['# Debugging', ''];
559
+ for (let i = 0; i < 50; i++) {
560
+ lines.push(`- Item ${i}`);
561
+ }
562
+ fsSync.writeFileSync(path.join(testDir, 'debugging.md'), lines.join('\n'), 'utf-8');
563
+ bridge.destroy();
564
+ bridge = new AutoMemoryBridge(backend, {
565
+ memoryDir: testDir,
566
+ maxIndexLines: 10,
567
+ pruneStrategy: 'fifo',
568
+ });
569
+ await bridge.curateIndex();
570
+ const indexContent = fsSync.readFileSync(bridge.getIndexPath(), 'utf-8');
571
+ // FIFO removes oldest (first) items, keeps newest
572
+ expect(indexContent).toContain('Item 49');
573
+ expect(indexContent).not.toContain('Item 0');
574
+ });
575
+ // #1556: curateIndex() used to overwrite a hand-curated MEMORY.md with a
576
+ // single-line stub when none of the files in memoryDir matched the
577
+ // hardcoded DEFAULT_TOPIC_MAPPING filenames (as happens when Claude Code's
578
+ // native `<type>_<topic>.md` convention is used). The fix is to skip the
579
+ // write entirely when there's nothing to curate.
580
+ it('should not overwrite hand-curated MEMORY.md when no topic files match (#1556)', async () => {
581
+ const indexPath = path.join(testDir, 'MEMORY.md');
582
+ const handCurated = '# My Hand-Curated Memory\n\n## Section 1\nImportant notes\n\n## Section 2\nMore notes\n';
583
+ fsSync.writeFileSync(indexPath, handCurated, 'utf-8');
584
+ // Write files using Claude Code's native <type>_<topic>.md convention —
585
+ // none of these filenames appear in DEFAULT_TOPIC_MAPPING.
586
+ fsSync.writeFileSync(path.join(testDir, 'user_role.md'), '# user role\ndata scientist', 'utf-8');
587
+ fsSync.writeFileSync(path.join(testDir, 'session_foo.md'), '# session\nfoo bar', 'utf-8');
588
+ fsSync.writeFileSync(path.join(testDir, 'feedback_tone.md'), '# feedback\nbe concise', 'utf-8');
589
+ let skipEvent;
590
+ bridge.on('index:skipped', (e) => { skipEvent = e; });
591
+ await bridge.curateIndex();
592
+ // MEMORY.md must be byte-identical to what we wrote
593
+ const after = fsSync.readFileSync(indexPath, 'utf-8');
594
+ expect(after).toBe(handCurated);
595
+ // And the bridge should emit the skip event with a reason
596
+ expect(skipEvent).toBeDefined();
597
+ expect(skipEvent.reason).toBe('no-matching-topic-files');
598
+ });
599
+ });
600
+ describe('getStatus', () => {
601
+ it('should report status for existing directory', async () => {
602
+ fsSync.writeFileSync(path.join(testDir, 'MEMORY.md'), '# Memory\n- Item 1\n- Item 2\n', 'utf-8');
603
+ const status = bridge.getStatus();
604
+ expect(status.exists).toBe(true);
605
+ expect(status.memoryDir).toBe(testDir);
606
+ expect(status.files.length).toBeGreaterThan(0);
607
+ expect(status.indexLines).toBeGreaterThanOrEqual(3);
608
+ });
609
+ it('should report status for non-existent directory', () => {
610
+ bridge.destroy();
611
+ bridge = new AutoMemoryBridge(backend, {
612
+ memoryDir: '/tmp/nonexistent-dir-xyz',
613
+ });
614
+ const status = bridge.getStatus();
615
+ expect(status.exists).toBe(false);
616
+ expect(status.files).toHaveLength(0);
617
+ });
618
+ it('should count buffered insights', async () => {
619
+ await bridge.recordInsight(createTestInsight());
620
+ await bridge.recordInsight(createTestInsight({ summary: 'Another insight' }));
621
+ const status = bridge.getStatus();
622
+ expect(status.bufferedInsights).toBe(2);
623
+ });
624
+ it('should report lastSyncTime after sync', async () => {
625
+ expect(bridge.getStatus().lastSyncTime).toBe(0);
626
+ await bridge.syncToAutoMemory();
627
+ expect(bridge.getStatus().lastSyncTime).toBeGreaterThan(0);
628
+ });
629
+ });
630
+ describe('recordInsight - key uniqueness', () => {
631
+ it('should generate unique keys for rapid sequential inserts', async () => {
632
+ // Record multiple insights as fast as possible (same ms possible)
633
+ await bridge.recordInsight(createTestInsight({ summary: 'Insight A' }));
634
+ await bridge.recordInsight(createTestInsight({ summary: 'Insight B' }));
635
+ await bridge.recordInsight(createTestInsight({ summary: 'Insight C' }));
636
+ // All three should have unique keys
637
+ const keys = backend.storedEntries.map(e => e.key);
638
+ const uniqueKeys = new Set(keys);
639
+ expect(uniqueKeys.size).toBe(3);
640
+ });
641
+ });
642
+ describe('syncToAutoMemory - error handling', () => {
643
+ it('should emit sync:failed on backend query error', async () => {
644
+ const handler = vi.fn();
645
+ bridge.on('sync:failed', handler);
646
+ // Make ensureMemoryDir throw
647
+ backend.query.mockRejectedValueOnce(new Error('DB connection lost'));
648
+ // Record an insight so there's something to sync
649
+ await bridge.recordInsight(createTestInsight());
650
+ // The sync should still succeed for the buffered part
651
+ // because queryRecentInsights has its own try/catch
652
+ const result = await bridge.syncToAutoMemory();
653
+ expect(result.errors).toHaveLength(0);
654
+ });
655
+ it('should report errors for individual insight write failures', async () => {
656
+ // Create a read-only file to force a write error
657
+ const topicPath = bridge.getTopicPath('debugging');
658
+ fsSync.writeFileSync(topicPath, '# Debugging\n\n- Existing\n', 'utf-8');
659
+ fsSync.chmodSync(topicPath, 0o444); // read-only
660
+ await bridge.recordInsight(createTestInsight());
661
+ const result = await bridge.syncToAutoMemory();
662
+ // Should have error from trying to write to read-only file
663
+ expect(result.errors.length).toBeGreaterThan(0);
664
+ // Restore permissions for cleanup
665
+ fsSync.chmodSync(topicPath, 0o644);
666
+ });
667
+ });
668
+ describe('syncToAutoMemory - append to existing topic file', () => {
669
+ it('should append new insight to existing topic file', async () => {
670
+ // Create initial topic file
671
+ const topicPath = bridge.getTopicPath('debugging');
672
+ fsSync.writeFileSync(topicPath, '# Debugging\n\n- Existing item\n', 'utf-8');
673
+ bridge.destroy();
674
+ bridge = new AutoMemoryBridge(backend, {
675
+ memoryDir: testDir,
676
+ syncMode: 'on-write',
677
+ });
678
+ await bridge.recordInsight(createTestInsight({ summary: 'New insight' }));
679
+ const content = fsSync.readFileSync(topicPath, 'utf-8');
680
+ expect(content).toContain('Existing item');
681
+ expect(content).toContain('New insight');
682
+ });
683
+ it('should prune topic file when it exceeds maxTopicFileLines', async () => {
684
+ // Create a topic file near the limit
685
+ const topicPath = bridge.getTopicPath('debugging');
686
+ const lines = ['# Debugging', '', 'Description'];
687
+ for (let i = 0; i < 500; i++) {
688
+ lines.push(`- Entry ${i}`);
689
+ }
690
+ fsSync.writeFileSync(topicPath, lines.join('\n'), 'utf-8');
691
+ bridge.destroy();
692
+ bridge = new AutoMemoryBridge(backend, {
693
+ memoryDir: testDir,
694
+ syncMode: 'on-write',
695
+ maxTopicFileLines: 500,
696
+ });
697
+ await bridge.recordInsight(createTestInsight({ summary: 'Overflow insight' }));
698
+ const content = fsSync.readFileSync(topicPath, 'utf-8');
699
+ expect(content).toContain('Overflow insight');
700
+ // Old entries near the top should have been pruned
701
+ expect(content).not.toContain('Entry 0');
702
+ // Header should be preserved
703
+ expect(content).toContain('# Debugging');
704
+ });
705
+ });
706
+ describe('syncToAutoMemory - classifyEntry coverage', () => {
707
+ it('should classify by metadata category when present', async () => {
708
+ const entry = {
709
+ id: 'e1',
710
+ key: 'insight:security:999:0',
711
+ content: 'SQL injection found',
712
+ tags: ['insight'],
713
+ metadata: { category: 'security', summary: 'SQL injection found', confidence: 0.9 },
714
+ };
715
+ backend.query.mockResolvedValueOnce([entry]);
716
+ await bridge.syncToAutoMemory();
717
+ expect(fsSync.existsSync(bridge.getTopicPath('security'))).toBe(true);
718
+ const content = fsSync.readFileSync(bridge.getTopicPath('security'), 'utf-8');
719
+ expect(content).toContain('SQL injection found');
720
+ });
721
+ it('should classify by tags when metadata category is absent', async () => {
722
+ const entry = {
723
+ id: 'e2',
724
+ key: 'insight:unknown:999:0',
725
+ content: 'Performance is slow',
726
+ tags: ['insight', 'performance', 'benchmark'],
727
+ metadata: { summary: 'Performance is slow', confidence: 0.85 },
728
+ };
729
+ backend.query.mockResolvedValueOnce([entry]);
730
+ await bridge.syncToAutoMemory();
731
+ expect(fsSync.existsSync(bridge.getTopicPath('performance'))).toBe(true);
732
+ });
733
+ it('should default to project-patterns for unclassifiable entries', async () => {
734
+ const entry = {
735
+ id: 'e3',
736
+ key: 'insight:misc:999:0',
737
+ content: 'Miscellaneous note',
738
+ tags: ['insight'],
739
+ metadata: { summary: 'Miscellaneous note', confidence: 0.8 },
740
+ };
741
+ backend.query.mockResolvedValueOnce([entry]);
742
+ await bridge.syncToAutoMemory();
743
+ expect(fsSync.existsSync(bridge.getTopicPath('project-patterns'))).toBe(true);
744
+ });
745
+ it('should classify debugging tags correctly', async () => {
746
+ const bugEntry = {
747
+ id: 'e4',
748
+ key: 'insight:bug:999:0',
749
+ content: 'Found a bug',
750
+ tags: ['insight', 'bug'],
751
+ metadata: { summary: 'Found a bug', confidence: 0.9 },
752
+ };
753
+ backend.query.mockResolvedValueOnce([bugEntry]);
754
+ await bridge.syncToAutoMemory();
755
+ expect(fsSync.existsSync(bridge.getTopicPath('debugging'))).toBe(true);
756
+ });
757
+ it('should classify swarm/agent tags correctly', async () => {
758
+ const swarmEntry = {
759
+ id: 'e5',
760
+ key: 'insight:swarm:999:0',
761
+ content: 'Swarm completed successfully',
762
+ tags: ['insight', 'swarm'],
763
+ metadata: { summary: 'Swarm completed successfully', confidence: 0.9 },
764
+ };
765
+ backend.query.mockResolvedValueOnce([swarmEntry]);
766
+ await bridge.syncToAutoMemory();
767
+ expect(fsSync.existsSync(bridge.getTopicPath('swarm-results'))).toBe(true);
768
+ });
769
+ });
770
+ describe('importFromAutoMemory - edge cases', () => {
771
+ it('should emit import:completed event', async () => {
772
+ const handler = vi.fn();
773
+ bridge.on('import:completed', handler);
774
+ fsSync.writeFileSync(path.join(testDir, 'test.md'), '## Section\nContent here\n', 'utf-8');
775
+ await bridge.importFromAutoMemory();
776
+ expect(handler).toHaveBeenCalledWith(expect.objectContaining({
777
+ imported: expect.any(Number),
778
+ durationMs: expect.any(Number),
779
+ }));
780
+ });
781
+ it('should import files with no ## headings as a single untitled entry (issue #2283)', async () => {
782
+ // Pre-#2283 the parser dropped these silently. Now a file with body but
783
+ // no sub-headings imports as one entry with the full body as content.
784
+ fsSync.writeFileSync(path.join(testDir, 'empty.md'), '# Just a title\nSome text without sections\n', 'utf-8');
785
+ const result = await bridge.importFromAutoMemory();
786
+ expect(result.imported).toBe(1);
787
+ expect(result.files).toContain('empty.md');
788
+ });
789
+ });
790
+ describe('curateIndex - edge cases', () => {
791
+ it('should skip index write when topic files have no extractable summaries', async () => {
792
+ // #1556: curateIndex must be non-destructive when there's nothing to
793
+ // curate. Previously it would overwrite MEMORY.md with a title-only
794
+ // stub; now it emits 'index:skipped' and leaves any existing file alone.
795
+ fsSync.writeFileSync(path.join(testDir, 'debugging.md'), '# Debugging\n\n', 'utf-8');
796
+ let skipEvent;
797
+ bridge.on('index:skipped', (e) => { skipEvent = e; });
798
+ await bridge.curateIndex();
799
+ expect(skipEvent).toBeDefined();
800
+ expect(skipEvent.reason).toBe('no-matching-topic-files');
801
+ expect(fsSync.existsSync(bridge.getIndexPath())).toBe(false);
802
+ });
803
+ it('should emit index:curated event', async () => {
804
+ const handler = vi.fn();
805
+ bridge.on('index:curated', handler);
806
+ fsSync.writeFileSync(path.join(testDir, 'debugging.md'), '# Debugging\n\n- An item\n', 'utf-8');
807
+ await bridge.curateIndex();
808
+ expect(handler).toHaveBeenCalledWith(expect.objectContaining({
809
+ lines: expect.any(Number),
810
+ }));
811
+ });
812
+ it('should handle pruneStrategy=lru same as fifo', async () => {
813
+ const lines = ['# Debugging', ''];
814
+ for (let i = 0; i < 50; i++) {
815
+ lines.push(`- Item ${i}`);
816
+ }
817
+ fsSync.writeFileSync(path.join(testDir, 'debugging.md'), lines.join('\n'), 'utf-8');
818
+ bridge.destroy();
819
+ bridge = new AutoMemoryBridge(backend, {
820
+ memoryDir: testDir,
821
+ maxIndexLines: 10,
822
+ pruneStrategy: 'lru',
823
+ });
824
+ await bridge.curateIndex();
825
+ const indexContent = fsSync.readFileSync(bridge.getIndexPath(), 'utf-8');
826
+ // LRU removes oldest (first) items, same as FIFO
827
+ expect(indexContent).toContain('Item 49');
828
+ expect(indexContent).not.toContain('Item 0');
829
+ });
830
+ });
831
+ describe('destroy', () => {
832
+ it('should clean up periodic sync timer', () => {
833
+ const periodicBridge = new AutoMemoryBridge(backend, {
834
+ memoryDir: testDir,
835
+ syncMode: 'periodic',
836
+ syncIntervalMs: 1000,
837
+ });
838
+ periodicBridge.destroy();
839
+ });
840
+ it('should remove all listeners', () => {
841
+ bridge.on('insight:recorded', () => { });
842
+ bridge.on('sync:completed', () => { });
843
+ bridge.destroy();
844
+ expect(bridge.listenerCount('insight:recorded')).toBe(0);
845
+ expect(bridge.listenerCount('sync:completed')).toBe(0);
846
+ });
847
+ });
848
+ });
849
+ //# sourceMappingURL=auto-memory-bridge.test.js.map