@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
@@ -8,7 +8,7 @@
8
8
  * @module server/toolHandlers
9
9
  */
10
10
  import path from 'node:path';
11
- import { formatToolResponse, formatTextResponse, formatRawResponse, validateWithSchema, validateFilePath, BatchCreateEntitiesSchema, BatchCreateRelationsSchema, EntityNamesSchema, DeleteRelationsSchema, AddObservationsInputSchema, DeleteObservationsInputSchema, ArchiveCriteriaSchema, SavedSearchInputSchema, SavedSearchUpdateSchema, ImportFormatSchema, ExtendedExportFormatSchema, MergeStrategySchema, ExportFilterSchema, SearchQuerySchema, HybridSearchManager, QueryAnalyzer, QueryPlanner, ReflectionManager, ObservationNormalizer, RefIndex, AuditLog, GovernanceManager, FreshnessManager, ArtifactManager, CollaborativeSynthesis, FailureDistillation, CognitiveLoadAnalyzer, ConsolidationScheduler, DreamEngine, DistillationPipeline, DefaultDistillationPolicy, NoOpDistillationPolicy, computeEntropy, passesEntropyFilter, EntropyFilterStage, getRoleProfile, listRoleProfiles, QueryCostEstimator, ContradictionDetector, PiiRedactor, DecisionManager, RankedSearch, clearAllSearchCaches, getAllCacheStats, } from '@danielsimonjr/memoryjs';
11
+ import { formatToolResponse, formatTextResponse, formatRawResponse, validateWithSchema, validateFilePath, BatchCreateEntitiesSchema, BatchCreateRelationsSchema, EntityNamesSchema, DeleteRelationsSchema, AddObservationsInputSchema, DeleteObservationsInputSchema, ArchiveCriteriaSchema, SavedSearchInputSchema, SavedSearchUpdateSchema, ImportFormatSchema, ExtendedExportFormatSchema, MergeStrategySchema, ExportFilterSchema, SearchQuerySchema, HybridSearchManager, QueryAnalyzer, QueryPlanner, ReflectionManager, ObservationNormalizer, RefIndex, FreshnessManager, ArtifactManager, CollaborativeSynthesis, FailureDistillation, CognitiveLoadAnalyzer, ConsolidationScheduler, DreamEngine, DistillationPipeline, DefaultDistillationPolicy, NoOpDistillationPolicy, computeEntropy, passesEntropyFilter, EntropyFilterStage, getRoleProfile, listRoleProfiles, QueryCostEstimator, ContradictionDetector, PiiRedactor, DecisionManager, RankedSearch, RelationConsolidator, clearAllSearchCaches, getAllCacheStats, } from '@danielsimonjr/memoryjs';
12
12
  import { promises as fs } from 'node:fs';
13
13
  import { performance } from 'node:perf_hooks';
14
14
  import { z } from 'zod';
@@ -17,8 +17,6 @@ import { maybeCompressResponse } from './responseCompressor.js';
17
17
  // WeakMap-based singletons keyed on ManagerContext to avoid re-instantiation per request.
18
18
  // These managers are not on ManagerContext directly, so we wire them up once per ctx.
19
19
  const refIndexMap = new WeakMap();
20
- const auditLogMap = new WeakMap();
21
- const governanceMap = new WeakMap();
22
20
  const freshnessMap = new WeakMap();
23
21
  const artifactManagerMap = new WeakMap();
24
22
  const distillationPipelineMap = new WeakMap();
@@ -39,9 +37,29 @@ function getStorageFilePath(ctx) {
39
37
  // type-cast). Older versions of this helper looked for `filePath` and
40
38
  // silently fell back to 'memory.jsonl' — which made diag / size / reindex
41
39
  // reports point at the wrong file. Try both field names defensively.
40
+ // SQLiteStorage exposes NEITHER field — it has a public `getFilePath()` accessor backed by
41
+ // `validatedDbFilePath`. Without this branch the helper fell through to the literal
42
+ // 'memory.jsonl', which resolves against cwd: diag then stat'd an unrelated file and reported
43
+ // it as your store (`exists: true` with that file's size) while writes went to memory.db.
42
44
  const storage = ctx.storage;
45
+ if (typeof storage.getFilePath === 'function') {
46
+ try {
47
+ const resolved = storage.getFilePath();
48
+ if (resolved)
49
+ return resolved;
50
+ }
51
+ catch { /* fall through to the field lookups below */ }
52
+ }
43
53
  return storage.memoryFilePath ?? storage.filePath ?? 'memory.jsonl';
44
54
  }
55
+ // Sidecar path for the serialized Cue–Tag–Content graph, following the
56
+ // library's `<basename>-<suffix>` convention (memory.jsonl → memory-reconstructive.json).
57
+ function reconstructiveSidecarPath(ctx) {
58
+ const storagePath = getStorageFilePath(ctx);
59
+ const ext = path.extname(storagePath);
60
+ const base = ext ? storagePath.slice(0, -ext.length) : storagePath;
61
+ return `${base}-reconstructive.json`;
62
+ }
45
63
  function getRefIndex(ctx) {
46
64
  if (!refIndexMap.has(ctx)) {
47
65
  const storagePath = getStorageFilePath(ctx);
@@ -50,22 +68,6 @@ function getRefIndex(ctx) {
50
68
  }
51
69
  return refIndexMap.get(ctx);
52
70
  }
53
- function getAuditLog(ctx) {
54
- if (!auditLogMap.has(ctx)) {
55
- const storagePath = getStorageFilePath(ctx);
56
- const dir = path.dirname(storagePath);
57
- auditLogMap.set(ctx, new AuditLog(path.join(dir, 'memory-audit.jsonl')));
58
- }
59
- return auditLogMap.get(ctx);
60
- }
61
- function getGovernanceManager(ctx) {
62
- if (!governanceMap.has(ctx)) {
63
- // GovernanceManager constructor accepts GraphStorage; ctx.storage is GraphStorage
64
- // eslint-disable-next-line @typescript-eslint/no-explicit-any
65
- governanceMap.set(ctx, new GovernanceManager(ctx.storage, getAuditLog(ctx)));
66
- }
67
- return governanceMap.get(ctx);
68
- }
69
71
  function getFreshnessManager(ctx) {
70
72
  if (!freshnessMap.has(ctx)) {
71
73
  freshnessMap.set(ctx, new FreshnessManager(ctx.storage));
@@ -438,7 +440,33 @@ export const toolHandlers = {
438
440
  const limit = args.limit !== undefined
439
441
  ? validateWithSchema(args.limit, z.number().int().positive().max(200), 'Invalid limit')
440
442
  : 10;
441
- const hybridSearch = new HybridSearchManager(ctx.semanticSearch, ctx.rankedSearch);
443
+ const graphWeight = args.graphWeight !== undefined
444
+ ? validateWithSchema(args.graphWeight, z.number().min(0).max(1), 'Invalid graphWeight')
445
+ : undefined;
446
+ const expandNeighborsArgs = args.expandNeighbors !== undefined
447
+ ? validateWithSchema(args.expandNeighbors, z.object({
448
+ topK: z.number().int().positive().max(100).optional(),
449
+ damping: z.number().min(0).max(1).optional(),
450
+ }).strict(), 'Invalid expandNeighbors')
451
+ : undefined;
452
+ // Only 1-hop expansion is supported by memoryjs, so `hops` is fixed here
453
+ // rather than exposed in the tool schema.
454
+ const expandNeighbors = expandNeighborsArgs !== undefined
455
+ ? { hops: 1, ...expandNeighborsArgs }
456
+ : undefined;
457
+ const explain = args.explain !== undefined
458
+ ? validateWithSchema(args.explain, z.boolean(), 'Invalid explain flag')
459
+ : undefined;
460
+ const lookFor = args.lookFor !== undefined
461
+ ? validateWithSchema(args.lookFor, z.string().min(1), 'Invalid lookFor')
462
+ : undefined;
463
+ // ctx.hybridSearchManager only attaches the GraphRankPrior when
464
+ // MEMORY_HYBRID_GRAPH_WEIGHT is set; per-call graph options need the prior
465
+ // wired explicitly or they would be silently inert.
466
+ const wantsGraphChannel = (graphWeight !== undefined && graphWeight > 0) || expandNeighbors !== undefined;
467
+ const hybridSearch = wantsGraphChannel
468
+ ? new HybridSearchManager(ctx.semanticSearch, ctx.rankedSearch, ctx.graphRankPrior)
469
+ : ctx.hybridSearchManager;
442
470
  const graph = await ctx.storage.loadGraph();
443
471
  const results = await hybridSearch.searchWithEntities(graph, query, {
444
472
  semanticWeight: weights?.semantic ?? 0.5,
@@ -456,6 +484,10 @@ export const toolHandlers = {
456
484
  }
457
485
  : undefined,
458
486
  limit,
487
+ graphWeight,
488
+ expandNeighbors,
489
+ explain,
490
+ lookFor,
459
491
  });
460
492
  return formatToolResponse({
461
493
  query,
@@ -463,6 +495,7 @@ export const toolHandlers = {
463
495
  semantic: weights?.semantic ?? 0.5,
464
496
  lexical: weights?.lexical ?? 0.3,
465
497
  symbolic: weights?.symbolic ?? 0.2,
498
+ ...(graphWeight !== undefined ? { graph: graphWeight } : {}),
466
499
  },
467
500
  resultCount: results.length,
468
501
  results: results.map((r) => ({
@@ -472,6 +505,9 @@ export const toolHandlers = {
472
505
  matchedLayers: r.matchedLayers,
473
506
  observations: r.entity.observations.slice(0, 3),
474
507
  tags: r.entity.tags,
508
+ ...(r.evidencePaths !== undefined ? { evidencePaths: r.evidencePaths } : {}),
509
+ ...(r.evidenceTruncated !== undefined ? { evidenceTruncated: r.evidenceTruncated } : {}),
510
+ ...(r.lookForScore !== undefined ? { lookForScore: r.lookForScore } : {}),
475
511
  })),
476
512
  });
477
513
  },
@@ -512,7 +548,7 @@ export const toolHandlers = {
512
548
  const planner = new QueryPlanner();
513
549
  plan = planner.createPlan(query, analysis);
514
550
  }
515
- const hybridSearch = new HybridSearchManager(ctx.semanticSearch, ctx.rankedSearch);
551
+ const hybridSearch = ctx.hybridSearchManager;
516
552
  const reflection = new ReflectionManager(hybridSearch, analyzer);
517
553
  const graph = await ctx.storage.loadGraph();
518
554
  const result = await reflection.retrieveWithReflection(graph, query, {
@@ -1076,7 +1112,7 @@ export const toolHandlers = {
1076
1112
  },
1077
1113
  // ==================== GOVERNANCE HANDLERS ====================
1078
1114
  set_governance_policy: async (ctx, args) => {
1079
- const gm = getGovernanceManager(ctx);
1115
+ const gm = ctx.governanceManager;
1080
1116
  // GovernancePolicy uses function callbacks; we translate boolean args into allow/deny functions
1081
1117
  const allowCreate = args.canCreate !== undefined
1082
1118
  ? validateWithSchema(args.canCreate, z.boolean(), 'Invalid canCreate')
@@ -1115,20 +1151,20 @@ export const toolHandlers = {
1115
1151
  const limit = args.limit !== undefined
1116
1152
  ? validateWithSchema(args.limit, z.number().int().min(1).max(1000), 'Invalid limit')
1117
1153
  : 50;
1118
- const al = getAuditLog(ctx);
1154
+ const al = ctx.governanceManager.auditLog;
1119
1155
  let entries = await al.query(filter);
1120
1156
  entries = entries.slice(0, limit);
1121
1157
  return formatToolResponse({ entries, count: entries.length });
1122
1158
  },
1123
1159
  audit_history: async (ctx, args) => {
1124
1160
  const entityName = validateWithSchema(args.entityName, z.string().min(1), 'Invalid entityName');
1125
- const al = getAuditLog(ctx);
1161
+ const al = ctx.governanceManager.auditLog;
1126
1162
  const entries = await al.getHistory(entityName);
1127
1163
  return formatToolResponse({ entityName, entries, count: entries.length });
1128
1164
  },
1129
1165
  rollback_operation: async (ctx, args) => {
1130
1166
  const auditEntryId = validateWithSchema(args.auditEntryId, z.string().min(1), 'Invalid auditEntryId');
1131
- const gm = getGovernanceManager(ctx);
1167
+ const gm = ctx.governanceManager;
1132
1168
  await gm.rollback(auditEntryId);
1133
1169
  return formatTextResponse(`Operation "${auditEntryId}" rolled back successfully`);
1134
1170
  },
@@ -2431,7 +2467,10 @@ export const toolHandlers = {
2431
2467
  runtime: { node: process.version, platform: process.platform, arch: process.arch, pid: process.pid },
2432
2468
  storage: {
2433
2469
  path: storagePath,
2434
- type: process.env.MEMORY_STORAGE_TYPE ?? 'jsonl',
2470
+ // Mirror index.ts's normalization exactly. Echoing the raw env var made diag report
2471
+ // whatever was set (e.g. a typo, or 'sqlite' back when it was ignored) rather than the
2472
+ // backend actually in use — a diagnostic that confirmed the bug instead of exposing it.
2473
+ type: process.env.MEMORY_STORAGE_TYPE === 'sqlite' ? 'sqlite' : 'jsonl',
2435
2474
  exists,
2436
2475
  sizeBytes,
2437
2476
  entities: stats.totalEntities,
@@ -2745,6 +2784,198 @@ export const toolHandlers = {
2745
2784
  inDegree: incoming.length,
2746
2785
  });
2747
2786
  },
2787
+ // ==================== EVENT MEMORY HANDLERS (memoryjs v3.0.0) ====================
2788
+ record_event: async (ctx, args) => {
2789
+ const input = validateWithSchema(args, z.object({
2790
+ action: z.string().min(1),
2791
+ actor: z.string().min(1),
2792
+ target: z.string().min(1).optional(),
2793
+ context: z.string().min(1).optional(),
2794
+ participants: z.array(z.string().min(1)).optional(),
2795
+ occurredAt: z.string().min(1).optional(),
2796
+ flowKey: z.string().min(1).optional(),
2797
+ detail: z.array(z.string()).optional(),
2798
+ importance: z.number().optional(),
2799
+ }).strict(), 'Invalid event input');
2800
+ const event = await ctx.eventManager.recordEvent(input);
2801
+ return formatToolResponse({ event });
2802
+ },
2803
+ get_event: async (ctx, args) => {
2804
+ const name = validateWithSchema(args.name, z.string().min(1), 'Invalid event name');
2805
+ const event = await ctx.eventManager.getEvent(name);
2806
+ if (!event) {
2807
+ return formatTextResponse(`Event "${name}" not found`);
2808
+ }
2809
+ return formatToolResponse({ event });
2810
+ },
2811
+ query_events: async (ctx, args) => {
2812
+ const filter = validateWithSchema(args, z.object({
2813
+ actor: z.string().min(1).optional(),
2814
+ target: z.string().min(1).optional(),
2815
+ action: z.string().min(1).optional(),
2816
+ flowKey: z.string().min(1).optional(),
2817
+ timeRange: z.object({
2818
+ start: z.string().min(1).optional(),
2819
+ end: z.string().min(1).optional(),
2820
+ }).strict().optional(),
2821
+ limit: z.number().int().positive().max(1000).optional(),
2822
+ }).strict(), 'Invalid event filter');
2823
+ const events = await ctx.eventManager.queryEvents(filter);
2824
+ return formatToolResponse({ events, count: events.length });
2825
+ },
2826
+ get_event_flow: async (ctx, args) => {
2827
+ const flowKey = validateWithSchema(args.flowKey, z.string().min(1), 'Invalid flowKey');
2828
+ const events = await ctx.eventManager.getFlow(flowKey);
2829
+ return formatToolResponse({ flowKey, events, count: events.length });
2830
+ },
2831
+ who_did_what: async (ctx, args) => {
2832
+ const filter = validateWithSchema(args, z.object({
2833
+ target: z.string().min(1).optional(),
2834
+ context: z.string().min(1).optional(),
2835
+ timeRange: z.object({
2836
+ start: z.string().min(1).optional(),
2837
+ end: z.string().min(1).optional(),
2838
+ }).strict().optional(),
2839
+ limit: z.number().int().positive().max(1000).optional(),
2840
+ }).strict(), 'Invalid filter');
2841
+ const entries = await ctx.eventManager.whoDidWhat(filter);
2842
+ return formatToolResponse({ entries, count: entries.length });
2843
+ },
2844
+ // ==================== RECONSTRUCTIVE MEMORY HANDLERS (memoryjs v3.0.0) ====================
2845
+ ingest_dialogue: async (ctx, args) => {
2846
+ const turns = validateWithSchema(args.turns, z.array(z.object({
2847
+ id: z.string().min(1),
2848
+ speaker: z.string().optional(),
2849
+ text: z.string().min(1),
2850
+ timestamp: z.string().optional(),
2851
+ }).strict()).min(1), 'Invalid dialogue turns');
2852
+ const rm = ctx.reconstructiveMemory();
2853
+ const result = await rm.ingest(turns);
2854
+ return formatToolResponse({
2855
+ distillation: result,
2856
+ persisted: rm.lastPersistResult,
2857
+ stats: rm.stats(),
2858
+ });
2859
+ },
2860
+ reconstruct_memory: async (ctx, args) => {
2861
+ const query = validateWithSchema(args.query, z.string().min(1), 'Invalid query');
2862
+ const options = validateWithSchema({
2863
+ maxSteps: args.maxSteps,
2864
+ perStepBudget: args.perStepBudget,
2865
+ evidenceTarget: args.evidenceTarget,
2866
+ }, z.object({
2867
+ maxSteps: z.number().int().positive().max(32).optional(),
2868
+ perStepBudget: z.number().int().positive().max(100).optional(),
2869
+ evidenceTarget: z.number().int().positive().max(100).optional(),
2870
+ }), 'Invalid reconstruction options');
2871
+ const result = await ctx.reconstructiveMemory().reconstruct(query, options);
2872
+ return formatToolResponse(result);
2873
+ },
2874
+ reconstructive_memory_stats: async (ctx) => {
2875
+ return formatToolResponse(ctx.reconstructiveMemory().stats());
2876
+ },
2877
+ // ==================== RELATION CONSOLIDATION HANDLERS (memoryjs v3.0.0) ====================
2878
+ analyze_relation_duplicates: async (ctx) => {
2879
+ const consolidator = new RelationConsolidator(ctx.relationManager, ctx.entityManager, {
2880
+ embedding: ctx.semanticSearch?.getEmbeddingService(),
2881
+ });
2882
+ const report = await consolidator.analyze();
2883
+ return formatToolResponse(report);
2884
+ },
2885
+ consolidate_relations: async (ctx, args) => {
2886
+ const apply = args.apply !== undefined
2887
+ ? validateWithSchema(args.apply, z.boolean(), 'Invalid apply flag')
2888
+ : false;
2889
+ const consolidator = new RelationConsolidator(ctx.relationManager, ctx.entityManager, {
2890
+ embedding: ctx.semanticSearch?.getEmbeddingService(),
2891
+ });
2892
+ const result = await consolidator.consolidate({ apply });
2893
+ return formatToolResponse(result);
2894
+ },
2895
+ // ==================== AGENT REFLECTION HANDLERS (memoryjs v3.0.0) ====================
2896
+ create_reflection: async (ctx, args) => {
2897
+ const parsed = validateWithSchema(args, z.object({
2898
+ scope: z.enum(['session', 'project', 'global']),
2899
+ summary: z.string().min(1),
2900
+ evidence: z.array(z.string().min(1)).min(1),
2901
+ generalizationConfidence: z.number().min(0).max(1),
2902
+ keyInsights: z.array(z.string().min(1)).max(5).optional(),
2903
+ experienceType: z.string().min(1).optional(),
2904
+ sourceSessionId: z.string().min(1).optional(),
2905
+ sourceProjectId: z.string().min(1).optional(),
2906
+ importance: z.number().optional(),
2907
+ agentId: z.string().min(1).optional(),
2908
+ }).strict(), 'Invalid reflection input');
2909
+ const reflection = await ctx.reflectionManager.create({
2910
+ scope: parsed.scope,
2911
+ summary: parsed.summary,
2912
+ evidence: parsed.evidence,
2913
+ generalization_confidence: parsed.generalizationConfidence,
2914
+ keyInsights: parsed.keyInsights,
2915
+ experienceType: parsed.experienceType,
2916
+ sourceSessionId: parsed.sourceSessionId,
2917
+ sourceProjectId: parsed.sourceProjectId,
2918
+ }, { importance: parsed.importance, agentId: parsed.agentId });
2919
+ return formatToolResponse({ reflection });
2920
+ },
2921
+ list_reflections: async (ctx, args) => {
2922
+ const options = validateWithSchema(args, z.object({
2923
+ scope: z.enum(['session', 'project', 'global']).optional(),
2924
+ sourceSessionId: z.string().min(1).optional(),
2925
+ sourceProjectId: z.string().min(1).optional(),
2926
+ minConfidence: z.number().min(0).max(1).optional(),
2927
+ includeArchived: z.boolean().optional(),
2928
+ limit: z.number().int().positive().max(1000).optional(),
2929
+ }).strict(), 'Invalid list options');
2930
+ const reflections = await ctx.reflectionManager.list(options);
2931
+ return formatToolResponse({ reflections, count: reflections.length });
2932
+ },
2933
+ get_relevant_reflections: async (ctx, args) => {
2934
+ const sessionId = validateWithSchema(args.sessionId, z.string().min(1), 'Invalid sessionId');
2935
+ const options = validateWithSchema({
2936
+ sessionEntityNames: args.sessionEntityNames,
2937
+ minConfidence: args.minConfidence,
2938
+ limit: args.limit,
2939
+ }, z.object({
2940
+ sessionEntityNames: z.array(z.string().min(1)).optional(),
2941
+ minConfidence: z.number().min(0).max(1).optional(),
2942
+ limit: z.number().int().positive().max(1000).optional(),
2943
+ }), 'Invalid relevance options');
2944
+ const reflections = await ctx.reflectionManager.getRelevantForSession(sessionId, options);
2945
+ return formatToolResponse({ sessionId, reflections, count: reflections.length });
2946
+ },
2947
+ archive_reflection: async (ctx, args) => {
2948
+ const id = validateWithSchema(args.id, z.string().min(1), 'Invalid reflection id');
2949
+ const result = await ctx.reflectionManager.archive(id);
2950
+ return formatToolResponse(result);
2951
+ },
2952
+ // ==================== RECONSTRUCTIVE MEMORY PERSISTENCE HANDLERS (memoryjs v3.0.0) ====================
2953
+ save_reconstructive_memory: async (ctx) => {
2954
+ const rm = ctx.reconstructiveMemory();
2955
+ const snapshot = rm.toSnapshot();
2956
+ const sidecarPath = reconstructiveSidecarPath(ctx);
2957
+ await fs.writeFile(sidecarPath, JSON.stringify(snapshot), 'utf-8');
2958
+ return formatToolResponse({ path: sidecarPath, stats: rm.stats() });
2959
+ },
2960
+ load_reconstructive_memory: async (ctx) => {
2961
+ const sidecarPath = reconstructiveSidecarPath(ctx);
2962
+ let raw;
2963
+ try {
2964
+ raw = await fs.readFile(sidecarPath, 'utf-8');
2965
+ }
2966
+ catch {
2967
+ throw new Error(`No reconstructive memory snapshot at "${sidecarPath}" — run save_reconstructive_memory first`);
2968
+ }
2969
+ const snapshot = validateWithSchema(JSON.parse(raw), z.object({
2970
+ cues: z.array(z.unknown()),
2971
+ tags: z.array(z.unknown()),
2972
+ contents: z.array(z.unknown()),
2973
+ triples: z.array(z.unknown()),
2974
+ }), `Invalid reconstructive memory snapshot at "${sidecarPath}"`);
2975
+ const rm = ctx.reconstructiveMemory();
2976
+ rm.loadSnapshot(snapshot);
2977
+ return formatToolResponse({ path: sidecarPath, stats: rm.stats() });
2978
+ },
2748
2979
  };
2749
2980
  /**
2750
2981
  * Handle a tool call by dispatching to the appropriate handler.
@@ -0,0 +1,13 @@
1
+ /**
2
+ * Types Module - Barrel Export
3
+ *
4
+ * Central export point for all type definitions used throughout the
5
+ * Memory MCP Server. All types are consolidated in types.ts (Phase 5 cleanup).
6
+ *
7
+ * @example
8
+ * ```typescript
9
+ * import { Entity, Relation, KnowledgeGraph, SearchResult } from './types/index.js';
10
+ * ```
11
+ */
12
+ export type { Entity, Relation, KnowledgeGraph, ReadonlyKnowledgeGraph, SearchResult, SavedSearch, BooleanQueryNode, DocumentVector, TFIDFIndex, FuzzyCacheKey, BooleanCacheEntry, PaginatedCacheEntry, TokenizedEntity, GraphStats, ValidationReport, ValidationIssue, ValidationWarning, CacheCompressionStats, ArchiveResultExtended, ExportFilter, ExportOptions, ExportResult, ImportResult, CompressionResult, BackupOptions, BackupResult, RestoreResult, BackupMetadataExtended, BackupInfoExtended, TagAlias, IGraphStorage, StorageConfig, LowercaseData, TraversalOptions, TraversalResult, PathResult, ConnectedComponentsResult, CentralityResult, WeightedRelation, EmbeddingService, SemanticSearchResult, IVectorStore, VectorSearchResult, EmbeddingConfig, SemanticIndexOptions, } from './types.js';
13
+ //# sourceMappingURL=index.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../../src/types/index.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;GAUG;AAEH,YAAY,EAEV,MAAM,EACN,QAAQ,EACR,cAAc,EACd,sBAAsB,EAEtB,YAAY,EACZ,WAAW,EACX,gBAAgB,EAChB,cAAc,EACd,UAAU,EAEV,aAAa,EACb,iBAAiB,EACjB,mBAAmB,EACnB,eAAe,EAEf,UAAU,EACV,gBAAgB,EAChB,eAAe,EACf,iBAAiB,EACjB,qBAAqB,EAErB,qBAAqB,EAErB,YAAY,EACZ,aAAa,EACb,YAAY,EACZ,YAAY,EACZ,iBAAiB,EAEjB,aAAa,EACb,YAAY,EACZ,aAAa,EACb,sBAAsB,EACtB,kBAAkB,EAElB,QAAQ,EAER,aAAa,EACb,aAAa,EACb,aAAa,EAEb,gBAAgB,EAChB,eAAe,EACf,UAAU,EACV,yBAAyB,EACzB,gBAAgB,EAChB,gBAAgB,EAEhB,gBAAgB,EAChB,oBAAoB,EACpB,YAAY,EACZ,kBAAkB,EAClB,eAAe,EACf,oBAAoB,GACrB,MAAM,YAAY,CAAC"}
@@ -0,0 +1,12 @@
1
+ /**
2
+ * Types Module - Barrel Export
3
+ *
4
+ * Central export point for all type definitions used throughout the
5
+ * Memory MCP Server. All types are consolidated in types.ts (Phase 5 cleanup).
6
+ *
7
+ * @example
8
+ * ```typescript
9
+ * import { Entity, Relation, KnowledgeGraph, SearchResult } from './types/index.js';
10
+ * ```
11
+ */
12
+ export {};