@sparkleideas/shared 3.0.0-alpha.7

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 (96) hide show
  1. package/README.md +323 -0
  2. package/__tests__/hooks/bash-safety.test.ts +289 -0
  3. package/__tests__/hooks/file-organization.test.ts +335 -0
  4. package/__tests__/hooks/git-commit.test.ts +336 -0
  5. package/__tests__/hooks/index.ts +23 -0
  6. package/__tests__/hooks/session-hooks.test.ts +357 -0
  7. package/__tests__/hooks/task-hooks.test.ts +193 -0
  8. package/docs/EVENTS_IMPLEMENTATION_SUMMARY.md +388 -0
  9. package/docs/EVENTS_QUICK_REFERENCE.md +470 -0
  10. package/docs/EVENTS_README.md +352 -0
  11. package/package.json +39 -0
  12. package/src/core/config/defaults.ts +207 -0
  13. package/src/core/config/index.ts +15 -0
  14. package/src/core/config/loader.ts +271 -0
  15. package/src/core/config/schema.ts +188 -0
  16. package/src/core/config/validator.ts +209 -0
  17. package/src/core/event-bus.ts +236 -0
  18. package/src/core/index.ts +22 -0
  19. package/src/core/interfaces/agent.interface.ts +251 -0
  20. package/src/core/interfaces/coordinator.interface.ts +363 -0
  21. package/src/core/interfaces/event.interface.ts +267 -0
  22. package/src/core/interfaces/index.ts +19 -0
  23. package/src/core/interfaces/memory.interface.ts +332 -0
  24. package/src/core/interfaces/task.interface.ts +223 -0
  25. package/src/core/orchestrator/event-coordinator.ts +122 -0
  26. package/src/core/orchestrator/health-monitor.ts +214 -0
  27. package/src/core/orchestrator/index.ts +89 -0
  28. package/src/core/orchestrator/lifecycle-manager.ts +263 -0
  29. package/src/core/orchestrator/session-manager.ts +279 -0
  30. package/src/core/orchestrator/task-manager.ts +317 -0
  31. package/src/events/domain-events.ts +584 -0
  32. package/src/events/event-store.test.ts +387 -0
  33. package/src/events/event-store.ts +588 -0
  34. package/src/events/example-usage.ts +293 -0
  35. package/src/events/index.ts +90 -0
  36. package/src/events/projections.ts +561 -0
  37. package/src/events/state-reconstructor.ts +349 -0
  38. package/src/events.ts +367 -0
  39. package/src/hooks/INTEGRATION.md +658 -0
  40. package/src/hooks/README.md +532 -0
  41. package/src/hooks/example-usage.ts +499 -0
  42. package/src/hooks/executor.ts +379 -0
  43. package/src/hooks/hooks.test.ts +421 -0
  44. package/src/hooks/index.ts +131 -0
  45. package/src/hooks/registry.ts +333 -0
  46. package/src/hooks/safety/bash-safety.ts +604 -0
  47. package/src/hooks/safety/file-organization.ts +473 -0
  48. package/src/hooks/safety/git-commit.ts +623 -0
  49. package/src/hooks/safety/index.ts +46 -0
  50. package/src/hooks/session-hooks.ts +559 -0
  51. package/src/hooks/task-hooks.ts +513 -0
  52. package/src/hooks/types.ts +357 -0
  53. package/src/hooks/verify-exports.test.ts +125 -0
  54. package/src/index.ts +195 -0
  55. package/src/mcp/connection-pool.ts +438 -0
  56. package/src/mcp/index.ts +183 -0
  57. package/src/mcp/server.ts +774 -0
  58. package/src/mcp/session-manager.ts +428 -0
  59. package/src/mcp/tool-registry.ts +566 -0
  60. package/src/mcp/transport/http.ts +557 -0
  61. package/src/mcp/transport/index.ts +294 -0
  62. package/src/mcp/transport/stdio.ts +324 -0
  63. package/src/mcp/transport/websocket.ts +484 -0
  64. package/src/mcp/types.ts +565 -0
  65. package/src/plugin-interface.ts +663 -0
  66. package/src/plugin-loader.ts +638 -0
  67. package/src/plugin-registry.ts +604 -0
  68. package/src/plugins/index.ts +34 -0
  69. package/src/plugins/official/hive-mind-plugin.ts +330 -0
  70. package/src/plugins/official/index.ts +24 -0
  71. package/src/plugins/official/maestro-plugin.ts +508 -0
  72. package/src/plugins/types.ts +108 -0
  73. package/src/resilience/bulkhead.ts +277 -0
  74. package/src/resilience/circuit-breaker.ts +326 -0
  75. package/src/resilience/index.ts +26 -0
  76. package/src/resilience/rate-limiter.ts +420 -0
  77. package/src/resilience/retry.ts +224 -0
  78. package/src/security/index.ts +39 -0
  79. package/src/security/input-validation.ts +265 -0
  80. package/src/security/secure-random.ts +159 -0
  81. package/src/services/index.ts +16 -0
  82. package/src/services/v3-progress.service.ts +505 -0
  83. package/src/types/agent.types.ts +144 -0
  84. package/src/types/index.ts +22 -0
  85. package/src/types/mcp.types.ts +300 -0
  86. package/src/types/memory.types.ts +263 -0
  87. package/src/types/swarm.types.ts +255 -0
  88. package/src/types/task.types.ts +205 -0
  89. package/src/types.ts +367 -0
  90. package/src/utils/secure-logger.d.ts +69 -0
  91. package/src/utils/secure-logger.d.ts.map +1 -0
  92. package/src/utils/secure-logger.js +208 -0
  93. package/src/utils/secure-logger.js.map +1 -0
  94. package/src/utils/secure-logger.ts +257 -0
  95. package/tmp.json +0 -0
  96. package/tsconfig.json +9 -0
@@ -0,0 +1,513 @@
1
+ /**
2
+ * V3 Task Lifecycle Hooks
3
+ *
4
+ * Provides pre-task and post-task hooks for task execution lifecycle.
5
+ * Integrates with ReasoningBank for learning and pattern recognition.
6
+ *
7
+ * @module v3/shared/hooks/task-hooks
8
+ */
9
+
10
+ import {
11
+ HookEvent,
12
+ HookContext,
13
+ HookResult,
14
+ HookPriority,
15
+ TaskInfo,
16
+ } from './types.js';
17
+ import { HookRegistry } from './registry.js';
18
+
19
+ /**
20
+ * Pre-task hook result with agent suggestions
21
+ */
22
+ export interface PreTaskHookResult extends HookResult {
23
+ /** Suggested agents for the task */
24
+ suggestedAgents?: AgentSuggestion[];
25
+ /** Task complexity estimation */
26
+ complexity?: 'low' | 'medium' | 'high';
27
+ /** Estimated duration in milliseconds */
28
+ estimatedDuration?: number;
29
+ /** Related patterns from ReasoningBank */
30
+ patterns?: TaskPattern[];
31
+ /** Potential risks */
32
+ risks?: string[];
33
+ /** Recommendations */
34
+ recommendations?: string[];
35
+ }
36
+
37
+ /**
38
+ * Post-task hook result with learning data
39
+ */
40
+ export interface PostTaskHookResult extends HookResult {
41
+ /** Task outcome */
42
+ outcome?: TaskOutcome;
43
+ /** Learning updates applied */
44
+ learningUpdates?: LearningUpdate;
45
+ /** Pattern ID if a new pattern was created */
46
+ patternId?: string;
47
+ /** Trajectory ID for ReasoningBank */
48
+ trajectoryId?: string;
49
+ }
50
+
51
+ /**
52
+ * Agent suggestion for task routing
53
+ */
54
+ export interface AgentSuggestion {
55
+ /** Agent type */
56
+ type: string;
57
+ /** Confidence score (0-1) */
58
+ confidence: number;
59
+ /** Reason for suggestion */
60
+ reason: string;
61
+ /** Capabilities relevant to this task */
62
+ capabilities?: string[];
63
+ }
64
+
65
+ /**
66
+ * Task pattern from ReasoningBank
67
+ */
68
+ export interface TaskPattern {
69
+ /** Pattern identifier */
70
+ id: string;
71
+ /** Pattern description */
72
+ description: string;
73
+ /** Match score (0-1) */
74
+ matchScore: number;
75
+ /** Historical success rate */
76
+ successRate: number;
77
+ /** Average duration in ms */
78
+ avgDuration: number;
79
+ /** Recommended strategies */
80
+ strategies?: string[];
81
+ }
82
+
83
+ /**
84
+ * Task outcome for learning
85
+ */
86
+ export interface TaskOutcome {
87
+ /** Whether the task succeeded */
88
+ success: boolean;
89
+ /** Duration in milliseconds */
90
+ duration: number;
91
+ /** Quality score (0-1) */
92
+ quality?: number;
93
+ /** Error details if failed */
94
+ error?: string;
95
+ /** Output artifacts */
96
+ artifacts?: string[];
97
+ /** Agent that executed the task */
98
+ agent?: string;
99
+ }
100
+
101
+ /**
102
+ * Learning update result
103
+ */
104
+ export interface LearningUpdate {
105
+ /** Number of patterns updated */
106
+ patternsUpdated: number;
107
+ /** Number of new patterns created */
108
+ newPatterns: number;
109
+ /** Confidence adjustments made */
110
+ confidenceAdjusted: number;
111
+ /** Trajectories recorded */
112
+ trajectoriesRecorded: number;
113
+ }
114
+
115
+ /**
116
+ * Task store for tracking active tasks
117
+ */
118
+ interface TaskStore {
119
+ taskId: string;
120
+ description: string;
121
+ startTime: number;
122
+ metadata?: Record<string, unknown>;
123
+ suggestedAgents?: AgentSuggestion[];
124
+ }
125
+
126
+ /**
127
+ * Task Hooks Manager
128
+ *
129
+ * Manages pre-task and post-task hooks with ReasoningBank integration.
130
+ */
131
+ export class TaskHooksManager {
132
+ private registry: HookRegistry;
133
+ private activeTasks: Map<string, TaskStore> = new Map();
134
+ private taskPatterns: Map<string, TaskPattern[]> = new Map();
135
+
136
+ constructor(registry: HookRegistry) {
137
+ this.registry = registry;
138
+ this.registerDefaultHooks();
139
+ }
140
+
141
+ /**
142
+ * Register default task hooks
143
+ */
144
+ private registerDefaultHooks(): void {
145
+ // Pre-task hook for agent suggestion
146
+ this.registry.register(
147
+ HookEvent.PreTaskExecute,
148
+ this.handlePreTask.bind(this),
149
+ HookPriority.Normal,
150
+ { name: 'task-hooks:pre-task' }
151
+ );
152
+
153
+ // Post-task hook for learning
154
+ this.registry.register(
155
+ HookEvent.PostTaskExecute,
156
+ this.handlePostTask.bind(this),
157
+ HookPriority.Normal,
158
+ { name: 'task-hooks:post-task' }
159
+ );
160
+ }
161
+
162
+ /**
163
+ * Handle pre-task execution
164
+ */
165
+ async handlePreTask(context: HookContext): Promise<PreTaskHookResult> {
166
+ const task = context.task;
167
+ if (!task) {
168
+ return { success: false, error: new Error('No task in context') };
169
+ }
170
+
171
+ // Store task for tracking
172
+ const taskStore: TaskStore = {
173
+ taskId: task.id,
174
+ description: task.description,
175
+ startTime: Date.now(),
176
+ metadata: task.metadata,
177
+ };
178
+
179
+ // Analyze task and suggest agents
180
+ const analysis = await this.analyzeTask(task);
181
+
182
+ taskStore.suggestedAgents = analysis.suggestedAgents;
183
+ this.activeTasks.set(task.id, taskStore);
184
+
185
+ // Store patterns for this task
186
+ if (analysis.patterns.length > 0) {
187
+ this.taskPatterns.set(task.id, analysis.patterns);
188
+ }
189
+
190
+ return {
191
+ success: true,
192
+ suggestedAgents: analysis.suggestedAgents,
193
+ complexity: analysis.complexity,
194
+ estimatedDuration: analysis.estimatedDuration,
195
+ patterns: analysis.patterns,
196
+ risks: analysis.risks,
197
+ recommendations: analysis.recommendations,
198
+ data: {
199
+ task: {
200
+ ...task,
201
+ metadata: {
202
+ ...task.metadata,
203
+ suggestedAgents: analysis.suggestedAgents.map(a => a.type),
204
+ complexity: analysis.complexity,
205
+ },
206
+ },
207
+ },
208
+ };
209
+ }
210
+
211
+ /**
212
+ * Handle post-task execution
213
+ */
214
+ async handlePostTask(context: HookContext): Promise<PostTaskHookResult> {
215
+ const task = context.task;
216
+ if (!task) {
217
+ return { success: false, error: new Error('No task in context') };
218
+ }
219
+
220
+ const taskStore = this.activeTasks.get(task.id);
221
+ const patterns = this.taskPatterns.get(task.id);
222
+
223
+ // Calculate duration
224
+ const duration = taskStore ? Date.now() - taskStore.startTime : 0;
225
+
226
+ // Extract outcome from context metadata
227
+ const success = context.metadata?.success !== false;
228
+ const quality = context.metadata?.quality as number | undefined;
229
+ const error = context.metadata?.error as string | undefined;
230
+ const agent = context.metadata?.agent as string | undefined;
231
+
232
+ const outcome: TaskOutcome = {
233
+ success,
234
+ duration,
235
+ quality,
236
+ error,
237
+ agent,
238
+ artifacts: context.metadata?.artifacts as string[] | undefined,
239
+ };
240
+
241
+ // Record learning trajectory
242
+ const learningUpdates = await this.recordLearning(task, outcome, patterns);
243
+
244
+ // Clean up
245
+ this.activeTasks.delete(task.id);
246
+ this.taskPatterns.delete(task.id);
247
+
248
+ return {
249
+ success: true,
250
+ outcome,
251
+ learningUpdates,
252
+ patternId: learningUpdates.newPatterns > 0 ? `pattern-${task.id}` : undefined,
253
+ trajectoryId: `trajectory-${task.id}-${Date.now()}`,
254
+ };
255
+ }
256
+
257
+ /**
258
+ * Analyze task for agent suggestions and patterns
259
+ */
260
+ private async analyzeTask(task: TaskInfo): Promise<{
261
+ suggestedAgents: AgentSuggestion[];
262
+ complexity: 'low' | 'medium' | 'high';
263
+ estimatedDuration: number;
264
+ patterns: TaskPattern[];
265
+ risks: string[];
266
+ recommendations: string[];
267
+ }> {
268
+ const description = task.description.toLowerCase();
269
+
270
+ // Pattern-based agent suggestion
271
+ const suggestedAgents: AgentSuggestion[] = [];
272
+ const patterns: TaskPattern[] = [];
273
+ const risks: string[] = [];
274
+ const recommendations: string[] = [];
275
+
276
+ // Analyze task keywords for agent routing
277
+ const agentPatterns: Array<{
278
+ keywords: string[];
279
+ agent: string;
280
+ capabilities: string[];
281
+ }> = [
282
+ {
283
+ keywords: ['implement', 'code', 'create', 'build', 'develop', 'write'],
284
+ agent: 'coder',
285
+ capabilities: ['code-generation', 'implementation', 'debugging'],
286
+ },
287
+ {
288
+ keywords: ['test', 'spec', 'coverage', 'unit', 'integration'],
289
+ agent: 'tester',
290
+ capabilities: ['unit-testing', 'integration-testing', 'coverage-analysis'],
291
+ },
292
+ {
293
+ keywords: ['review', 'check', 'audit', 'analyze'],
294
+ agent: 'reviewer',
295
+ capabilities: ['code-review', 'quality-analysis', 'best-practices'],
296
+ },
297
+ {
298
+ keywords: ['research', 'investigate', 'explore', 'study'],
299
+ agent: 'researcher',
300
+ capabilities: ['research', 'analysis', 'documentation'],
301
+ },
302
+ {
303
+ keywords: ['security', 'vulnerability', 'cve', 'threat'],
304
+ agent: 'security-architect',
305
+ capabilities: ['security-analysis', 'vulnerability-detection', 'threat-modeling'],
306
+ },
307
+ {
308
+ keywords: ['performance', 'optimize', 'speed', 'memory'],
309
+ agent: 'performance-engineer',
310
+ capabilities: ['performance-optimization', 'profiling', 'benchmarking'],
311
+ },
312
+ {
313
+ keywords: ['architect', 'design', 'structure', 'pattern'],
314
+ agent: 'core-architect',
315
+ capabilities: ['architecture-design', 'pattern-application', 'system-design'],
316
+ },
317
+ {
318
+ keywords: ['memory', 'storage', 'database', 'cache'],
319
+ agent: 'memory-specialist',
320
+ capabilities: ['memory-management', 'data-persistence', 'caching'],
321
+ },
322
+ {
323
+ keywords: ['swarm', 'coordinate', 'orchestrate', 'agent'],
324
+ agent: 'swarm-specialist',
325
+ capabilities: ['swarm-coordination', 'agent-orchestration', 'distributed-systems'],
326
+ },
327
+ ];
328
+
329
+ // Score each agent based on keyword matches
330
+ for (const pattern of agentPatterns) {
331
+ let matchCount = 0;
332
+ for (const keyword of pattern.keywords) {
333
+ if (description.includes(keyword)) {
334
+ matchCount++;
335
+ }
336
+ }
337
+
338
+ if (matchCount > 0) {
339
+ const confidence = Math.min(0.3 + matchCount * 0.2, 0.95);
340
+ suggestedAgents.push({
341
+ type: pattern.agent,
342
+ confidence,
343
+ reason: `Matched keywords: ${pattern.keywords.filter(k => description.includes(k)).join(', ')}`,
344
+ capabilities: pattern.capabilities,
345
+ });
346
+ }
347
+ }
348
+
349
+ // Sort by confidence
350
+ suggestedAgents.sort((a, b) => b.confidence - a.confidence);
351
+
352
+ // If no matches, default to coder
353
+ if (suggestedAgents.length === 0) {
354
+ suggestedAgents.push({
355
+ type: 'coder',
356
+ confidence: 0.5,
357
+ reason: 'Default agent for unclassified tasks',
358
+ capabilities: ['code-generation', 'implementation'],
359
+ });
360
+ }
361
+
362
+ // Estimate complexity based on description length and keywords
363
+ let complexity: 'low' | 'medium' | 'high' = 'medium';
364
+ const complexityKeywords = ['complex', 'large', 'multiple', 'refactor', 'redesign', 'critical'];
365
+ const simpleKeywords = ['simple', 'small', 'quick', 'fix', 'minor', 'typo'];
366
+
367
+ const hasComplexKeywords = complexityKeywords.some(k => description.includes(k));
368
+ const hasSimpleKeywords = simpleKeywords.some(k => description.includes(k));
369
+
370
+ if (hasComplexKeywords) {
371
+ complexity = 'high';
372
+ } else if (hasSimpleKeywords) {
373
+ complexity = 'low';
374
+ } else if (description.length > 200) {
375
+ complexity = 'high';
376
+ } else if (description.length < 50) {
377
+ complexity = 'low';
378
+ }
379
+
380
+ // Estimate duration based on complexity
381
+ const durationMap = {
382
+ low: 5 * 60 * 1000, // 5 minutes
383
+ medium: 30 * 60 * 1000, // 30 minutes
384
+ high: 2 * 60 * 60 * 1000, // 2 hours
385
+ };
386
+ const estimatedDuration = durationMap[complexity];
387
+
388
+ // Detect risks
389
+ if (description.includes('production') || description.includes('live')) {
390
+ risks.push('Task involves production environment');
391
+ }
392
+ if (description.includes('delete') || description.includes('remove')) {
393
+ risks.push('Task involves destructive operations');
394
+ }
395
+ if (description.includes('security') || description.includes('auth')) {
396
+ risks.push('Task involves security-sensitive operations');
397
+ }
398
+ if (description.includes('database') || description.includes('migration')) {
399
+ risks.push('Task involves database changes');
400
+ }
401
+
402
+ // Add recommendations
403
+ if (complexity === 'high') {
404
+ recommendations.push('Consider breaking this task into smaller subtasks');
405
+ }
406
+ if (suggestedAgents.length > 1) {
407
+ recommendations.push('Consider using multiple agents for better coverage');
408
+ }
409
+ if (risks.length > 0) {
410
+ recommendations.push('Review risks before proceeding');
411
+ }
412
+
413
+ return {
414
+ suggestedAgents,
415
+ complexity,
416
+ estimatedDuration,
417
+ patterns,
418
+ risks,
419
+ recommendations,
420
+ };
421
+ }
422
+
423
+ /**
424
+ * Record learning trajectory
425
+ */
426
+ private async recordLearning(
427
+ task: TaskInfo,
428
+ outcome: TaskOutcome,
429
+ patterns?: TaskPattern[]
430
+ ): Promise<LearningUpdate> {
431
+ // In a real implementation, this would integrate with ReasoningBank
432
+ // For now, we track basic statistics
433
+
434
+ const learningUpdate: LearningUpdate = {
435
+ patternsUpdated: patterns?.length || 0,
436
+ newPatterns: outcome.success ? 1 : 0,
437
+ confidenceAdjusted: patterns?.length || 0,
438
+ trajectoriesRecorded: 1,
439
+ };
440
+
441
+ return learningUpdate;
442
+ }
443
+
444
+ /**
445
+ * Execute pre-task hook manually
446
+ */
447
+ async executePreTask(
448
+ taskId: string,
449
+ description: string,
450
+ metadata?: Record<string, unknown>
451
+ ): Promise<PreTaskHookResult> {
452
+ const context: HookContext = {
453
+ event: HookEvent.PreTaskExecute,
454
+ timestamp: new Date(),
455
+ task: {
456
+ id: taskId,
457
+ description,
458
+ metadata,
459
+ },
460
+ };
461
+
462
+ return this.handlePreTask(context);
463
+ }
464
+
465
+ /**
466
+ * Execute post-task hook manually
467
+ */
468
+ async executePostTask(
469
+ taskId: string,
470
+ success: boolean,
471
+ metadata?: Record<string, unknown>
472
+ ): Promise<PostTaskHookResult> {
473
+ const taskStore = this.activeTasks.get(taskId);
474
+
475
+ const context: HookContext = {
476
+ event: HookEvent.PostTaskExecute,
477
+ timestamp: new Date(),
478
+ task: {
479
+ id: taskId,
480
+ description: taskStore?.description || 'Unknown task',
481
+ metadata: taskStore?.metadata,
482
+ },
483
+ metadata: {
484
+ ...metadata,
485
+ success,
486
+ },
487
+ };
488
+
489
+ return this.handlePostTask(context);
490
+ }
491
+
492
+ /**
493
+ * Get active tasks
494
+ */
495
+ getActiveTasks(): Map<string, TaskStore> {
496
+ return new Map(this.activeTasks);
497
+ }
498
+
499
+ /**
500
+ * Clear all active tasks
501
+ */
502
+ clearActiveTasks(): void {
503
+ this.activeTasks.clear();
504
+ this.taskPatterns.clear();
505
+ }
506
+ }
507
+
508
+ /**
509
+ * Create task hooks manager
510
+ */
511
+ export function createTaskHooksManager(registry: HookRegistry): TaskHooksManager {
512
+ return new TaskHooksManager(registry);
513
+ }