@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.
Files changed (247) hide show
  1. package/ARCHITECTURE.md +547 -547
  2. package/BENCHMARKS.md +238 -238
  3. package/README.md +310 -181
  4. package/dist/ai-sdk/tools.d.ts +2 -2
  5. package/dist/ai-sdk/tools.js +2 -2
  6. package/dist/client/ClientMemoryManager.js +2 -2
  7. package/dist/client/ClientMemoryManager.js.map +1 -1
  8. package/dist/client/PersonalDataWallet.d.ts.map +1 -1
  9. package/dist/client/SimplePDWClient.d.ts +29 -1
  10. package/dist/client/SimplePDWClient.d.ts.map +1 -1
  11. package/dist/client/SimplePDWClient.js +45 -13
  12. package/dist/client/SimplePDWClient.js.map +1 -1
  13. package/dist/client/namespaces/EmbeddingsNamespace.d.ts +1 -1
  14. package/dist/client/namespaces/EmbeddingsNamespace.js +1 -1
  15. package/dist/client/namespaces/MemoryNamespace.d.ts +31 -0
  16. package/dist/client/namespaces/MemoryNamespace.d.ts.map +1 -1
  17. package/dist/client/namespaces/MemoryNamespace.js +272 -39
  18. package/dist/client/namespaces/MemoryNamespace.js.map +1 -1
  19. package/dist/client/namespaces/consolidated/AINamespace.d.ts +2 -2
  20. package/dist/client/namespaces/consolidated/AINamespace.js +2 -2
  21. package/dist/client/namespaces/consolidated/BlockchainNamespace.d.ts +12 -2
  22. package/dist/client/namespaces/consolidated/BlockchainNamespace.d.ts.map +1 -1
  23. package/dist/client/namespaces/consolidated/BlockchainNamespace.js +62 -4
  24. package/dist/client/namespaces/consolidated/BlockchainNamespace.js.map +1 -1
  25. package/dist/client/namespaces/consolidated/StorageNamespace.d.ts +67 -2
  26. package/dist/client/namespaces/consolidated/StorageNamespace.d.ts.map +1 -1
  27. package/dist/client/namespaces/consolidated/StorageNamespace.js +549 -16
  28. package/dist/client/namespaces/consolidated/StorageNamespace.js.map +1 -1
  29. package/dist/config/ConfigurationHelper.js +61 -61
  30. package/dist/config/defaults.js +2 -2
  31. package/dist/config/defaults.js.map +1 -1
  32. package/dist/graph/GraphService.js +21 -21
  33. package/dist/graph/GraphService.js.map +1 -1
  34. package/dist/index.d.ts +3 -1
  35. package/dist/index.d.ts.map +1 -1
  36. package/dist/index.js +3 -1
  37. package/dist/index.js.map +1 -1
  38. package/dist/infrastructure/seal/EncryptionService.d.ts +9 -5
  39. package/dist/infrastructure/seal/EncryptionService.d.ts.map +1 -1
  40. package/dist/infrastructure/seal/EncryptionService.js +37 -15
  41. package/dist/infrastructure/seal/EncryptionService.js.map +1 -1
  42. package/dist/infrastructure/seal/SealService.d.ts +13 -5
  43. package/dist/infrastructure/seal/SealService.d.ts.map +1 -1
  44. package/dist/infrastructure/seal/SealService.js +36 -34
  45. package/dist/infrastructure/seal/SealService.js.map +1 -1
  46. package/dist/langchain/createPDWRAG.js +30 -30
  47. package/dist/retrieval/MemoryDecryptionPipeline.d.ts.map +1 -1
  48. package/dist/retrieval/MemoryDecryptionPipeline.js +2 -1
  49. package/dist/retrieval/MemoryDecryptionPipeline.js.map +1 -1
  50. package/dist/retrieval/MemoryRetrievalService.d.ts +31 -0
  51. package/dist/retrieval/MemoryRetrievalService.d.ts.map +1 -1
  52. package/dist/retrieval/MemoryRetrievalService.js +44 -4
  53. package/dist/retrieval/MemoryRetrievalService.js.map +1 -1
  54. package/dist/services/CapabilityService.d.ts.map +1 -1
  55. package/dist/services/CapabilityService.js +30 -14
  56. package/dist/services/CapabilityService.js.map +1 -1
  57. package/dist/services/CrossContextPermissionService.d.ts.map +1 -1
  58. package/dist/services/CrossContextPermissionService.js +9 -7
  59. package/dist/services/CrossContextPermissionService.js.map +1 -1
  60. package/dist/services/EmbeddingService.d.ts +28 -1
  61. package/dist/services/EmbeddingService.d.ts.map +1 -1
  62. package/dist/services/EmbeddingService.js +54 -0
  63. package/dist/services/EmbeddingService.js.map +1 -1
  64. package/dist/services/EncryptionService.d.ts.map +1 -1
  65. package/dist/services/EncryptionService.js +6 -5
  66. package/dist/services/EncryptionService.js.map +1 -1
  67. package/dist/services/GeminiAIService.js +309 -309
  68. package/dist/services/IndexManager.d.ts +5 -1
  69. package/dist/services/IndexManager.d.ts.map +1 -1
  70. package/dist/services/IndexManager.js +17 -40
  71. package/dist/services/IndexManager.js.map +1 -1
  72. package/dist/services/QueryService.js +1 -1
  73. package/dist/services/QueryService.js.map +1 -1
  74. package/dist/services/StorageService.d.ts +11 -0
  75. package/dist/services/StorageService.d.ts.map +1 -1
  76. package/dist/services/StorageService.js +73 -10
  77. package/dist/services/StorageService.js.map +1 -1
  78. package/dist/services/TransactionService.d.ts +20 -0
  79. package/dist/services/TransactionService.d.ts.map +1 -1
  80. package/dist/services/TransactionService.js +43 -0
  81. package/dist/services/TransactionService.js.map +1 -1
  82. package/dist/services/ViewService.js +2 -2
  83. package/dist/services/ViewService.js.map +1 -1
  84. package/dist/services/storage/QuiltBatchManager.d.ts +101 -1
  85. package/dist/services/storage/QuiltBatchManager.d.ts.map +1 -1
  86. package/dist/services/storage/QuiltBatchManager.js +410 -20
  87. package/dist/services/storage/QuiltBatchManager.js.map +1 -1
  88. package/dist/services/storage/index.d.ts +1 -1
  89. package/dist/services/storage/index.d.ts.map +1 -1
  90. package/dist/services/storage/index.js.map +1 -1
  91. package/dist/utils/LRUCache.d.ts +106 -0
  92. package/dist/utils/LRUCache.d.ts.map +1 -0
  93. package/dist/utils/LRUCache.js +281 -0
  94. package/dist/utils/LRUCache.js.map +1 -0
  95. package/dist/utils/index.d.ts +1 -0
  96. package/dist/utils/index.d.ts.map +1 -1
  97. package/dist/utils/index.js +2 -0
  98. package/dist/utils/index.js.map +1 -1
  99. package/dist/utils/memoryIndexOnChain.d.ts +212 -0
  100. package/dist/utils/memoryIndexOnChain.d.ts.map +1 -0
  101. package/dist/utils/memoryIndexOnChain.js +312 -0
  102. package/dist/utils/memoryIndexOnChain.js.map +1 -0
  103. package/dist/utils/rebuildIndexNode.d.ts +29 -0
  104. package/dist/utils/rebuildIndexNode.d.ts.map +1 -1
  105. package/dist/utils/rebuildIndexNode.js +366 -98
  106. package/dist/utils/rebuildIndexNode.js.map +1 -1
  107. package/dist/vector/HnswWasmService.d.ts +20 -5
  108. package/dist/vector/HnswWasmService.d.ts.map +1 -1
  109. package/dist/vector/HnswWasmService.js +73 -40
  110. package/dist/vector/HnswWasmService.js.map +1 -1
  111. package/dist/vector/IHnswService.d.ts +10 -1
  112. package/dist/vector/IHnswService.d.ts.map +1 -1
  113. package/dist/vector/IHnswService.js.map +1 -1
  114. package/dist/vector/NodeHnswService.d.ts +16 -0
  115. package/dist/vector/NodeHnswService.d.ts.map +1 -1
  116. package/dist/vector/NodeHnswService.js +84 -5
  117. package/dist/vector/NodeHnswService.js.map +1 -1
  118. package/dist/vector/createHnswService.d.ts +1 -1
  119. package/dist/vector/createHnswService.js +1 -1
  120. package/dist/vector/index.d.ts +1 -1
  121. package/dist/vector/index.js +1 -1
  122. package/package.json +157 -157
  123. package/src/access/PermissionService.ts +635 -635
  124. package/src/aggregation/AggregationService.ts +389 -389
  125. package/src/ai-sdk/PDWVectorStore.ts +715 -715
  126. package/src/ai-sdk/index.ts +65 -65
  127. package/src/ai-sdk/tools.ts +460 -460
  128. package/src/ai-sdk/types.ts +404 -404
  129. package/src/batch/BatchManager.ts +597 -597
  130. package/src/batch/BatchingService.ts +429 -429
  131. package/src/batch/MemoryProcessingCache.ts +492 -492
  132. package/src/batch/index.ts +30 -30
  133. package/src/browser.ts +200 -200
  134. package/src/client/ClientMemoryManager.ts +987 -987
  135. package/src/client/PersonalDataWallet.ts +345 -345
  136. package/src/client/SimplePDWClient.ts +1289 -1222
  137. package/src/client/factory.ts +154 -154
  138. package/src/client/namespaces/AnalyticsNamespace.ts +377 -377
  139. package/src/client/namespaces/BatchNamespace.ts +356 -356
  140. package/src/client/namespaces/CacheNamespace.ts +123 -123
  141. package/src/client/namespaces/CapabilityNamespace.ts +217 -217
  142. package/src/client/namespaces/ClassifyNamespace.ts +169 -169
  143. package/src/client/namespaces/ContextNamespace.ts +297 -297
  144. package/src/client/namespaces/EmbeddingsNamespace.ts +99 -99
  145. package/src/client/namespaces/EncryptionNamespace.ts +221 -221
  146. package/src/client/namespaces/GraphNamespace.ts +468 -468
  147. package/src/client/namespaces/IndexNamespace.ts +361 -361
  148. package/src/client/namespaces/MemoryNamespace.ts +1422 -1135
  149. package/src/client/namespaces/PermissionsNamespace.ts +254 -254
  150. package/src/client/namespaces/PipelineNamespace.ts +220 -220
  151. package/src/client/namespaces/SearchNamespace.ts +1049 -1049
  152. package/src/client/namespaces/StorageNamespace.ts +458 -458
  153. package/src/client/namespaces/TxNamespace.ts +260 -260
  154. package/src/client/namespaces/WalletNamespace.ts +243 -243
  155. package/src/client/namespaces/consolidated/AINamespace.ts +449 -449
  156. package/src/client/namespaces/consolidated/BlockchainNamespace.ts +607 -546
  157. package/src/client/namespaces/consolidated/SecurityNamespace.ts +648 -648
  158. package/src/client/namespaces/consolidated/StorageNamespace.ts +1141 -497
  159. package/src/client/namespaces/consolidated/index.ts +39 -39
  160. package/src/client/signers/KeypairSigner.ts +108 -108
  161. package/src/client/signers/UnifiedSigner.ts +110 -110
  162. package/src/client/signers/WalletAdapterSigner.ts +159 -159
  163. package/src/client/signers/index.ts +26 -26
  164. package/src/config/ConfigurationHelper.ts +412 -412
  165. package/src/config/defaults.ts +51 -51
  166. package/src/config/index.ts +8 -8
  167. package/src/config/validation.ts +70 -70
  168. package/src/core/index.ts +14 -14
  169. package/src/core/interfaces/IService.ts +307 -307
  170. package/src/core/interfaces/index.ts +8 -8
  171. package/src/core/types/capability.ts +297 -297
  172. package/src/core/types/index.ts +870 -870
  173. package/src/core/types/wallet.ts +270 -270
  174. package/src/core/types.ts +9 -9
  175. package/src/core/wallet.ts +222 -222
  176. package/src/embedding/index.ts +19 -19
  177. package/src/embedding/types.ts +357 -357
  178. package/src/errors/index.ts +602 -602
  179. package/src/errors/recovery.ts +461 -461
  180. package/src/errors/validation.ts +567 -567
  181. package/src/generated/pdw/capability.ts +319 -319
  182. package/src/graph/GraphService.ts +887 -887
  183. package/src/graph/KnowledgeGraphManager.ts +728 -728
  184. package/src/graph/index.ts +25 -25
  185. package/src/index.ts +498 -474
  186. package/src/infrastructure/index.ts +22 -22
  187. package/src/infrastructure/seal/EncryptionService.ts +628 -603
  188. package/src/infrastructure/seal/SealService.ts +613 -615
  189. package/src/infrastructure/seal/index.ts +9 -9
  190. package/src/infrastructure/sui/BlockchainManager.ts +627 -627
  191. package/src/infrastructure/sui/SuiService.ts +888 -888
  192. package/src/infrastructure/sui/index.ts +9 -9
  193. package/src/infrastructure/walrus/StorageManager.ts +604 -604
  194. package/src/infrastructure/walrus/WalrusStorageService.ts +612 -612
  195. package/src/infrastructure/walrus/index.ts +9 -9
  196. package/src/langchain/PDWEmbeddings.ts +145 -145
  197. package/src/langchain/PDWVectorStore.ts +456 -456
  198. package/src/langchain/createPDWRAG.ts +303 -303
  199. package/src/langchain/index.ts +47 -47
  200. package/src/permissions/ConsentRepository.browser.ts +249 -249
  201. package/src/permissions/ConsentRepository.ts +364 -364
  202. package/src/pipeline/MemoryPipeline.ts +862 -862
  203. package/src/pipeline/PipelineManager.ts +683 -683
  204. package/src/pipeline/index.ts +26 -26
  205. package/src/retrieval/AdvancedSearchService.ts +629 -629
  206. package/src/retrieval/MemoryAnalyticsService.ts +711 -711
  207. package/src/retrieval/MemoryDecryptionPipeline.ts +825 -824
  208. package/src/retrieval/MemoryRetrievalService.ts +904 -830
  209. package/src/retrieval/index.ts +42 -42
  210. package/src/services/BatchService.ts +352 -352
  211. package/src/services/CapabilityService.ts +464 -448
  212. package/src/services/ClassifierService.ts +465 -465
  213. package/src/services/CrossContextPermissionService.ts +486 -484
  214. package/src/services/EmbeddingService.ts +771 -706
  215. package/src/services/EncryptionService.ts +712 -711
  216. package/src/services/GeminiAIService.ts +753 -753
  217. package/src/services/IndexManager.ts +977 -1004
  218. package/src/services/MemoryIndexService.ts +1003 -1003
  219. package/src/services/MemoryService.ts +369 -369
  220. package/src/services/QueryService.ts +890 -890
  221. package/src/services/StorageService.ts +1182 -1111
  222. package/src/services/TransactionService.ts +838 -790
  223. package/src/services/VectorService.ts +462 -462
  224. package/src/services/ViewService.ts +484 -484
  225. package/src/services/index.ts +25 -25
  226. package/src/services/storage/BlobAttributesManager.ts +333 -333
  227. package/src/services/storage/KnowledgeGraphManager.ts +425 -425
  228. package/src/services/storage/MemorySearchManager.ts +387 -387
  229. package/src/services/storage/QuiltBatchManager.ts +1130 -660
  230. package/src/services/storage/WalrusMetadataManager.ts +268 -268
  231. package/src/services/storage/WalrusStorageManager.ts +287 -287
  232. package/src/services/storage/index.ts +57 -52
  233. package/src/types/index.ts +13 -13
  234. package/src/utils/LRUCache.ts +378 -0
  235. package/src/utils/index.ts +76 -68
  236. package/src/utils/memoryIndexOnChain.ts +507 -0
  237. package/src/utils/rebuildIndex.ts +290 -290
  238. package/src/utils/rebuildIndexNode.ts +771 -424
  239. package/src/vector/BrowserHnswIndexService.ts +758 -758
  240. package/src/vector/HnswWasmService.ts +731 -679
  241. package/src/vector/IHnswService.ts +233 -224
  242. package/src/vector/NodeHnswService.ts +833 -735
  243. package/src/vector/VectorManager.ts +478 -478
  244. package/src/vector/createHnswService.ts +135 -135
  245. package/src/vector/index.ts +56 -56
  246. package/src/wallet/ContextWalletService.ts +656 -656
  247. package/src/wallet/MainWalletService.ts +317 -317
@@ -1,684 +1,684 @@
1
- /**
2
- * PipelineManager - High-Level Pipeline Orchestration
3
- *
4
- * Manages multiple pipeline instances, provides scheduling, monitoring,
5
- * and administration capabilities for memory processing workflows.
6
- */
7
-
8
- import { MemoryPipeline, PipelineConfig, PipelineExecution } from './MemoryPipeline';
9
- import { Memory } from '../embedding/types';
10
-
11
- export interface PipelineManagerConfig {
12
- maxConcurrentPipelines?: number;
13
- defaultPipelineConfig?: PipelineConfig;
14
- enableScheduling?: boolean;
15
- enableHealthChecks?: boolean;
16
- healthCheckIntervalMs?: number;
17
- enableMetricsCollection?: boolean;
18
- metricsRetentionDays?: number;
19
- }
20
-
21
- export interface ManagedPipeline {
22
- id: string;
23
- name: string;
24
- pipeline: MemoryPipeline;
25
- config: PipelineConfig;
26
- status: 'active' | 'paused' | 'stopped';
27
- createdAt: Date;
28
- lastUsed: Date;
29
- executionCount: number;
30
- }
31
-
32
- export interface PipelineSchedule {
33
- id: string;
34
- pipelineId: string;
35
- userId: string;
36
- memories: Memory[];
37
- scheduledAt: Date;
38
- priority: 'low' | 'normal' | 'high';
39
- status: 'scheduled' | 'running' | 'completed' | 'failed';
40
- result?: PipelineExecution[];
41
- }
42
-
43
- export interface SystemMetrics {
44
- totalPipelines: number;
45
- activePipelines: number;
46
- totalExecutions: number;
47
- activeExecutions: number;
48
- systemLoad: number;
49
- memoryUsage: {
50
- used: number;
51
- total: number;
52
- percentage: number;
53
- };
54
- performance: {
55
- averageExecutionTime: number;
56
- throughput: number;
57
- successRate: number;
58
- };
59
- health: {
60
- status: 'healthy' | 'degraded' | 'critical';
61
- issues: string[];
62
- lastCheck: Date;
63
- };
64
- }
65
-
66
- export interface PipelineTemplate {
67
- name: string;
68
- description: string;
69
- config: PipelineConfig;
70
- category: 'basic' | 'advanced' | 'custom';
71
- tags: string[];
72
- }
73
-
74
- /**
75
- * High-level pipeline management and orchestration
76
- */
77
- export class PipelineManager {
78
- private pipelines = new Map<string, ManagedPipeline>();
79
- private schedules = new Map<string, PipelineSchedule>();
80
- private healthCheckTimer?: NodeJS.Timeout;
81
-
82
- private readonly config: Required<PipelineManagerConfig>;
83
- private systemMetrics: SystemMetrics = {
84
- totalPipelines: 0,
85
- activePipelines: 0,
86
- totalExecutions: 0,
87
- activeExecutions: 0,
88
- systemLoad: 0,
89
- memoryUsage: { used: 0, total: 0, percentage: 0 },
90
- performance: { averageExecutionTime: 0, throughput: 0, successRate: 0 },
91
- health: { status: 'healthy', issues: [], lastCheck: new Date() }
92
- };
93
-
94
- private readonly PIPELINE_TEMPLATES: PipelineTemplate[] = [
95
- {
96
- name: 'Basic Memory Processing',
97
- description: 'Simple memory processing with embedding and storage',
98
- category: 'basic',
99
- tags: ['embedding', 'storage'],
100
- config: {
101
- embedding: { enableBatching: true, batchSize: 10 },
102
- storage: { enableEncryption: false },
103
- blockchain: { enableOwnershipTracking: false }
104
- }
105
- },
106
- {
107
- name: 'Full Decentralized Pipeline',
108
- description: 'Complete pipeline with all features enabled',
109
- category: 'advanced',
110
- tags: ['embedding', 'vector', 'graph', 'storage', 'blockchain'],
111
- config: {
112
- embedding: { enableBatching: true, batchSize: 20 },
113
- vector: { enablePersistence: true },
114
- graph: { enableExtraction: true, confidenceThreshold: 0.7 },
115
- storage: { enableEncryption: true, enableBatching: true },
116
- blockchain: { enableOwnershipTracking: true, enableBatching: true }
117
- }
118
- },
119
- {
120
- name: 'High-Performance Batch Processing',
121
- description: 'Optimized for high-throughput batch processing',
122
- category: 'advanced',
123
- tags: ['batch', 'performance', 'throughput'],
124
- config: {
125
- embedding: { enableBatching: true, batchSize: 50 },
126
- batch: { enableBatching: true, batchSize: 100, batchDelayMs: 2000 },
127
- vector: { maxElements: 50000 },
128
- skipFailedSteps: true,
129
- maxRetryAttempts: 1
130
- }
131
- }
132
- ];
133
-
134
- constructor(config: PipelineManagerConfig = {}) {
135
- this.config = {
136
- maxConcurrentPipelines: config.maxConcurrentPipelines || 10,
137
- defaultPipelineConfig: config.defaultPipelineConfig || {},
138
- enableScheduling: config.enableScheduling !== false,
139
- enableHealthChecks: config.enableHealthChecks !== false,
140
- healthCheckIntervalMs: config.healthCheckIntervalMs || 30000, // 30 seconds
141
- enableMetricsCollection: config.enableMetricsCollection !== false,
142
- metricsRetentionDays: config.metricsRetentionDays || 7
143
- };
144
-
145
- this.startHealthChecks();
146
- }
147
-
148
- // ==================== PIPELINE MANAGEMENT ====================
149
-
150
- /**
151
- * Create a new managed pipeline
152
- */
153
- createPipeline(
154
- name: string,
155
- config: PipelineConfig = {},
156
- options: {
157
- autoStart?: boolean;
158
- description?: string;
159
- } = {}
160
- ): string {
161
- if (this.pipelines.size >= this.config.maxConcurrentPipelines) {
162
- throw new Error(`Maximum concurrent pipelines limit reached: ${this.config.maxConcurrentPipelines}`);
163
- }
164
-
165
- const pipelineId = this.generatePipelineId();
166
- const mergedConfig = { ...this.config.defaultPipelineConfig, ...config };
167
-
168
- const managedPipeline: ManagedPipeline = {
169
- id: pipelineId,
170
- name,
171
- pipeline: new MemoryPipeline(mergedConfig),
172
- config: mergedConfig,
173
- status: options.autoStart !== false ? 'active' : 'paused',
174
- createdAt: new Date(),
175
- lastUsed: new Date(),
176
- executionCount: 0
177
- };
178
-
179
- this.pipelines.set(pipelineId, managedPipeline);
180
- this.systemMetrics.totalPipelines++;
181
-
182
- if (managedPipeline.status === 'active') {
183
- this.systemMetrics.activePipelines++;
184
- }
185
-
186
- console.log(`✅ Created pipeline: ${name} (${pipelineId})`);
187
-
188
- return pipelineId;
189
- }
190
-
191
- /**
192
- * Create pipeline from template
193
- */
194
- createPipelineFromTemplate(
195
- templateName: string,
196
- customName: string,
197
- configOverrides: Partial<PipelineConfig> = {}
198
- ): string {
199
- const template = this.PIPELINE_TEMPLATES.find(t => t.name === templateName);
200
- if (!template) {
201
- throw new Error(`Pipeline template not found: ${templateName}`);
202
- }
203
-
204
- const config = { ...template.config, ...configOverrides };
205
- return this.createPipeline(customName, config);
206
- }
207
-
208
- /**
209
- * Get pipeline templates
210
- */
211
- getPipelineTemplates(): PipelineTemplate[] {
212
- return [...this.PIPELINE_TEMPLATES];
213
- }
214
-
215
- /**
216
- * Get managed pipeline
217
- */
218
- getPipeline(pipelineId: string): ManagedPipeline | null {
219
- return this.pipelines.get(pipelineId) || null;
220
- }
221
-
222
- /**
223
- * List all pipelines
224
- */
225
- listPipelines(): ManagedPipeline[] {
226
- return Array.from(this.pipelines.values());
227
- }
228
-
229
- /**
230
- * Start pipeline
231
- */
232
- startPipeline(pipelineId: string): boolean {
233
- const managedPipeline = this.pipelines.get(pipelineId);
234
- if (!managedPipeline) {
235
- return false;
236
- }
237
-
238
- if (managedPipeline.status !== 'active') {
239
- managedPipeline.status = 'active';
240
- this.systemMetrics.activePipelines++;
241
- console.log(`▶️ Started pipeline: ${managedPipeline.name}`);
242
- }
243
-
244
- return true;
245
- }
246
-
247
- /**
248
- * Pause pipeline
249
- */
250
- pausePipeline(pipelineId: string): boolean {
251
- const managedPipeline = this.pipelines.get(pipelineId);
252
- if (!managedPipeline) {
253
- return false;
254
- }
255
-
256
- if (managedPipeline.status === 'active') {
257
- managedPipeline.status = 'paused';
258
- this.systemMetrics.activePipelines--;
259
- console.log(`⏸️ Paused pipeline: ${managedPipeline.name}`);
260
- }
261
-
262
- return true;
263
- }
264
-
265
- /**
266
- * Stop and remove pipeline
267
- */
268
- removePipeline(pipelineId: string): boolean {
269
- const managedPipeline = this.pipelines.get(pipelineId);
270
- if (!managedPipeline) {
271
- return false;
272
- }
273
-
274
- if (managedPipeline.status === 'active') {
275
- this.systemMetrics.activePipelines--;
276
- }
277
-
278
- this.pipelines.delete(pipelineId);
279
- this.systemMetrics.totalPipelines--;
280
-
281
- console.log(`🗑️ Removed pipeline: ${managedPipeline.name}`);
282
-
283
- return true;
284
- }
285
-
286
- // ==================== MEMORY PROCESSING ====================
287
-
288
- /**
289
- * Process memory using specified pipeline
290
- */
291
- async processMemory(
292
- pipelineId: string,
293
- memory: Memory,
294
- userId: string,
295
- options?: any
296
- ): Promise<PipelineExecution> {
297
- const managedPipeline = this.pipelines.get(pipelineId);
298
- if (!managedPipeline) {
299
- throw new Error(`Pipeline not found: ${pipelineId}`);
300
- }
301
-
302
- if (managedPipeline.status !== 'active') {
303
- throw new Error(`Pipeline is not active: ${managedPipeline.name}`);
304
- }
305
-
306
- // Update pipeline usage
307
- managedPipeline.lastUsed = new Date();
308
- managedPipeline.executionCount++;
309
- this.systemMetrics.totalExecutions++;
310
- this.systemMetrics.activeExecutions++;
311
-
312
- try {
313
- const execution = await managedPipeline.pipeline.processMemory(memory, userId, options);
314
-
315
- // Update metrics
316
- this.systemMetrics.activeExecutions--;
317
- this.updatePerformanceMetrics(managedPipeline);
318
-
319
- return execution;
320
-
321
- } catch (error) {
322
- this.systemMetrics.activeExecutions--;
323
- throw error;
324
- }
325
- }
326
-
327
- /**
328
- * Process memories in batch using specified pipeline
329
- */
330
- async processMemoriesBatch(
331
- pipelineId: string,
332
- memories: Memory[],
333
- userId: string,
334
- options?: any
335
- ): Promise<PipelineExecution[]> {
336
- const managedPipeline = this.pipelines.get(pipelineId);
337
- if (!managedPipeline) {
338
- throw new Error(`Pipeline not found: ${pipelineId}`);
339
- }
340
-
341
- if (managedPipeline.status !== 'active') {
342
- throw new Error(`Pipeline is not active: ${managedPipeline.name}`);
343
- }
344
-
345
- // Update pipeline usage
346
- managedPipeline.lastUsed = new Date();
347
- managedPipeline.executionCount += memories.length;
348
- this.systemMetrics.totalExecutions += memories.length;
349
- this.systemMetrics.activeExecutions += memories.length;
350
-
351
- try {
352
- const executions = await managedPipeline.pipeline.processMemoriesBatch(memories, userId, options);
353
-
354
- // Update metrics
355
- this.systemMetrics.activeExecutions -= memories.length;
356
- this.updatePerformanceMetrics(managedPipeline);
357
-
358
- return executions;
359
-
360
- } catch (error) {
361
- this.systemMetrics.activeExecutions -= memories.length;
362
- throw error;
363
- }
364
- }
365
-
366
- // ==================== SCHEDULING ====================
367
-
368
- /**
369
- * Schedule memory processing
370
- */
371
- scheduleMemoryProcessing(
372
- pipelineId: string,
373
- userId: string,
374
- memories: Memory[],
375
- scheduledAt: Date,
376
- priority: 'low' | 'normal' | 'high' = 'normal'
377
- ): string {
378
- if (!this.config.enableScheduling) {
379
- throw new Error('Scheduling is not enabled');
380
- }
381
-
382
- const scheduleId = this.generateScheduleId();
383
- const schedule: PipelineSchedule = {
384
- id: scheduleId,
385
- pipelineId,
386
- userId,
387
- memories,
388
- scheduledAt,
389
- priority,
390
- status: 'scheduled'
391
- };
392
-
393
- this.schedules.set(scheduleId, schedule);
394
-
395
- // Set timeout for execution
396
- const delay = scheduledAt.getTime() - Date.now();
397
- if (delay > 0) {
398
- setTimeout(() => {
399
- this.executeScheduledProcessing(scheduleId);
400
- }, delay);
401
- } else {
402
- // Execute immediately if time has passed
403
- setImmediate(() => this.executeScheduledProcessing(scheduleId));
404
- }
405
-
406
- console.log(`📅 Scheduled processing for ${memories.length} memories at ${scheduledAt.toISOString()}`);
407
-
408
- return scheduleId;
409
- }
410
-
411
- /**
412
- * Get scheduled processing jobs
413
- */
414
- getScheduledJobs(): PipelineSchedule[] {
415
- return Array.from(this.schedules.values());
416
- }
417
-
418
- /**
419
- * Cancel scheduled job
420
- */
421
- cancelScheduledJob(scheduleId: string): boolean {
422
- const schedule = this.schedules.get(scheduleId);
423
- if (!schedule || schedule.status !== 'scheduled') {
424
- return false;
425
- }
426
-
427
- schedule.status = 'failed';
428
- console.log(`❌ Cancelled scheduled job: ${scheduleId}`);
429
-
430
- return true;
431
- }
432
-
433
- // ==================== MONITORING & HEALTH ====================
434
-
435
- /**
436
- * Get system metrics
437
- */
438
- getSystemMetrics(): SystemMetrics {
439
- this.updateSystemMetrics();
440
- return { ...this.systemMetrics };
441
- }
442
-
443
- /**
444
- * Get pipeline health status
445
- */
446
- getPipelineHealth(pipelineId: string): any {
447
- const managedPipeline = this.pipelines.get(pipelineId);
448
- if (!managedPipeline) {
449
- return null;
450
- }
451
-
452
- return managedPipeline.pipeline.getPipelineHealth();
453
- }
454
-
455
- /**
456
- * Get all pipeline executions
457
- */
458
- getAllExecutions(): { pipelineId: string; executions: PipelineExecution[] }[] {
459
- const results: { pipelineId: string; executions: PipelineExecution[] }[] = [];
460
-
461
- for (const [pipelineId, managedPipeline] of this.pipelines.entries()) {
462
- const executions = managedPipeline.pipeline.getUserExecutions(''); // Get all executions
463
- results.push({ pipelineId, executions });
464
- }
465
-
466
- return results;
467
- }
468
-
469
- /**
470
- * Cleanup completed executions across all pipelines
471
- */
472
- cleanupCompletedExecutions(): number {
473
- let totalCleared = 0;
474
-
475
- for (const managedPipeline of this.pipelines.values()) {
476
- const cleared = managedPipeline.pipeline.clearCompletedExecutions();
477
- totalCleared += cleared;
478
- }
479
-
480
- console.log(`🧹 Cleaned up ${totalCleared} completed executions across all pipelines`);
481
-
482
- return totalCleared;
483
- }
484
-
485
- /**
486
- * Get system health summary
487
- */
488
- getSystemHealth(): {
489
- overallStatus: 'healthy' | 'degraded' | 'critical';
490
- pipelineHealth: Array<{ pipelineId: string; status: string; issues: string[] }>;
491
- systemLoad: number;
492
- recommendations: string[];
493
- } {
494
- const pipelineHealth = [];
495
- let overallStatus: 'healthy' | 'degraded' | 'critical' = 'healthy';
496
- const recommendations: string[] = [];
497
-
498
- // Check each pipeline health
499
- for (const [pipelineId, managedPipeline] of this.pipelines.entries()) {
500
- const health = managedPipeline.pipeline.getPipelineHealth();
501
- pipelineHealth.push({
502
- pipelineId,
503
- status: health.status,
504
- issues: health.issues
505
- });
506
-
507
- if (health.status === 'critical') {
508
- overallStatus = 'critical';
509
- } else if (health.status === 'degraded' && overallStatus !== 'critical') {
510
- overallStatus = 'degraded';
511
- }
512
- }
513
-
514
- // System-level recommendations
515
- if (this.systemMetrics.activePipelines > 8) {
516
- recommendations.push('High number of active pipelines - consider consolidation');
517
- }
518
-
519
- if (this.systemMetrics.systemLoad > 0.8) {
520
- recommendations.push('High system load - consider reducing concurrent operations');
521
- }
522
-
523
- return {
524
- overallStatus,
525
- pipelineHealth,
526
- systemLoad: this.systemMetrics.systemLoad,
527
- recommendations
528
- };
529
- }
530
-
531
- /**
532
- * Shutdown pipeline manager
533
- */
534
- shutdown(): void {
535
- console.log('🛑 Shutting down PipelineManager...');
536
-
537
- // Clear health check timer
538
- if (this.healthCheckTimer) {
539
- clearInterval(this.healthCheckTimer);
540
- }
541
-
542
- // Pause all pipelines
543
- for (const [pipelineId] of this.pipelines.entries()) {
544
- this.pausePipeline(pipelineId);
545
- }
546
-
547
- console.log('✅ PipelineManager shutdown complete');
548
- }
549
-
550
- // ==================== PRIVATE METHODS ====================
551
-
552
- private async executeScheduledProcessing(scheduleId: string): Promise<void> {
553
- const schedule = this.schedules.get(scheduleId);
554
- if (!schedule || schedule.status !== 'scheduled') {
555
- return;
556
- }
557
-
558
- schedule.status = 'running';
559
-
560
- try {
561
- console.log(`🚀 Executing scheduled processing: ${scheduleId}`);
562
-
563
- const executions = await this.processMemoriesBatch(
564
- schedule.pipelineId,
565
- schedule.memories,
566
- schedule.userId
567
- );
568
-
569
- schedule.status = 'completed';
570
- schedule.result = executions;
571
-
572
- console.log(`✅ Scheduled processing completed: ${scheduleId}`);
573
-
574
- } catch (error) {
575
- schedule.status = 'failed';
576
- console.error(`❌ Scheduled processing failed: ${scheduleId}`, error);
577
- }
578
- }
579
-
580
- private startHealthChecks(): void {
581
- if (!this.config.enableHealthChecks) {
582
- return;
583
- }
584
-
585
- this.healthCheckTimer = setInterval(() => {
586
- this.performHealthCheck();
587
- }, this.config.healthCheckIntervalMs);
588
-
589
- console.log(`💚 Started health checks (interval: ${this.config.healthCheckIntervalMs}ms)`);
590
- }
591
-
592
- private performHealthCheck(): void {
593
- const issues: string[] = [];
594
- let status: 'healthy' | 'degraded' | 'critical' = 'healthy';
595
-
596
- // Check system load
597
- const activeExecutions = this.systemMetrics.activeExecutions;
598
- const maxConcurrent = this.config.maxConcurrentPipelines * 10; // Estimated max
599
-
600
- this.systemMetrics.systemLoad = activeExecutions / maxConcurrent;
601
-
602
- if (this.systemMetrics.systemLoad > 0.9) {
603
- issues.push('System overloaded');
604
- status = 'critical';
605
- } else if (this.systemMetrics.systemLoad > 0.7) {
606
- issues.push('High system load');
607
- if (status === 'healthy') status = 'degraded';
608
- }
609
-
610
- // Check pipeline health
611
- for (const managedPipeline of this.pipelines.values()) {
612
- const pipelineHealth = managedPipeline.pipeline.getPipelineHealth();
613
- if (pipelineHealth.status === 'critical') {
614
- issues.push(`Pipeline ${managedPipeline.name} is critical`);
615
- status = 'critical';
616
- } else if (pipelineHealth.status === 'degraded') {
617
- issues.push(`Pipeline ${managedPipeline.name} is degraded`);
618
- if (status === 'healthy') status = 'degraded';
619
- }
620
- }
621
-
622
- this.systemMetrics.health = {
623
- status,
624
- issues,
625
- lastCheck: new Date()
626
- };
627
-
628
- if (issues.length > 0) {
629
- console.warn(`⚠️ Health check issues detected:`, issues);
630
- }
631
- }
632
-
633
- private updateSystemMetrics(): void {
634
- // Update basic counts
635
- this.systemMetrics.totalPipelines = this.pipelines.size;
636
- this.systemMetrics.activePipelines = Array.from(this.pipelines.values())
637
- .filter(p => p.status === 'active').length;
638
-
639
- // Calculate performance metrics
640
- let totalExecutions = 0;
641
- let totalProcessingTime = 0;
642
- let successfulExecutions = 0;
643
-
644
- for (const managedPipeline of this.pipelines.values()) {
645
- const metrics = managedPipeline.pipeline.getPipelineMetrics();
646
- totalExecutions += metrics.totalExecutions;
647
- successfulExecutions += metrics.successfulExecutions;
648
- totalProcessingTime += metrics.averageProcessingTime * metrics.totalExecutions;
649
- }
650
-
651
- this.systemMetrics.performance = {
652
- averageExecutionTime: totalExecutions > 0 ? totalProcessingTime / totalExecutions : 0,
653
- throughput: Array.from(this.pipelines.values()).reduce((sum, p) =>
654
- sum + p.pipeline.getPipelineMetrics().throughput.memoriesPerHour, 0
655
- ),
656
- successRate: totalExecutions > 0 ? successfulExecutions / totalExecutions : 1
657
- };
658
-
659
- // Update memory usage (simplified)
660
- this.systemMetrics.memoryUsage = {
661
- used: this.systemMetrics.activeExecutions * 10, // Estimated MB per execution
662
- total: 1024, // Estimated total available MB
663
- percentage: (this.systemMetrics.activeExecutions * 10) / 1024
664
- };
665
- }
666
-
667
- private updatePerformanceMetrics(managedPipeline: ManagedPipeline): void {
668
- // Update performance tracking for the pipeline
669
- const metrics = managedPipeline.pipeline.getPipelineMetrics();
670
-
671
- // Could implement more sophisticated performance tracking here
672
- // For now, metrics are tracked within each pipeline
673
- }
674
-
675
- private generatePipelineId(): string {
676
- return `pipeline_${Date.now()}_${Math.random().toString(36).substring(2, 9)}`;
677
- }
678
-
679
- private generateScheduleId(): string {
680
- return `schedule_${Date.now()}_${Math.random().toString(36).substring(2, 9)}`;
681
- }
682
- }
683
-
1
+ /**
2
+ * PipelineManager - High-Level Pipeline Orchestration
3
+ *
4
+ * Manages multiple pipeline instances, provides scheduling, monitoring,
5
+ * and administration capabilities for memory processing workflows.
6
+ */
7
+
8
+ import { MemoryPipeline, PipelineConfig, PipelineExecution } from './MemoryPipeline';
9
+ import { Memory } from '../embedding/types';
10
+
11
+ export interface PipelineManagerConfig {
12
+ maxConcurrentPipelines?: number;
13
+ defaultPipelineConfig?: PipelineConfig;
14
+ enableScheduling?: boolean;
15
+ enableHealthChecks?: boolean;
16
+ healthCheckIntervalMs?: number;
17
+ enableMetricsCollection?: boolean;
18
+ metricsRetentionDays?: number;
19
+ }
20
+
21
+ export interface ManagedPipeline {
22
+ id: string;
23
+ name: string;
24
+ pipeline: MemoryPipeline;
25
+ config: PipelineConfig;
26
+ status: 'active' | 'paused' | 'stopped';
27
+ createdAt: Date;
28
+ lastUsed: Date;
29
+ executionCount: number;
30
+ }
31
+
32
+ export interface PipelineSchedule {
33
+ id: string;
34
+ pipelineId: string;
35
+ userId: string;
36
+ memories: Memory[];
37
+ scheduledAt: Date;
38
+ priority: 'low' | 'normal' | 'high';
39
+ status: 'scheduled' | 'running' | 'completed' | 'failed';
40
+ result?: PipelineExecution[];
41
+ }
42
+
43
+ export interface SystemMetrics {
44
+ totalPipelines: number;
45
+ activePipelines: number;
46
+ totalExecutions: number;
47
+ activeExecutions: number;
48
+ systemLoad: number;
49
+ memoryUsage: {
50
+ used: number;
51
+ total: number;
52
+ percentage: number;
53
+ };
54
+ performance: {
55
+ averageExecutionTime: number;
56
+ throughput: number;
57
+ successRate: number;
58
+ };
59
+ health: {
60
+ status: 'healthy' | 'degraded' | 'critical';
61
+ issues: string[];
62
+ lastCheck: Date;
63
+ };
64
+ }
65
+
66
+ export interface PipelineTemplate {
67
+ name: string;
68
+ description: string;
69
+ config: PipelineConfig;
70
+ category: 'basic' | 'advanced' | 'custom';
71
+ tags: string[];
72
+ }
73
+
74
+ /**
75
+ * High-level pipeline management and orchestration
76
+ */
77
+ export class PipelineManager {
78
+ private pipelines = new Map<string, ManagedPipeline>();
79
+ private schedules = new Map<string, PipelineSchedule>();
80
+ private healthCheckTimer?: NodeJS.Timeout;
81
+
82
+ private readonly config: Required<PipelineManagerConfig>;
83
+ private systemMetrics: SystemMetrics = {
84
+ totalPipelines: 0,
85
+ activePipelines: 0,
86
+ totalExecutions: 0,
87
+ activeExecutions: 0,
88
+ systemLoad: 0,
89
+ memoryUsage: { used: 0, total: 0, percentage: 0 },
90
+ performance: { averageExecutionTime: 0, throughput: 0, successRate: 0 },
91
+ health: { status: 'healthy', issues: [], lastCheck: new Date() }
92
+ };
93
+
94
+ private readonly PIPELINE_TEMPLATES: PipelineTemplate[] = [
95
+ {
96
+ name: 'Basic Memory Processing',
97
+ description: 'Simple memory processing with embedding and storage',
98
+ category: 'basic',
99
+ tags: ['embedding', 'storage'],
100
+ config: {
101
+ embedding: { enableBatching: true, batchSize: 10 },
102
+ storage: { enableEncryption: false },
103
+ blockchain: { enableOwnershipTracking: false }
104
+ }
105
+ },
106
+ {
107
+ name: 'Full Decentralized Pipeline',
108
+ description: 'Complete pipeline with all features enabled',
109
+ category: 'advanced',
110
+ tags: ['embedding', 'vector', 'graph', 'storage', 'blockchain'],
111
+ config: {
112
+ embedding: { enableBatching: true, batchSize: 20 },
113
+ vector: { enablePersistence: true },
114
+ graph: { enableExtraction: true, confidenceThreshold: 0.7 },
115
+ storage: { enableEncryption: true, enableBatching: true },
116
+ blockchain: { enableOwnershipTracking: true, enableBatching: true }
117
+ }
118
+ },
119
+ {
120
+ name: 'High-Performance Batch Processing',
121
+ description: 'Optimized for high-throughput batch processing',
122
+ category: 'advanced',
123
+ tags: ['batch', 'performance', 'throughput'],
124
+ config: {
125
+ embedding: { enableBatching: true, batchSize: 50 },
126
+ batch: { enableBatching: true, batchSize: 100, batchDelayMs: 2000 },
127
+ vector: { maxElements: 50000 },
128
+ skipFailedSteps: true,
129
+ maxRetryAttempts: 1
130
+ }
131
+ }
132
+ ];
133
+
134
+ constructor(config: PipelineManagerConfig = {}) {
135
+ this.config = {
136
+ maxConcurrentPipelines: config.maxConcurrentPipelines || 10,
137
+ defaultPipelineConfig: config.defaultPipelineConfig || {},
138
+ enableScheduling: config.enableScheduling !== false,
139
+ enableHealthChecks: config.enableHealthChecks !== false,
140
+ healthCheckIntervalMs: config.healthCheckIntervalMs || 30000, // 30 seconds
141
+ enableMetricsCollection: config.enableMetricsCollection !== false,
142
+ metricsRetentionDays: config.metricsRetentionDays || 7
143
+ };
144
+
145
+ this.startHealthChecks();
146
+ }
147
+
148
+ // ==================== PIPELINE MANAGEMENT ====================
149
+
150
+ /**
151
+ * Create a new managed pipeline
152
+ */
153
+ createPipeline(
154
+ name: string,
155
+ config: PipelineConfig = {},
156
+ options: {
157
+ autoStart?: boolean;
158
+ description?: string;
159
+ } = {}
160
+ ): string {
161
+ if (this.pipelines.size >= this.config.maxConcurrentPipelines) {
162
+ throw new Error(`Maximum concurrent pipelines limit reached: ${this.config.maxConcurrentPipelines}`);
163
+ }
164
+
165
+ const pipelineId = this.generatePipelineId();
166
+ const mergedConfig = { ...this.config.defaultPipelineConfig, ...config };
167
+
168
+ const managedPipeline: ManagedPipeline = {
169
+ id: pipelineId,
170
+ name,
171
+ pipeline: new MemoryPipeline(mergedConfig),
172
+ config: mergedConfig,
173
+ status: options.autoStart !== false ? 'active' : 'paused',
174
+ createdAt: new Date(),
175
+ lastUsed: new Date(),
176
+ executionCount: 0
177
+ };
178
+
179
+ this.pipelines.set(pipelineId, managedPipeline);
180
+ this.systemMetrics.totalPipelines++;
181
+
182
+ if (managedPipeline.status === 'active') {
183
+ this.systemMetrics.activePipelines++;
184
+ }
185
+
186
+ console.log(`✅ Created pipeline: ${name} (${pipelineId})`);
187
+
188
+ return pipelineId;
189
+ }
190
+
191
+ /**
192
+ * Create pipeline from template
193
+ */
194
+ createPipelineFromTemplate(
195
+ templateName: string,
196
+ customName: string,
197
+ configOverrides: Partial<PipelineConfig> = {}
198
+ ): string {
199
+ const template = this.PIPELINE_TEMPLATES.find(t => t.name === templateName);
200
+ if (!template) {
201
+ throw new Error(`Pipeline template not found: ${templateName}`);
202
+ }
203
+
204
+ const config = { ...template.config, ...configOverrides };
205
+ return this.createPipeline(customName, config);
206
+ }
207
+
208
+ /**
209
+ * Get pipeline templates
210
+ */
211
+ getPipelineTemplates(): PipelineTemplate[] {
212
+ return [...this.PIPELINE_TEMPLATES];
213
+ }
214
+
215
+ /**
216
+ * Get managed pipeline
217
+ */
218
+ getPipeline(pipelineId: string): ManagedPipeline | null {
219
+ return this.pipelines.get(pipelineId) || null;
220
+ }
221
+
222
+ /**
223
+ * List all pipelines
224
+ */
225
+ listPipelines(): ManagedPipeline[] {
226
+ return Array.from(this.pipelines.values());
227
+ }
228
+
229
+ /**
230
+ * Start pipeline
231
+ */
232
+ startPipeline(pipelineId: string): boolean {
233
+ const managedPipeline = this.pipelines.get(pipelineId);
234
+ if (!managedPipeline) {
235
+ return false;
236
+ }
237
+
238
+ if (managedPipeline.status !== 'active') {
239
+ managedPipeline.status = 'active';
240
+ this.systemMetrics.activePipelines++;
241
+ console.log(`▶️ Started pipeline: ${managedPipeline.name}`);
242
+ }
243
+
244
+ return true;
245
+ }
246
+
247
+ /**
248
+ * Pause pipeline
249
+ */
250
+ pausePipeline(pipelineId: string): boolean {
251
+ const managedPipeline = this.pipelines.get(pipelineId);
252
+ if (!managedPipeline) {
253
+ return false;
254
+ }
255
+
256
+ if (managedPipeline.status === 'active') {
257
+ managedPipeline.status = 'paused';
258
+ this.systemMetrics.activePipelines--;
259
+ console.log(`⏸️ Paused pipeline: ${managedPipeline.name}`);
260
+ }
261
+
262
+ return true;
263
+ }
264
+
265
+ /**
266
+ * Stop and remove pipeline
267
+ */
268
+ removePipeline(pipelineId: string): boolean {
269
+ const managedPipeline = this.pipelines.get(pipelineId);
270
+ if (!managedPipeline) {
271
+ return false;
272
+ }
273
+
274
+ if (managedPipeline.status === 'active') {
275
+ this.systemMetrics.activePipelines--;
276
+ }
277
+
278
+ this.pipelines.delete(pipelineId);
279
+ this.systemMetrics.totalPipelines--;
280
+
281
+ console.log(`🗑️ Removed pipeline: ${managedPipeline.name}`);
282
+
283
+ return true;
284
+ }
285
+
286
+ // ==================== MEMORY PROCESSING ====================
287
+
288
+ /**
289
+ * Process memory using specified pipeline
290
+ */
291
+ async processMemory(
292
+ pipelineId: string,
293
+ memory: Memory,
294
+ userId: string,
295
+ options?: any
296
+ ): Promise<PipelineExecution> {
297
+ const managedPipeline = this.pipelines.get(pipelineId);
298
+ if (!managedPipeline) {
299
+ throw new Error(`Pipeline not found: ${pipelineId}`);
300
+ }
301
+
302
+ if (managedPipeline.status !== 'active') {
303
+ throw new Error(`Pipeline is not active: ${managedPipeline.name}`);
304
+ }
305
+
306
+ // Update pipeline usage
307
+ managedPipeline.lastUsed = new Date();
308
+ managedPipeline.executionCount++;
309
+ this.systemMetrics.totalExecutions++;
310
+ this.systemMetrics.activeExecutions++;
311
+
312
+ try {
313
+ const execution = await managedPipeline.pipeline.processMemory(memory, userId, options);
314
+
315
+ // Update metrics
316
+ this.systemMetrics.activeExecutions--;
317
+ this.updatePerformanceMetrics(managedPipeline);
318
+
319
+ return execution;
320
+
321
+ } catch (error) {
322
+ this.systemMetrics.activeExecutions--;
323
+ throw error;
324
+ }
325
+ }
326
+
327
+ /**
328
+ * Process memories in batch using specified pipeline
329
+ */
330
+ async processMemoriesBatch(
331
+ pipelineId: string,
332
+ memories: Memory[],
333
+ userId: string,
334
+ options?: any
335
+ ): Promise<PipelineExecution[]> {
336
+ const managedPipeline = this.pipelines.get(pipelineId);
337
+ if (!managedPipeline) {
338
+ throw new Error(`Pipeline not found: ${pipelineId}`);
339
+ }
340
+
341
+ if (managedPipeline.status !== 'active') {
342
+ throw new Error(`Pipeline is not active: ${managedPipeline.name}`);
343
+ }
344
+
345
+ // Update pipeline usage
346
+ managedPipeline.lastUsed = new Date();
347
+ managedPipeline.executionCount += memories.length;
348
+ this.systemMetrics.totalExecutions += memories.length;
349
+ this.systemMetrics.activeExecutions += memories.length;
350
+
351
+ try {
352
+ const executions = await managedPipeline.pipeline.processMemoriesBatch(memories, userId, options);
353
+
354
+ // Update metrics
355
+ this.systemMetrics.activeExecutions -= memories.length;
356
+ this.updatePerformanceMetrics(managedPipeline);
357
+
358
+ return executions;
359
+
360
+ } catch (error) {
361
+ this.systemMetrics.activeExecutions -= memories.length;
362
+ throw error;
363
+ }
364
+ }
365
+
366
+ // ==================== SCHEDULING ====================
367
+
368
+ /**
369
+ * Schedule memory processing
370
+ */
371
+ scheduleMemoryProcessing(
372
+ pipelineId: string,
373
+ userId: string,
374
+ memories: Memory[],
375
+ scheduledAt: Date,
376
+ priority: 'low' | 'normal' | 'high' = 'normal'
377
+ ): string {
378
+ if (!this.config.enableScheduling) {
379
+ throw new Error('Scheduling is not enabled');
380
+ }
381
+
382
+ const scheduleId = this.generateScheduleId();
383
+ const schedule: PipelineSchedule = {
384
+ id: scheduleId,
385
+ pipelineId,
386
+ userId,
387
+ memories,
388
+ scheduledAt,
389
+ priority,
390
+ status: 'scheduled'
391
+ };
392
+
393
+ this.schedules.set(scheduleId, schedule);
394
+
395
+ // Set timeout for execution
396
+ const delay = scheduledAt.getTime() - Date.now();
397
+ if (delay > 0) {
398
+ setTimeout(() => {
399
+ this.executeScheduledProcessing(scheduleId);
400
+ }, delay);
401
+ } else {
402
+ // Execute immediately if time has passed
403
+ setImmediate(() => this.executeScheduledProcessing(scheduleId));
404
+ }
405
+
406
+ console.log(`📅 Scheduled processing for ${memories.length} memories at ${scheduledAt.toISOString()}`);
407
+
408
+ return scheduleId;
409
+ }
410
+
411
+ /**
412
+ * Get scheduled processing jobs
413
+ */
414
+ getScheduledJobs(): PipelineSchedule[] {
415
+ return Array.from(this.schedules.values());
416
+ }
417
+
418
+ /**
419
+ * Cancel scheduled job
420
+ */
421
+ cancelScheduledJob(scheduleId: string): boolean {
422
+ const schedule = this.schedules.get(scheduleId);
423
+ if (!schedule || schedule.status !== 'scheduled') {
424
+ return false;
425
+ }
426
+
427
+ schedule.status = 'failed';
428
+ console.log(`❌ Cancelled scheduled job: ${scheduleId}`);
429
+
430
+ return true;
431
+ }
432
+
433
+ // ==================== MONITORING & HEALTH ====================
434
+
435
+ /**
436
+ * Get system metrics
437
+ */
438
+ getSystemMetrics(): SystemMetrics {
439
+ this.updateSystemMetrics();
440
+ return { ...this.systemMetrics };
441
+ }
442
+
443
+ /**
444
+ * Get pipeline health status
445
+ */
446
+ getPipelineHealth(pipelineId: string): any {
447
+ const managedPipeline = this.pipelines.get(pipelineId);
448
+ if (!managedPipeline) {
449
+ return null;
450
+ }
451
+
452
+ return managedPipeline.pipeline.getPipelineHealth();
453
+ }
454
+
455
+ /**
456
+ * Get all pipeline executions
457
+ */
458
+ getAllExecutions(): { pipelineId: string; executions: PipelineExecution[] }[] {
459
+ const results: { pipelineId: string; executions: PipelineExecution[] }[] = [];
460
+
461
+ for (const [pipelineId, managedPipeline] of this.pipelines.entries()) {
462
+ const executions = managedPipeline.pipeline.getUserExecutions(''); // Get all executions
463
+ results.push({ pipelineId, executions });
464
+ }
465
+
466
+ return results;
467
+ }
468
+
469
+ /**
470
+ * Cleanup completed executions across all pipelines
471
+ */
472
+ cleanupCompletedExecutions(): number {
473
+ let totalCleared = 0;
474
+
475
+ for (const managedPipeline of this.pipelines.values()) {
476
+ const cleared = managedPipeline.pipeline.clearCompletedExecutions();
477
+ totalCleared += cleared;
478
+ }
479
+
480
+ console.log(`🧹 Cleaned up ${totalCleared} completed executions across all pipelines`);
481
+
482
+ return totalCleared;
483
+ }
484
+
485
+ /**
486
+ * Get system health summary
487
+ */
488
+ getSystemHealth(): {
489
+ overallStatus: 'healthy' | 'degraded' | 'critical';
490
+ pipelineHealth: Array<{ pipelineId: string; status: string; issues: string[] }>;
491
+ systemLoad: number;
492
+ recommendations: string[];
493
+ } {
494
+ const pipelineHealth = [];
495
+ let overallStatus: 'healthy' | 'degraded' | 'critical' = 'healthy';
496
+ const recommendations: string[] = [];
497
+
498
+ // Check each pipeline health
499
+ for (const [pipelineId, managedPipeline] of this.pipelines.entries()) {
500
+ const health = managedPipeline.pipeline.getPipelineHealth();
501
+ pipelineHealth.push({
502
+ pipelineId,
503
+ status: health.status,
504
+ issues: health.issues
505
+ });
506
+
507
+ if (health.status === 'critical') {
508
+ overallStatus = 'critical';
509
+ } else if (health.status === 'degraded' && overallStatus !== 'critical') {
510
+ overallStatus = 'degraded';
511
+ }
512
+ }
513
+
514
+ // System-level recommendations
515
+ if (this.systemMetrics.activePipelines > 8) {
516
+ recommendations.push('High number of active pipelines - consider consolidation');
517
+ }
518
+
519
+ if (this.systemMetrics.systemLoad > 0.8) {
520
+ recommendations.push('High system load - consider reducing concurrent operations');
521
+ }
522
+
523
+ return {
524
+ overallStatus,
525
+ pipelineHealth,
526
+ systemLoad: this.systemMetrics.systemLoad,
527
+ recommendations
528
+ };
529
+ }
530
+
531
+ /**
532
+ * Shutdown pipeline manager
533
+ */
534
+ shutdown(): void {
535
+ console.log('🛑 Shutting down PipelineManager...');
536
+
537
+ // Clear health check timer
538
+ if (this.healthCheckTimer) {
539
+ clearInterval(this.healthCheckTimer);
540
+ }
541
+
542
+ // Pause all pipelines
543
+ for (const [pipelineId] of this.pipelines.entries()) {
544
+ this.pausePipeline(pipelineId);
545
+ }
546
+
547
+ console.log('✅ PipelineManager shutdown complete');
548
+ }
549
+
550
+ // ==================== PRIVATE METHODS ====================
551
+
552
+ private async executeScheduledProcessing(scheduleId: string): Promise<void> {
553
+ const schedule = this.schedules.get(scheduleId);
554
+ if (!schedule || schedule.status !== 'scheduled') {
555
+ return;
556
+ }
557
+
558
+ schedule.status = 'running';
559
+
560
+ try {
561
+ console.log(`🚀 Executing scheduled processing: ${scheduleId}`);
562
+
563
+ const executions = await this.processMemoriesBatch(
564
+ schedule.pipelineId,
565
+ schedule.memories,
566
+ schedule.userId
567
+ );
568
+
569
+ schedule.status = 'completed';
570
+ schedule.result = executions;
571
+
572
+ console.log(`✅ Scheduled processing completed: ${scheduleId}`);
573
+
574
+ } catch (error) {
575
+ schedule.status = 'failed';
576
+ console.error(`❌ Scheduled processing failed: ${scheduleId}`, error);
577
+ }
578
+ }
579
+
580
+ private startHealthChecks(): void {
581
+ if (!this.config.enableHealthChecks) {
582
+ return;
583
+ }
584
+
585
+ this.healthCheckTimer = setInterval(() => {
586
+ this.performHealthCheck();
587
+ }, this.config.healthCheckIntervalMs);
588
+
589
+ console.log(`💚 Started health checks (interval: ${this.config.healthCheckIntervalMs}ms)`);
590
+ }
591
+
592
+ private performHealthCheck(): void {
593
+ const issues: string[] = [];
594
+ let status: 'healthy' | 'degraded' | 'critical' = 'healthy';
595
+
596
+ // Check system load
597
+ const activeExecutions = this.systemMetrics.activeExecutions;
598
+ const maxConcurrent = this.config.maxConcurrentPipelines * 10; // Estimated max
599
+
600
+ this.systemMetrics.systemLoad = activeExecutions / maxConcurrent;
601
+
602
+ if (this.systemMetrics.systemLoad > 0.9) {
603
+ issues.push('System overloaded');
604
+ status = 'critical';
605
+ } else if (this.systemMetrics.systemLoad > 0.7) {
606
+ issues.push('High system load');
607
+ if (status === 'healthy') status = 'degraded';
608
+ }
609
+
610
+ // Check pipeline health
611
+ for (const managedPipeline of this.pipelines.values()) {
612
+ const pipelineHealth = managedPipeline.pipeline.getPipelineHealth();
613
+ if (pipelineHealth.status === 'critical') {
614
+ issues.push(`Pipeline ${managedPipeline.name} is critical`);
615
+ status = 'critical';
616
+ } else if (pipelineHealth.status === 'degraded') {
617
+ issues.push(`Pipeline ${managedPipeline.name} is degraded`);
618
+ if (status === 'healthy') status = 'degraded';
619
+ }
620
+ }
621
+
622
+ this.systemMetrics.health = {
623
+ status,
624
+ issues,
625
+ lastCheck: new Date()
626
+ };
627
+
628
+ if (issues.length > 0) {
629
+ console.warn(`⚠️ Health check issues detected:`, issues);
630
+ }
631
+ }
632
+
633
+ private updateSystemMetrics(): void {
634
+ // Update basic counts
635
+ this.systemMetrics.totalPipelines = this.pipelines.size;
636
+ this.systemMetrics.activePipelines = Array.from(this.pipelines.values())
637
+ .filter(p => p.status === 'active').length;
638
+
639
+ // Calculate performance metrics
640
+ let totalExecutions = 0;
641
+ let totalProcessingTime = 0;
642
+ let successfulExecutions = 0;
643
+
644
+ for (const managedPipeline of this.pipelines.values()) {
645
+ const metrics = managedPipeline.pipeline.getPipelineMetrics();
646
+ totalExecutions += metrics.totalExecutions;
647
+ successfulExecutions += metrics.successfulExecutions;
648
+ totalProcessingTime += metrics.averageProcessingTime * metrics.totalExecutions;
649
+ }
650
+
651
+ this.systemMetrics.performance = {
652
+ averageExecutionTime: totalExecutions > 0 ? totalProcessingTime / totalExecutions : 0,
653
+ throughput: Array.from(this.pipelines.values()).reduce((sum, p) =>
654
+ sum + p.pipeline.getPipelineMetrics().throughput.memoriesPerHour, 0
655
+ ),
656
+ successRate: totalExecutions > 0 ? successfulExecutions / totalExecutions : 1
657
+ };
658
+
659
+ // Update memory usage (simplified)
660
+ this.systemMetrics.memoryUsage = {
661
+ used: this.systemMetrics.activeExecutions * 10, // Estimated MB per execution
662
+ total: 1024, // Estimated total available MB
663
+ percentage: (this.systemMetrics.activeExecutions * 10) / 1024
664
+ };
665
+ }
666
+
667
+ private updatePerformanceMetrics(managedPipeline: ManagedPipeline): void {
668
+ // Update performance tracking for the pipeline
669
+ const metrics = managedPipeline.pipeline.getPipelineMetrics();
670
+
671
+ // Could implement more sophisticated performance tracking here
672
+ // For now, metrics are tracked within each pipeline
673
+ }
674
+
675
+ private generatePipelineId(): string {
676
+ return `pipeline_${Date.now()}_${Math.random().toString(36).substring(2, 9)}`;
677
+ }
678
+
679
+ private generateScheduleId(): string {
680
+ return `schedule_${Date.now()}_${Math.random().toString(36).substring(2, 9)}`;
681
+ }
682
+ }
683
+
684
684
  export default PipelineManager;