@equilateral_ai/mindmeld 3.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 (86) hide show
  1. package/README.md +300 -0
  2. package/hooks/README.md +494 -0
  3. package/hooks/pre-compact.js +392 -0
  4. package/hooks/session-start.js +264 -0
  5. package/package.json +90 -0
  6. package/scripts/harvest.js +561 -0
  7. package/scripts/init-project.js +437 -0
  8. package/scripts/inject.js +388 -0
  9. package/src/collaboration/CollaborationPrompt.js +460 -0
  10. package/src/core/AlertEngine.js +813 -0
  11. package/src/core/AlertNotifier.js +363 -0
  12. package/src/core/CorrelationAnalyzer.js +774 -0
  13. package/src/core/CurationEngine.js +688 -0
  14. package/src/core/LLMPatternDetector.js +508 -0
  15. package/src/core/LoadBearingDetector.js +242 -0
  16. package/src/core/NotificationService.js +1032 -0
  17. package/src/core/PatternValidator.js +355 -0
  18. package/src/core/README.md +160 -0
  19. package/src/core/RapportOrchestrator.js +446 -0
  20. package/src/core/RelevanceDetector.js +577 -0
  21. package/src/core/StandardsIngestion.js +575 -0
  22. package/src/core/TeamLoadBearingDetector.js +431 -0
  23. package/src/database/dbOperations.js +105 -0
  24. package/src/handlers/activity/activityGetMe.js +98 -0
  25. package/src/handlers/activity/activityGetTeam.js +130 -0
  26. package/src/handlers/alerts/alertsAcknowledge.js +91 -0
  27. package/src/handlers/alerts/alertsGet.js +250 -0
  28. package/src/handlers/collaborators/collaboratorAdd.js +201 -0
  29. package/src/handlers/collaborators/collaboratorInvite.js +218 -0
  30. package/src/handlers/collaborators/collaboratorList.js +88 -0
  31. package/src/handlers/collaborators/collaboratorRemove.js +127 -0
  32. package/src/handlers/collaborators/inviteAccept.js +122 -0
  33. package/src/handlers/context/contextGet.js +57 -0
  34. package/src/handlers/context/invariantsGet.js +74 -0
  35. package/src/handlers/context/loopsGet.js +82 -0
  36. package/src/handlers/context/notesCreate.js +74 -0
  37. package/src/handlers/context/purposeGet.js +78 -0
  38. package/src/handlers/correlations/correlationsDeveloperGet.js +226 -0
  39. package/src/handlers/correlations/correlationsGet.js +93 -0
  40. package/src/handlers/correlations/correlationsProjectGet.js +161 -0
  41. package/src/handlers/github/githubConnectionStatus.js +49 -0
  42. package/src/handlers/github/githubDiscoverPatterns.js +364 -0
  43. package/src/handlers/github/githubOAuthCallback.js +166 -0
  44. package/src/handlers/github/githubOAuthStart.js +59 -0
  45. package/src/handlers/github/githubPatternsReview.js +109 -0
  46. package/src/handlers/github/githubReposList.js +105 -0
  47. package/src/handlers/helpers/checkSuperAdmin.js +85 -0
  48. package/src/handlers/helpers/dbOperations.js +53 -0
  49. package/src/handlers/helpers/errorHandler.js +49 -0
  50. package/src/handlers/helpers/index.js +106 -0
  51. package/src/handlers/helpers/lambdaWrapper.js +60 -0
  52. package/src/handlers/helpers/responseUtil.js +55 -0
  53. package/src/handlers/helpers/subscriptionTiers.js +1168 -0
  54. package/src/handlers/notifications/getPreferences.js +84 -0
  55. package/src/handlers/notifications/sendNotification.js +170 -0
  56. package/src/handlers/notifications/updatePreferences.js +316 -0
  57. package/src/handlers/patterns/patternUsagePost.js +182 -0
  58. package/src/handlers/patterns/patternViolationPost.js +185 -0
  59. package/src/handlers/projects/projectCreate.js +107 -0
  60. package/src/handlers/projects/projectDelete.js +82 -0
  61. package/src/handlers/projects/projectGet.js +95 -0
  62. package/src/handlers/projects/projectUpdate.js +118 -0
  63. package/src/handlers/reports/aiLeverage.js +206 -0
  64. package/src/handlers/reports/engineeringInvestment.js +132 -0
  65. package/src/handlers/reports/riskForecast.js +186 -0
  66. package/src/handlers/reports/standardsRoi.js +162 -0
  67. package/src/handlers/scheduled/analyzeCorrelations.js +178 -0
  68. package/src/handlers/scheduled/analyzeGitHistory.js +510 -0
  69. package/src/handlers/scheduled/generateAlerts.js +135 -0
  70. package/src/handlers/scheduled/refreshActivity.js +21 -0
  71. package/src/handlers/scheduled/scanCompliance.js +334 -0
  72. package/src/handlers/sessions/sessionEndPost.js +180 -0
  73. package/src/handlers/sessions/sessionStandardsPost.js +135 -0
  74. package/src/handlers/stripe/addonManagePost.js +240 -0
  75. package/src/handlers/stripe/billingPortalPost.js +93 -0
  76. package/src/handlers/stripe/enterpriseCheckoutPost.js +272 -0
  77. package/src/handlers/stripe/seatsUpdatePost.js +185 -0
  78. package/src/handlers/stripe/subscriptionCancelDelete.js +169 -0
  79. package/src/handlers/stripe/subscriptionCreatePost.js +221 -0
  80. package/src/handlers/stripe/subscriptionUpdatePut.js +163 -0
  81. package/src/handlers/stripe/webhookPost.js +454 -0
  82. package/src/handlers/users/cognitoPostConfirmation.js +150 -0
  83. package/src/handlers/users/userEntitlementsGet.js +89 -0
  84. package/src/handlers/users/userGet.js +114 -0
  85. package/src/handlers/webhooks/githubWebhook.js +223 -0
  86. package/src/index.js +969 -0
@@ -0,0 +1,446 @@
1
+ /**
2
+ * Rapport Orchestrator - Multi-Agent Integration Layer
3
+ * Integrates Rapport's pattern discovery with existing 63-agent ecosystem
4
+ *
5
+ * Phase 6: Multi-Agent Orchestration
6
+ *
7
+ * Key Integration:
8
+ * - Leverages existing PatternHarvestingAgent, AuditorAgent, SecurityReviewerAgent, KnowledgeSynthesisAgent
9
+ * - Creates RapportCurationWorkflow for pattern -> standard pipeline
10
+ * - Background sync daemon for .equilateral-standards monitoring
11
+ * - Event-driven architecture for real-time updates
12
+ */
13
+
14
+ const EventEmitter = require('events');
15
+ const fs = require('fs').promises;
16
+ const path = require('path');
17
+ const { watch } = require('fs');
18
+
19
+ class RapportOrchestrator extends EventEmitter {
20
+ constructor(config = {}) {
21
+ super();
22
+
23
+ this.config = {
24
+ rapportRoot: config.rapportRoot || process.cwd(),
25
+ equilateralAgentsPath: config.equilateralAgentsPath || path.join(__dirname, '../../../EquilateralAgents'),
26
+ standardsPath: config.standardsPath || '.equilateral-standards',
27
+ enableBackgroundSync: config.enableBackgroundSync !== false,
28
+ syncInterval: config.syncInterval || 300000, // 5 minutes
29
+ ...config
30
+ };
31
+
32
+ this.agents = new Map();
33
+ this.workflows = new Map();
34
+ this.backgroundJobs = new Map();
35
+ this.standardsWatcher = null;
36
+ this.initialized = false;
37
+ }
38
+
39
+ /**
40
+ * Initialize Rapport Orchestrator with agent system integration
41
+ */
42
+ async initialize() {
43
+ try {
44
+ console.log('[RapportOrchestrator] Initializing with multi-agent integration...');
45
+
46
+ // 1. Connect to existing EquilateralAgents system
47
+ await this.connectToAgentSystem();
48
+
49
+ // 2. Register Rapport-specific workflows
50
+ await this.registerWorkflows();
51
+
52
+ // 3. Start background sync daemon (if enabled)
53
+ if (this.config.enableBackgroundSync) {
54
+ await this.startBackgroundSync();
55
+ }
56
+
57
+ this.initialized = true;
58
+ this.emit('initialized', {
59
+ agents: Array.from(this.agents.keys()),
60
+ workflows: Array.from(this.workflows.keys()),
61
+ backgroundSync: this.config.enableBackgroundSync
62
+ });
63
+
64
+ console.log('[RapportOrchestrator] Initialization complete');
65
+ return { success: true, status: 'initialized' };
66
+
67
+ } catch (error) {
68
+ console.error('[RapportOrchestrator] Initialization failed:', error);
69
+ this.emit('error', { component: 'orchestrator', error });
70
+ throw error;
71
+ }
72
+ }
73
+
74
+ /**
75
+ * Connect to existing EquilateralAgents system
76
+ * Leverages the 63-agent infrastructure without recreating it
77
+ */
78
+ async connectToAgentSystem() {
79
+ try {
80
+ // Import core agents from EquilateralAgents (if available)
81
+ const agentsPath = path.join(this.config.equilateralAgentsPath, 'src/agents/specialists');
82
+
83
+ // Core agents needed for Rapport curation workflow
84
+ const coreAgents = [
85
+ 'PatternHarvestingAgent',
86
+ 'AuditorAgent',
87
+ 'SecurityReviewerAgent',
88
+ 'KnowledgeSynthesisAgent'
89
+ ];
90
+
91
+ for (const agentName of coreAgents) {
92
+ try {
93
+ const agentPath = path.join(agentsPath, `${agentName}.js`);
94
+ const AgentClass = require(agentPath);
95
+
96
+ // Register agent (lazy instantiation)
97
+ this.agents.set(agentName, {
98
+ name: agentName,
99
+ class: AgentClass,
100
+ instance: null,
101
+ status: 'registered'
102
+ });
103
+
104
+ console.log(`[RapportOrchestrator] Registered agent: ${agentName}`);
105
+ } catch (error) {
106
+ console.warn(`[RapportOrchestrator] Could not load ${agentName}:`, error.message);
107
+ }
108
+ }
109
+
110
+ // If no agents found, use fallback mode
111
+ if (this.agents.size === 0) {
112
+ console.warn('[RapportOrchestrator] No EquilateralAgents found, using standalone mode');
113
+ }
114
+
115
+ } catch (error) {
116
+ console.warn('[RapportOrchestrator] Agent system connection failed, using standalone mode:', error.message);
117
+ }
118
+ }
119
+
120
+ /**
121
+ * Get or instantiate an agent (lazy loading)
122
+ */
123
+ getAgent(agentName) {
124
+ if (!this.agents.has(agentName)) {
125
+ throw new Error(`Agent ${agentName} not registered`);
126
+ }
127
+
128
+ const agentInfo = this.agents.get(agentName);
129
+
130
+ // Return cached instance if available
131
+ if (agentInfo.instance) {
132
+ return agentInfo.instance;
133
+ }
134
+
135
+ // Instantiate agent
136
+ const AgentClass = agentInfo.class;
137
+ const instance = new AgentClass({
138
+ projectRoot: this.config.rapportRoot
139
+ });
140
+
141
+ // Cache instance
142
+ agentInfo.instance = instance;
143
+ agentInfo.status = 'active';
144
+
145
+ console.log(`[RapportOrchestrator] Instantiated agent: ${agentName}`);
146
+ return instance;
147
+ }
148
+
149
+ /**
150
+ * Register Rapport-specific workflows
151
+ */
152
+ async registerWorkflows() {
153
+ // Workflow 1: Pattern Curation Pipeline
154
+ this.workflows.set('rapport-curate-pattern', {
155
+ name: 'rapport-curate-pattern',
156
+ description: 'Curate discovered pattern into standard',
157
+ steps: [
158
+ { agent: 'PatternHarvestingAgent', method: 'gatherEvidence', parallel: false },
159
+ { agent: 'AuditorAgent', method: 'validateCompliance', parallel: false },
160
+ { agent: 'SecurityReviewerAgent', method: 'reviewPattern', parallel: false },
161
+ { agent: 'KnowledgeSynthesisAgent', method: 'generateStandard', parallel: false }
162
+ ]
163
+ });
164
+
165
+ // Workflow 2: Standards Validation
166
+ this.workflows.set('rapport-validate-standards', {
167
+ name: 'rapport-validate-standards',
168
+ description: 'Validate code against ingested standards',
169
+ steps: [
170
+ { agent: 'PatternHarvestingAgent', method: 'detectPatterns', parallel: false },
171
+ { agent: 'AuditorAgent', method: 'validateStandards', parallel: false }
172
+ ]
173
+ });
174
+
175
+ // Workflow 3: Standards Sync
176
+ this.workflows.set('rapport-sync-standards', {
177
+ name: 'rapport-sync-standards',
178
+ description: 'Sync .equilateral-standards into Rapport',
179
+ steps: [
180
+ { agent: 'PatternHarvestingAgent', method: 'discoverStandards', parallel: false },
181
+ { agent: 'KnowledgeSynthesisAgent', method: 'synthesizeStandards', parallel: false }
182
+ ]
183
+ });
184
+
185
+ console.log(`[RapportOrchestrator] Registered ${this.workflows.size} workflows`);
186
+ }
187
+
188
+ /**
189
+ * Execute a workflow
190
+ */
191
+ async executeWorkflow(workflowName, params = {}) {
192
+ if (!this.workflows.has(workflowName)) {
193
+ throw new Error(`Workflow ${workflowName} not found`);
194
+ }
195
+
196
+ const workflow = this.workflows.get(workflowName);
197
+ const workflowId = `${workflowName}_${Date.now()}`;
198
+
199
+ this.emit('workflow:started', { workflowId, workflow: workflowName, params });
200
+
201
+ try {
202
+ const results = {
203
+ workflowId,
204
+ workflowName,
205
+ steps: [],
206
+ startedAt: new Date().toISOString(),
207
+ status: 'running'
208
+ };
209
+
210
+ // Execute workflow steps sequentially (for now)
211
+ for (const step of workflow.steps) {
212
+ const stepResult = await this.executeWorkflowStep(step, params, workflowId);
213
+ results.steps.push(stepResult);
214
+
215
+ // Fail workflow if critical step fails
216
+ if (!stepResult.success && step.required !== false) {
217
+ results.status = 'failed';
218
+ results.failedAt = step.agent;
219
+ this.emit('workflow:failed', results);
220
+ return results;
221
+ }
222
+ }
223
+
224
+ results.status = 'completed';
225
+ results.completedAt = new Date().toISOString();
226
+
227
+ this.emit('workflow:completed', results);
228
+ return results;
229
+
230
+ } catch (error) {
231
+ this.emit('workflow:failed', { workflowId, error: error.message });
232
+ throw error;
233
+ }
234
+ }
235
+
236
+ /**
237
+ * Execute a single workflow step
238
+ */
239
+ async executeWorkflowStep(step, params, workflowId) {
240
+ const { agent: agentName, method, parallel } = step;
241
+
242
+ this.emit('step:started', { workflowId, agent: agentName, method });
243
+
244
+ try {
245
+ // Get agent instance (lazy load if needed)
246
+ const agent = this.getAgent(agentName);
247
+
248
+ // Execute agent method
249
+ let result;
250
+ if (typeof agent[method] === 'function') {
251
+ result = await agent[method](params);
252
+ } else {
253
+ // Fallback to generic execute method
254
+ result = await agent.execute({ task: method, ...params });
255
+ }
256
+
257
+ this.emit('step:completed', { workflowId, agent: agentName, method, result });
258
+
259
+ return {
260
+ agent: agentName,
261
+ method,
262
+ success: true,
263
+ result,
264
+ completedAt: new Date().toISOString()
265
+ };
266
+
267
+ } catch (error) {
268
+ this.emit('step:failed', { workflowId, agent: agentName, method, error: error.message });
269
+
270
+ return {
271
+ agent: agentName,
272
+ method,
273
+ success: false,
274
+ error: error.message,
275
+ failedAt: new Date().toISOString()
276
+ };
277
+ }
278
+ }
279
+
280
+ /**
281
+ * Start background sync daemon for .equilateral-standards monitoring
282
+ */
283
+ async startBackgroundSync() {
284
+ console.log('[RapportOrchestrator] Starting background sync daemon...');
285
+
286
+ // 1. Initial sync
287
+ await this.syncStandards();
288
+
289
+ // 2. Set up file watcher for .equilateral-standards/
290
+ const standardsPath = path.join(this.config.rapportRoot, this.config.standardsPath);
291
+
292
+ try {
293
+ this.standardsWatcher = watch(standardsPath, { recursive: true }, async (eventType, filename) => {
294
+ if (filename && filename.endsWith('.md')) {
295
+ console.log(`[RapportOrchestrator] Standards change detected: ${filename}`);
296
+ this.emit('standards:changed', { filename, eventType });
297
+
298
+ // Debounce sync to avoid rapid-fire updates
299
+ if (this.syncDebounceTimer) {
300
+ clearTimeout(this.syncDebounceTimer);
301
+ }
302
+
303
+ this.syncDebounceTimer = setTimeout(async () => {
304
+ await this.syncStandards();
305
+ }, 5000); // 5 second debounce
306
+ }
307
+ });
308
+
309
+ console.log('[RapportOrchestrator] File watcher active on:', standardsPath);
310
+ } catch (error) {
311
+ console.warn('[RapportOrchestrator] Could not watch standards directory:', error.message);
312
+ }
313
+
314
+ // 3. Set up periodic sync interval
315
+ this.backgroundJobs.set('standards-sync', setInterval(async () => {
316
+ console.log('[RapportOrchestrator] Running periodic standards sync...');
317
+ await this.syncStandards();
318
+ }, this.config.syncInterval));
319
+ }
320
+
321
+ /**
322
+ * Sync .equilateral-standards into Rapport database
323
+ */
324
+ async syncStandards() {
325
+ try {
326
+ console.log('[RapportOrchestrator] Syncing standards...');
327
+
328
+ const result = await this.executeWorkflow('rapport-sync-standards', {
329
+ standardsPath: path.join(this.config.rapportRoot, this.config.standardsPath)
330
+ });
331
+
332
+ if (result.status === 'completed') {
333
+ this.emit('standards:synced', {
334
+ timestamp: new Date().toISOString(),
335
+ result
336
+ });
337
+ console.log('[RapportOrchestrator] Standards sync completed');
338
+ } else {
339
+ console.warn('[RapportOrchestrator] Standards sync failed:', result);
340
+ }
341
+
342
+ return result;
343
+
344
+ } catch (error) {
345
+ console.error('[RapportOrchestrator] Standards sync error:', error);
346
+ this.emit('standards:sync-failed', { error: error.message });
347
+ }
348
+ }
349
+
350
+ /**
351
+ * Curate a pattern into a standard
352
+ * Main entry point for pattern -> standard promotion
353
+ */
354
+ async curatePattern(patternId, options = {}) {
355
+ console.log(`[RapportOrchestrator] Curating pattern: ${patternId}`);
356
+
357
+ try {
358
+ const result = await this.executeWorkflow('rapport-curate-pattern', {
359
+ patternId,
360
+ ...options
361
+ });
362
+
363
+ if (result.status === 'completed') {
364
+ this.emit('pattern:curated', {
365
+ patternId,
366
+ result
367
+ });
368
+ }
369
+
370
+ return result;
371
+
372
+ } catch (error) {
373
+ console.error('[RapportOrchestrator] Pattern curation failed:', error);
374
+ throw error;
375
+ }
376
+ }
377
+
378
+ /**
379
+ * Validate code against standards
380
+ */
381
+ async validateStandards(codeContext) {
382
+ console.log('[RapportOrchestrator] Validating standards...');
383
+
384
+ try {
385
+ const result = await this.executeWorkflow('rapport-validate-standards', {
386
+ codeContext
387
+ });
388
+
389
+ return result;
390
+
391
+ } catch (error) {
392
+ console.error('[RapportOrchestrator] Standards validation failed:', error);
393
+ throw error;
394
+ }
395
+ }
396
+
397
+ /**
398
+ * Get orchestrator status
399
+ */
400
+ getStatus() {
401
+ return {
402
+ initialized: this.initialized,
403
+ agents: {
404
+ registered: this.agents.size,
405
+ active: Array.from(this.agents.values()).filter(a => a.status === 'active').length,
406
+ list: Array.from(this.agents.keys())
407
+ },
408
+ workflows: {
409
+ registered: this.workflows.size,
410
+ list: Array.from(this.workflows.keys())
411
+ },
412
+ backgroundSync: {
413
+ enabled: this.config.enableBackgroundSync,
414
+ watching: !!this.standardsWatcher,
415
+ jobs: Array.from(this.backgroundJobs.keys())
416
+ }
417
+ };
418
+ }
419
+
420
+ /**
421
+ * Shutdown orchestrator and cleanup
422
+ */
423
+ async shutdown() {
424
+ console.log('[RapportOrchestrator] Shutting down...');
425
+
426
+ // Close file watcher
427
+ if (this.standardsWatcher) {
428
+ this.standardsWatcher.close();
429
+ }
430
+
431
+ // Clear background jobs
432
+ for (const [name, job] of this.backgroundJobs) {
433
+ clearInterval(job);
434
+ console.log(`[RapportOrchestrator] Stopped background job: ${name}`);
435
+ }
436
+
437
+ this.backgroundJobs.clear();
438
+ this.agents.clear();
439
+ this.workflows.clear();
440
+
441
+ this.emit('shutdown');
442
+ console.log('[RapportOrchestrator] Shutdown complete');
443
+ }
444
+ }
445
+
446
+ module.exports = RapportOrchestrator;