@danielsimonjr/memory-mcp 12.5.2 → 12.7.1

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 (159) hide show
  1. package/README.md +158 -14
  2. package/dist/core/EntityManager.d.ts +263 -0
  3. package/dist/core/EntityManager.d.ts.map +1 -0
  4. package/dist/core/EntityManager.js +478 -0
  5. package/dist/core/GraphStorage.d.ts +344 -0
  6. package/dist/core/GraphStorage.d.ts.map +1 -0
  7. package/dist/core/GraphStorage.js +708 -0
  8. package/dist/core/GraphTraversal.d.ts +136 -0
  9. package/dist/core/GraphTraversal.d.ts.map +1 -0
  10. package/dist/core/GraphTraversal.js +556 -0
  11. package/dist/core/HierarchyManager.d.ts +111 -0
  12. package/dist/core/HierarchyManager.d.ts.map +1 -0
  13. package/dist/core/HierarchyManager.js +224 -0
  14. package/dist/core/ManagerContext.d.ts +72 -0
  15. package/dist/core/ManagerContext.d.ts.map +1 -0
  16. package/dist/core/ManagerContext.js +118 -0
  17. package/dist/core/ObservationManager.d.ts +85 -0
  18. package/dist/core/ObservationManager.d.ts.map +1 -0
  19. package/dist/core/ObservationManager.js +123 -0
  20. package/dist/core/RelationManager.d.ts +131 -0
  21. package/dist/core/RelationManager.d.ts.map +1 -0
  22. package/dist/core/RelationManager.js +210 -0
  23. package/dist/core/SQLiteStorage.d.ts +354 -0
  24. package/dist/core/SQLiteStorage.d.ts.map +1 -0
  25. package/dist/core/SQLiteStorage.js +917 -0
  26. package/dist/core/StorageFactory.d.ts +45 -0
  27. package/dist/core/StorageFactory.d.ts.map +1 -0
  28. package/dist/core/StorageFactory.js +64 -0
  29. package/dist/core/TransactionManager.d.ts +259 -0
  30. package/dist/core/TransactionManager.d.ts.map +1 -0
  31. package/dist/core/TransactionManager.js +392 -0
  32. package/dist/core/index.d.ts +16 -0
  33. package/dist/core/index.d.ts.map +1 -0
  34. package/dist/core/index.js +17 -0
  35. package/dist/features/AnalyticsManager.d.ts +44 -0
  36. package/dist/features/AnalyticsManager.d.ts.map +1 -0
  37. package/dist/features/AnalyticsManager.js +223 -0
  38. package/dist/features/ArchiveManager.d.ts +121 -0
  39. package/dist/features/ArchiveManager.d.ts.map +1 -0
  40. package/dist/features/ArchiveManager.js +240 -0
  41. package/dist/features/CompressionManager.d.ts +109 -0
  42. package/dist/features/CompressionManager.d.ts.map +1 -0
  43. package/dist/features/CompressionManager.js +404 -0
  44. package/dist/features/IOManager.d.ts +221 -0
  45. package/dist/features/IOManager.d.ts.map +1 -0
  46. package/dist/features/IOManager.js +997 -0
  47. package/dist/features/StreamingExporter.d.ts +105 -0
  48. package/dist/features/StreamingExporter.d.ts.map +1 -0
  49. package/dist/features/StreamingExporter.js +150 -0
  50. package/dist/features/TagManager.d.ts +147 -0
  51. package/dist/features/TagManager.d.ts.map +1 -0
  52. package/dist/features/TagManager.js +210 -0
  53. package/dist/features/index.d.ts +12 -0
  54. package/dist/features/index.d.ts.map +1 -0
  55. package/dist/features/index.js +11 -0
  56. package/dist/index.js +16 -4
  57. package/dist/search/BasicSearch.d.ts +51 -0
  58. package/dist/search/BasicSearch.d.ts.map +1 -0
  59. package/dist/search/BasicSearch.js +137 -0
  60. package/dist/search/BooleanSearch.d.ts +98 -0
  61. package/dist/search/BooleanSearch.d.ts.map +1 -0
  62. package/dist/search/BooleanSearch.js +430 -0
  63. package/dist/search/EmbeddingService.d.ts +178 -0
  64. package/dist/search/EmbeddingService.d.ts.map +1 -0
  65. package/dist/search/EmbeddingService.js +358 -0
  66. package/dist/search/FuzzySearch.d.ts +118 -0
  67. package/dist/search/FuzzySearch.d.ts.map +1 -0
  68. package/dist/search/FuzzySearch.js +312 -0
  69. package/dist/search/RankedSearch.d.ts +71 -0
  70. package/dist/search/RankedSearch.d.ts.map +1 -0
  71. package/dist/search/RankedSearch.js +238 -0
  72. package/dist/search/SavedSearchManager.d.ts +79 -0
  73. package/dist/search/SavedSearchManager.d.ts.map +1 -0
  74. package/dist/search/SavedSearchManager.js +145 -0
  75. package/dist/search/SearchFilterChain.d.ts +120 -0
  76. package/dist/search/SearchFilterChain.d.ts.map +1 -0
  77. package/dist/search/SearchFilterChain.js +185 -0
  78. package/dist/search/SearchManager.d.ts +285 -0
  79. package/dist/search/SearchManager.d.ts.map +1 -0
  80. package/dist/search/SearchManager.js +338 -0
  81. package/dist/search/SearchSuggestions.d.ts +27 -0
  82. package/dist/search/SearchSuggestions.d.ts.map +1 -0
  83. package/dist/search/SearchSuggestions.js +57 -0
  84. package/dist/search/SemanticSearch.d.ts +146 -0
  85. package/dist/search/SemanticSearch.d.ts.map +1 -0
  86. package/dist/search/SemanticSearch.js +313 -0
  87. package/dist/search/TFIDFIndexManager.d.ts +63 -0
  88. package/dist/search/TFIDFIndexManager.d.ts.map +1 -0
  89. package/dist/search/TFIDFIndexManager.js +215 -0
  90. package/dist/search/VectorStore.d.ts +235 -0
  91. package/dist/search/VectorStore.d.ts.map +1 -0
  92. package/dist/search/VectorStore.js +311 -0
  93. package/dist/search/index.d.ts +18 -0
  94. package/dist/search/index.d.ts.map +1 -0
  95. package/dist/search/index.js +21 -0
  96. package/dist/server/MCPServer.d.ts.map +1 -1
  97. package/dist/server/toolDefinitions.d.ts +1 -1
  98. package/dist/server/toolDefinitions.d.ts.map +1 -1
  99. package/dist/server/toolDefinitions.js +254 -2
  100. package/dist/server/toolHandlers.d.ts.map +1 -1
  101. package/dist/server/toolHandlers.js +257 -26
  102. package/dist/types/index.d.ts +13 -0
  103. package/dist/types/index.d.ts.map +1 -0
  104. package/dist/types/index.js +12 -0
  105. package/dist/types/types.d.ts +1234 -0
  106. package/dist/types/types.d.ts.map +1 -0
  107. package/dist/types/types.js +9 -0
  108. package/dist/utils/compressedCache.d.ts +192 -0
  109. package/dist/utils/compressedCache.d.ts.map +1 -0
  110. package/dist/utils/compressedCache.js +309 -0
  111. package/dist/utils/compressionUtil.d.ts +214 -0
  112. package/dist/utils/compressionUtil.d.ts.map +1 -0
  113. package/dist/utils/compressionUtil.js +247 -0
  114. package/dist/utils/constants.d.ts +245 -0
  115. package/dist/utils/constants.d.ts.map +1 -0
  116. package/dist/utils/constants.js +252 -0
  117. package/dist/utils/entityUtils.d.ts +321 -0
  118. package/dist/utils/entityUtils.d.ts.map +1 -0
  119. package/dist/utils/entityUtils.js +538 -0
  120. package/dist/utils/errors.d.ts +77 -0
  121. package/dist/utils/errors.d.ts.map +1 -0
  122. package/dist/utils/errors.js +121 -0
  123. package/dist/utils/formatters.d.ts +145 -0
  124. package/dist/utils/formatters.d.ts.map +1 -0
  125. package/dist/utils/formatters.js +132 -0
  126. package/dist/utils/index.d.ts +22 -0
  127. package/dist/utils/index.d.ts.map +1 -0
  128. package/dist/utils/index.js +75 -0
  129. package/dist/utils/indexes.d.ts +270 -0
  130. package/dist/utils/indexes.d.ts.map +1 -0
  131. package/dist/utils/indexes.js +526 -0
  132. package/dist/utils/logger.d.ts +24 -0
  133. package/dist/utils/logger.d.ts.map +1 -0
  134. package/dist/utils/logger.js +33 -0
  135. package/dist/utils/parallelUtils.d.ts +72 -0
  136. package/dist/utils/parallelUtils.d.ts.map +1 -0
  137. package/dist/utils/parallelUtils.js +169 -0
  138. package/dist/utils/schemas.d.ts +374 -0
  139. package/dist/utils/schemas.d.ts.map +1 -0
  140. package/dist/utils/schemas.js +484 -0
  141. package/dist/utils/searchAlgorithms.d.ts +99 -0
  142. package/dist/utils/searchAlgorithms.d.ts.map +1 -0
  143. package/dist/utils/searchAlgorithms.js +167 -0
  144. package/dist/utils/searchCache.d.ts +108 -0
  145. package/dist/utils/searchCache.d.ts.map +1 -0
  146. package/dist/utils/searchCache.js +209 -0
  147. package/dist/utils/taskScheduler.d.ts +290 -0
  148. package/dist/utils/taskScheduler.d.ts.map +1 -0
  149. package/dist/utils/taskScheduler.js +466 -0
  150. package/dist/workers/WorkerPool.d.ts +81 -0
  151. package/dist/workers/WorkerPool.d.ts.map +1 -0
  152. package/dist/workers/WorkerPool.js +121 -0
  153. package/dist/workers/index.d.ts +12 -0
  154. package/dist/workers/index.d.ts.map +1 -0
  155. package/dist/workers/index.js +9 -0
  156. package/dist/workers/levenshteinWorker.d.ts +60 -0
  157. package/dist/workers/levenshteinWorker.d.ts.map +1 -0
  158. package/dist/workers/levenshteinWorker.js +98 -0
  159. package/package.json +9 -8
@@ -0,0 +1,478 @@
1
+ /**
2
+ * Entity Manager
3
+ *
4
+ * Handles CRUD operations for entities in the knowledge graph.
5
+ * Focused on core entity and tag operations only (Phase 4: Consolidate God Objects).
6
+ *
7
+ * @module core/EntityManager
8
+ */
9
+ import { EntityNotFoundError, InvalidImportanceError, ValidationError } from '../utils/errors.js';
10
+ import { BatchCreateEntitiesSchema, UpdateEntitySchema, EntityNamesSchema } from '../utils/index.js';
11
+ import { GRAPH_LIMITS } from '../utils/constants.js';
12
+ /**
13
+ * Minimum importance value (least important).
14
+ */
15
+ export const MIN_IMPORTANCE = 0;
16
+ /**
17
+ * Maximum importance value (most important).
18
+ */
19
+ export const MAX_IMPORTANCE = 10;
20
+ /**
21
+ * Manages entity operations with automatic timestamp handling.
22
+ */
23
+ export class EntityManager {
24
+ storage;
25
+ constructor(storage) {
26
+ this.storage = storage;
27
+ }
28
+ /**
29
+ * Create multiple entities in a single batch operation.
30
+ *
31
+ * This method performs the following operations:
32
+ * - Filters out entities that already exist (duplicate names)
33
+ * - Automatically adds createdAt and lastModified timestamps
34
+ * - Normalizes all tags to lowercase for consistent searching
35
+ * - Validates importance values (must be between 0-10)
36
+ *
37
+ * @param entities - Array of entities to create. Each entity must have a unique name.
38
+ * @returns Promise resolving to array of newly created entities (excludes duplicates)
39
+ * @throws {InvalidImportanceError} If any entity has importance outside the valid range [0-10]
40
+ *
41
+ * @example
42
+ * ```typescript
43
+ * const manager = new EntityManager(storage);
44
+ *
45
+ * // Create single entity
46
+ * const results = await manager.createEntities([{
47
+ * name: 'Alice',
48
+ * entityType: 'person',
49
+ * observations: ['Works as engineer', 'Lives in Seattle'],
50
+ * importance: 7,
51
+ * tags: ['Team', 'Engineering']
52
+ * }]);
53
+ *
54
+ * // Create multiple entities at once
55
+ * const users = await manager.createEntities([
56
+ * { name: 'Bob', entityType: 'person', observations: [] },
57
+ * { name: 'Charlie', entityType: 'person', observations: [] }
58
+ * ]);
59
+ * ```
60
+ */
61
+ async createEntities(entities) {
62
+ // Validate input
63
+ const validation = BatchCreateEntitiesSchema.safeParse(entities);
64
+ if (!validation.success) {
65
+ const errors = validation.error.issues.map((e) => `${e.path.join('.')}: ${e.message}`);
66
+ throw new ValidationError('Invalid entity data', errors);
67
+ }
68
+ // Use read-only graph for checking existing entities
69
+ const readGraph = await this.storage.loadGraph();
70
+ const timestamp = new Date().toISOString();
71
+ // Check graph size limits
72
+ const entitiesToAdd = entities.filter(e => !readGraph.entities.some(existing => existing.name === e.name));
73
+ if (readGraph.entities.length + entitiesToAdd.length > GRAPH_LIMITS.MAX_ENTITIES) {
74
+ throw new ValidationError('Graph size limit exceeded', [`Adding ${entitiesToAdd.length} entities would exceed maximum of ${GRAPH_LIMITS.MAX_ENTITIES} entities`]);
75
+ }
76
+ const newEntities = entitiesToAdd
77
+ .map(e => {
78
+ const entity = {
79
+ ...e,
80
+ createdAt: e.createdAt || timestamp,
81
+ lastModified: e.lastModified || timestamp,
82
+ };
83
+ // Normalize tags to lowercase
84
+ if (e.tags) {
85
+ entity.tags = e.tags.map(tag => tag.toLowerCase());
86
+ }
87
+ // Validate importance
88
+ if (e.importance !== undefined) {
89
+ if (e.importance < MIN_IMPORTANCE || e.importance > MAX_IMPORTANCE) {
90
+ throw new InvalidImportanceError(e.importance, MIN_IMPORTANCE, MAX_IMPORTANCE);
91
+ }
92
+ entity.importance = e.importance;
93
+ }
94
+ return entity;
95
+ });
96
+ // OPTIMIZED: Use append for single entity, bulk save for multiple
97
+ // (N individual appends is slower than one bulk write)
98
+ if (newEntities.length === 1) {
99
+ await this.storage.appendEntity(newEntities[0]);
100
+ }
101
+ else if (newEntities.length > 1) {
102
+ const graph = await this.storage.getGraphForMutation();
103
+ graph.entities.push(...newEntities);
104
+ await this.storage.saveGraph(graph);
105
+ }
106
+ return newEntities;
107
+ }
108
+ /**
109
+ * Delete multiple entities by name in a single batch operation.
110
+ *
111
+ * This method performs cascading deletion:
112
+ * - Removes all specified entities from the graph
113
+ * - Automatically removes all relations where these entities are source or target
114
+ * - Silently ignores entity names that don't exist (no error thrown)
115
+ *
116
+ * @param entityNames - Array of entity names to delete
117
+ * @returns Promise that resolves when deletion is complete
118
+ *
119
+ * @example
120
+ * ```typescript
121
+ * const manager = new EntityManager(storage);
122
+ *
123
+ * // Delete single entity
124
+ * await manager.deleteEntities(['Alice']);
125
+ *
126
+ * // Delete multiple entities at once
127
+ * await manager.deleteEntities(['Bob', 'Charlie', 'Dave']);
128
+ *
129
+ * // Safe to delete non-existent entities (no error)
130
+ * await manager.deleteEntities(['NonExistent']); // No error thrown
131
+ * ```
132
+ */
133
+ async deleteEntities(entityNames) {
134
+ // Validate input
135
+ const validation = EntityNamesSchema.safeParse(entityNames);
136
+ if (!validation.success) {
137
+ const errors = validation.error.issues.map((e) => `${e.path.join('.')}: ${e.message}`);
138
+ throw new ValidationError('Invalid entity names', errors);
139
+ }
140
+ const graph = await this.storage.getGraphForMutation();
141
+ // OPTIMIZED: Use Set for O(1) lookups instead of O(n) includes()
142
+ const namesToDelete = new Set(entityNames);
143
+ graph.entities = graph.entities.filter(e => !namesToDelete.has(e.name));
144
+ graph.relations = graph.relations.filter(r => !namesToDelete.has(r.from) && !namesToDelete.has(r.to));
145
+ await this.storage.saveGraph(graph);
146
+ }
147
+ /**
148
+ * Retrieve a single entity by its unique name.
149
+ *
150
+ * This is a read-only operation that does not modify the graph.
151
+ * Entity names are case-sensitive.
152
+ *
153
+ * @param name - The unique name of the entity to retrieve
154
+ * @returns Promise resolving to the Entity object if found, or null if not found
155
+ *
156
+ * @example
157
+ * ```typescript
158
+ * const manager = new EntityManager(storage);
159
+ *
160
+ * // Get an existing entity
161
+ * const alice = await manager.getEntity('Alice');
162
+ * if (alice) {
163
+ * console.log(alice.observations);
164
+ * console.log(alice.importance);
165
+ * }
166
+ *
167
+ * // Handle non-existent entity
168
+ * const missing = await manager.getEntity('NonExistent');
169
+ * console.log(missing); // null
170
+ * ```
171
+ */
172
+ async getEntity(name) {
173
+ const graph = await this.storage.loadGraph();
174
+ return graph.entities.find(e => e.name === name) || null;
175
+ }
176
+ /**
177
+ * Update one or more fields of an existing entity.
178
+ *
179
+ * This method allows partial updates - only the fields specified in the updates
180
+ * object will be changed. All other fields remain unchanged.
181
+ * The lastModified timestamp is automatically updated.
182
+ *
183
+ * @param name - The unique name of the entity to update
184
+ * @param updates - Partial entity object containing only the fields to update
185
+ * @returns Promise resolving to the fully updated Entity object
186
+ * @throws {EntityNotFoundError} If no entity with the given name exists
187
+ *
188
+ * @example
189
+ * ```typescript
190
+ * const manager = new EntityManager(storage);
191
+ *
192
+ * // Update importance only
193
+ * const updated = await manager.updateEntity('Alice', {
194
+ * importance: 9
195
+ * });
196
+ *
197
+ * // Update multiple fields
198
+ * await manager.updateEntity('Bob', {
199
+ * entityType: 'senior_engineer',
200
+ * tags: ['leadership', 'architecture'],
201
+ * observations: ['Led project X', 'Designed system Y']
202
+ * });
203
+ *
204
+ * // Add observations (requires reading existing entity first)
205
+ * const entity = await manager.getEntity('Charlie');
206
+ * if (entity) {
207
+ * await manager.updateEntity('Charlie', {
208
+ * observations: [...entity.observations, 'New observation']
209
+ * });
210
+ * }
211
+ * ```
212
+ */
213
+ async updateEntity(name, updates) {
214
+ // Validate input
215
+ const validation = UpdateEntitySchema.safeParse(updates);
216
+ if (!validation.success) {
217
+ const errors = validation.error.issues.map((e) => `${e.path.join('.')}: ${e.message}`);
218
+ throw new ValidationError('Invalid update data', errors);
219
+ }
220
+ const graph = await this.storage.getGraphForMutation();
221
+ const entity = graph.entities.find(e => e.name === name);
222
+ if (!entity) {
223
+ throw new EntityNotFoundError(name);
224
+ }
225
+ // Apply updates
226
+ Object.assign(entity, updates);
227
+ entity.lastModified = new Date().toISOString();
228
+ await this.storage.saveGraph(graph);
229
+ return entity;
230
+ }
231
+ /**
232
+ * Update multiple entities in a single batch operation.
233
+ *
234
+ * This method is more efficient than calling updateEntity multiple times
235
+ * as it loads and saves the graph only once. All updates are applied atomically.
236
+ * The lastModified timestamp is automatically updated for all entities.
237
+ *
238
+ * @param updates - Array of updates, each containing entity name and changes
239
+ * @returns Promise resolving to array of updated entities
240
+ * @throws {EntityNotFoundError} If any entity is not found
241
+ * @throws {ValidationError} If any update data is invalid
242
+ *
243
+ * @example
244
+ * ```typescript
245
+ * const manager = new EntityManager(storage);
246
+ *
247
+ * // Update multiple entities at once
248
+ * const updated = await manager.batchUpdate([
249
+ * { name: 'Alice', updates: { importance: 9 } },
250
+ * { name: 'Bob', updates: { importance: 8, tags: ['senior'] } },
251
+ * { name: 'Charlie', updates: { entityType: 'lead_engineer' } }
252
+ * ]);
253
+ *
254
+ * console.log(`Updated ${updated.length} entities`);
255
+ *
256
+ * // Efficiently update many entities (single graph load/save)
257
+ * const massUpdate = employees.map(name => ({
258
+ * name,
259
+ * updates: { tags: ['team-2024'] }
260
+ * }));
261
+ * await manager.batchUpdate(massUpdate);
262
+ * ```
263
+ */
264
+ async batchUpdate(updates) {
265
+ // Validate all updates first
266
+ for (const { updates: updateData } of updates) {
267
+ const validation = UpdateEntitySchema.safeParse(updateData);
268
+ if (!validation.success) {
269
+ const errors = validation.error.issues.map((e) => `${e.path.join('.')}: ${e.message}`);
270
+ throw new ValidationError('Invalid update data', errors);
271
+ }
272
+ }
273
+ const graph = await this.storage.getGraphForMutation();
274
+ const timestamp = new Date().toISOString();
275
+ const updatedEntities = [];
276
+ // OPTIMIZED: Build Map for O(1) lookups instead of O(n) find() per update
277
+ const entityIndex = new Map();
278
+ graph.entities.forEach((e, i) => entityIndex.set(e.name, i));
279
+ for (const { name, updates: updateData } of updates) {
280
+ const idx = entityIndex.get(name);
281
+ if (idx === undefined) {
282
+ throw new EntityNotFoundError(name);
283
+ }
284
+ const entity = graph.entities[idx];
285
+ // Apply updates
286
+ Object.assign(entity, updateData);
287
+ entity.lastModified = timestamp;
288
+ updatedEntities.push(entity);
289
+ }
290
+ await this.storage.saveGraph(graph);
291
+ return updatedEntities;
292
+ }
293
+ // ============================================================
294
+ // TAG OPERATIONS
295
+ // ============================================================
296
+ /**
297
+ * Add tags to an entity.
298
+ *
299
+ * Tags are normalized to lowercase and duplicates are filtered out.
300
+ *
301
+ * @param entityName - Name of the entity
302
+ * @param tags - Tags to add
303
+ * @returns Result with entity name and added tags
304
+ * @throws {EntityNotFoundError} If entity is not found
305
+ */
306
+ async addTags(entityName, tags) {
307
+ // OPTIMIZED: Use O(1) NameIndex lookup instead of loadGraph() + O(n) find()
308
+ const entity = this.storage.getEntityByName(entityName);
309
+ if (!entity) {
310
+ throw new EntityNotFoundError(entityName);
311
+ }
312
+ // Initialize tags array if it doesn't exist
313
+ const existingTags = entity.tags || [];
314
+ // Normalize tags to lowercase and filter out duplicates
315
+ const normalizedTags = tags.map(tag => tag.toLowerCase());
316
+ const newTags = normalizedTags.filter(tag => !existingTags.includes(tag));
317
+ if (newTags.length > 0) {
318
+ // OPTIMIZED: Use updateEntity for in-place update + append
319
+ await this.storage.updateEntity(entityName, { tags: [...existingTags, ...newTags] });
320
+ }
321
+ return { entityName, addedTags: newTags };
322
+ }
323
+ /**
324
+ * Remove tags from an entity.
325
+ *
326
+ * @param entityName - Name of the entity
327
+ * @param tags - Tags to remove
328
+ * @returns Result with entity name and removed tags
329
+ * @throws {EntityNotFoundError} If entity is not found
330
+ */
331
+ async removeTags(entityName, tags) {
332
+ const graph = await this.storage.getGraphForMutation();
333
+ const timestamp = new Date().toISOString();
334
+ const entity = graph.entities.find(e => e.name === entityName);
335
+ if (!entity) {
336
+ throw new EntityNotFoundError(entityName);
337
+ }
338
+ if (!entity.tags) {
339
+ return { entityName, removedTags: [] };
340
+ }
341
+ // Normalize tags to lowercase
342
+ const normalizedTags = tags.map(tag => tag.toLowerCase());
343
+ const originalLength = entity.tags.length;
344
+ // Capture existing tags (lowercase) BEFORE filtering to accurately track removals
345
+ const existingTagsLower = entity.tags.map(t => t.toLowerCase());
346
+ // Filter out the tags to remove
347
+ entity.tags = entity.tags.filter(tag => !normalizedTags.includes(tag.toLowerCase()));
348
+ // A tag was removed if it existed in the original tags
349
+ const removedTags = normalizedTags.filter(tag => existingTagsLower.includes(tag));
350
+ // Update lastModified timestamp if tags were removed
351
+ if (entity.tags.length < originalLength) {
352
+ entity.lastModified = timestamp;
353
+ }
354
+ await this.storage.saveGraph(graph);
355
+ return { entityName, removedTags };
356
+ }
357
+ /**
358
+ * Set importance level for an entity.
359
+ *
360
+ * @param entityName - Name of the entity
361
+ * @param importance - Importance level (0-10)
362
+ * @returns Result with entity name and importance
363
+ * @throws {EntityNotFoundError} If entity is not found
364
+ * @throws {Error} If importance is out of range
365
+ */
366
+ async setImportance(entityName, importance) {
367
+ // Validate importance range (0-10)
368
+ if (importance < 0 || importance > 10) {
369
+ throw new Error(`Importance must be between 0 and 10, got ${importance}`);
370
+ }
371
+ // OPTIMIZED: Use O(1) NameIndex lookup instead of loadGraph() + O(n) find()
372
+ const entity = this.storage.getEntityByName(entityName);
373
+ if (!entity) {
374
+ throw new EntityNotFoundError(entityName);
375
+ }
376
+ // Use updateEntity for in-place update + append
377
+ await this.storage.updateEntity(entityName, { importance });
378
+ return { entityName, importance };
379
+ }
380
+ /**
381
+ * Add tags to multiple entities in a single operation.
382
+ *
383
+ * @param entityNames - Names of entities to tag
384
+ * @param tags - Tags to add to each entity
385
+ * @returns Array of results showing which tags were added to each entity
386
+ */
387
+ async addTagsToMultipleEntities(entityNames, tags) {
388
+ const graph = await this.storage.getGraphForMutation();
389
+ const timestamp = new Date().toISOString();
390
+ const normalizedTags = tags.map(tag => tag.toLowerCase());
391
+ const results = [];
392
+ for (const entityName of entityNames) {
393
+ const entity = graph.entities.find(e => e.name === entityName);
394
+ if (!entity) {
395
+ continue; // Skip non-existent entities
396
+ }
397
+ // Initialize tags array if it doesn't exist
398
+ if (!entity.tags) {
399
+ entity.tags = [];
400
+ }
401
+ // Filter out duplicates
402
+ const newTags = normalizedTags.filter(tag => !entity.tags.includes(tag));
403
+ entity.tags.push(...newTags);
404
+ // Update lastModified timestamp if tags were added
405
+ if (newTags.length > 0) {
406
+ entity.lastModified = timestamp;
407
+ }
408
+ results.push({ entityName, addedTags: newTags });
409
+ }
410
+ await this.storage.saveGraph(graph);
411
+ return results;
412
+ }
413
+ /**
414
+ * Replace a tag with a new tag across all entities (rename tag).
415
+ *
416
+ * @param oldTag - Tag to replace
417
+ * @param newTag - New tag value
418
+ * @returns Result with affected entities and count
419
+ */
420
+ async replaceTag(oldTag, newTag) {
421
+ const graph = await this.storage.getGraphForMutation();
422
+ const timestamp = new Date().toISOString();
423
+ const normalizedOldTag = oldTag.toLowerCase();
424
+ const normalizedNewTag = newTag.toLowerCase();
425
+ const affectedEntities = [];
426
+ for (const entity of graph.entities) {
427
+ if (!entity.tags || !entity.tags.includes(normalizedOldTag)) {
428
+ continue;
429
+ }
430
+ // Replace old tag with new tag
431
+ const index = entity.tags.indexOf(normalizedOldTag);
432
+ entity.tags[index] = normalizedNewTag;
433
+ entity.lastModified = timestamp;
434
+ affectedEntities.push(entity.name);
435
+ }
436
+ await this.storage.saveGraph(graph);
437
+ return { affectedEntities, count: affectedEntities.length };
438
+ }
439
+ /**
440
+ * Merge two tags into one target tag across all entities.
441
+ *
442
+ * Combines tag1 and tag2 into targetTag. Any entity with either tag1 or tag2
443
+ * will have both removed and targetTag added (if not already present).
444
+ *
445
+ * @param tag1 - First tag to merge
446
+ * @param tag2 - Second tag to merge
447
+ * @param targetTag - Target tag to merge into
448
+ * @returns Object with affected entity names and count
449
+ */
450
+ async mergeTags(tag1, tag2, targetTag) {
451
+ const graph = await this.storage.getGraphForMutation();
452
+ const timestamp = new Date().toISOString();
453
+ const normalizedTag1 = tag1.toLowerCase();
454
+ const normalizedTag2 = tag2.toLowerCase();
455
+ const normalizedTargetTag = targetTag.toLowerCase();
456
+ const affectedEntities = [];
457
+ for (const entity of graph.entities) {
458
+ if (!entity.tags) {
459
+ continue;
460
+ }
461
+ const hasTag1 = entity.tags.includes(normalizedTag1);
462
+ const hasTag2 = entity.tags.includes(normalizedTag2);
463
+ if (!hasTag1 && !hasTag2) {
464
+ continue;
465
+ }
466
+ // Remove both tags
467
+ entity.tags = entity.tags.filter(tag => tag !== normalizedTag1 && tag !== normalizedTag2);
468
+ // Add target tag if not already present
469
+ if (!entity.tags.includes(normalizedTargetTag)) {
470
+ entity.tags.push(normalizedTargetTag);
471
+ }
472
+ entity.lastModified = timestamp;
473
+ affectedEntities.push(entity.name);
474
+ }
475
+ await this.storage.saveGraph(graph);
476
+ return { affectedEntities, count: affectedEntities.length };
477
+ }
478
+ }