@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,494 @@
1
+ # Rapport Claude Code Hooks
2
+
3
+ **Phase 5: Claude Code Integration**
4
+
5
+ This directory contains hooks for integrating Rapport with Claude Code, enabling real-time context injection and pattern harvesting during development sessions.
6
+
7
+ ---
8
+
9
+ ## Available Hooks
10
+
11
+ ### 1. `session-start.js` - Context Injection
12
+
13
+ **Purpose**: Inject ONLY relevant standards and team patterns at session start
14
+
15
+ **Execution**: Called when Claude Code session begins
16
+
17
+ **Performance**: < 500ms target (achieves ~200ms)
18
+
19
+ **Output**: Formatted markdown context with:
20
+ - Project name and team members
21
+ - Top 10 most relevant standards
22
+ - High-correlation team patterns
23
+ - Recent team learning (last 7 days)
24
+
25
+ **Usage**:
26
+ ```bash
27
+ # Test directly
28
+ node hooks/session-start.js
29
+
30
+ # Via npm script
31
+ npm run test:session-start
32
+ ```
33
+
34
+ **Configuration**:
35
+ ```json
36
+ {
37
+ "claudeCode": {
38
+ "hooks": {
39
+ "sessionStart": "hooks/session-start.js"
40
+ }
41
+ }
42
+ }
43
+ ```
44
+
45
+ ### 2. `pre-compact.js` - Pattern Harvesting
46
+
47
+ **Purpose**: Harvest patterns and validate compliance before conversation compaction
48
+
49
+ **Execution**: Called before Claude Code compacts conversation history
50
+
51
+ **Output**: JSON summary with:
52
+ - Patterns detected count
53
+ - Violations found
54
+ - Patterns reinforced
55
+ - Promotion candidates
56
+
57
+ **Usage**:
58
+ ```bash
59
+ # Test directly
60
+ node hooks/pre-compact.js '{"transcript":"Created handler with wrapHandler"}'
61
+
62
+ # Via npm script
63
+ npm run test:pre-compact
64
+ ```
65
+
66
+ **Configuration**:
67
+ ```json
68
+ {
69
+ "claudeCode": {
70
+ "hooks": {
71
+ "preCompact": "hooks/pre-compact.js"
72
+ }
73
+ }
74
+ }
75
+ ```
76
+
77
+ ---
78
+
79
+ ## How Hooks Work
80
+
81
+ ### SessionStart Flow
82
+
83
+ ```
84
+ 1. Claude Code calls session-start.js
85
+ 2. Hook checks if Rapport configured
86
+ 3. If not configured → return empty string (instant)
87
+ 4. If configured:
88
+ a. Ensure standards ingested (cached check)
89
+ b. Detect project context
90
+ c. Identify relevant standards (top 10)
91
+ d. Load team patterns (correlation > 0.7)
92
+ e. Format context injection
93
+ 5. Return formatted context to Claude Code
94
+ 6. Claude Code injects into system prompt
95
+ ```
96
+
97
+ ### PreCompact Flow
98
+
99
+ ```
100
+ 1. Claude Code calls pre-compact.js with session transcript
101
+ 2. Hook checks if Rapport configured
102
+ 3. If not configured → return skipped status
103
+ 4. If configured:
104
+ a. Extract file changes from transcript
105
+ b. Detect patterns in changed files
106
+ c. Validate patterns against standards
107
+ d. Record violations for team learning
108
+ e. Reinforce valid patterns
109
+ f. Check for promotion candidates
110
+ 5. Return summary to Claude Code
111
+ ```
112
+
113
+ ---
114
+
115
+ ## Performance Characteristics
116
+
117
+ ### SessionStart
118
+
119
+ | Metric | Target | Achieved |
120
+ |--------|--------|----------|
121
+ | First run (with ingestion) | < 1000ms | ~500ms |
122
+ | Subsequent runs (cached) | < 500ms | ~200ms |
123
+ | Unconfigured project | < 50ms | ~10ms |
124
+
125
+ **Optimizations**:
126
+ - Fast bail if Rapport not configured
127
+ - Cached standards ingestion check
128
+ - Limited to top 10 standards
129
+ - Efficient project structure analysis
130
+ - No deep file content parsing
131
+
132
+ ### PreCompact
133
+
134
+ | Metric | Target | Achieved |
135
+ |--------|--------|----------|
136
+ | Pattern detection | < 500ms | ~200-300ms |
137
+ | Validation | < 200ms | ~100-150ms |
138
+ | Total execution | < 1000ms | ~300-500ms |
139
+
140
+ **Optimizations**:
141
+ - Parallel pattern validation
142
+ - Cached database queries
143
+ - Simple regex-based pattern detection
144
+ - Graceful degradation on errors
145
+
146
+ ---
147
+
148
+ ## Graceful Degradation
149
+
150
+ Both hooks are designed to **never block Claude Code sessions**:
151
+
152
+ 1. **Configuration Missing**: Return empty/skipped
153
+ 2. **Database Unavailable**: Return cached data
154
+ 3. **Standards Not Ingested**: Skip validation
155
+ 4. **Hook Execution Error**: Log and return empty
156
+ 5. **Timeout**: Return partial results
157
+
158
+ **Example**:
159
+ ```javascript
160
+ try {
161
+ const context = await injectContext();
162
+ return context;
163
+ } catch (error) {
164
+ console.error('[Rapport] Hook error (non-fatal):', error.message);
165
+ return ''; // Don't block session
166
+ }
167
+ ```
168
+
169
+ ---
170
+
171
+ ## Testing
172
+
173
+ ### Comprehensive Test Suite
174
+
175
+ ```bash
176
+ # Run all tests
177
+ npm run test:hooks
178
+
179
+ # Test specific hooks
180
+ npm run test:session-start
181
+ npm run test:pre-compact
182
+
183
+ # Performance benchmark
184
+ npm run test:benchmark
185
+ ```
186
+
187
+ ### Test Script: `scripts/test-claude-hooks.js`
188
+
189
+ **Features**:
190
+ - SessionStart hook testing
191
+ - PreCompact hook testing
192
+ - RapportClient integration testing
193
+ - RelevanceDetector testing
194
+ - Performance benchmarking (5 iterations)
195
+
196
+ **Example Output**:
197
+ ```
198
+ === Performance Benchmark ===
199
+
200
+ Iteration 1: 245ms
201
+ Iteration 2: 198ms
202
+ Iteration 3: 187ms
203
+ Iteration 4: 192ms
204
+ Iteration 5: 201ms
205
+
206
+ Results:
207
+ Average: 204.60ms
208
+ Min: 187ms
209
+ Max: 245ms
210
+ Target: 500ms
211
+ ✓ PASSED
212
+ ```
213
+
214
+ ---
215
+
216
+ ## Configuration
217
+
218
+ ### Required Files
219
+
220
+ 1. **`.rapport/config.json`**: Project configuration
221
+ ```json
222
+ {
223
+ "projectId": "project_abc123",
224
+ "projectName": "my-project",
225
+ "collaborators": [...]
226
+ }
227
+ ```
228
+
229
+ 2. **`.equilateral-standards/`**: Symlink to standards repo
230
+ ```bash
231
+ ln -s ../equilateral-standards .equilateral-standards
232
+ ```
233
+
234
+ 3. **`package.json`**: Hook configuration
235
+ ```json
236
+ {
237
+ "claudeCode": {
238
+ "hooks": {
239
+ "sessionStart": "hooks/session-start.js",
240
+ "preCompact": "hooks/pre-compact.js"
241
+ }
242
+ }
243
+ }
244
+ ```
245
+
246
+ ### Optional Configuration
247
+
248
+ ```json
249
+ {
250
+ "claudeCode": {
251
+ "config": {
252
+ "standardsPath": ".equilateral-standards",
253
+ "maxContextLength": 50000,
254
+ "maxStandards": 10,
255
+ "sessionStartTimeout": 500
256
+ }
257
+ }
258
+ }
259
+ ```
260
+
261
+ ---
262
+
263
+ ## Example Outputs
264
+
265
+ ### SessionStart Context
266
+
267
+ ```markdown
268
+ # Rapport Context - my-project
269
+
270
+ ## Team
271
+ - Jim Ford (jim@equilateral.ai)
272
+ - Team Member (member@company.com)
273
+
274
+ ## Relevant Standards
275
+
276
+ ### Lambda Database Connection
277
+ **Category**: serverless-saas-aws
278
+ **Rule**: NEVER use connection pools in Lambda functions
279
+
280
+ **Example**:
281
+ ```javascript
282
+ let client;
283
+ async function getClient() {
284
+ if (!client) {
285
+ client = new Client({
286
+ connectionString: process.env.DB_CONNECTION_STRING
287
+ });
288
+ await client.connect();
289
+ }
290
+ return client;
291
+ }
292
+ ```
293
+
294
+ **Anti-patterns**:
295
+ - ❌ Using new Pool() in Lambda functions
296
+ - ❌ Fetching SSM parameters at runtime
297
+
298
+ ---
299
+
300
+ ### API Gateway CORS Standards
301
+ **Category**: serverless-saas-aws
302
+ **Rule**: NEVER use DefaultAuthorizer (breaks CORS preflight)
303
+
304
+ **Example**:
305
+ ```yaml
306
+ GetUserFunction:
307
+ Type: AWS::Serverless::Function
308
+ Properties:
309
+ Auth:
310
+ Authorizer: MyAuthorizer
311
+ ```
312
+
313
+ **Anti-patterns**:
314
+ - ❌ DefaultAuthorizer in SAM templates
315
+
316
+ ## Team Patterns
317
+
318
+ ### wrapHandler Usage
319
+ **Correlation**: 95%
320
+ **Usage**: 42 times across 5 projects
321
+ **Rule**: Always use wrapHandler for Lambda functions
322
+
323
+ ---
324
+
325
+ *Context provided by Rapport - mindmeld.dev*
326
+ ```
327
+
328
+ ### PreCompact Summary
329
+
330
+ ```json
331
+ {
332
+ "patternsDetected": 5,
333
+ "violations": 1,
334
+ "reinforced": 4,
335
+ "promotionCandidates": 0,
336
+ "elapsed": 287
337
+ }
338
+ ```
339
+
340
+ ---
341
+
342
+ ## Troubleshooting
343
+
344
+ ### Hook Not Executing
345
+
346
+ **Symptoms**: Context not appearing in Claude Code
347
+
348
+ **Solutions**:
349
+ 1. Check `package.json` has correct hook paths
350
+ 2. Verify hooks are executable: `chmod +x hooks/*.js`
351
+ 3. Ensure `.rapport/config.json` exists
352
+ 4. Check Claude Code logs for errors
353
+
354
+ ### Slow Performance
355
+
356
+ **Symptoms**: SessionStart takes > 1 second
357
+
358
+ **Solutions**:
359
+ 1. Run `npm run test:benchmark` to measure
360
+ 2. Check if standards need ingestion
361
+ 3. Verify database connection is fast
362
+ 4. Reduce `maxStandards` in config
363
+
364
+ ### No Standards Shown
365
+
366
+ **Symptoms**: Context empty or minimal
367
+
368
+ **Solutions**:
369
+ 1. Verify `.equilateral-standards/` exists
370
+ 2. Check standards ingestion: `SELECT COUNT(*) FROM rapport.standards_patterns`
371
+ 3. Test RelevanceDetector: `npm run test:hooks --relevance`
372
+ 4. Verify project characteristics detected
373
+
374
+ ### Violations Not Detected
375
+
376
+ **Symptoms**: PreCompact always shows 0 violations
377
+
378
+ **Solutions**:
379
+ 1. Check standards_patterns table populated
380
+ 2. Verify PatternValidator working: `npm run test:hooks --client`
381
+ 3. Check session transcript format
382
+ 4. Verify pattern detection logic
383
+
384
+ ---
385
+
386
+ ## Architecture
387
+
388
+ ```
389
+ hooks/
390
+ ├── session-start.js
391
+ │ ├── injectContext()
392
+ │ ├── checkRapportConfiguration()
393
+ │ └── formatContextInjection()
394
+
395
+ └── pre-compact.js
396
+ ├── harvestPatterns()
397
+ ├── validatePatterns()
398
+ └── checkPromotionCandidates()
399
+
400
+ ↓ Uses ↓
401
+
402
+ src/index.js (RapportClient)
403
+ ├── ensureStandardsIngested()
404
+ ├── getRelevantStandards()
405
+ ├── detectPatternsFromSession()
406
+ ├── validatePattern()
407
+ ├── recordViolation()
408
+ └── reinforcePattern()
409
+
410
+ ↓ Uses ↓
411
+
412
+ src/core/
413
+ ├── RelevanceDetector.js
414
+ │ └── detectRelevantStandards()
415
+ ├── PatternValidator.js
416
+ │ └── validatePattern()
417
+ └── StandardsIngestion.js
418
+ └── ingestEquilateralStandards()
419
+ ```
420
+
421
+ ---
422
+
423
+ ## Integration Points
424
+
425
+ ### Claude Code
426
+
427
+ **SessionStart**:
428
+ - Called at session initialization
429
+ - Receives context string
430
+ - Injects into system prompt
431
+
432
+ **PreCompact**:
433
+ - Called before compaction
434
+ - Receives session transcript JSON
435
+ - Processes results asynchronously
436
+
437
+ ### Rapport Database
438
+
439
+ **Tables Used**:
440
+ - `rapport.standards_patterns` - Ingested standards
441
+ - `rapport.pattern_usage` - Pattern reinforcement
442
+ - `rapport.projects` - Project configuration
443
+
444
+ ### .equilateral-standards
445
+
446
+ **Read Operations**:
447
+ - Standards markdown files
448
+ - Anti-pattern examples
449
+ - Cost impact data
450
+ - Enforcement rules
451
+
452
+ ---
453
+
454
+ ## Best Practices
455
+
456
+ ### Do's
457
+
458
+ ✅ Keep SessionStart under 500ms
459
+ ✅ Always gracefully degrade on errors
460
+ ✅ Limit context to top 10 standards
461
+ ✅ Use cached ingestion checks
462
+ ✅ Log timing information
463
+
464
+ ### Don'ts
465
+
466
+ ❌ Never block Claude Code session
467
+ ❌ Don't fetch all standards
468
+ ❌ Avoid deep file content parsing
469
+ ❌ Don't make network calls during hooks
470
+ ❌ Don't fail on missing configuration
471
+
472
+ ---
473
+
474
+ ## Future Enhancements
475
+
476
+ 1. **Dynamic Standard Selection**: ML-based relevance scoring
477
+ 2. **User Preferences**: Customize standard visibility
478
+ 3. **Context Caching**: Redis-based cache layer
479
+ 4. **Incremental Learning**: Real-time pattern updates
480
+ 5. **Cross-Project Insights**: Share patterns across projects
481
+
482
+ ---
483
+
484
+ ## Support
485
+
486
+ **Documentation**: `/Users/jamesford/Source/rapport/docs/PHASE_5_CLAUDE_CODE_INTEGRATION.md`
487
+ **Test Suite**: `npm run test:hooks`
488
+ **Issues**: Contact jim@equilateral.ai
489
+
490
+ ---
491
+
492
+ **Version**: 3.0.0
493
+ **Status**: ✅ Production Ready
494
+ **Last Updated**: 2025-12-20