@cmdoss/memwal-sdk 0.6.2 → 0.8.0
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.
- package/ARCHITECTURE.md +547 -547
- package/BENCHMARKS.md +238 -238
- package/README.md +310 -181
- package/dist/ai-sdk/tools.d.ts +2 -2
- package/dist/ai-sdk/tools.js +2 -2
- package/dist/client/ClientMemoryManager.js +2 -2
- package/dist/client/ClientMemoryManager.js.map +1 -1
- package/dist/client/PersonalDataWallet.d.ts.map +1 -1
- package/dist/client/SimplePDWClient.d.ts +29 -1
- package/dist/client/SimplePDWClient.d.ts.map +1 -1
- package/dist/client/SimplePDWClient.js +45 -13
- package/dist/client/SimplePDWClient.js.map +1 -1
- package/dist/client/namespaces/EmbeddingsNamespace.d.ts +1 -1
- package/dist/client/namespaces/EmbeddingsNamespace.js +1 -1
- package/dist/client/namespaces/MemoryNamespace.d.ts +31 -0
- package/dist/client/namespaces/MemoryNamespace.d.ts.map +1 -1
- package/dist/client/namespaces/MemoryNamespace.js +272 -39
- package/dist/client/namespaces/MemoryNamespace.js.map +1 -1
- package/dist/client/namespaces/consolidated/AINamespace.d.ts +2 -2
- package/dist/client/namespaces/consolidated/AINamespace.js +2 -2
- package/dist/client/namespaces/consolidated/BlockchainNamespace.d.ts +12 -2
- package/dist/client/namespaces/consolidated/BlockchainNamespace.d.ts.map +1 -1
- package/dist/client/namespaces/consolidated/BlockchainNamespace.js +62 -4
- package/dist/client/namespaces/consolidated/BlockchainNamespace.js.map +1 -1
- package/dist/client/namespaces/consolidated/StorageNamespace.d.ts +67 -2
- package/dist/client/namespaces/consolidated/StorageNamespace.d.ts.map +1 -1
- package/dist/client/namespaces/consolidated/StorageNamespace.js +549 -16
- package/dist/client/namespaces/consolidated/StorageNamespace.js.map +1 -1
- package/dist/config/ConfigurationHelper.js +61 -61
- package/dist/config/defaults.js +2 -2
- package/dist/config/defaults.js.map +1 -1
- package/dist/graph/GraphService.js +21 -21
- package/dist/graph/GraphService.js.map +1 -1
- package/dist/index.d.ts +3 -1
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +3 -1
- package/dist/index.js.map +1 -1
- package/dist/infrastructure/seal/EncryptionService.d.ts +9 -5
- package/dist/infrastructure/seal/EncryptionService.d.ts.map +1 -1
- package/dist/infrastructure/seal/EncryptionService.js +37 -15
- package/dist/infrastructure/seal/EncryptionService.js.map +1 -1
- package/dist/infrastructure/seal/SealService.d.ts +13 -5
- package/dist/infrastructure/seal/SealService.d.ts.map +1 -1
- package/dist/infrastructure/seal/SealService.js +36 -34
- package/dist/infrastructure/seal/SealService.js.map +1 -1
- package/dist/langchain/createPDWRAG.js +30 -30
- package/dist/retrieval/MemoryDecryptionPipeline.d.ts.map +1 -1
- package/dist/retrieval/MemoryDecryptionPipeline.js +2 -1
- package/dist/retrieval/MemoryDecryptionPipeline.js.map +1 -1
- package/dist/retrieval/MemoryRetrievalService.d.ts +31 -0
- package/dist/retrieval/MemoryRetrievalService.d.ts.map +1 -1
- package/dist/retrieval/MemoryRetrievalService.js +44 -4
- package/dist/retrieval/MemoryRetrievalService.js.map +1 -1
- package/dist/services/CapabilityService.d.ts.map +1 -1
- package/dist/services/CapabilityService.js +30 -14
- package/dist/services/CapabilityService.js.map +1 -1
- package/dist/services/CrossContextPermissionService.d.ts.map +1 -1
- package/dist/services/CrossContextPermissionService.js +9 -7
- package/dist/services/CrossContextPermissionService.js.map +1 -1
- package/dist/services/EmbeddingService.d.ts +28 -1
- package/dist/services/EmbeddingService.d.ts.map +1 -1
- package/dist/services/EmbeddingService.js +54 -0
- package/dist/services/EmbeddingService.js.map +1 -1
- package/dist/services/EncryptionService.d.ts.map +1 -1
- package/dist/services/EncryptionService.js +6 -5
- package/dist/services/EncryptionService.js.map +1 -1
- package/dist/services/GeminiAIService.js +309 -309
- package/dist/services/IndexManager.d.ts +5 -1
- package/dist/services/IndexManager.d.ts.map +1 -1
- package/dist/services/IndexManager.js +17 -40
- package/dist/services/IndexManager.js.map +1 -1
- package/dist/services/QueryService.js +1 -1
- package/dist/services/QueryService.js.map +1 -1
- package/dist/services/StorageService.d.ts +11 -0
- package/dist/services/StorageService.d.ts.map +1 -1
- package/dist/services/StorageService.js +73 -10
- package/dist/services/StorageService.js.map +1 -1
- package/dist/services/TransactionService.d.ts +20 -0
- package/dist/services/TransactionService.d.ts.map +1 -1
- package/dist/services/TransactionService.js +43 -0
- package/dist/services/TransactionService.js.map +1 -1
- package/dist/services/ViewService.js +2 -2
- package/dist/services/ViewService.js.map +1 -1
- package/dist/services/storage/QuiltBatchManager.d.ts +101 -1
- package/dist/services/storage/QuiltBatchManager.d.ts.map +1 -1
- package/dist/services/storage/QuiltBatchManager.js +410 -20
- package/dist/services/storage/QuiltBatchManager.js.map +1 -1
- package/dist/services/storage/index.d.ts +1 -1
- package/dist/services/storage/index.d.ts.map +1 -1
- package/dist/services/storage/index.js.map +1 -1
- package/dist/utils/LRUCache.d.ts +106 -0
- package/dist/utils/LRUCache.d.ts.map +1 -0
- package/dist/utils/LRUCache.js +281 -0
- package/dist/utils/LRUCache.js.map +1 -0
- package/dist/utils/index.d.ts +1 -0
- package/dist/utils/index.d.ts.map +1 -1
- package/dist/utils/index.js +2 -0
- package/dist/utils/index.js.map +1 -1
- package/dist/utils/memoryIndexOnChain.d.ts +212 -0
- package/dist/utils/memoryIndexOnChain.d.ts.map +1 -0
- package/dist/utils/memoryIndexOnChain.js +312 -0
- package/dist/utils/memoryIndexOnChain.js.map +1 -0
- package/dist/utils/rebuildIndexNode.d.ts +29 -0
- package/dist/utils/rebuildIndexNode.d.ts.map +1 -1
- package/dist/utils/rebuildIndexNode.js +366 -98
- package/dist/utils/rebuildIndexNode.js.map +1 -1
- package/dist/vector/HnswWasmService.d.ts +20 -5
- package/dist/vector/HnswWasmService.d.ts.map +1 -1
- package/dist/vector/HnswWasmService.js +73 -40
- package/dist/vector/HnswWasmService.js.map +1 -1
- package/dist/vector/IHnswService.d.ts +10 -1
- package/dist/vector/IHnswService.d.ts.map +1 -1
- package/dist/vector/IHnswService.js.map +1 -1
- package/dist/vector/NodeHnswService.d.ts +16 -0
- package/dist/vector/NodeHnswService.d.ts.map +1 -1
- package/dist/vector/NodeHnswService.js +84 -5
- package/dist/vector/NodeHnswService.js.map +1 -1
- package/dist/vector/createHnswService.d.ts +1 -1
- package/dist/vector/createHnswService.js +1 -1
- package/dist/vector/index.d.ts +1 -1
- package/dist/vector/index.js +1 -1
- package/package.json +157 -157
- package/src/access/PermissionService.ts +635 -635
- package/src/aggregation/AggregationService.ts +389 -389
- package/src/ai-sdk/PDWVectorStore.ts +715 -715
- package/src/ai-sdk/index.ts +65 -65
- package/src/ai-sdk/tools.ts +460 -460
- package/src/ai-sdk/types.ts +404 -404
- package/src/batch/BatchManager.ts +597 -597
- package/src/batch/BatchingService.ts +429 -429
- package/src/batch/MemoryProcessingCache.ts +492 -492
- package/src/batch/index.ts +30 -30
- package/src/browser.ts +200 -200
- package/src/client/ClientMemoryManager.ts +987 -987
- package/src/client/PersonalDataWallet.ts +345 -345
- package/src/client/SimplePDWClient.ts +1289 -1222
- package/src/client/factory.ts +154 -154
- package/src/client/namespaces/AnalyticsNamespace.ts +377 -377
- package/src/client/namespaces/BatchNamespace.ts +356 -356
- package/src/client/namespaces/CacheNamespace.ts +123 -123
- package/src/client/namespaces/CapabilityNamespace.ts +217 -217
- package/src/client/namespaces/ClassifyNamespace.ts +169 -169
- package/src/client/namespaces/ContextNamespace.ts +297 -297
- package/src/client/namespaces/EmbeddingsNamespace.ts +99 -99
- package/src/client/namespaces/EncryptionNamespace.ts +221 -221
- package/src/client/namespaces/GraphNamespace.ts +468 -468
- package/src/client/namespaces/IndexNamespace.ts +361 -361
- package/src/client/namespaces/MemoryNamespace.ts +1422 -1135
- package/src/client/namespaces/PermissionsNamespace.ts +254 -254
- package/src/client/namespaces/PipelineNamespace.ts +220 -220
- package/src/client/namespaces/SearchNamespace.ts +1049 -1049
- package/src/client/namespaces/StorageNamespace.ts +458 -458
- package/src/client/namespaces/TxNamespace.ts +260 -260
- package/src/client/namespaces/WalletNamespace.ts +243 -243
- package/src/client/namespaces/consolidated/AINamespace.ts +449 -449
- package/src/client/namespaces/consolidated/BlockchainNamespace.ts +607 -546
- package/src/client/namespaces/consolidated/SecurityNamespace.ts +648 -648
- package/src/client/namespaces/consolidated/StorageNamespace.ts +1141 -497
- package/src/client/namespaces/consolidated/index.ts +39 -39
- package/src/client/signers/KeypairSigner.ts +108 -108
- package/src/client/signers/UnifiedSigner.ts +110 -110
- package/src/client/signers/WalletAdapterSigner.ts +159 -159
- package/src/client/signers/index.ts +26 -26
- package/src/config/ConfigurationHelper.ts +412 -412
- package/src/config/defaults.ts +51 -51
- package/src/config/index.ts +8 -8
- package/src/config/validation.ts +70 -70
- package/src/core/index.ts +14 -14
- package/src/core/interfaces/IService.ts +307 -307
- package/src/core/interfaces/index.ts +8 -8
- package/src/core/types/capability.ts +297 -297
- package/src/core/types/index.ts +870 -870
- package/src/core/types/wallet.ts +270 -270
- package/src/core/types.ts +9 -9
- package/src/core/wallet.ts +222 -222
- package/src/embedding/index.ts +19 -19
- package/src/embedding/types.ts +357 -357
- package/src/errors/index.ts +602 -602
- package/src/errors/recovery.ts +461 -461
- package/src/errors/validation.ts +567 -567
- package/src/generated/pdw/capability.ts +319 -319
- package/src/graph/GraphService.ts +887 -887
- package/src/graph/KnowledgeGraphManager.ts +728 -728
- package/src/graph/index.ts +25 -25
- package/src/index.ts +498 -474
- package/src/infrastructure/index.ts +22 -22
- package/src/infrastructure/seal/EncryptionService.ts +628 -603
- package/src/infrastructure/seal/SealService.ts +613 -615
- package/src/infrastructure/seal/index.ts +9 -9
- package/src/infrastructure/sui/BlockchainManager.ts +627 -627
- package/src/infrastructure/sui/SuiService.ts +888 -888
- package/src/infrastructure/sui/index.ts +9 -9
- package/src/infrastructure/walrus/StorageManager.ts +604 -604
- package/src/infrastructure/walrus/WalrusStorageService.ts +612 -612
- package/src/infrastructure/walrus/index.ts +9 -9
- package/src/langchain/PDWEmbeddings.ts +145 -145
- package/src/langchain/PDWVectorStore.ts +456 -456
- package/src/langchain/createPDWRAG.ts +303 -303
- package/src/langchain/index.ts +47 -47
- package/src/permissions/ConsentRepository.browser.ts +249 -249
- package/src/permissions/ConsentRepository.ts +364 -364
- package/src/pipeline/MemoryPipeline.ts +862 -862
- package/src/pipeline/PipelineManager.ts +683 -683
- package/src/pipeline/index.ts +26 -26
- package/src/retrieval/AdvancedSearchService.ts +629 -629
- package/src/retrieval/MemoryAnalyticsService.ts +711 -711
- package/src/retrieval/MemoryDecryptionPipeline.ts +825 -824
- package/src/retrieval/MemoryRetrievalService.ts +904 -830
- package/src/retrieval/index.ts +42 -42
- package/src/services/BatchService.ts +352 -352
- package/src/services/CapabilityService.ts +464 -448
- package/src/services/ClassifierService.ts +465 -465
- package/src/services/CrossContextPermissionService.ts +486 -484
- package/src/services/EmbeddingService.ts +771 -706
- package/src/services/EncryptionService.ts +712 -711
- package/src/services/GeminiAIService.ts +753 -753
- package/src/services/IndexManager.ts +977 -1004
- package/src/services/MemoryIndexService.ts +1003 -1003
- package/src/services/MemoryService.ts +369 -369
- package/src/services/QueryService.ts +890 -890
- package/src/services/StorageService.ts +1182 -1111
- package/src/services/TransactionService.ts +838 -790
- package/src/services/VectorService.ts +462 -462
- package/src/services/ViewService.ts +484 -484
- package/src/services/index.ts +25 -25
- package/src/services/storage/BlobAttributesManager.ts +333 -333
- package/src/services/storage/KnowledgeGraphManager.ts +425 -425
- package/src/services/storage/MemorySearchManager.ts +387 -387
- package/src/services/storage/QuiltBatchManager.ts +1130 -660
- package/src/services/storage/WalrusMetadataManager.ts +268 -268
- package/src/services/storage/WalrusStorageManager.ts +287 -287
- package/src/services/storage/index.ts +57 -52
- package/src/types/index.ts +13 -13
- package/src/utils/LRUCache.ts +378 -0
- package/src/utils/index.ts +76 -68
- package/src/utils/memoryIndexOnChain.ts +507 -0
- package/src/utils/rebuildIndex.ts +290 -290
- package/src/utils/rebuildIndexNode.ts +771 -424
- package/src/vector/BrowserHnswIndexService.ts +758 -758
- package/src/vector/HnswWasmService.ts +731 -679
- package/src/vector/IHnswService.ts +233 -224
- package/src/vector/NodeHnswService.ts +833 -735
- package/src/vector/VectorManager.ts +478 -478
- package/src/vector/createHnswService.ts +135 -135
- package/src/vector/index.ts +56 -56
- package/src/wallet/ContextWalletService.ts +656 -656
- package/src/wallet/MainWalletService.ts +317 -317
|
@@ -1,831 +1,905 @@
|
|
|
1
|
-
/**
|
|
2
|
-
* MemoryRetrievalService - Unified Memory Retrieval & Search
|
|
3
|
-
*
|
|
4
|
-
* Consolidates all memory retrieval operations into a single, powerful service
|
|
5
|
-
* with advanced caching, decryption, analytics, and multi-dimensional search.
|
|
6
|
-
*
|
|
7
|
-
* Features:
|
|
8
|
-
* - 🔍 Vector similarity search with HNSW indexing
|
|
9
|
-
* - 📊 Semantic search with AI understanding
|
|
10
|
-
* - 🕒 Time-based and metadata filtering
|
|
11
|
-
* - 🔐 Automatic SEAL decryption pipeline
|
|
12
|
-
* - 📈 Memory analytics and relationship discovery
|
|
13
|
-
* - ⚡ Multi-tier caching for performance
|
|
14
|
-
* - 🔄 Real-time memory streaming
|
|
15
|
-
* - 📤 Export and backup capabilities
|
|
16
|
-
*/
|
|
17
|
-
|
|
18
|
-
import { EmbeddingService } from '../services/EmbeddingService';
|
|
19
|
-
import { VectorManager } from '../vector/VectorManager';
|
|
20
|
-
import { KnowledgeGraphManager } from '../graph/KnowledgeGraphManager';
|
|
21
|
-
import { StorageManager } from '../infrastructure/walrus/StorageManager';
|
|
22
|
-
import { BlockchainManager } from '../infrastructure/sui/BlockchainManager';
|
|
23
|
-
import { EncryptionService } from '../services/EncryptionService';
|
|
24
|
-
import { BatchManager } from '../batch/BatchManager';
|
|
25
|
-
import { MemoryDecryptionPipeline, DecryptionConfig } from './MemoryDecryptionPipeline';
|
|
26
|
-
|
|
27
|
-
// Enhanced types for unified retrieval
|
|
28
|
-
export interface UnifiedMemoryQuery {
|
|
29
|
-
// Core search parameters
|
|
30
|
-
query?: string;
|
|
31
|
-
userId: string;
|
|
32
|
-
|
|
33
|
-
// Search types
|
|
34
|
-
searchType?: 'vector' | 'semantic' | 'keyword' | 'hybrid' | 'graph' | 'temporal';
|
|
35
|
-
|
|
36
|
-
// Filtering options
|
|
37
|
-
categories?: string[];
|
|
38
|
-
dateRange?: {
|
|
39
|
-
start?: Date;
|
|
40
|
-
end?: Date;
|
|
41
|
-
};
|
|
42
|
-
importanceRange?: {
|
|
43
|
-
min?: number;
|
|
44
|
-
max?: number;
|
|
45
|
-
};
|
|
46
|
-
tags?: string[];
|
|
47
|
-
contentTypes?: string[];
|
|
48
|
-
|
|
49
|
-
// Vector search parameters
|
|
50
|
-
similarity?: {
|
|
51
|
-
threshold?: number;
|
|
52
|
-
k?: number;
|
|
53
|
-
efSearch?: number;
|
|
54
|
-
};
|
|
55
|
-
|
|
56
|
-
// Graph search parameters
|
|
57
|
-
graphTraversal?: {
|
|
58
|
-
maxDepth?: number;
|
|
59
|
-
includeEntities?: string[];
|
|
60
|
-
excludeRelations?: string[];
|
|
61
|
-
};
|
|
62
|
-
|
|
63
|
-
// Result options
|
|
64
|
-
includeContent?: boolean;
|
|
65
|
-
includeMetadata?: boolean;
|
|
66
|
-
includeEmbeddings?: boolean;
|
|
67
|
-
includeAnalytics?: boolean;
|
|
68
|
-
|
|
69
|
-
// Performance options
|
|
70
|
-
useCache?: boolean;
|
|
71
|
-
timeout?: number;
|
|
72
|
-
batchSize?: number;
|
|
73
|
-
}
|
|
74
|
-
|
|
75
|
-
export interface UnifiedMemoryResult {
|
|
76
|
-
id: string;
|
|
77
|
-
content?: string;
|
|
78
|
-
category: string;
|
|
79
|
-
created: Date;
|
|
80
|
-
updated?: Date;
|
|
81
|
-
|
|
82
|
-
// Scoring and relevance
|
|
83
|
-
similarity?: number;
|
|
84
|
-
relevanceScore: number;
|
|
85
|
-
searchRelevance: {
|
|
86
|
-
vectorSimilarity?: number;
|
|
87
|
-
semanticMatch?: number;
|
|
88
|
-
keywordMatch?: number;
|
|
89
|
-
graphRelevance?: number;
|
|
90
|
-
temporalRelevance?: number;
|
|
91
|
-
};
|
|
92
|
-
|
|
93
|
-
// Rich metadata
|
|
94
|
-
metadata: {
|
|
95
|
-
owner: string;
|
|
96
|
-
size: number;
|
|
97
|
-
importance: number;
|
|
98
|
-
tags: string[];
|
|
99
|
-
contentType: string;
|
|
100
|
-
isEncrypted: boolean;
|
|
101
|
-
accessCount?: number;
|
|
102
|
-
lastAccessed?: Date;
|
|
103
|
-
};
|
|
104
|
-
|
|
105
|
-
// Storage information
|
|
106
|
-
storage: {
|
|
107
|
-
blobId: string;
|
|
108
|
-
walrusHash?: string;
|
|
109
|
-
blockchainId?: string;
|
|
110
|
-
cacheStatus: 'cached' | 'retrieved' | 'not-cached';
|
|
111
|
-
};
|
|
112
|
-
|
|
113
|
-
// Relationships and context
|
|
114
|
-
relationships?: {
|
|
115
|
-
relatedMemories: string[];
|
|
116
|
-
knowledgeGraphNodes: string[];
|
|
117
|
-
semanticClusters: string[];
|
|
118
|
-
};
|
|
119
|
-
|
|
120
|
-
// Analytics
|
|
121
|
-
analytics?: {
|
|
122
|
-
viewCount: number;
|
|
123
|
-
shareCount: number;
|
|
124
|
-
editCount: number;
|
|
125
|
-
sentimentScore?: number;
|
|
126
|
-
topicDistribution?: Record<string, number>;
|
|
127
|
-
};
|
|
128
|
-
}
|
|
129
|
-
|
|
130
|
-
export interface RetrievalStats {
|
|
131
|
-
totalResults: number;
|
|
132
|
-
processingTime: number;
|
|
133
|
-
cacheHitRate: number;
|
|
134
|
-
searchBreakdown: {
|
|
135
|
-
vectorSearchTime: number;
|
|
136
|
-
semanticAnalysisTime: number;
|
|
137
|
-
decryptionTime: number;
|
|
138
|
-
graphTraversalTime: number;
|
|
139
|
-
};
|
|
140
|
-
dataSourcesUsed: string[];
|
|
141
|
-
qualityMetrics: {
|
|
142
|
-
averageRelevance: number;
|
|
143
|
-
diversityScore: number;
|
|
144
|
-
freshnessScore: number;
|
|
145
|
-
};
|
|
146
|
-
}
|
|
147
|
-
|
|
148
|
-
export interface RetrievalContext {
|
|
149
|
-
query: UnifiedMemoryQuery;
|
|
150
|
-
results: UnifiedMemoryResult[];
|
|
151
|
-
stats: RetrievalStats;
|
|
152
|
-
suggestions: {
|
|
153
|
-
relatedQueries: string[];
|
|
154
|
-
filterSuggestions: string[];
|
|
155
|
-
explorationPaths: string[];
|
|
156
|
-
};
|
|
157
|
-
timeline?: {
|
|
158
|
-
events: Array<{
|
|
159
|
-
date: Date;
|
|
160
|
-
type: 'created' | 'modified' | 'accessed' | 'shared';
|
|
161
|
-
memoryId: string;
|
|
162
|
-
description: string;
|
|
163
|
-
}>;
|
|
164
|
-
};
|
|
165
|
-
}
|
|
166
|
-
|
|
167
|
-
/**
|
|
168
|
-
* Unified Memory Retrieval Service
|
|
169
|
-
*/
|
|
170
|
-
export class MemoryRetrievalService {
|
|
171
|
-
private embeddingService: EmbeddingService;
|
|
172
|
-
private vectorManager: VectorManager;
|
|
173
|
-
private graphManager: KnowledgeGraphManager;
|
|
174
|
-
private storageManager: StorageManager;
|
|
175
|
-
private blockchainManager: BlockchainManager;
|
|
176
|
-
private encryptionService: EncryptionService | null;
|
|
177
|
-
private batchManager: BatchManager;
|
|
178
|
-
private decryptionPipeline: MemoryDecryptionPipeline | null;
|
|
179
|
-
|
|
180
|
-
// Multi-tier caching system
|
|
181
|
-
private queryCache = new Map<string, { result: RetrievalContext; timestamp: number }>();
|
|
182
|
-
private contentCache = new Map<string, { content: string; metadata: any; timestamp: number }>();
|
|
183
|
-
private analyticsCache = new Map<string, { analytics: any; timestamp: number }>();
|
|
184
|
-
|
|
185
|
-
// Cache TTL settings
|
|
186
|
-
private readonly QUERY_CACHE_TTL
|
|
187
|
-
private readonly CONTENT_CACHE_TTL
|
|
188
|
-
private readonly ANALYTICS_CACHE_TTL
|
|
189
|
-
|
|
190
|
-
|
|
191
|
-
|
|
192
|
-
|
|
193
|
-
|
|
194
|
-
|
|
195
|
-
|
|
196
|
-
|
|
197
|
-
|
|
198
|
-
|
|
199
|
-
|
|
200
|
-
|
|
201
|
-
|
|
202
|
-
|
|
203
|
-
|
|
204
|
-
|
|
205
|
-
|
|
206
|
-
|
|
207
|
-
|
|
208
|
-
|
|
209
|
-
|
|
210
|
-
|
|
211
|
-
|
|
212
|
-
|
|
213
|
-
|
|
214
|
-
|
|
215
|
-
|
|
216
|
-
|
|
217
|
-
|
|
218
|
-
|
|
219
|
-
|
|
220
|
-
|
|
221
|
-
|
|
222
|
-
|
|
223
|
-
|
|
224
|
-
|
|
225
|
-
|
|
226
|
-
|
|
227
|
-
|
|
228
|
-
|
|
229
|
-
|
|
230
|
-
|
|
231
|
-
|
|
232
|
-
|
|
233
|
-
|
|
234
|
-
|
|
235
|
-
|
|
236
|
-
|
|
237
|
-
|
|
238
|
-
|
|
239
|
-
|
|
240
|
-
|
|
241
|
-
|
|
242
|
-
|
|
243
|
-
|
|
244
|
-
|
|
245
|
-
|
|
246
|
-
|
|
247
|
-
|
|
248
|
-
|
|
249
|
-
|
|
250
|
-
|
|
251
|
-
|
|
252
|
-
|
|
253
|
-
|
|
254
|
-
|
|
255
|
-
|
|
256
|
-
|
|
257
|
-
|
|
258
|
-
|
|
259
|
-
|
|
260
|
-
|
|
261
|
-
|
|
262
|
-
|
|
263
|
-
|
|
264
|
-
|
|
265
|
-
|
|
266
|
-
|
|
267
|
-
|
|
268
|
-
|
|
269
|
-
|
|
270
|
-
|
|
271
|
-
|
|
272
|
-
|
|
273
|
-
|
|
274
|
-
|
|
275
|
-
|
|
276
|
-
|
|
277
|
-
|
|
278
|
-
|
|
279
|
-
|
|
280
|
-
|
|
281
|
-
|
|
282
|
-
|
|
283
|
-
|
|
284
|
-
|
|
285
|
-
|
|
286
|
-
|
|
287
|
-
|
|
288
|
-
|
|
289
|
-
|
|
290
|
-
|
|
291
|
-
|
|
292
|
-
}
|
|
293
|
-
|
|
294
|
-
//
|
|
295
|
-
|
|
296
|
-
|
|
297
|
-
|
|
298
|
-
|
|
299
|
-
|
|
300
|
-
|
|
301
|
-
|
|
302
|
-
|
|
303
|
-
|
|
304
|
-
|
|
305
|
-
|
|
306
|
-
|
|
307
|
-
|
|
308
|
-
|
|
309
|
-
|
|
310
|
-
|
|
311
|
-
|
|
312
|
-
|
|
313
|
-
|
|
314
|
-
|
|
315
|
-
|
|
316
|
-
|
|
317
|
-
|
|
318
|
-
|
|
319
|
-
|
|
320
|
-
|
|
321
|
-
|
|
322
|
-
|
|
323
|
-
|
|
324
|
-
|
|
325
|
-
|
|
326
|
-
|
|
327
|
-
|
|
328
|
-
|
|
329
|
-
'
|
|
330
|
-
|
|
331
|
-
|
|
332
|
-
|
|
333
|
-
|
|
334
|
-
|
|
335
|
-
|
|
336
|
-
|
|
337
|
-
|
|
338
|
-
|
|
339
|
-
|
|
340
|
-
|
|
341
|
-
|
|
342
|
-
|
|
343
|
-
|
|
344
|
-
|
|
345
|
-
|
|
346
|
-
|
|
347
|
-
|
|
348
|
-
query
|
|
349
|
-
|
|
350
|
-
|
|
351
|
-
|
|
352
|
-
|
|
353
|
-
|
|
354
|
-
|
|
355
|
-
|
|
356
|
-
|
|
357
|
-
|
|
358
|
-
|
|
359
|
-
|
|
360
|
-
|
|
361
|
-
|
|
362
|
-
|
|
363
|
-
|
|
364
|
-
|
|
365
|
-
|
|
366
|
-
|
|
367
|
-
|
|
368
|
-
|
|
369
|
-
|
|
370
|
-
|
|
371
|
-
|
|
372
|
-
|
|
373
|
-
|
|
374
|
-
|
|
375
|
-
|
|
376
|
-
|
|
377
|
-
|
|
378
|
-
|
|
379
|
-
|
|
380
|
-
|
|
381
|
-
stats
|
|
382
|
-
|
|
383
|
-
|
|
384
|
-
|
|
385
|
-
|
|
386
|
-
|
|
387
|
-
|
|
388
|
-
//
|
|
389
|
-
const
|
|
390
|
-
|
|
391
|
-
|
|
392
|
-
|
|
393
|
-
|
|
394
|
-
|
|
395
|
-
|
|
396
|
-
|
|
397
|
-
|
|
398
|
-
|
|
399
|
-
|
|
400
|
-
|
|
401
|
-
|
|
402
|
-
|
|
403
|
-
|
|
404
|
-
|
|
405
|
-
|
|
406
|
-
|
|
407
|
-
|
|
408
|
-
|
|
409
|
-
|
|
410
|
-
|
|
411
|
-
|
|
412
|
-
|
|
413
|
-
|
|
414
|
-
|
|
415
|
-
|
|
416
|
-
|
|
417
|
-
|
|
418
|
-
|
|
419
|
-
|
|
420
|
-
|
|
421
|
-
|
|
422
|
-
|
|
423
|
-
|
|
424
|
-
|
|
425
|
-
|
|
426
|
-
|
|
427
|
-
|
|
428
|
-
|
|
429
|
-
|
|
430
|
-
|
|
431
|
-
|
|
432
|
-
|
|
433
|
-
|
|
434
|
-
|
|
435
|
-
|
|
436
|
-
|
|
437
|
-
|
|
438
|
-
|
|
439
|
-
|
|
440
|
-
|
|
441
|
-
|
|
442
|
-
|
|
443
|
-
|
|
444
|
-
|
|
445
|
-
|
|
446
|
-
|
|
447
|
-
|
|
448
|
-
|
|
449
|
-
|
|
450
|
-
|
|
451
|
-
|
|
452
|
-
|
|
453
|
-
|
|
454
|
-
|
|
455
|
-
|
|
456
|
-
|
|
457
|
-
|
|
458
|
-
|
|
459
|
-
query
|
|
460
|
-
|
|
461
|
-
|
|
462
|
-
|
|
463
|
-
|
|
464
|
-
|
|
465
|
-
|
|
466
|
-
|
|
467
|
-
|
|
468
|
-
|
|
469
|
-
|
|
470
|
-
|
|
471
|
-
|
|
472
|
-
|
|
473
|
-
|
|
474
|
-
|
|
475
|
-
|
|
476
|
-
|
|
477
|
-
|
|
478
|
-
|
|
479
|
-
|
|
480
|
-
|
|
481
|
-
|
|
482
|
-
|
|
483
|
-
|
|
484
|
-
|
|
485
|
-
|
|
486
|
-
|
|
487
|
-
|
|
488
|
-
|
|
489
|
-
|
|
490
|
-
|
|
491
|
-
|
|
492
|
-
|
|
493
|
-
|
|
494
|
-
const
|
|
495
|
-
|
|
496
|
-
|
|
497
|
-
|
|
498
|
-
|
|
499
|
-
|
|
500
|
-
|
|
501
|
-
|
|
502
|
-
|
|
503
|
-
|
|
504
|
-
|
|
505
|
-
|
|
506
|
-
|
|
507
|
-
|
|
508
|
-
|
|
509
|
-
|
|
510
|
-
|
|
511
|
-
|
|
512
|
-
|
|
513
|
-
|
|
514
|
-
|
|
515
|
-
|
|
516
|
-
|
|
517
|
-
|
|
518
|
-
|
|
519
|
-
|
|
520
|
-
|
|
521
|
-
|
|
522
|
-
|
|
523
|
-
|
|
524
|
-
|
|
525
|
-
|
|
526
|
-
|
|
527
|
-
|
|
528
|
-
|
|
529
|
-
|
|
530
|
-
|
|
531
|
-
|
|
532
|
-
|
|
533
|
-
|
|
534
|
-
|
|
535
|
-
|
|
536
|
-
|
|
537
|
-
|
|
538
|
-
|
|
539
|
-
|
|
540
|
-
|
|
541
|
-
|
|
542
|
-
|
|
543
|
-
|
|
544
|
-
|
|
545
|
-
|
|
546
|
-
|
|
547
|
-
|
|
548
|
-
|
|
549
|
-
|
|
550
|
-
|
|
551
|
-
|
|
552
|
-
|
|
553
|
-
|
|
554
|
-
|
|
555
|
-
|
|
556
|
-
|
|
557
|
-
query
|
|
558
|
-
|
|
559
|
-
|
|
560
|
-
|
|
561
|
-
|
|
562
|
-
|
|
563
|
-
|
|
564
|
-
|
|
565
|
-
|
|
566
|
-
|
|
567
|
-
|
|
568
|
-
|
|
569
|
-
|
|
570
|
-
|
|
571
|
-
|
|
572
|
-
|
|
573
|
-
|
|
574
|
-
|
|
575
|
-
|
|
576
|
-
|
|
577
|
-
|
|
578
|
-
|
|
579
|
-
|
|
580
|
-
|
|
581
|
-
|
|
582
|
-
|
|
583
|
-
|
|
584
|
-
|
|
585
|
-
|
|
586
|
-
|
|
587
|
-
|
|
588
|
-
|
|
589
|
-
|
|
590
|
-
|
|
591
|
-
|
|
592
|
-
|
|
593
|
-
|
|
594
|
-
|
|
595
|
-
|
|
596
|
-
|
|
597
|
-
|
|
598
|
-
|
|
599
|
-
|
|
600
|
-
|
|
601
|
-
|
|
602
|
-
|
|
603
|
-
|
|
604
|
-
|
|
605
|
-
|
|
606
|
-
|
|
607
|
-
|
|
608
|
-
|
|
609
|
-
|
|
610
|
-
|
|
611
|
-
|
|
612
|
-
|
|
613
|
-
|
|
614
|
-
|
|
615
|
-
|
|
616
|
-
|
|
617
|
-
|
|
618
|
-
|
|
619
|
-
|
|
620
|
-
|
|
621
|
-
|
|
622
|
-
|
|
623
|
-
|
|
624
|
-
|
|
625
|
-
|
|
626
|
-
|
|
627
|
-
|
|
628
|
-
|
|
629
|
-
|
|
630
|
-
|
|
631
|
-
|
|
632
|
-
|
|
633
|
-
|
|
634
|
-
|
|
635
|
-
|
|
636
|
-
|
|
637
|
-
|
|
638
|
-
|
|
639
|
-
|
|
640
|
-
|
|
641
|
-
|
|
642
|
-
|
|
643
|
-
|
|
644
|
-
|
|
645
|
-
|
|
646
|
-
|
|
647
|
-
|
|
648
|
-
|
|
649
|
-
|
|
650
|
-
|
|
651
|
-
|
|
652
|
-
return
|
|
653
|
-
|
|
654
|
-
|
|
655
|
-
|
|
656
|
-
|
|
657
|
-
|
|
658
|
-
|
|
659
|
-
|
|
660
|
-
|
|
661
|
-
|
|
662
|
-
|
|
663
|
-
|
|
664
|
-
|
|
665
|
-
|
|
666
|
-
|
|
667
|
-
|
|
668
|
-
|
|
669
|
-
|
|
670
|
-
|
|
671
|
-
|
|
672
|
-
|
|
673
|
-
|
|
674
|
-
|
|
675
|
-
|
|
676
|
-
|
|
677
|
-
|
|
678
|
-
|
|
679
|
-
|
|
680
|
-
|
|
681
|
-
|
|
682
|
-
|
|
683
|
-
|
|
684
|
-
|
|
685
|
-
|
|
686
|
-
|
|
687
|
-
|
|
688
|
-
|
|
689
|
-
|
|
690
|
-
|
|
691
|
-
|
|
692
|
-
|
|
693
|
-
|
|
694
|
-
|
|
695
|
-
|
|
696
|
-
|
|
697
|
-
|
|
698
|
-
|
|
699
|
-
|
|
700
|
-
|
|
701
|
-
|
|
702
|
-
|
|
703
|
-
|
|
704
|
-
|
|
705
|
-
|
|
706
|
-
|
|
707
|
-
|
|
708
|
-
|
|
709
|
-
|
|
710
|
-
|
|
711
|
-
|
|
712
|
-
|
|
713
|
-
|
|
714
|
-
|
|
715
|
-
|
|
716
|
-
|
|
717
|
-
|
|
718
|
-
|
|
719
|
-
|
|
720
|
-
|
|
721
|
-
|
|
722
|
-
|
|
723
|
-
|
|
724
|
-
|
|
725
|
-
|
|
726
|
-
|
|
727
|
-
|
|
728
|
-
|
|
729
|
-
|
|
730
|
-
|
|
731
|
-
|
|
732
|
-
|
|
733
|
-
|
|
734
|
-
|
|
735
|
-
|
|
736
|
-
|
|
737
|
-
|
|
738
|
-
|
|
739
|
-
|
|
740
|
-
|
|
741
|
-
|
|
742
|
-
|
|
743
|
-
|
|
744
|
-
|
|
745
|
-
|
|
746
|
-
|
|
747
|
-
|
|
748
|
-
|
|
749
|
-
|
|
750
|
-
|
|
751
|
-
|
|
752
|
-
|
|
753
|
-
|
|
754
|
-
|
|
755
|
-
|
|
756
|
-
|
|
757
|
-
|
|
758
|
-
|
|
759
|
-
|
|
760
|
-
|
|
761
|
-
|
|
762
|
-
|
|
763
|
-
|
|
764
|
-
|
|
765
|
-
|
|
766
|
-
|
|
767
|
-
|
|
768
|
-
|
|
769
|
-
|
|
770
|
-
|
|
771
|
-
|
|
772
|
-
|
|
773
|
-
|
|
774
|
-
|
|
775
|
-
|
|
776
|
-
|
|
777
|
-
|
|
778
|
-
|
|
779
|
-
|
|
780
|
-
|
|
781
|
-
|
|
782
|
-
|
|
783
|
-
|
|
784
|
-
|
|
785
|
-
|
|
786
|
-
|
|
787
|
-
|
|
788
|
-
|
|
789
|
-
|
|
790
|
-
|
|
791
|
-
|
|
792
|
-
|
|
793
|
-
|
|
794
|
-
|
|
795
|
-
|
|
796
|
-
|
|
797
|
-
|
|
798
|
-
|
|
799
|
-
|
|
800
|
-
|
|
801
|
-
|
|
802
|
-
|
|
803
|
-
|
|
804
|
-
|
|
805
|
-
|
|
806
|
-
|
|
807
|
-
|
|
808
|
-
|
|
809
|
-
|
|
810
|
-
|
|
811
|
-
|
|
812
|
-
|
|
813
|
-
|
|
814
|
-
|
|
815
|
-
|
|
816
|
-
|
|
817
|
-
|
|
818
|
-
|
|
819
|
-
|
|
820
|
-
|
|
821
|
-
|
|
822
|
-
|
|
823
|
-
|
|
824
|
-
|
|
825
|
-
|
|
826
|
-
|
|
827
|
-
|
|
828
|
-
|
|
829
|
-
|
|
830
|
-
|
|
1
|
+
/**
|
|
2
|
+
* MemoryRetrievalService - Unified Memory Retrieval & Search
|
|
3
|
+
*
|
|
4
|
+
* Consolidates all memory retrieval operations into a single, powerful service
|
|
5
|
+
* with advanced caching, decryption, analytics, and multi-dimensional search.
|
|
6
|
+
*
|
|
7
|
+
* Features:
|
|
8
|
+
* - 🔍 Vector similarity search with HNSW indexing
|
|
9
|
+
* - 📊 Semantic search with AI understanding
|
|
10
|
+
* - 🕒 Time-based and metadata filtering
|
|
11
|
+
* - 🔐 Automatic SEAL decryption pipeline
|
|
12
|
+
* - 📈 Memory analytics and relationship discovery
|
|
13
|
+
* - ⚡ Multi-tier caching for performance
|
|
14
|
+
* - 🔄 Real-time memory streaming
|
|
15
|
+
* - 📤 Export and backup capabilities
|
|
16
|
+
*/
|
|
17
|
+
|
|
18
|
+
import { EmbeddingService } from '../services/EmbeddingService';
|
|
19
|
+
import { VectorManager } from '../vector/VectorManager';
|
|
20
|
+
import { KnowledgeGraphManager } from '../graph/KnowledgeGraphManager';
|
|
21
|
+
import { StorageManager } from '../infrastructure/walrus/StorageManager';
|
|
22
|
+
import { BlockchainManager } from '../infrastructure/sui/BlockchainManager';
|
|
23
|
+
import { EncryptionService } from '../services/EncryptionService';
|
|
24
|
+
import { BatchManager } from '../batch/BatchManager';
|
|
25
|
+
import { MemoryDecryptionPipeline, DecryptionConfig } from './MemoryDecryptionPipeline';
|
|
26
|
+
|
|
27
|
+
// Enhanced types for unified retrieval
|
|
28
|
+
export interface UnifiedMemoryQuery {
|
|
29
|
+
// Core search parameters
|
|
30
|
+
query?: string;
|
|
31
|
+
userId: string;
|
|
32
|
+
|
|
33
|
+
// Search types
|
|
34
|
+
searchType?: 'vector' | 'semantic' | 'keyword' | 'hybrid' | 'graph' | 'temporal';
|
|
35
|
+
|
|
36
|
+
// Filtering options
|
|
37
|
+
categories?: string[];
|
|
38
|
+
dateRange?: {
|
|
39
|
+
start?: Date;
|
|
40
|
+
end?: Date;
|
|
41
|
+
};
|
|
42
|
+
importanceRange?: {
|
|
43
|
+
min?: number;
|
|
44
|
+
max?: number;
|
|
45
|
+
};
|
|
46
|
+
tags?: string[];
|
|
47
|
+
contentTypes?: string[];
|
|
48
|
+
|
|
49
|
+
// Vector search parameters
|
|
50
|
+
similarity?: {
|
|
51
|
+
threshold?: number;
|
|
52
|
+
k?: number;
|
|
53
|
+
efSearch?: number;
|
|
54
|
+
};
|
|
55
|
+
|
|
56
|
+
// Graph search parameters
|
|
57
|
+
graphTraversal?: {
|
|
58
|
+
maxDepth?: number;
|
|
59
|
+
includeEntities?: string[];
|
|
60
|
+
excludeRelations?: string[];
|
|
61
|
+
};
|
|
62
|
+
|
|
63
|
+
// Result options
|
|
64
|
+
includeContent?: boolean;
|
|
65
|
+
includeMetadata?: boolean;
|
|
66
|
+
includeEmbeddings?: boolean;
|
|
67
|
+
includeAnalytics?: boolean;
|
|
68
|
+
|
|
69
|
+
// Performance options
|
|
70
|
+
useCache?: boolean;
|
|
71
|
+
timeout?: number;
|
|
72
|
+
batchSize?: number;
|
|
73
|
+
}
|
|
74
|
+
|
|
75
|
+
export interface UnifiedMemoryResult {
|
|
76
|
+
id: string;
|
|
77
|
+
content?: string;
|
|
78
|
+
category: string;
|
|
79
|
+
created: Date;
|
|
80
|
+
updated?: Date;
|
|
81
|
+
|
|
82
|
+
// Scoring and relevance
|
|
83
|
+
similarity?: number;
|
|
84
|
+
relevanceScore: number;
|
|
85
|
+
searchRelevance: {
|
|
86
|
+
vectorSimilarity?: number;
|
|
87
|
+
semanticMatch?: number;
|
|
88
|
+
keywordMatch?: number;
|
|
89
|
+
graphRelevance?: number;
|
|
90
|
+
temporalRelevance?: number;
|
|
91
|
+
};
|
|
92
|
+
|
|
93
|
+
// Rich metadata
|
|
94
|
+
metadata: {
|
|
95
|
+
owner: string;
|
|
96
|
+
size: number;
|
|
97
|
+
importance: number;
|
|
98
|
+
tags: string[];
|
|
99
|
+
contentType: string;
|
|
100
|
+
isEncrypted: boolean;
|
|
101
|
+
accessCount?: number;
|
|
102
|
+
lastAccessed?: Date;
|
|
103
|
+
};
|
|
104
|
+
|
|
105
|
+
// Storage information
|
|
106
|
+
storage: {
|
|
107
|
+
blobId: string;
|
|
108
|
+
walrusHash?: string;
|
|
109
|
+
blockchainId?: string;
|
|
110
|
+
cacheStatus: 'cached' | 'retrieved' | 'not-cached';
|
|
111
|
+
};
|
|
112
|
+
|
|
113
|
+
// Relationships and context
|
|
114
|
+
relationships?: {
|
|
115
|
+
relatedMemories: string[];
|
|
116
|
+
knowledgeGraphNodes: string[];
|
|
117
|
+
semanticClusters: string[];
|
|
118
|
+
};
|
|
119
|
+
|
|
120
|
+
// Analytics
|
|
121
|
+
analytics?: {
|
|
122
|
+
viewCount: number;
|
|
123
|
+
shareCount: number;
|
|
124
|
+
editCount: number;
|
|
125
|
+
sentimentScore?: number;
|
|
126
|
+
topicDistribution?: Record<string, number>;
|
|
127
|
+
};
|
|
128
|
+
}
|
|
129
|
+
|
|
130
|
+
export interface RetrievalStats {
|
|
131
|
+
totalResults: number;
|
|
132
|
+
processingTime: number;
|
|
133
|
+
cacheHitRate: number;
|
|
134
|
+
searchBreakdown: {
|
|
135
|
+
vectorSearchTime: number;
|
|
136
|
+
semanticAnalysisTime: number;
|
|
137
|
+
decryptionTime: number;
|
|
138
|
+
graphTraversalTime: number;
|
|
139
|
+
};
|
|
140
|
+
dataSourcesUsed: string[];
|
|
141
|
+
qualityMetrics: {
|
|
142
|
+
averageRelevance: number;
|
|
143
|
+
diversityScore: number;
|
|
144
|
+
freshnessScore: number;
|
|
145
|
+
};
|
|
146
|
+
}
|
|
147
|
+
|
|
148
|
+
export interface RetrievalContext {
|
|
149
|
+
query: UnifiedMemoryQuery;
|
|
150
|
+
results: UnifiedMemoryResult[];
|
|
151
|
+
stats: RetrievalStats;
|
|
152
|
+
suggestions: {
|
|
153
|
+
relatedQueries: string[];
|
|
154
|
+
filterSuggestions: string[];
|
|
155
|
+
explorationPaths: string[];
|
|
156
|
+
};
|
|
157
|
+
timeline?: {
|
|
158
|
+
events: Array<{
|
|
159
|
+
date: Date;
|
|
160
|
+
type: 'created' | 'modified' | 'accessed' | 'shared';
|
|
161
|
+
memoryId: string;
|
|
162
|
+
description: string;
|
|
163
|
+
}>;
|
|
164
|
+
};
|
|
165
|
+
}
|
|
166
|
+
|
|
167
|
+
/**
|
|
168
|
+
* Unified Memory Retrieval Service
|
|
169
|
+
*/
|
|
170
|
+
export class MemoryRetrievalService {
|
|
171
|
+
private embeddingService: EmbeddingService;
|
|
172
|
+
private vectorManager: VectorManager;
|
|
173
|
+
private graphManager: KnowledgeGraphManager;
|
|
174
|
+
private storageManager: StorageManager;
|
|
175
|
+
private blockchainManager: BlockchainManager;
|
|
176
|
+
private encryptionService: EncryptionService | null;
|
|
177
|
+
private batchManager: BatchManager;
|
|
178
|
+
private decryptionPipeline: MemoryDecryptionPipeline | null;
|
|
179
|
+
|
|
180
|
+
// Multi-tier caching system
|
|
181
|
+
private queryCache = new Map<string, { result: RetrievalContext; timestamp: number }>();
|
|
182
|
+
private contentCache = new Map<string, { content: string; metadata: any; timestamp: number }>();
|
|
183
|
+
private analyticsCache = new Map<string, { analytics: any; timestamp: number }>();
|
|
184
|
+
|
|
185
|
+
// Cache TTL settings (configurable)
|
|
186
|
+
private readonly QUERY_CACHE_TTL: number;
|
|
187
|
+
private readonly CONTENT_CACHE_TTL: number;
|
|
188
|
+
private readonly ANALYTICS_CACHE_TTL: number;
|
|
189
|
+
|
|
190
|
+
// Cache size limits to prevent memory leaks (configurable)
|
|
191
|
+
private readonly MAX_QUERY_CACHE_SIZE: number;
|
|
192
|
+
private readonly MAX_CONTENT_CACHE_SIZE: number;
|
|
193
|
+
private readonly MAX_ANALYTICS_CACHE_SIZE: number;
|
|
194
|
+
|
|
195
|
+
constructor(config?: {
|
|
196
|
+
embeddingService?: EmbeddingService;
|
|
197
|
+
vectorManager?: VectorManager;
|
|
198
|
+
graphManager?: KnowledgeGraphManager;
|
|
199
|
+
storageManager?: StorageManager;
|
|
200
|
+
blockchainManager?: BlockchainManager;
|
|
201
|
+
encryptionService?: EncryptionService;
|
|
202
|
+
batchManager?: BatchManager;
|
|
203
|
+
decryptionConfig?: DecryptionConfig;
|
|
204
|
+
/** Cache configuration for memory management */
|
|
205
|
+
cacheConfig?: {
|
|
206
|
+
/** Query cache TTL in ms (default: 5 minutes) */
|
|
207
|
+
queryCacheTtlMs?: number;
|
|
208
|
+
/** Content cache TTL in ms (default: 30 minutes) */
|
|
209
|
+
contentCacheTtlMs?: number;
|
|
210
|
+
/** Analytics cache TTL in ms (default: 1 hour) */
|
|
211
|
+
analyticsCacheTtlMs?: number;
|
|
212
|
+
/** Max query cache entries (default: 100) */
|
|
213
|
+
maxQueryCacheSize?: number;
|
|
214
|
+
/** Max content cache entries (default: 50) */
|
|
215
|
+
maxContentCacheSize?: number;
|
|
216
|
+
/** Max analytics cache entries (default: 100) */
|
|
217
|
+
maxAnalyticsCacheSize?: number;
|
|
218
|
+
};
|
|
219
|
+
}) {
|
|
220
|
+
// Initialize cache settings with configurable defaults
|
|
221
|
+
this.QUERY_CACHE_TTL = config?.cacheConfig?.queryCacheTtlMs ?? 5 * 60 * 1000; // 5 minutes
|
|
222
|
+
this.CONTENT_CACHE_TTL = config?.cacheConfig?.contentCacheTtlMs ?? 30 * 60 * 1000; // 30 minutes
|
|
223
|
+
this.ANALYTICS_CACHE_TTL = config?.cacheConfig?.analyticsCacheTtlMs ?? 60 * 60 * 1000; // 1 hour
|
|
224
|
+
this.MAX_QUERY_CACHE_SIZE = config?.cacheConfig?.maxQueryCacheSize ?? 100;
|
|
225
|
+
this.MAX_CONTENT_CACHE_SIZE = config?.cacheConfig?.maxContentCacheSize ?? 50; // Content can be large
|
|
226
|
+
this.MAX_ANALYTICS_CACHE_SIZE = config?.cacheConfig?.maxAnalyticsCacheSize ?? 100;
|
|
227
|
+
// Initialize services (can be injected or created with default configs)
|
|
228
|
+
this.embeddingService = config?.embeddingService ?? new EmbeddingService();
|
|
229
|
+
this.storageManager = config?.storageManager ?? new StorageManager();
|
|
230
|
+
this.vectorManager = config?.vectorManager ?? new VectorManager({
|
|
231
|
+
embedding: { apiKey: '' },
|
|
232
|
+
index: { dimension: 3072 },
|
|
233
|
+
batch: { maxBatchSize: 10 }
|
|
234
|
+
});
|
|
235
|
+
this.graphManager = config?.graphManager ?? new KnowledgeGraphManager();
|
|
236
|
+
this.blockchainManager = config?.blockchainManager ?? new BlockchainManager();
|
|
237
|
+
this.encryptionService = config?.encryptionService ?? null;
|
|
238
|
+
this.batchManager = config?.batchManager ?? new BatchManager();
|
|
239
|
+
|
|
240
|
+
// Initialize decryption pipeline only if encryption service is provided
|
|
241
|
+
this.decryptionPipeline = this.encryptionService
|
|
242
|
+
? new MemoryDecryptionPipeline(
|
|
243
|
+
this.encryptionService,
|
|
244
|
+
this.storageManager,
|
|
245
|
+
config?.decryptionConfig
|
|
246
|
+
)
|
|
247
|
+
: null;
|
|
248
|
+
}
|
|
249
|
+
|
|
250
|
+
// ==================== UNIFIED SEARCH ====================
|
|
251
|
+
|
|
252
|
+
/**
|
|
253
|
+
* Main unified search method - handles all types of memory retrieval
|
|
254
|
+
*/
|
|
255
|
+
async searchMemories(query: UnifiedMemoryQuery): Promise<RetrievalContext> {
|
|
256
|
+
const startTime = Date.now();
|
|
257
|
+
|
|
258
|
+
// Check cache first
|
|
259
|
+
const cacheKey = this.generateCacheKey(query);
|
|
260
|
+
if (query.useCache !== false) {
|
|
261
|
+
const cached = this.getCachedQuery(cacheKey);
|
|
262
|
+
if (cached) {
|
|
263
|
+
return cached;
|
|
264
|
+
}
|
|
265
|
+
}
|
|
266
|
+
|
|
267
|
+
try {
|
|
268
|
+
// Execute search based on type
|
|
269
|
+
let results: UnifiedMemoryResult[];
|
|
270
|
+
let searchStats: Partial<RetrievalStats['searchBreakdown']> = {};
|
|
271
|
+
|
|
272
|
+
switch (query.searchType || 'hybrid') {
|
|
273
|
+
case 'vector':
|
|
274
|
+
results = await this.performVectorSearch(query, searchStats);
|
|
275
|
+
break;
|
|
276
|
+
case 'semantic':
|
|
277
|
+
results = await this.performSemanticSearch(query, searchStats);
|
|
278
|
+
break;
|
|
279
|
+
case 'keyword':
|
|
280
|
+
results = await this.performKeywordSearch(query, searchStats);
|
|
281
|
+
break;
|
|
282
|
+
case 'graph':
|
|
283
|
+
results = await this.performGraphSearch(query, searchStats);
|
|
284
|
+
break;
|
|
285
|
+
case 'temporal':
|
|
286
|
+
results = await this.performTemporalSearch(query, searchStats);
|
|
287
|
+
break;
|
|
288
|
+
case 'hybrid':
|
|
289
|
+
default:
|
|
290
|
+
results = await this.performHybridSearch(query, searchStats);
|
|
291
|
+
break;
|
|
292
|
+
}
|
|
293
|
+
|
|
294
|
+
// Apply filters and post-processing
|
|
295
|
+
results = await this.applyFilters(results, query);
|
|
296
|
+
results = await this.enrichResults(results, query);
|
|
297
|
+
results = this.rankAndSortResults(results, query);
|
|
298
|
+
|
|
299
|
+
// Auto-decrypt encrypted memories if decryption is available
|
|
300
|
+
if (this.decryptionPipeline?.isReady()) {
|
|
301
|
+
try {
|
|
302
|
+
results = await this.decryptionPipeline.decryptMemoryResults(results, query.userId);
|
|
303
|
+
} catch (error) {
|
|
304
|
+
console.warn('⚠️ Auto-decryption failed, returning encrypted results:', error);
|
|
305
|
+
}
|
|
306
|
+
}
|
|
307
|
+
|
|
308
|
+
// Generate stats and suggestions
|
|
309
|
+
const stats = this.generateStats(results, searchStats, startTime);
|
|
310
|
+
const suggestions = await this.generateSuggestions(query, results);
|
|
311
|
+
const timeline = await this.generateTimeline(results, query);
|
|
312
|
+
|
|
313
|
+
const context: RetrievalContext = {
|
|
314
|
+
query,
|
|
315
|
+
results,
|
|
316
|
+
stats,
|
|
317
|
+
suggestions,
|
|
318
|
+
timeline
|
|
319
|
+
};
|
|
320
|
+
|
|
321
|
+
// Cache the results
|
|
322
|
+
if (query.useCache !== false) {
|
|
323
|
+
this.cacheQuery(cacheKey, context);
|
|
324
|
+
}
|
|
325
|
+
|
|
326
|
+
return context;
|
|
327
|
+
|
|
328
|
+
} catch (error) {
|
|
329
|
+
throw new Error(`Memory retrieval failed: ${error instanceof Error ? error.message : 'Unknown error'}`);
|
|
330
|
+
}
|
|
331
|
+
}
|
|
332
|
+
|
|
333
|
+
// ==================== SPECIFIC SEARCH IMPLEMENTATIONS ====================
|
|
334
|
+
|
|
335
|
+
/**
|
|
336
|
+
* Vector similarity search using HNSW index
|
|
337
|
+
*/
|
|
338
|
+
private async performVectorSearch(
|
|
339
|
+
query: UnifiedMemoryQuery,
|
|
340
|
+
stats: Partial<RetrievalStats['searchBreakdown']>
|
|
341
|
+
): Promise<UnifiedMemoryResult[]> {
|
|
342
|
+
const vectorStart = Date.now();
|
|
343
|
+
|
|
344
|
+
if (!query.query) {
|
|
345
|
+
throw new Error('Vector search requires a query string');
|
|
346
|
+
}
|
|
347
|
+
|
|
348
|
+
// Generate query embedding
|
|
349
|
+
const embedding = await this.embeddingService.embedText({
|
|
350
|
+
text: query.query,
|
|
351
|
+
taskType: 'RETRIEVAL_QUERY'
|
|
352
|
+
});
|
|
353
|
+
|
|
354
|
+
// Search vector index
|
|
355
|
+
const vectorResults = await this.vectorManager.searchSimilarTexts(
|
|
356
|
+
'default-user',
|
|
357
|
+
query.query,
|
|
358
|
+
{
|
|
359
|
+
k: query.similarity?.k || 10,
|
|
360
|
+
efSearch: query.similarity?.efSearch || 100,
|
|
361
|
+
threshold: query.similarity?.threshold || 0.7
|
|
362
|
+
}
|
|
363
|
+
);
|
|
364
|
+
|
|
365
|
+
stats.vectorSearchTime = Date.now() - vectorStart;
|
|
366
|
+
|
|
367
|
+
// Convert to unified format
|
|
368
|
+
return await this.convertVectorResults(vectorResults.results, query);
|
|
369
|
+
}
|
|
370
|
+
|
|
371
|
+
/**
|
|
372
|
+
* Semantic search with AI understanding
|
|
373
|
+
*/
|
|
374
|
+
private async performSemanticSearch(
|
|
375
|
+
query: UnifiedMemoryQuery,
|
|
376
|
+
stats: Partial<RetrievalStats['searchBreakdown']>
|
|
377
|
+
): Promise<UnifiedMemoryResult[]> {
|
|
378
|
+
const semanticStart = Date.now();
|
|
379
|
+
|
|
380
|
+
// First, get vector results as base
|
|
381
|
+
const vectorResults = await this.performVectorSearch(query, stats);
|
|
382
|
+
|
|
383
|
+
// Apply semantic analysis for better understanding
|
|
384
|
+
if (query.query) {
|
|
385
|
+
// Analyze query semantics
|
|
386
|
+
const semanticAnalysis = await this.analyzeQuerySemantics(query.query);
|
|
387
|
+
|
|
388
|
+
// Re-rank results based on semantic understanding
|
|
389
|
+
for (const result of vectorResults) {
|
|
390
|
+
result.searchRelevance.semanticMatch = await this.calculateSemanticMatch(
|
|
391
|
+
result,
|
|
392
|
+
semanticAnalysis
|
|
393
|
+
);
|
|
394
|
+
result.relevanceScore = this.combineRelevanceScores(result.searchRelevance);
|
|
395
|
+
}
|
|
396
|
+
}
|
|
397
|
+
|
|
398
|
+
stats.semanticAnalysisTime = (stats.semanticAnalysisTime || 0) + (Date.now() - semanticStart);
|
|
399
|
+
|
|
400
|
+
return vectorResults;
|
|
401
|
+
}
|
|
402
|
+
|
|
403
|
+
/**
|
|
404
|
+
* Knowledge graph traversal search
|
|
405
|
+
*/
|
|
406
|
+
private async performGraphSearch(
|
|
407
|
+
query: UnifiedMemoryQuery,
|
|
408
|
+
stats: Partial<RetrievalStats['searchBreakdown']>
|
|
409
|
+
): Promise<UnifiedMemoryResult[]> {
|
|
410
|
+
const graphStart = Date.now();
|
|
411
|
+
|
|
412
|
+
const results: UnifiedMemoryResult[] = [];
|
|
413
|
+
|
|
414
|
+
if (query.query) {
|
|
415
|
+
// Search graph for related entities and memories
|
|
416
|
+
const graphResults = await this.graphManager.searchGraph(
|
|
417
|
+
query.query,
|
|
418
|
+
{
|
|
419
|
+
maxResults: query.similarity?.k || 20
|
|
420
|
+
}
|
|
421
|
+
);
|
|
422
|
+
|
|
423
|
+
// Find memories related to discovered entities
|
|
424
|
+
for (const entity of graphResults.entities) {
|
|
425
|
+
const relatedMemories = await this.graphManager.findMemoriesRelatedToEntity(
|
|
426
|
+
entity.label || entity.id,
|
|
427
|
+
query.userId
|
|
428
|
+
);
|
|
429
|
+
|
|
430
|
+
const memoryIds = Array.isArray(relatedMemories) ? relatedMemories :
|
|
431
|
+
(relatedMemories?.memories || []);
|
|
432
|
+
for (const memoryId of memoryIds) {
|
|
433
|
+
const memory = await this.retrieveMemoryById(memoryId, query);
|
|
434
|
+
if (memory) {
|
|
435
|
+
memory.searchRelevance.graphRelevance = entity.confidence || 0.8;
|
|
436
|
+
results.push(memory);
|
|
437
|
+
}
|
|
438
|
+
}
|
|
439
|
+
}
|
|
440
|
+
}
|
|
441
|
+
|
|
442
|
+
stats.graphTraversalTime = Date.now() - graphStart;
|
|
443
|
+
return results;
|
|
444
|
+
}
|
|
445
|
+
|
|
446
|
+
/**
|
|
447
|
+
* Temporal/time-based search
|
|
448
|
+
*/
|
|
449
|
+
private async performTemporalSearch(
|
|
450
|
+
query: UnifiedMemoryQuery,
|
|
451
|
+
stats: Partial<RetrievalStats['searchBreakdown']>
|
|
452
|
+
): Promise<UnifiedMemoryResult[]> {
|
|
453
|
+
// Get all user memories
|
|
454
|
+
const allMemories = await this.getAllUserMemories(query.userId);
|
|
455
|
+
|
|
456
|
+
// Filter by date range
|
|
457
|
+
let filteredMemories = allMemories;
|
|
458
|
+
|
|
459
|
+
if (query.dateRange?.start) {
|
|
460
|
+
filteredMemories = filteredMemories.filter(
|
|
461
|
+
m => m.created >= query.dateRange!.start!
|
|
462
|
+
);
|
|
463
|
+
}
|
|
464
|
+
|
|
465
|
+
if (query.dateRange?.end) {
|
|
466
|
+
filteredMemories = filteredMemories.filter(
|
|
467
|
+
m => m.created <= query.dateRange!.end!
|
|
468
|
+
);
|
|
469
|
+
}
|
|
470
|
+
|
|
471
|
+
// Calculate temporal relevance
|
|
472
|
+
filteredMemories.forEach(memory => {
|
|
473
|
+
memory.searchRelevance.temporalRelevance = this.calculateTemporalRelevance(
|
|
474
|
+
memory.created,
|
|
475
|
+
query.dateRange
|
|
476
|
+
);
|
|
477
|
+
});
|
|
478
|
+
|
|
479
|
+
return filteredMemories;
|
|
480
|
+
}
|
|
481
|
+
|
|
482
|
+
/**
|
|
483
|
+
* Keyword-based search
|
|
484
|
+
*/
|
|
485
|
+
private async performKeywordSearch(
|
|
486
|
+
query: UnifiedMemoryQuery,
|
|
487
|
+
stats: Partial<RetrievalStats['searchBreakdown']>
|
|
488
|
+
): Promise<UnifiedMemoryResult[]> {
|
|
489
|
+
if (!query.query) {
|
|
490
|
+
return [];
|
|
491
|
+
}
|
|
492
|
+
|
|
493
|
+
const keywords = query.query.toLowerCase().split(/\s+/);
|
|
494
|
+
const allMemories = await this.getAllUserMemories(query.userId);
|
|
495
|
+
|
|
496
|
+
// Score memories based on keyword matches
|
|
497
|
+
const results = allMemories.filter(memory => {
|
|
498
|
+
const content = (memory.content || '').toLowerCase();
|
|
499
|
+
const matchCount = keywords.filter(keyword =>
|
|
500
|
+
content.includes(keyword)
|
|
501
|
+
).length;
|
|
502
|
+
|
|
503
|
+
if (matchCount > 0) {
|
|
504
|
+
memory.searchRelevance.keywordMatch = matchCount / keywords.length;
|
|
505
|
+
return true;
|
|
506
|
+
}
|
|
507
|
+
|
|
508
|
+
return false;
|
|
509
|
+
});
|
|
510
|
+
|
|
511
|
+
return results;
|
|
512
|
+
}
|
|
513
|
+
|
|
514
|
+
/**
|
|
515
|
+
* Hybrid search combining multiple methods
|
|
516
|
+
*/
|
|
517
|
+
private async performHybridSearch(
|
|
518
|
+
query: UnifiedMemoryQuery,
|
|
519
|
+
stats: Partial<RetrievalStats['searchBreakdown']>
|
|
520
|
+
): Promise<UnifiedMemoryResult[]> {
|
|
521
|
+
const allResults: UnifiedMemoryResult[] = [];
|
|
522
|
+
const resultMap = new Map<string, UnifiedMemoryResult>();
|
|
523
|
+
|
|
524
|
+
// Perform multiple search types
|
|
525
|
+
if (query.query) {
|
|
526
|
+
// Vector search
|
|
527
|
+
const vectorResults = await this.performVectorSearch(query, stats);
|
|
528
|
+
vectorResults.forEach(result => {
|
|
529
|
+
result.searchRelevance.vectorSimilarity = result.similarity || 0;
|
|
530
|
+
resultMap.set(result.id, result);
|
|
531
|
+
});
|
|
532
|
+
|
|
533
|
+
// Semantic enhancement
|
|
534
|
+
const semanticResults = await this.performSemanticSearch(query, stats);
|
|
535
|
+
semanticResults.forEach(result => {
|
|
536
|
+
const existing = resultMap.get(result.id);
|
|
537
|
+
if (existing) {
|
|
538
|
+
existing.searchRelevance.semanticMatch = result.searchRelevance.semanticMatch;
|
|
539
|
+
} else {
|
|
540
|
+
resultMap.set(result.id, result);
|
|
541
|
+
}
|
|
542
|
+
});
|
|
543
|
+
|
|
544
|
+
// Graph search
|
|
545
|
+
const graphResults = await this.performGraphSearch(query, stats);
|
|
546
|
+
graphResults.forEach(result => {
|
|
547
|
+
const existing = resultMap.get(result.id);
|
|
548
|
+
if (existing) {
|
|
549
|
+
existing.searchRelevance.graphRelevance = result.searchRelevance.graphRelevance;
|
|
550
|
+
} else {
|
|
551
|
+
resultMap.set(result.id, result);
|
|
552
|
+
}
|
|
553
|
+
});
|
|
554
|
+
}
|
|
555
|
+
|
|
556
|
+
// Temporal search if date range specified
|
|
557
|
+
if (query.dateRange) {
|
|
558
|
+
const temporalResults = await this.performTemporalSearch(query, stats);
|
|
559
|
+
temporalResults.forEach(result => {
|
|
560
|
+
const existing = resultMap.get(result.id);
|
|
561
|
+
if (existing) {
|
|
562
|
+
existing.searchRelevance.temporalRelevance = result.searchRelevance.temporalRelevance;
|
|
563
|
+
} else {
|
|
564
|
+
resultMap.set(result.id, result);
|
|
565
|
+
}
|
|
566
|
+
});
|
|
567
|
+
}
|
|
568
|
+
|
|
569
|
+
// Combine and calculate final relevance scores
|
|
570
|
+
Array.from(resultMap.values()).forEach(result => {
|
|
571
|
+
result.relevanceScore = this.combineRelevanceScores(result.searchRelevance);
|
|
572
|
+
});
|
|
573
|
+
|
|
574
|
+
return Array.from(resultMap.values());
|
|
575
|
+
}
|
|
576
|
+
|
|
577
|
+
// ==================== HELPER METHODS ====================
|
|
578
|
+
|
|
579
|
+
/**
|
|
580
|
+
* Apply filters to search results
|
|
581
|
+
*/
|
|
582
|
+
private async applyFilters(
|
|
583
|
+
results: UnifiedMemoryResult[],
|
|
584
|
+
query: UnifiedMemoryQuery
|
|
585
|
+
): Promise<UnifiedMemoryResult[]> {
|
|
586
|
+
let filtered = results;
|
|
587
|
+
|
|
588
|
+
// Category filter
|
|
589
|
+
if (query.categories && query.categories.length > 0) {
|
|
590
|
+
filtered = filtered.filter(result =>
|
|
591
|
+
query.categories!.includes(result.category)
|
|
592
|
+
);
|
|
593
|
+
}
|
|
594
|
+
|
|
595
|
+
// Importance filter
|
|
596
|
+
if (query.importanceRange) {
|
|
597
|
+
filtered = filtered.filter(result => {
|
|
598
|
+
const importance = result.metadata.importance;
|
|
599
|
+
return (!query.importanceRange!.min || importance >= query.importanceRange!.min) &&
|
|
600
|
+
(!query.importanceRange!.max || importance <= query.importanceRange!.max);
|
|
601
|
+
});
|
|
602
|
+
}
|
|
603
|
+
|
|
604
|
+
// Tags filter
|
|
605
|
+
if (query.tags && query.tags.length > 0) {
|
|
606
|
+
filtered = filtered.filter(result =>
|
|
607
|
+
query.tags!.some(tag => result.metadata.tags.includes(tag))
|
|
608
|
+
);
|
|
609
|
+
}
|
|
610
|
+
|
|
611
|
+
// Content type filter
|
|
612
|
+
if (query.contentTypes && query.contentTypes.length > 0) {
|
|
613
|
+
filtered = filtered.filter(result =>
|
|
614
|
+
query.contentTypes!.includes(result.metadata.contentType)
|
|
615
|
+
);
|
|
616
|
+
}
|
|
617
|
+
|
|
618
|
+
return filtered;
|
|
619
|
+
}
|
|
620
|
+
|
|
621
|
+
/**
|
|
622
|
+
* Enrich results with additional data
|
|
623
|
+
*/
|
|
624
|
+
private async enrichResults(
|
|
625
|
+
results: UnifiedMemoryResult[],
|
|
626
|
+
query: UnifiedMemoryQuery
|
|
627
|
+
): Promise<UnifiedMemoryResult[]> {
|
|
628
|
+
const enriched = await Promise.all(results.map(async (result) => {
|
|
629
|
+
// Load content if requested
|
|
630
|
+
if (query.includeContent && !result.content) {
|
|
631
|
+
try {
|
|
632
|
+
const content = await this.loadMemoryContent(result.storage.blobId, query.userId);
|
|
633
|
+
result.content = content;
|
|
634
|
+
} catch (error) {
|
|
635
|
+
console.warn(`Failed to load content for memory ${result.id}:`, error);
|
|
636
|
+
}
|
|
637
|
+
}
|
|
638
|
+
|
|
639
|
+
// Load analytics if requested
|
|
640
|
+
if (query.includeAnalytics) {
|
|
641
|
+
result.analytics = await this.loadMemoryAnalytics(result.id);
|
|
642
|
+
}
|
|
643
|
+
|
|
644
|
+
// Load relationships if requested
|
|
645
|
+
if (query.includeMetadata) {
|
|
646
|
+
result.relationships = await this.loadMemoryRelationships(result.id, query.userId);
|
|
647
|
+
}
|
|
648
|
+
|
|
649
|
+
return result;
|
|
650
|
+
}));
|
|
651
|
+
|
|
652
|
+
return enriched;
|
|
653
|
+
}
|
|
654
|
+
|
|
655
|
+
// ... [Continuing with remaining helper methods]
|
|
656
|
+
|
|
657
|
+
/**
|
|
658
|
+
* Rank and sort results by relevance
|
|
659
|
+
*/
|
|
660
|
+
private rankAndSortResults(
|
|
661
|
+
results: UnifiedMemoryResult[],
|
|
662
|
+
query: UnifiedMemoryQuery
|
|
663
|
+
): UnifiedMemoryResult[] {
|
|
664
|
+
return results
|
|
665
|
+
.sort((a, b) => b.relevanceScore - a.relevanceScore)
|
|
666
|
+
.slice(0, query.similarity?.k || 50);
|
|
667
|
+
}
|
|
668
|
+
|
|
669
|
+
/**
|
|
670
|
+
* Generate comprehensive search statistics
|
|
671
|
+
*/
|
|
672
|
+
private generateStats(
|
|
673
|
+
results: UnifiedMemoryResult[],
|
|
674
|
+
searchBreakdown: Partial<RetrievalStats['searchBreakdown']>,
|
|
675
|
+
startTime: number
|
|
676
|
+
): RetrievalStats {
|
|
677
|
+
const totalTime = Date.now() - startTime;
|
|
678
|
+
|
|
679
|
+
return {
|
|
680
|
+
totalResults: results.length,
|
|
681
|
+
processingTime: totalTime,
|
|
682
|
+
cacheHitRate: this.calculateCacheHitRate(),
|
|
683
|
+
searchBreakdown: {
|
|
684
|
+
vectorSearchTime: searchBreakdown.vectorSearchTime || 0,
|
|
685
|
+
semanticAnalysisTime: searchBreakdown.semanticAnalysisTime || 0,
|
|
686
|
+
decryptionTime: searchBreakdown.decryptionTime || 0,
|
|
687
|
+
graphTraversalTime: searchBreakdown.graphTraversalTime || 0
|
|
688
|
+
},
|
|
689
|
+
dataSourcesUsed: this.getDataSourcesUsed(results),
|
|
690
|
+
qualityMetrics: {
|
|
691
|
+
averageRelevance: results.reduce((sum, r) => sum + r.relevanceScore, 0) / results.length || 0,
|
|
692
|
+
diversityScore: this.calculateDiversityScore(results),
|
|
693
|
+
freshnessScore: this.calculateFreshnessScore(results)
|
|
694
|
+
}
|
|
695
|
+
};
|
|
696
|
+
}
|
|
697
|
+
|
|
698
|
+
// ==================== CACHE MANAGEMENT ====================
|
|
699
|
+
|
|
700
|
+
private generateCacheKey(query: UnifiedMemoryQuery): string {
|
|
701
|
+
return `query:${JSON.stringify(query)}`;
|
|
702
|
+
}
|
|
703
|
+
|
|
704
|
+
private getCachedQuery(key: string): RetrievalContext | null {
|
|
705
|
+
const cached = this.queryCache.get(key);
|
|
706
|
+
if (cached && Date.now() - cached.timestamp < this.QUERY_CACHE_TTL) {
|
|
707
|
+
return cached.result;
|
|
708
|
+
}
|
|
709
|
+
this.queryCache.delete(key);
|
|
710
|
+
return null;
|
|
711
|
+
}
|
|
712
|
+
|
|
713
|
+
private cacheQuery(key: string, result: RetrievalContext): void {
|
|
714
|
+
this.enforceCacheLimit(this.queryCache, this.MAX_QUERY_CACHE_SIZE, this.QUERY_CACHE_TTL);
|
|
715
|
+
this.queryCache.set(key, { result, timestamp: Date.now() });
|
|
716
|
+
}
|
|
717
|
+
|
|
718
|
+
/**
|
|
719
|
+
* Cache content with size limit enforcement
|
|
720
|
+
*/
|
|
721
|
+
private cacheContent(key: string, content: string, metadata: any): void {
|
|
722
|
+
this.enforceCacheLimit(this.contentCache, this.MAX_CONTENT_CACHE_SIZE, this.CONTENT_CACHE_TTL);
|
|
723
|
+
this.contentCache.set(key, { content, metadata, timestamp: Date.now() });
|
|
724
|
+
}
|
|
725
|
+
|
|
726
|
+
/**
|
|
727
|
+
* Cache analytics with size limit enforcement
|
|
728
|
+
*/
|
|
729
|
+
private cacheAnalytics(key: string, analytics: any): void {
|
|
730
|
+
this.enforceCacheLimit(this.analyticsCache, this.MAX_ANALYTICS_CACHE_SIZE, this.ANALYTICS_CACHE_TTL);
|
|
731
|
+
this.analyticsCache.set(key, { analytics, timestamp: Date.now() });
|
|
732
|
+
}
|
|
733
|
+
|
|
734
|
+
/**
|
|
735
|
+
* Enforce cache size limit using LRU eviction (oldest entries first)
|
|
736
|
+
* Also removes expired entries based on TTL
|
|
737
|
+
*/
|
|
738
|
+
private enforceCacheLimit<T extends { timestamp: number }>(
|
|
739
|
+
cache: Map<string, T>,
|
|
740
|
+
maxSize: number,
|
|
741
|
+
ttl: number
|
|
742
|
+
): void {
|
|
743
|
+
// First, clean up expired entries
|
|
744
|
+
const now = Date.now();
|
|
745
|
+
|
|
746
|
+
for (const [key, value] of cache.entries()) {
|
|
747
|
+
if (now - value.timestamp > ttl) {
|
|
748
|
+
cache.delete(key);
|
|
749
|
+
}
|
|
750
|
+
}
|
|
751
|
+
|
|
752
|
+
// If still over limit, remove oldest entries (LRU)
|
|
753
|
+
if (cache.size >= maxSize) {
|
|
754
|
+
const entries = Array.from(cache.entries())
|
|
755
|
+
.sort((a, b) => a[1].timestamp - b[1].timestamp);
|
|
756
|
+
|
|
757
|
+
const toRemove = cache.size - maxSize + 1; // +1 to make room for new entry
|
|
758
|
+
for (let i = 0; i < toRemove && i < entries.length; i++) {
|
|
759
|
+
cache.delete(entries[i][0]);
|
|
760
|
+
}
|
|
761
|
+
}
|
|
762
|
+
}
|
|
763
|
+
|
|
764
|
+
// ==================== UTILITY METHODS ====================
|
|
765
|
+
|
|
766
|
+
private calculateCacheHitRate(): number {
|
|
767
|
+
// Implementation for cache hit rate calculation
|
|
768
|
+
return 0.85; // Placeholder
|
|
769
|
+
}
|
|
770
|
+
|
|
771
|
+
private getDataSourcesUsed(results: UnifiedMemoryResult[]): string[] {
|
|
772
|
+
const sources = new Set<string>();
|
|
773
|
+
results.forEach(result => {
|
|
774
|
+
if (result.storage.cacheStatus === 'cached') sources.add('cache');
|
|
775
|
+
if (result.storage.walrusHash) sources.add('walrus');
|
|
776
|
+
if (result.storage.blockchainId) sources.add('blockchain');
|
|
777
|
+
});
|
|
778
|
+
return Array.from(sources);
|
|
779
|
+
}
|
|
780
|
+
|
|
781
|
+
private calculateDiversityScore(results: UnifiedMemoryResult[]): number {
|
|
782
|
+
const categories = new Set(results.map(r => r.category));
|
|
783
|
+
return categories.size / Math.max(results.length, 1);
|
|
784
|
+
}
|
|
785
|
+
|
|
786
|
+
private calculateFreshnessScore(results: UnifiedMemoryResult[]): number {
|
|
787
|
+
const now = Date.now();
|
|
788
|
+
const avgAge = results.reduce((sum, r) => sum + (now - r.created.getTime()), 0) / results.length;
|
|
789
|
+
const maxAge = 365 * 24 * 60 * 60 * 1000; // 1 year in ms
|
|
790
|
+
return Math.max(0, 1 - (avgAge / maxAge));
|
|
791
|
+
}
|
|
792
|
+
|
|
793
|
+
// Placeholder methods - to be implemented
|
|
794
|
+
private async convertVectorResults(vectorResults: any[], query: UnifiedMemoryQuery): Promise<UnifiedMemoryResult[]> {
|
|
795
|
+
// Convert vector search results to unified format
|
|
796
|
+
return [];
|
|
797
|
+
}
|
|
798
|
+
|
|
799
|
+
private async analyzeQuerySemantics(query: string): Promise<any> {
|
|
800
|
+
// Analyze query for semantic understanding
|
|
801
|
+
return {};
|
|
802
|
+
}
|
|
803
|
+
|
|
804
|
+
private async calculateSemanticMatch(result: UnifiedMemoryResult, semantics: any): Promise<number> {
|
|
805
|
+
// Calculate semantic match score
|
|
806
|
+
return 0.8;
|
|
807
|
+
}
|
|
808
|
+
|
|
809
|
+
private combineRelevanceScores(scores: UnifiedMemoryResult['searchRelevance']): number {
|
|
810
|
+
// Combine different relevance scores into final score
|
|
811
|
+
const weights = {
|
|
812
|
+
vectorSimilarity: 0.4,
|
|
813
|
+
semanticMatch: 0.3,
|
|
814
|
+
keywordMatch: 0.1,
|
|
815
|
+
graphRelevance: 0.15,
|
|
816
|
+
temporalRelevance: 0.05
|
|
817
|
+
};
|
|
818
|
+
|
|
819
|
+
return (scores.vectorSimilarity || 0) * weights.vectorSimilarity +
|
|
820
|
+
(scores.semanticMatch || 0) * weights.semanticMatch +
|
|
821
|
+
(scores.keywordMatch || 0) * weights.keywordMatch +
|
|
822
|
+
(scores.graphRelevance || 0) * weights.graphRelevance +
|
|
823
|
+
(scores.temporalRelevance || 0) * weights.temporalRelevance;
|
|
824
|
+
}
|
|
825
|
+
|
|
826
|
+
private calculateTemporalRelevance(date: Date, range?: { start?: Date; end?: Date }): number {
|
|
827
|
+
// Calculate temporal relevance score
|
|
828
|
+
return 0.7;
|
|
829
|
+
}
|
|
830
|
+
|
|
831
|
+
private async getAllUserMemories(userId: string): Promise<UnifiedMemoryResult[]> {
|
|
832
|
+
// Get all memories for user from blockchain
|
|
833
|
+
return [];
|
|
834
|
+
}
|
|
835
|
+
|
|
836
|
+
private async retrieveMemoryById(memoryId: string, query: UnifiedMemoryQuery): Promise<UnifiedMemoryResult | null> {
|
|
837
|
+
// Retrieve specific memory by ID
|
|
838
|
+
return null;
|
|
839
|
+
}
|
|
840
|
+
|
|
841
|
+
private async loadMemoryContent(blobId: string, userId: string): Promise<string> {
|
|
842
|
+
// Load and decrypt memory content
|
|
843
|
+
return "";
|
|
844
|
+
}
|
|
845
|
+
|
|
846
|
+
private async loadMemoryAnalytics(memoryId: string): Promise<any> {
|
|
847
|
+
// Load memory analytics data
|
|
848
|
+
return {};
|
|
849
|
+
}
|
|
850
|
+
|
|
851
|
+
private async loadMemoryRelationships(memoryId: string, userId: string): Promise<any> {
|
|
852
|
+
// Load memory relationships from knowledge graph
|
|
853
|
+
return {};
|
|
854
|
+
}
|
|
855
|
+
|
|
856
|
+
private async generateSuggestions(query: UnifiedMemoryQuery, results: UnifiedMemoryResult[]): Promise<any> {
|
|
857
|
+
// Generate query suggestions and exploration paths
|
|
858
|
+
return {
|
|
859
|
+
relatedQueries: [],
|
|
860
|
+
filterSuggestions: [],
|
|
861
|
+
explorationPaths: []
|
|
862
|
+
};
|
|
863
|
+
}
|
|
864
|
+
|
|
865
|
+
private async generateTimeline(results: UnifiedMemoryResult[], query: UnifiedMemoryQuery): Promise<any> {
|
|
866
|
+
// Generate timeline of memory events
|
|
867
|
+
return undefined;
|
|
868
|
+
}
|
|
869
|
+
|
|
870
|
+
// ==================== PUBLIC API ====================
|
|
871
|
+
|
|
872
|
+
/**
|
|
873
|
+
* Get comprehensive memory retrieval statistics
|
|
874
|
+
*/
|
|
875
|
+
getRetrievalStats(): {
|
|
876
|
+
cacheStats: { queries: number; content: number; analytics: number };
|
|
877
|
+
performanceMetrics: any;
|
|
878
|
+
} {
|
|
879
|
+
return {
|
|
880
|
+
cacheStats: {
|
|
881
|
+
queries: this.queryCache.size,
|
|
882
|
+
content: this.contentCache.size,
|
|
883
|
+
analytics: this.analyticsCache.size
|
|
884
|
+
},
|
|
885
|
+
performanceMetrics: {}
|
|
886
|
+
};
|
|
887
|
+
}
|
|
888
|
+
|
|
889
|
+
/**
|
|
890
|
+
* Clear all caches
|
|
891
|
+
*/
|
|
892
|
+
clearCache(): void {
|
|
893
|
+
this.queryCache.clear();
|
|
894
|
+
this.contentCache.clear();
|
|
895
|
+
this.analyticsCache.clear();
|
|
896
|
+
}
|
|
897
|
+
|
|
898
|
+
/**
|
|
899
|
+
* Warm up caches for a user
|
|
900
|
+
*/
|
|
901
|
+
async warmupCache(userId: string): Promise<void> {
|
|
902
|
+
// Pre-load frequently accessed data
|
|
903
|
+
console.log(`Warming up cache for user ${userId}`);
|
|
904
|
+
}
|
|
831
905
|
}
|