@cmdoss/memwal-sdk 0.8.0 → 1.0.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 (209) hide show
  1. package/README.md +522 -160
  2. package/dist/client/ClientMemoryManager.d.ts.map +1 -1
  3. package/dist/client/ClientMemoryManager.js +25 -8
  4. package/dist/client/ClientMemoryManager.js.map +1 -1
  5. package/dist/client/PersonalDataWallet.d.ts.map +1 -1
  6. package/dist/client/SimplePDWClient.d.ts +62 -2
  7. package/dist/client/SimplePDWClient.d.ts.map +1 -1
  8. package/dist/client/SimplePDWClient.js +96 -11
  9. package/dist/client/SimplePDWClient.js.map +1 -1
  10. package/dist/client/namespaces/IndexNamespace.d.ts +1 -1
  11. package/dist/client/namespaces/IndexNamespace.d.ts.map +1 -1
  12. package/dist/client/namespaces/IndexNamespace.js +7 -4
  13. package/dist/client/namespaces/IndexNamespace.js.map +1 -1
  14. package/dist/client/namespaces/MemoryNamespace.d.ts +47 -0
  15. package/dist/client/namespaces/MemoryNamespace.d.ts.map +1 -1
  16. package/dist/client/namespaces/MemoryNamespace.js +257 -27
  17. package/dist/client/namespaces/MemoryNamespace.js.map +1 -1
  18. package/dist/client/namespaces/consolidated/AdvancedNamespace.d.ts +215 -0
  19. package/dist/client/namespaces/consolidated/AdvancedNamespace.d.ts.map +1 -0
  20. package/dist/client/namespaces/consolidated/AdvancedNamespace.js +214 -0
  21. package/dist/client/namespaces/consolidated/AdvancedNamespace.js.map +1 -0
  22. package/dist/client/namespaces/consolidated/StorageNamespace.d.ts +3 -1
  23. package/dist/client/namespaces/consolidated/StorageNamespace.d.ts.map +1 -1
  24. package/dist/client/namespaces/consolidated/StorageNamespace.js.map +1 -1
  25. package/dist/client/namespaces/consolidated/index.d.ts +1 -0
  26. package/dist/client/namespaces/consolidated/index.d.ts.map +1 -1
  27. package/dist/client/namespaces/consolidated/index.js +1 -0
  28. package/dist/client/namespaces/consolidated/index.js.map +1 -1
  29. package/dist/config/ConfigurationHelper.js +61 -61
  30. package/dist/config/defaults.d.ts.map +1 -1
  31. package/dist/config/defaults.js +9 -4
  32. package/dist/config/defaults.js.map +1 -1
  33. package/dist/config/index.d.ts +1 -0
  34. package/dist/config/index.d.ts.map +1 -1
  35. package/dist/config/index.js +2 -0
  36. package/dist/config/index.js.map +1 -1
  37. package/dist/config/modelDefaults.d.ts +67 -0
  38. package/dist/config/modelDefaults.d.ts.map +1 -0
  39. package/dist/config/modelDefaults.js +91 -0
  40. package/dist/config/modelDefaults.js.map +1 -0
  41. package/dist/core/types/index.d.ts +4 -0
  42. package/dist/core/types/index.d.ts.map +1 -1
  43. package/dist/core/types/index.js.map +1 -1
  44. package/dist/graph/GraphService.d.ts.map +1 -1
  45. package/dist/graph/GraphService.js +22 -21
  46. package/dist/graph/GraphService.js.map +1 -1
  47. package/dist/index.d.ts +1 -1
  48. package/dist/index.d.ts.map +1 -1
  49. package/dist/index.js +1 -1
  50. package/dist/index.js.map +1 -1
  51. package/dist/infrastructure/walrus/WalrusStorageService.d.ts +6 -0
  52. package/dist/infrastructure/walrus/WalrusStorageService.d.ts.map +1 -1
  53. package/dist/infrastructure/walrus/WalrusStorageService.js +23 -4
  54. package/dist/infrastructure/walrus/WalrusStorageService.js.map +1 -1
  55. package/dist/langchain/createPDWRAG.js +30 -30
  56. package/dist/pipeline/MemoryPipeline.d.ts.map +1 -1
  57. package/dist/pipeline/MemoryPipeline.js +2 -1
  58. package/dist/pipeline/MemoryPipeline.js.map +1 -1
  59. package/dist/services/EmbeddingService.d.ts +9 -0
  60. package/dist/services/EmbeddingService.d.ts.map +1 -1
  61. package/dist/services/EmbeddingService.js +31 -10
  62. package/dist/services/EmbeddingService.js.map +1 -1
  63. package/dist/services/GeminiAIService.d.ts.map +1 -1
  64. package/dist/services/GeminiAIService.js +311 -310
  65. package/dist/services/GeminiAIService.js.map +1 -1
  66. package/dist/services/MemoryIndexService.d.ts +2 -0
  67. package/dist/services/MemoryIndexService.d.ts.map +1 -1
  68. package/dist/services/MemoryIndexService.js +11 -4
  69. package/dist/services/MemoryIndexService.js.map +1 -1
  70. package/dist/services/StorageService.d.ts +4 -1
  71. package/dist/services/StorageService.d.ts.map +1 -1
  72. package/dist/services/StorageService.js.map +1 -1
  73. package/dist/services/VectorService.js +1 -1
  74. package/dist/services/VectorService.js.map +1 -1
  75. package/dist/services/storage/QuiltBatchManager.d.ts +7 -0
  76. package/dist/services/storage/QuiltBatchManager.d.ts.map +1 -1
  77. package/dist/services/storage/QuiltBatchManager.js +24 -5
  78. package/dist/services/storage/QuiltBatchManager.js.map +1 -1
  79. package/dist/services/storage/WalrusStorageManager.d.ts +10 -1
  80. package/dist/services/storage/WalrusStorageManager.d.ts.map +1 -1
  81. package/dist/services/storage/WalrusStorageManager.js +53 -12
  82. package/dist/services/storage/WalrusStorageManager.js.map +1 -1
  83. package/dist/vector/BrowserHnswIndexService.js +3 -3
  84. package/dist/vector/BrowserHnswIndexService.js.map +1 -1
  85. package/dist/vector/HnswWasmService.js +1 -1
  86. package/dist/vector/HnswWasmService.js.map +1 -1
  87. package/dist/vector/NodeHnswService.js +5 -5
  88. package/dist/vector/NodeHnswService.js.map +1 -1
  89. package/dist/vector/createHnswService.d.ts +4 -0
  90. package/dist/vector/createHnswService.d.ts.map +1 -1
  91. package/dist/vector/createHnswService.js +15 -3
  92. package/dist/vector/createHnswService.js.map +1 -1
  93. package/package.json +1 -1
  94. package/src/access/PermissionService.ts +635 -635
  95. package/src/aggregation/AggregationService.ts +389 -389
  96. package/src/ai-sdk/PDWVectorStore.ts +715 -715
  97. package/src/ai-sdk/index.ts +65 -65
  98. package/src/ai-sdk/tools.ts +460 -460
  99. package/src/ai-sdk/types.ts +404 -404
  100. package/src/batch/BatchManager.ts +597 -597
  101. package/src/batch/BatchingService.ts +429 -429
  102. package/src/batch/MemoryProcessingCache.ts +492 -492
  103. package/src/batch/index.ts +30 -30
  104. package/src/browser.ts +200 -200
  105. package/src/client/ClientMemoryManager.ts +1004 -987
  106. package/src/client/PersonalDataWallet.ts +345 -345
  107. package/src/client/SimplePDWClient.ts +1387 -1289
  108. package/src/client/factory.ts +154 -154
  109. package/src/client/namespaces/AnalyticsNamespace.ts +377 -377
  110. package/src/client/namespaces/BatchNamespace.ts +356 -356
  111. package/src/client/namespaces/CacheNamespace.ts +123 -123
  112. package/src/client/namespaces/CapabilityNamespace.ts +217 -217
  113. package/src/client/namespaces/ClassifyNamespace.ts +169 -169
  114. package/src/client/namespaces/ContextNamespace.ts +297 -297
  115. package/src/client/namespaces/EncryptionNamespace.ts +221 -221
  116. package/src/client/namespaces/GraphNamespace.ts +468 -468
  117. package/src/client/namespaces/IndexNamespace.ts +364 -361
  118. package/src/client/namespaces/MemoryNamespace.ts +1704 -1422
  119. package/src/client/namespaces/PermissionsNamespace.ts +254 -254
  120. package/src/client/namespaces/PipelineNamespace.ts +220 -220
  121. package/src/client/namespaces/StorageNamespace.ts +458 -458
  122. package/src/client/namespaces/TxNamespace.ts +260 -260
  123. package/src/client/namespaces/WalletNamespace.ts +243 -243
  124. package/src/client/namespaces/consolidated/AdvancedNamespace.ts +264 -0
  125. package/src/client/namespaces/consolidated/BlockchainNamespace.ts +607 -607
  126. package/src/client/namespaces/consolidated/SecurityNamespace.ts +648 -648
  127. package/src/client/namespaces/consolidated/StorageNamespace.ts +1143 -1141
  128. package/src/client/namespaces/consolidated/index.ts +41 -39
  129. package/src/client/signers/KeypairSigner.ts +108 -108
  130. package/src/client/signers/UnifiedSigner.ts +110 -110
  131. package/src/client/signers/WalletAdapterSigner.ts +159 -159
  132. package/src/client/signers/index.ts +26 -26
  133. package/src/config/ConfigurationHelper.ts +412 -412
  134. package/src/config/defaults.ts +56 -51
  135. package/src/config/index.ts +16 -9
  136. package/src/config/modelDefaults.ts +103 -0
  137. package/src/config/validation.ts +70 -70
  138. package/src/core/index.ts +14 -14
  139. package/src/core/interfaces/IService.ts +307 -307
  140. package/src/core/interfaces/index.ts +8 -8
  141. package/src/core/types/capability.ts +297 -297
  142. package/src/core/types/index.ts +874 -870
  143. package/src/core/types/wallet.ts +270 -270
  144. package/src/core/types.ts +9 -9
  145. package/src/core/wallet.ts +222 -222
  146. package/src/embedding/index.ts +19 -19
  147. package/src/embedding/types.ts +357 -357
  148. package/src/errors/index.ts +602 -602
  149. package/src/errors/recovery.ts +461 -461
  150. package/src/errors/validation.ts +567 -567
  151. package/src/generated/pdw/capability.ts +319 -319
  152. package/src/graph/GraphService.ts +888 -887
  153. package/src/graph/KnowledgeGraphManager.ts +728 -728
  154. package/src/graph/index.ts +25 -25
  155. package/src/index.ts +498 -498
  156. package/src/infrastructure/index.ts +22 -22
  157. package/src/infrastructure/seal/EncryptionService.ts +628 -628
  158. package/src/infrastructure/seal/SealService.ts +613 -613
  159. package/src/infrastructure/seal/index.ts +9 -9
  160. package/src/infrastructure/sui/BlockchainManager.ts +627 -627
  161. package/src/infrastructure/sui/SuiService.ts +888 -888
  162. package/src/infrastructure/sui/index.ts +9 -9
  163. package/src/infrastructure/walrus/StorageManager.ts +604 -604
  164. package/src/infrastructure/walrus/WalrusStorageService.ts +637 -612
  165. package/src/infrastructure/walrus/index.ts +9 -9
  166. package/src/langchain/createPDWRAG.ts +303 -303
  167. package/src/langchain/index.ts +47 -47
  168. package/src/permissions/ConsentRepository.browser.ts +249 -249
  169. package/src/permissions/ConsentRepository.ts +364 -364
  170. package/src/pipeline/MemoryPipeline.ts +863 -862
  171. package/src/pipeline/PipelineManager.ts +683 -683
  172. package/src/pipeline/index.ts +26 -26
  173. package/src/retrieval/AdvancedSearchService.ts +629 -629
  174. package/src/retrieval/MemoryAnalyticsService.ts +711 -711
  175. package/src/retrieval/MemoryDecryptionPipeline.ts +825 -825
  176. package/src/retrieval/index.ts +42 -42
  177. package/src/services/BatchService.ts +352 -352
  178. package/src/services/CapabilityService.ts +464 -464
  179. package/src/services/ClassifierService.ts +465 -465
  180. package/src/services/CrossContextPermissionService.ts +486 -486
  181. package/src/services/EmbeddingService.ts +796 -771
  182. package/src/services/EncryptionService.ts +712 -712
  183. package/src/services/GeminiAIService.ts +754 -753
  184. package/src/services/MemoryIndexService.ts +1009 -1003
  185. package/src/services/MemoryService.ts +369 -369
  186. package/src/services/QueryService.ts +890 -890
  187. package/src/services/StorageService.ts +1185 -1182
  188. package/src/services/TransactionService.ts +838 -838
  189. package/src/services/VectorService.ts +462 -462
  190. package/src/services/ViewService.ts +484 -484
  191. package/src/services/index.ts +25 -25
  192. package/src/services/storage/BlobAttributesManager.ts +333 -333
  193. package/src/services/storage/KnowledgeGraphManager.ts +425 -425
  194. package/src/services/storage/MemorySearchManager.ts +387 -387
  195. package/src/services/storage/QuiltBatchManager.ts +1157 -1130
  196. package/src/services/storage/WalrusMetadataManager.ts +268 -268
  197. package/src/services/storage/WalrusStorageManager.ts +333 -287
  198. package/src/services/storage/index.ts +57 -57
  199. package/src/types/index.ts +13 -13
  200. package/src/utils/index.ts +76 -76
  201. package/src/utils/memoryIndexOnChain.ts +507 -507
  202. package/src/vector/BrowserHnswIndexService.ts +758 -758
  203. package/src/vector/HnswWasmService.ts +731 -731
  204. package/src/vector/IHnswService.ts +233 -233
  205. package/src/vector/NodeHnswService.ts +833 -833
  206. package/src/vector/createHnswService.ts +147 -135
  207. package/src/vector/index.ts +56 -56
  208. package/src/wallet/ContextWalletService.ts +656 -656
  209. 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;