@danielsimonjr/memory-mcp 0.7.2 → 0.47.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 (70) hide show
  1. package/dist/__tests__/edge-cases/edge-cases.test.js +406 -0
  2. package/dist/__tests__/file-path.test.js +5 -5
  3. package/dist/__tests__/integration/workflows.test.js +449 -0
  4. package/dist/__tests__/knowledge-graph.test.js +8 -3
  5. package/dist/__tests__/performance/benchmarks.test.js +413 -0
  6. package/dist/__tests__/unit/core/EntityManager.test.js +334 -0
  7. package/dist/__tests__/unit/core/GraphStorage.test.js +205 -0
  8. package/dist/__tests__/unit/core/RelationManager.test.js +274 -0
  9. package/dist/__tests__/unit/features/CompressionManager.test.js +350 -0
  10. package/dist/__tests__/unit/search/BasicSearch.test.js +311 -0
  11. package/dist/__tests__/unit/search/BooleanSearch.test.js +432 -0
  12. package/dist/__tests__/unit/search/FuzzySearch.test.js +448 -0
  13. package/dist/__tests__/unit/search/RankedSearch.test.js +379 -0
  14. package/dist/__tests__/unit/utils/levenshtein.test.js +77 -0
  15. package/dist/core/EntityManager.js +554 -0
  16. package/dist/core/GraphStorage.js +172 -0
  17. package/dist/core/KnowledgeGraphManager.js +423 -0
  18. package/dist/core/ObservationManager.js +129 -0
  19. package/dist/core/RelationManager.js +186 -0
  20. package/dist/core/TransactionManager.js +389 -0
  21. package/dist/core/index.js +9 -0
  22. package/dist/features/AnalyticsManager.js +222 -0
  23. package/dist/features/ArchiveManager.js +74 -0
  24. package/dist/features/BackupManager.js +311 -0
  25. package/dist/features/CompressionManager.js +291 -0
  26. package/dist/features/ExportManager.js +305 -0
  27. package/dist/features/HierarchyManager.js +219 -0
  28. package/dist/features/ImportExportManager.js +50 -0
  29. package/dist/features/ImportManager.js +328 -0
  30. package/dist/features/TagManager.js +210 -0
  31. package/dist/features/index.js +12 -0
  32. package/dist/index.js +13 -996
  33. package/dist/memory.jsonl +18 -0
  34. package/dist/search/BasicSearch.js +131 -0
  35. package/dist/search/BooleanSearch.js +283 -0
  36. package/dist/search/FuzzySearch.js +96 -0
  37. package/dist/search/RankedSearch.js +190 -0
  38. package/dist/search/SavedSearchManager.js +145 -0
  39. package/dist/search/SearchFilterChain.js +187 -0
  40. package/dist/search/SearchManager.js +305 -0
  41. package/dist/search/SearchSuggestions.js +57 -0
  42. package/dist/search/TFIDFIndexManager.js +217 -0
  43. package/dist/search/index.js +14 -0
  44. package/dist/server/MCPServer.js +52 -0
  45. package/dist/server/toolDefinitions.js +732 -0
  46. package/dist/server/toolHandlers.js +117 -0
  47. package/dist/types/analytics.types.js +6 -0
  48. package/dist/types/entity.types.js +7 -0
  49. package/dist/types/import-export.types.js +7 -0
  50. package/dist/types/index.js +12 -0
  51. package/dist/types/search.types.js +7 -0
  52. package/dist/types/tag.types.js +6 -0
  53. package/dist/utils/constants.js +128 -0
  54. package/dist/utils/dateUtils.js +89 -0
  55. package/dist/utils/entityUtils.js +108 -0
  56. package/dist/utils/errors.js +121 -0
  57. package/dist/utils/filterUtils.js +155 -0
  58. package/dist/utils/index.js +39 -0
  59. package/dist/utils/levenshtein.js +62 -0
  60. package/dist/utils/logger.js +33 -0
  61. package/dist/utils/paginationUtils.js +81 -0
  62. package/dist/utils/pathUtils.js +115 -0
  63. package/dist/utils/responseFormatter.js +55 -0
  64. package/dist/utils/schemas.js +184 -0
  65. package/dist/utils/searchCache.js +209 -0
  66. package/dist/utils/tagUtils.js +107 -0
  67. package/dist/utils/tfidf.js +90 -0
  68. package/dist/utils/validationHelper.js +99 -0
  69. package/dist/utils/validationUtils.js +109 -0
  70. package/package.json +82 -48
@@ -0,0 +1,291 @@
1
+ /**
2
+ * Compression Manager
3
+ *
4
+ * Detects and merges duplicate entities to compress the knowledge graph.
5
+ *
6
+ * @module features/CompressionManager
7
+ */
8
+ import { levenshteinDistance } from '../utils/levenshtein.js';
9
+ import { EntityNotFoundError, InsufficientEntitiesError } from '../utils/errors.js';
10
+ import { SIMILARITY_WEIGHTS, DEFAULT_DUPLICATE_THRESHOLD } from '../utils/constants.js';
11
+ /**
12
+ * Manages graph compression through duplicate detection and merging.
13
+ */
14
+ export class CompressionManager {
15
+ storage;
16
+ constructor(storage) {
17
+ this.storage = storage;
18
+ }
19
+ /**
20
+ * Calculate similarity between two entities using multiple heuristics.
21
+ *
22
+ * Uses configurable weights defined in SIMILARITY_WEIGHTS constant.
23
+ * See SIMILARITY_WEIGHTS for the breakdown of scoring factors.
24
+ *
25
+ * @param e1 - First entity
26
+ * @param e2 - Second entity
27
+ * @returns Similarity score from 0 (completely different) to 1 (identical)
28
+ */
29
+ calculateEntitySimilarity(e1, e2) {
30
+ let score = 0;
31
+ let factors = 0;
32
+ // Name similarity (Levenshtein-based)
33
+ const nameDistance = levenshteinDistance(e1.name.toLowerCase(), e2.name.toLowerCase());
34
+ const maxNameLength = Math.max(e1.name.length, e2.name.length);
35
+ const nameSimilarity = 1 - nameDistance / maxNameLength;
36
+ score += nameSimilarity * SIMILARITY_WEIGHTS.NAME;
37
+ factors += SIMILARITY_WEIGHTS.NAME;
38
+ // Type similarity (exact match)
39
+ if (e1.entityType.toLowerCase() === e2.entityType.toLowerCase()) {
40
+ score += SIMILARITY_WEIGHTS.TYPE;
41
+ }
42
+ factors += SIMILARITY_WEIGHTS.TYPE;
43
+ // Observation overlap (Jaccard similarity)
44
+ const obs1Set = new Set(e1.observations.map(o => o.toLowerCase()));
45
+ const obs2Set = new Set(e2.observations.map(o => o.toLowerCase()));
46
+ const intersection = new Set([...obs1Set].filter(x => obs2Set.has(x)));
47
+ const union = new Set([...obs1Set, ...obs2Set]);
48
+ const observationSimilarity = union.size > 0 ? intersection.size / union.size : 0;
49
+ score += observationSimilarity * SIMILARITY_WEIGHTS.OBSERVATIONS;
50
+ factors += SIMILARITY_WEIGHTS.OBSERVATIONS;
51
+ // Tag overlap (Jaccard similarity)
52
+ if (e1.tags && e2.tags && (e1.tags.length > 0 || e2.tags.length > 0)) {
53
+ const tags1Set = new Set(e1.tags.map(t => t.toLowerCase()));
54
+ const tags2Set = new Set(e2.tags.map(t => t.toLowerCase()));
55
+ const tagIntersection = new Set([...tags1Set].filter(x => tags2Set.has(x)));
56
+ const tagUnion = new Set([...tags1Set, ...tags2Set]);
57
+ const tagSimilarity = tagUnion.size > 0 ? tagIntersection.size / tagUnion.size : 0;
58
+ score += tagSimilarity * SIMILARITY_WEIGHTS.TAGS;
59
+ factors += SIMILARITY_WEIGHTS.TAGS;
60
+ }
61
+ return factors > 0 ? score / factors : 0;
62
+ }
63
+ /**
64
+ * Find duplicate entities in the graph based on similarity threshold.
65
+ *
66
+ * OPTIMIZED: Uses bucketing strategies to reduce O(n²) comparisons:
67
+ * 1. Buckets entities by entityType (only compare same types)
68
+ * 2. Within each type, buckets by name prefix (first 2 chars normalized)
69
+ * 3. Only compares entities within same or adjacent buckets
70
+ *
71
+ * Complexity: O(n·k) where k is average bucket size (typically << n)
72
+ *
73
+ * @param threshold - Similarity threshold (0.0 to 1.0), default DEFAULT_DUPLICATE_THRESHOLD
74
+ * @returns Array of duplicate groups (each group has similar entities)
75
+ */
76
+ async findDuplicates(threshold = DEFAULT_DUPLICATE_THRESHOLD) {
77
+ const graph = await this.storage.loadGraph();
78
+ const duplicateGroups = [];
79
+ const processed = new Set();
80
+ // Step 1: Bucket entities by type (reduces comparisons drastically)
81
+ const typeMap = new Map();
82
+ for (const entity of graph.entities) {
83
+ const normalizedType = entity.entityType.toLowerCase();
84
+ if (!typeMap.has(normalizedType)) {
85
+ typeMap.set(normalizedType, []);
86
+ }
87
+ typeMap.get(normalizedType).push(entity);
88
+ }
89
+ // Step 2: For each type bucket, sub-bucket by name prefix
90
+ for (const entities of typeMap.values()) {
91
+ // Skip single-entity types (no duplicates possible)
92
+ if (entities.length < 2)
93
+ continue;
94
+ // Create name prefix buckets (first 2 chars, normalized)
95
+ const prefixMap = new Map();
96
+ for (const entity of entities) {
97
+ const prefix = entity.name.toLowerCase().slice(0, 2);
98
+ if (!prefixMap.has(prefix)) {
99
+ prefixMap.set(prefix, []);
100
+ }
101
+ prefixMap.get(prefix).push(entity);
102
+ }
103
+ // Step 3: Compare only within buckets (or adjacent buckets for fuzzy matching)
104
+ const prefixKeys = Array.from(prefixMap.keys()).sort();
105
+ for (let bucketIdx = 0; bucketIdx < prefixKeys.length; bucketIdx++) {
106
+ const currentPrefix = prefixKeys[bucketIdx];
107
+ const currentBucket = prefixMap.get(currentPrefix);
108
+ // Collect entities to compare: current bucket + adjacent buckets
109
+ const candidateEntities = [...currentBucket];
110
+ // Add next bucket if exists (handles fuzzy prefix matching)
111
+ if (bucketIdx + 1 < prefixKeys.length) {
112
+ candidateEntities.push(...prefixMap.get(prefixKeys[bucketIdx + 1]));
113
+ }
114
+ // Compare entities within candidate pool
115
+ for (let i = 0; i < currentBucket.length; i++) {
116
+ const entity1 = currentBucket[i];
117
+ if (processed.has(entity1.name))
118
+ continue;
119
+ const group = [entity1.name];
120
+ for (let j = 0; j < candidateEntities.length; j++) {
121
+ const entity2 = candidateEntities[j];
122
+ if (entity1.name === entity2.name || processed.has(entity2.name))
123
+ continue;
124
+ const similarity = this.calculateEntitySimilarity(entity1, entity2);
125
+ if (similarity >= threshold) {
126
+ group.push(entity2.name);
127
+ processed.add(entity2.name);
128
+ }
129
+ }
130
+ if (group.length > 1) {
131
+ duplicateGroups.push(group);
132
+ processed.add(entity1.name);
133
+ }
134
+ }
135
+ }
136
+ }
137
+ return duplicateGroups;
138
+ }
139
+ /**
140
+ * Merge a group of entities into a single entity.
141
+ *
142
+ * Merging strategy:
143
+ * - First entity is kept (or renamed to targetName)
144
+ * - Observations: Union of all observations
145
+ * - Tags: Union of all tags
146
+ * - Importance: Maximum importance value
147
+ * - createdAt: Earliest date
148
+ * - lastModified: Current timestamp
149
+ * - Relations: Redirected to kept entity, duplicates removed
150
+ *
151
+ * @param entityNames - Names of entities to merge (first one is kept)
152
+ * @param targetName - Optional new name for merged entity (default: first entity name)
153
+ * @returns The merged entity
154
+ * @throws {InsufficientEntitiesError} If less than 2 entities provided
155
+ * @throws {EntityNotFoundError} If any entity not found
156
+ */
157
+ async mergeEntities(entityNames, targetName) {
158
+ if (entityNames.length < 2) {
159
+ throw new InsufficientEntitiesError('merging', 2, entityNames.length);
160
+ }
161
+ const graph = await this.storage.loadGraph();
162
+ const entitiesToMerge = entityNames.map(name => {
163
+ const entity = graph.entities.find(e => e.name === name);
164
+ if (!entity) {
165
+ throw new EntityNotFoundError(name);
166
+ }
167
+ return entity;
168
+ });
169
+ const keepEntity = entitiesToMerge[0];
170
+ const mergeEntities = entitiesToMerge.slice(1);
171
+ // Merge observations (unique)
172
+ const allObservations = new Set();
173
+ for (const entity of entitiesToMerge) {
174
+ entity.observations.forEach(obs => allObservations.add(obs));
175
+ }
176
+ keepEntity.observations = Array.from(allObservations);
177
+ // Merge tags (unique)
178
+ const allTags = new Set();
179
+ for (const entity of entitiesToMerge) {
180
+ if (entity.tags) {
181
+ entity.tags.forEach(tag => allTags.add(tag));
182
+ }
183
+ }
184
+ if (allTags.size > 0) {
185
+ keepEntity.tags = Array.from(allTags);
186
+ }
187
+ // Use highest importance
188
+ const importances = entitiesToMerge
189
+ .map(e => e.importance)
190
+ .filter(imp => imp !== undefined);
191
+ if (importances.length > 0) {
192
+ keepEntity.importance = Math.max(...importances);
193
+ }
194
+ // Use earliest createdAt
195
+ const createdDates = entitiesToMerge
196
+ .map(e => e.createdAt)
197
+ .filter(date => date !== undefined);
198
+ if (createdDates.length > 0) {
199
+ keepEntity.createdAt = createdDates.sort()[0];
200
+ }
201
+ // Update lastModified
202
+ keepEntity.lastModified = new Date().toISOString();
203
+ // Rename if requested
204
+ if (targetName && targetName !== keepEntity.name) {
205
+ // Update all relations pointing to old name
206
+ graph.relations.forEach(rel => {
207
+ if (rel.from === keepEntity.name)
208
+ rel.from = targetName;
209
+ if (rel.to === keepEntity.name)
210
+ rel.to = targetName;
211
+ });
212
+ keepEntity.name = targetName;
213
+ }
214
+ // Update relations from merged entities to point to kept entity
215
+ for (const mergeEntity of mergeEntities) {
216
+ graph.relations.forEach(rel => {
217
+ if (rel.from === mergeEntity.name)
218
+ rel.from = keepEntity.name;
219
+ if (rel.to === mergeEntity.name)
220
+ rel.to = keepEntity.name;
221
+ });
222
+ }
223
+ // Remove duplicate relations
224
+ const uniqueRelations = new Map();
225
+ for (const relation of graph.relations) {
226
+ const key = `${relation.from}|${relation.to}|${relation.relationType}`;
227
+ if (!uniqueRelations.has(key)) {
228
+ uniqueRelations.set(key, relation);
229
+ }
230
+ }
231
+ graph.relations = Array.from(uniqueRelations.values());
232
+ // Remove merged entities
233
+ const mergeNames = new Set(mergeEntities.map(e => e.name));
234
+ graph.entities = graph.entities.filter(e => !mergeNames.has(e.name));
235
+ await this.storage.saveGraph(graph);
236
+ return keepEntity;
237
+ }
238
+ /**
239
+ * Compress the knowledge graph by finding and merging duplicates.
240
+ *
241
+ * @param threshold - Similarity threshold for duplicate detection (0.0 to 1.0), default DEFAULT_DUPLICATE_THRESHOLD
242
+ * @param dryRun - If true, only report what would be compressed without applying changes
243
+ * @returns Compression result with statistics
244
+ */
245
+ async compressGraph(threshold = DEFAULT_DUPLICATE_THRESHOLD, dryRun = false) {
246
+ const initialGraph = await this.storage.loadGraph();
247
+ const initialSize = JSON.stringify(initialGraph).length;
248
+ const duplicateGroups = await this.findDuplicates(threshold);
249
+ const result = {
250
+ duplicatesFound: duplicateGroups.reduce((sum, group) => sum + group.length, 0),
251
+ entitiesMerged: 0,
252
+ observationsCompressed: 0,
253
+ relationsConsolidated: 0,
254
+ spaceFreed: 0,
255
+ mergedEntities: [],
256
+ };
257
+ if (dryRun) {
258
+ // Just report what would happen
259
+ for (const group of duplicateGroups) {
260
+ result.mergedEntities.push({
261
+ kept: group[0],
262
+ merged: group.slice(1),
263
+ });
264
+ result.entitiesMerged += group.length - 1;
265
+ }
266
+ return result;
267
+ }
268
+ // Actually merge duplicates
269
+ for (const group of duplicateGroups) {
270
+ try {
271
+ await this.mergeEntities(group);
272
+ result.mergedEntities.push({
273
+ kept: group[0],
274
+ merged: group.slice(1),
275
+ });
276
+ result.entitiesMerged += group.length - 1;
277
+ }
278
+ catch (error) {
279
+ // Skip groups that fail to merge
280
+ console.error(`Failed to merge group ${group}:`, error);
281
+ }
282
+ }
283
+ // Calculate space saved
284
+ const finalGraph = await this.storage.loadGraph();
285
+ const finalSize = JSON.stringify(finalGraph).length;
286
+ result.spaceFreed = initialSize - finalSize;
287
+ // Count compressed observations (approximation)
288
+ result.observationsCompressed = result.entitiesMerged;
289
+ return result;
290
+ }
291
+ }
@@ -0,0 +1,305 @@
1
+ /**
2
+ * Export Manager
3
+ *
4
+ * Exports knowledge graphs to various formats (JSON, CSV, GraphML, GEXF, DOT, Markdown, Mermaid).
5
+ *
6
+ * @module features/ExportManager
7
+ */
8
+ /**
9
+ * Manages knowledge graph exports to multiple formats.
10
+ */
11
+ export class ExportManager {
12
+ /**
13
+ * Export graph to specified format.
14
+ *
15
+ * @param graph - Knowledge graph to export
16
+ * @param format - Export format
17
+ * @returns Formatted export string
18
+ */
19
+ exportGraph(graph, format) {
20
+ switch (format) {
21
+ case 'json':
22
+ return this.exportAsJson(graph);
23
+ case 'csv':
24
+ return this.exportAsCsv(graph);
25
+ case 'graphml':
26
+ return this.exportAsGraphML(graph);
27
+ case 'gexf':
28
+ return this.exportAsGEXF(graph);
29
+ case 'dot':
30
+ return this.exportAsDOT(graph);
31
+ case 'markdown':
32
+ return this.exportAsMarkdown(graph);
33
+ case 'mermaid':
34
+ return this.exportAsMermaid(graph);
35
+ default:
36
+ throw new Error(`Unsupported export format: ${format}`);
37
+ }
38
+ }
39
+ /**
40
+ * Export as pretty-printed JSON.
41
+ */
42
+ exportAsJson(graph) {
43
+ return JSON.stringify(graph, null, 2);
44
+ }
45
+ /**
46
+ * Export as CSV with proper escaping.
47
+ */
48
+ exportAsCsv(graph) {
49
+ const lines = [];
50
+ const escapeCsvField = (field) => {
51
+ if (field === undefined || field === null)
52
+ return '';
53
+ const str = String(field);
54
+ if (str.includes(',') || str.includes('"') || str.includes('\n')) {
55
+ return `"${str.replace(/"/g, '""')}"`;
56
+ }
57
+ return str;
58
+ };
59
+ // Entities section
60
+ lines.push('# ENTITIES');
61
+ lines.push('name,entityType,observations,createdAt,lastModified,tags,importance');
62
+ for (const entity of graph.entities) {
63
+ const observationsStr = entity.observations.join('; ');
64
+ const tagsStr = entity.tags ? entity.tags.join('; ') : '';
65
+ const importanceStr = entity.importance !== undefined ? String(entity.importance) : '';
66
+ lines.push([
67
+ escapeCsvField(entity.name),
68
+ escapeCsvField(entity.entityType),
69
+ escapeCsvField(observationsStr),
70
+ escapeCsvField(entity.createdAt),
71
+ escapeCsvField(entity.lastModified),
72
+ escapeCsvField(tagsStr),
73
+ escapeCsvField(importanceStr),
74
+ ].join(','));
75
+ }
76
+ // Relations section
77
+ lines.push('');
78
+ lines.push('# RELATIONS');
79
+ lines.push('from,to,relationType,createdAt,lastModified');
80
+ for (const relation of graph.relations) {
81
+ lines.push([
82
+ escapeCsvField(relation.from),
83
+ escapeCsvField(relation.to),
84
+ escapeCsvField(relation.relationType),
85
+ escapeCsvField(relation.createdAt),
86
+ escapeCsvField(relation.lastModified),
87
+ ].join(','));
88
+ }
89
+ return lines.join('\n');
90
+ }
91
+ /**
92
+ * Export as GraphML XML format.
93
+ */
94
+ exportAsGraphML(graph) {
95
+ const lines = [];
96
+ const escapeXml = (str) => {
97
+ if (str === undefined || str === null)
98
+ return '';
99
+ return String(str)
100
+ .replace(/&/g, '&amp;')
101
+ .replace(/</g, '&lt;')
102
+ .replace(/>/g, '&gt;')
103
+ .replace(/"/g, '&quot;')
104
+ .replace(/'/g, '&apos;');
105
+ };
106
+ lines.push('<?xml version="1.0" encoding="UTF-8"?>');
107
+ lines.push('<graphml xmlns="http://graphml.graphdrawing.org/xmlns">');
108
+ lines.push(' <key id="d0" for="node" attr.name="entityType" attr.type="string"/>');
109
+ lines.push(' <key id="d1" for="node" attr.name="observations" attr.type="string"/>');
110
+ lines.push(' <key id="d2" for="node" attr.name="createdAt" attr.type="string"/>');
111
+ lines.push(' <key id="d3" for="node" attr.name="lastModified" attr.type="string"/>');
112
+ lines.push(' <key id="d4" for="node" attr.name="tags" attr.type="string"/>');
113
+ lines.push(' <key id="d5" for="node" attr.name="importance" attr.type="double"/>');
114
+ lines.push(' <key id="e0" for="edge" attr.name="relationType" attr.type="string"/>');
115
+ lines.push(' <key id="e1" for="edge" attr.name="createdAt" attr.type="string"/>');
116
+ lines.push(' <key id="e2" for="edge" attr.name="lastModified" attr.type="string"/>');
117
+ lines.push(' <graph id="G" edgedefault="directed">');
118
+ // Nodes
119
+ for (const entity of graph.entities) {
120
+ const nodeId = escapeXml(entity.name);
121
+ lines.push(` <node id="${nodeId}">`);
122
+ lines.push(` <data key="d0">${escapeXml(entity.entityType)}</data>`);
123
+ lines.push(` <data key="d1">${escapeXml(entity.observations.join('; '))}</data>`);
124
+ if (entity.createdAt)
125
+ lines.push(` <data key="d2">${escapeXml(entity.createdAt)}</data>`);
126
+ if (entity.lastModified)
127
+ lines.push(` <data key="d3">${escapeXml(entity.lastModified)}</data>`);
128
+ if (entity.tags?.length)
129
+ lines.push(` <data key="d4">${escapeXml(entity.tags.join('; '))}</data>`);
130
+ if (entity.importance !== undefined)
131
+ lines.push(` <data key="d5">${entity.importance}</data>`);
132
+ lines.push(' </node>');
133
+ }
134
+ // Edges
135
+ let edgeId = 0;
136
+ for (const relation of graph.relations) {
137
+ const sourceId = escapeXml(relation.from);
138
+ const targetId = escapeXml(relation.to);
139
+ lines.push(` <edge id="e${edgeId}" source="${sourceId}" target="${targetId}">`);
140
+ lines.push(` <data key="e0">${escapeXml(relation.relationType)}</data>`);
141
+ if (relation.createdAt)
142
+ lines.push(` <data key="e1">${escapeXml(relation.createdAt)}</data>`);
143
+ if (relation.lastModified)
144
+ lines.push(` <data key="e2">${escapeXml(relation.lastModified)}</data>`);
145
+ lines.push(' </edge>');
146
+ edgeId++;
147
+ }
148
+ lines.push(' </graph>');
149
+ lines.push('</graphml>');
150
+ return lines.join('\n');
151
+ }
152
+ /**
153
+ * Export as GEXF format for Gephi.
154
+ */
155
+ exportAsGEXF(graph) {
156
+ const lines = [];
157
+ const escapeXml = (str) => {
158
+ if (str === undefined || str === null)
159
+ return '';
160
+ return String(str)
161
+ .replace(/&/g, '&amp;')
162
+ .replace(/</g, '&lt;')
163
+ .replace(/>/g, '&gt;')
164
+ .replace(/"/g, '&quot;')
165
+ .replace(/'/g, '&apos;');
166
+ };
167
+ lines.push('<?xml version="1.0" encoding="UTF-8"?>');
168
+ lines.push('<gexf xmlns="http://www.gexf.net/1.2draft" version="1.2">');
169
+ lines.push(' <meta>');
170
+ lines.push(' <creator>Memory MCP Server</creator>');
171
+ lines.push(' </meta>');
172
+ lines.push(' <graph mode="static" defaultedgetype="directed">');
173
+ lines.push(' <attributes class="node">');
174
+ lines.push(' <attribute id="0" title="entityType" type="string"/>');
175
+ lines.push(' <attribute id="1" title="observations" type="string"/>');
176
+ lines.push(' </attributes>');
177
+ lines.push(' <nodes>');
178
+ for (const entity of graph.entities) {
179
+ const nodeId = escapeXml(entity.name);
180
+ lines.push(` <node id="${nodeId}" label="${nodeId}">`);
181
+ lines.push(' <attvalues>');
182
+ lines.push(` <attvalue for="0" value="${escapeXml(entity.entityType)}"/>`);
183
+ lines.push(` <attvalue for="1" value="${escapeXml(entity.observations.join('; '))}"/>`);
184
+ lines.push(' </attvalues>');
185
+ lines.push(' </node>');
186
+ }
187
+ lines.push(' </nodes>');
188
+ lines.push(' <edges>');
189
+ let edgeId = 0;
190
+ for (const relation of graph.relations) {
191
+ const sourceId = escapeXml(relation.from);
192
+ const targetId = escapeXml(relation.to);
193
+ const label = escapeXml(relation.relationType);
194
+ lines.push(` <edge id="${edgeId}" source="${sourceId}" target="${targetId}" label="${label}"/>`);
195
+ edgeId++;
196
+ }
197
+ lines.push(' </edges>');
198
+ lines.push(' </graph>');
199
+ lines.push('</gexf>');
200
+ return lines.join('\n');
201
+ }
202
+ /**
203
+ * Export as DOT format for GraphViz.
204
+ */
205
+ exportAsDOT(graph) {
206
+ const lines = [];
207
+ const escapeDot = (str) => {
208
+ return '"' + str.replace(/\\/g, '\\\\').replace(/"/g, '\\"').replace(/\n/g, '\\n') + '"';
209
+ };
210
+ lines.push('digraph KnowledgeGraph {');
211
+ lines.push(' rankdir=LR;');
212
+ lines.push(' node [shape=box, style=rounded];');
213
+ lines.push('');
214
+ for (const entity of graph.entities) {
215
+ const nodeId = escapeDot(entity.name);
216
+ const label = [`${entity.name}`, `Type: ${entity.entityType}`];
217
+ if (entity.tags?.length)
218
+ label.push(`Tags: ${entity.tags.join(', ')}`);
219
+ const labelStr = escapeDot(label.join('\\n'));
220
+ lines.push(` ${nodeId} [label=${labelStr}];`);
221
+ }
222
+ lines.push('');
223
+ for (const relation of graph.relations) {
224
+ const fromId = escapeDot(relation.from);
225
+ const toId = escapeDot(relation.to);
226
+ const label = escapeDot(relation.relationType);
227
+ lines.push(` ${fromId} -> ${toId} [label=${label}];`);
228
+ }
229
+ lines.push('}');
230
+ return lines.join('\n');
231
+ }
232
+ /**
233
+ * Export as Markdown documentation.
234
+ */
235
+ exportAsMarkdown(graph) {
236
+ const lines = [];
237
+ lines.push('# Knowledge Graph Export');
238
+ lines.push('');
239
+ lines.push(`**Exported:** ${new Date().toISOString()}`);
240
+ lines.push(`**Entities:** ${graph.entities.length}`);
241
+ lines.push(`**Relations:** ${graph.relations.length}`);
242
+ lines.push('');
243
+ lines.push('## Entities');
244
+ lines.push('');
245
+ for (const entity of graph.entities) {
246
+ lines.push(`### ${entity.name}`);
247
+ lines.push('');
248
+ lines.push(`- **Type:** ${entity.entityType}`);
249
+ if (entity.tags?.length)
250
+ lines.push(`- **Tags:** ${entity.tags.map(t => `\`${t}\``).join(', ')}`);
251
+ if (entity.importance !== undefined)
252
+ lines.push(`- **Importance:** ${entity.importance}/10`);
253
+ if (entity.observations.length > 0) {
254
+ lines.push('');
255
+ lines.push('**Observations:**');
256
+ for (const obs of entity.observations) {
257
+ lines.push(`- ${obs}`);
258
+ }
259
+ }
260
+ lines.push('');
261
+ }
262
+ if (graph.relations.length > 0) {
263
+ lines.push('## Relations');
264
+ lines.push('');
265
+ for (const relation of graph.relations) {
266
+ lines.push(`- **${relation.from}** → *${relation.relationType}* → **${relation.to}**`);
267
+ }
268
+ lines.push('');
269
+ }
270
+ return lines.join('\n');
271
+ }
272
+ /**
273
+ * Export as Mermaid diagram.
274
+ */
275
+ exportAsMermaid(graph) {
276
+ const lines = [];
277
+ const sanitizeId = (str) => str.replace(/[^a-zA-Z0-9_]/g, '_');
278
+ const escapeLabel = (str) => str.replace(/"/g, '#quot;');
279
+ lines.push('graph LR');
280
+ lines.push(' %% Knowledge Graph');
281
+ lines.push('');
282
+ const nodeIds = new Map();
283
+ for (const entity of graph.entities) {
284
+ nodeIds.set(entity.name, sanitizeId(entity.name));
285
+ }
286
+ for (const entity of graph.entities) {
287
+ const nodeId = nodeIds.get(entity.name);
288
+ const labelParts = [entity.name, `Type: ${entity.entityType}`];
289
+ if (entity.tags?.length)
290
+ labelParts.push(`Tags: ${entity.tags.join(', ')}`);
291
+ const label = escapeLabel(labelParts.join('<br/>'));
292
+ lines.push(` ${nodeId}["${label}"]`);
293
+ }
294
+ lines.push('');
295
+ for (const relation of graph.relations) {
296
+ const fromId = nodeIds.get(relation.from);
297
+ const toId = nodeIds.get(relation.to);
298
+ if (fromId && toId) {
299
+ const label = escapeLabel(relation.relationType);
300
+ lines.push(` ${fromId} -->|"${label}"| ${toId}`);
301
+ }
302
+ }
303
+ return lines.join('\n');
304
+ }
305
+ }