fraim-framework 2.0.26 → 2.0.30

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 (104) hide show
  1. package/.github/workflows/deploy-fraim.yml +1 -1
  2. package/dist/registry/scripts/build-scripts-generator.js +205 -0
  3. package/dist/registry/scripts/cleanup-branch.js +258 -0
  4. package/dist/registry/scripts/evaluate-code-quality.js +66 -0
  5. package/dist/registry/scripts/exec-with-timeout.js +142 -0
  6. package/dist/registry/scripts/fraim-config.js +61 -0
  7. package/dist/registry/scripts/generate-engagement-emails.js +630 -0
  8. package/dist/registry/scripts/generic-issues-api.js +100 -0
  9. package/dist/registry/scripts/newsletter-helpers.js +731 -0
  10. package/dist/registry/scripts/openapi-generator.js +664 -0
  11. package/dist/registry/scripts/performance/profile-server.js +390 -0
  12. package/dist/registry/scripts/run-thank-you-workflow.js +92 -0
  13. package/dist/registry/scripts/send-newsletter-simple.js +85 -0
  14. package/dist/registry/scripts/send-thank-you-emails.js +54 -0
  15. package/dist/registry/scripts/validate-openapi-limits.js +311 -0
  16. package/dist/registry/scripts/validate-test-coverage.js +262 -0
  17. package/dist/registry/scripts/verify-test-coverage.js +66 -0
  18. package/dist/src/cli/commands/init.js +14 -12
  19. package/dist/src/cli/commands/sync.js +19 -2
  20. package/dist/src/cli/fraim.js +24 -22
  21. package/dist/src/cli/setup/first-run.js +13 -6
  22. package/dist/src/fraim/config-loader.js +0 -8
  23. package/dist/src/fraim/db-service.js +26 -15
  24. package/dist/src/fraim/issues.js +67 -0
  25. package/dist/src/fraim/setup-wizard.js +1 -69
  26. package/dist/src/fraim/types.js +0 -11
  27. package/dist/src/fraim-mcp-server.js +272 -18
  28. package/dist/src/utils/git-utils.js +1 -1
  29. package/dist/src/utils/version-utils.js +32 -0
  30. package/dist/tests/debug-tools.js +79 -0
  31. package/dist/tests/esm-compat.js +11 -0
  32. package/dist/tests/test-chalk-esm-issue.js +159 -0
  33. package/dist/tests/test-chalk-real-world.js +265 -0
  34. package/dist/tests/test-chalk-regression.js +327 -0
  35. package/dist/tests/test-chalk-resolution-issue.js +304 -0
  36. package/dist/tests/test-cli.js +0 -2
  37. package/dist/tests/test-fraim-install-chalk-issue.js +254 -0
  38. package/dist/tests/test-fraim-issues.js +59 -0
  39. package/dist/tests/test-genericization.js +1 -3
  40. package/dist/tests/test-mcp-connection.js +166 -0
  41. package/dist/tests/test-mcp-issue-integration.js +144 -0
  42. package/dist/tests/test-mcp-lifecycle-methods.js +312 -0
  43. package/dist/tests/test-node-compatibility.js +71 -0
  44. package/dist/tests/test-npm-install.js +66 -0
  45. package/dist/tests/test-npm-resolution-diagnostic.js +140 -0
  46. package/dist/tests/test-session-rehydration.js +145 -0
  47. package/dist/tests/test-standalone.js +2 -8
  48. package/dist/tests/test-sync-version-update.js +93 -0
  49. package/dist/tests/test-telemetry.js +190 -0
  50. package/package.json +10 -8
  51. package/registry/agent-guardrails.md +62 -54
  52. package/registry/rules/agent-success-criteria.md +52 -0
  53. package/registry/rules/agent-testing-guidelines.md +502 -502
  54. package/registry/rules/communication.md +121 -121
  55. package/registry/rules/continuous-learning.md +54 -54
  56. package/registry/rules/ephemeral-execution.md +10 -5
  57. package/registry/rules/hitl-ppe-record-analysis.md +302 -302
  58. package/registry/rules/local-development.md +251 -251
  59. package/registry/rules/software-development-lifecycle.md +104 -104
  60. package/registry/rules/successful-debugging-patterns.md +482 -478
  61. package/registry/rules/telemetry.md +67 -0
  62. package/registry/scripts/build-scripts-generator.ts +216 -215
  63. package/registry/scripts/cleanup-branch.ts +303 -284
  64. package/registry/scripts/code-quality-check.sh +559 -559
  65. package/registry/scripts/detect-tautological-tests.sh +38 -38
  66. package/registry/scripts/evaluate-code-quality.ts +1 -1
  67. package/registry/scripts/generate-engagement-emails.ts +744 -744
  68. package/registry/scripts/generic-issues-api.ts +110 -150
  69. package/registry/scripts/newsletter-helpers.ts +874 -874
  70. package/registry/scripts/openapi-generator.ts +695 -693
  71. package/registry/scripts/performance/profile-server.ts +5 -3
  72. package/registry/scripts/prep-issue.sh +468 -455
  73. package/registry/scripts/validate-openapi-limits.ts +366 -365
  74. package/registry/scripts/validate-test-coverage.ts +280 -280
  75. package/registry/scripts/verify-pr-comments.sh +70 -70
  76. package/registry/scripts/verify-test-coverage.ts +1 -1
  77. package/registry/templates/bootstrap/ARCHITECTURE-TEMPLATE.md +53 -53
  78. package/registry/templates/evidence/Implementation-BugEvidence.md +85 -85
  79. package/registry/templates/evidence/Implementation-FeatureEvidence.md +120 -120
  80. package/registry/templates/marketing/HBR-ARTICLE-TEMPLATE.md +66 -0
  81. package/registry/workflows/bootstrap/create-architecture.md +2 -2
  82. package/registry/workflows/bootstrap/evaluate-code-quality.md +3 -3
  83. package/registry/workflows/bootstrap/verify-test-coverage.md +2 -2
  84. package/registry/workflows/customer-development/insight-analysis.md +156 -156
  85. package/registry/workflows/customer-development/interview-preparation.md +421 -421
  86. package/registry/workflows/customer-development/strategic-brainstorming.md +146 -146
  87. package/registry/workflows/customer-development/thank-customers.md +193 -191
  88. package/registry/workflows/customer-development/weekly-newsletter.md +362 -352
  89. package/registry/workflows/improve-fraim/contribute.md +32 -0
  90. package/registry/workflows/improve-fraim/file-issue.md +32 -0
  91. package/registry/workflows/marketing/hbr-article.md +73 -0
  92. package/registry/workflows/performance/analyze-performance.md +63 -59
  93. package/registry/workflows/product-building/design.md +3 -2
  94. package/registry/workflows/product-building/implement.md +4 -3
  95. package/registry/workflows/product-building/prep-issue.md +28 -17
  96. package/registry/workflows/product-building/resolve.md +3 -2
  97. package/registry/workflows/product-building/retrospect.md +3 -2
  98. package/registry/workflows/product-building/spec.md +5 -4
  99. package/registry/workflows/product-building/test.md +3 -2
  100. package/registry/workflows/quality-assurance/iterative-improvement-cycle.md +562 -562
  101. package/registry/workflows/replicate/website-discovery-analysis.md +3 -3
  102. package/registry/workflows/reviewer/review-implementation-vs-design-spec.md +632 -632
  103. package/registry/workflows/reviewer/review-implementation-vs-feature-spec.md +669 -669
  104. package/tsconfig.json +2 -1
@@ -1,478 +1,482 @@
1
- # Successful Debugging Patterns for Complex Integrations
2
-
3
- ## INTENT
4
- To provide agents with proven patterns for debugging complex integrations, especially OAuth flows, API integrations, and multi-layer systems that require both UI automation and backend validation.
5
-
6
- ## PRINCIPLES
7
- - **Multi-Layer Validation**: Always validate at UI, API, and Database layers
8
- - **Iterative Enhancement**: Continuously refine approaches based on real-time feedback
9
- - **Appropriate Timeout Management**: Use different timeouts for different operation types
10
- - **Real-Time Monitoring**: Monitor logs and database state during complex operations
11
- - **Visual Debugging**: Use screenshots and visual feedback to understand UI state
12
- - **Prefer User-Visible Truth**: For UI flows, validate what the user sees/does (DOM + persisted state), not the order/timing of background requests
13
-
14
- ## CORE DEBUGGING PATTERN
15
-
16
- ### The "Repro -> Analyze → Implement → Test → Validate → Document → VERIFY COMPLETENESS" Pattern
17
-
18
- ```
19
- 1. REPRO: Reproduce the issue in a controlled environment. This can be manual using Playwright for UI issues, Curl for API issues, etc; or it can be through existing test cases. Run only the test case that fails. Mark it with tag `failing`, then run `npm run test-failing <test-suite>`
20
- 2. ANALYZE: Use tools to examine actual codebase (grep_search, Read)
21
- 3. IMPLEMENT: Make targeted changes based on real code analysis
22
- 4. TEST: Run the single test and ensure it passes. Then run comprehensive tests for evidence
23
- 5. VALIDATE: Verify functionality works end-to-end
24
- 6. DOCUMENT: Create test cases that replicate the flow and validate end state
25
- 7. VERIFY COMPLETENESS: Run comprehensive verification checklist (NEW CRITICAL STEP)
26
- 8. ITERATE: Refine based on real feedback and evidence
27
- ```
28
-
29
- ### **NEW: Mandatory Completeness Verification Pattern**
30
-
31
- Before declaring ANY work complete, **MUST** follow this systematic verification:
32
-
33
- ```bash
34
- # Step 1: Compilation Verification
35
- timeout 30s npx tsc --noEmit --skipLibCheck
36
- # MUST show 0 errors - fix any errors before proceeding
37
-
38
- # Step 2: Build Verification (if build script exists)
39
- timeout 60s npm run build
40
- # MUST complete successfully
41
-
42
- # Step 3: Comprehensive Search Verification
43
- # Search for ALL possible references using multiple patterns:
44
- grep_search --SearchPath . --Query "OldClassName" --MatchPerLine true
45
- grep_search --SearchPath . --Query "import.*OldClassName" --IsRegex true --MatchPerLine true
46
- grep_search --SearchPath . --Query "old-filename" --MatchPerLine true
47
- grep_search --SearchPath . --Query "oldMethodName" --MatchPerLine true
48
-
49
- # Step 4: Test Execution with Timeout
50
- timeout 30s npx tsx --test --test-reporter tap test-relevant-file.ts
51
-
52
- # Step 5: End-to-End Functionality Check
53
- # Verify main application workflows still work
54
- ```
55
-
56
- ### Enhanced Multi-Layer Debugging Pattern
57
-
58
- ```
59
- 1. Code Analysis (grep_search, find_by_name to understand current state)
60
- 2. UI Action (Playwright automation with screenshots)
61
- 3. Database Check (verify persistence and state changes)
62
- 4. Log Analysis (check server logs for errors/success)
63
- 5. API Testing (verify endpoints work correctly)
64
- 6. Integration Testing (test full workflows)
65
- 7. Evidence Collection (screenshots, logs, test results)
66
- 8. Refine Approach (improve based on findings)
67
- 9. Repeat (iterate until success with evidence)
68
- ```
69
-
70
- ## UI DEBUGGING WITH PLAYWRIGHT (AND PLAYWRIGHT MCP)
71
-
72
- When the bug is user-visible (empty UI, wrong modal opens, buttons do nothing), treat the browser as the source of truth.
73
-
74
- ### Evidence-first UI debugging loop
75
- 1. **Reproduce in the browser** (manual or Playwright).
76
- 2. **Capture evidence**:
77
- - Browser console output (errors + warnings)
78
- - DOM snapshot (preferred) and/or screenshot
79
- - The exact URL + the exact click sequence
80
- 3. **Instrument to make failures obvious**:
81
- - Log `requestfailed` URLs and error text
82
- - Log HTTP >= 400 responses (method + URL)
83
- 4. **Fix the root cause** (DOM wiring, event binding, auth headers, data mapping).
84
- 5. **Re-run the same click path** to prove the UI behaves correctly.
85
-
86
- ### Playwright MCP usage (required when asked to "pop the browser")
87
- If you are asked to confirm a fix visually:
88
- - Use Playwright MCP tools to `navigate`, `click`, and capture a `browser_snapshot`.
89
- - Validate the specific UI element/state changed (e.g., form opens, list renders, “No meetings” disappears).
90
-
91
- ### E2E test stabilization checklist (when tests time out)
92
- - Prefer waiting on UI state (`waitForSelector`, text visible, DOM class changes) over `waitForResponse` predicates.
93
- - Avoid coupling to background requests that can vary (telemetry, analysis triggers, service worker, polling).
94
- - If UI is optional/feature-flagged, **do not re-enable product UI just to satisfy tests**; gate the test sub-flow or validate via API/DB.
95
- - Ensure the server is up (or auto-start it) and clean up reliably (use `after()` hooks).
96
-
97
- ## SPECIFIC SCRIPTS AND COMMANDS
98
-
99
- ### 1. Long-Running Server Management
100
-
101
- **Start Server with Proper Timeout:**
102
- ```bash
103
- # Use 1-hour timeout for server processes
104
- npx tsx .ai-agents/scripts/exec-with-timeout.ts --timeout 3600 -- npm run dev &
105
- ```
106
-
107
- **Monitor Server Logs in Real-Time:**
108
- ```bash
109
- # Real-time monitoring
110
- npx tsx .ai-agents/scripts/exec-with-timeout.ts --timeout 30 -- tail -f server.log
111
-
112
- # Historical log analysis
113
- npx tsx .ai-agents/scripts/exec-with-timeout.ts --timeout 30 -- tail -100 server.log
114
-
115
- # Look for errors in logs
116
- npx tsx .ai-agents/scripts/exec-with-timeout.ts --timeout 30 -- grep error server.log
117
- ```
118
-
119
- **Check Server Status:**
120
- ```bash
121
- # Verify server is running on correct port
122
- npx tsx .ai-agents/scripts/exec-with-timeout.ts --timeout 30 -- netstat -ano | findstr :<port>
123
-
124
- # Test API endpoints
125
- npx tsx .ai-agents/scripts/exec-with-timeout.ts --timeout 30 -- curl -s "http://localhost:<port>/<endpoint>"
126
- ```
127
-
128
- ### 2. Code Analysis and Understanding
129
-
130
- **CRITICAL: Always Analyze Before Implementing**
131
- Before making any changes, use tools to understand the current codebase:
132
-
133
- ```bash
134
- # Find all files that import a specific module
135
- grep_search --SearchPath src --Query "import.*GmailService" --IsRegex true --MatchPerLine true
136
-
137
- # Find files by pattern
138
- find_by_name --SearchDirectory src --Pattern "*email*" --Type file
139
-
140
- # Read specific files to understand implementation
141
- Read --file_path src/email/email-service.ts
142
- ```
143
-
144
- **Pattern Analysis Requirements:**
145
- 1. **Examine existing patterns** in the codebase (e.g., CalendarService pattern)
146
- 2. **Use grep_search** to find all dependencies and usage
147
- 3. **Read actual implementations** to understand current architecture
148
- 4. **Document findings** with real code examples and line numbers
149
-
150
- ### 3. Playwright UI Automation with Visual Debugging
151
-
152
- **IMPORTANT: Tool Troubleshooting Pattern**
153
- When MCP Playwright tools fail with errors like `TypeError: (0 , import_server2.firstRootPath) is not a function`:
154
-
155
- 1. **Check for existing working Playwright tests** in the project
156
- 2. **Use direct Playwright library** instead of MCP tools
157
- 3. **Look for test files** like `test-dashboard-ui.ts`, `test-hitl-ui.ts` as templates
158
- 4. **Create custom test scripts** using the direct library approach
159
-
160
- **Basic Playwright Script Template:**
161
- ```typescript
162
- import { chromium } from 'playwright';
163
-
164
- async function debugUIFlow() {
165
- const browser = await chromium.launch({
166
- headless: false,
167
- slowMo: 2000 // Human-like delays
168
- });
169
-
170
- try {
171
- const page = await browser.newPage();
172
-
173
- // Step 1: Navigate
174
- await page.goto(targetUrl);
175
- await page.waitForLoadState('networkidle');
176
-
177
- // Step 2: Take screenshot for debugging
178
- await page.screenshot({ path: 'debug-step-1.png' });
179
- console.log('📸 Screenshot saved: debug-step-1.png');
180
-
181
- // Step 3: Perform action
182
- await page.fill('input[type="email"]', 'test@example.com');
183
- await page.click('button:has-text("Next")');
184
-
185
- // Step 4: Take another screenshot
186
- await page.screenshot({ path: 'debug-step-2.png' });
187
- console.log('📸 Screenshot saved: debug-step-2.png');
188
-
189
- // Step 5-N: Iterate on above until scenario is fully validated
190
-
191
-
192
- } catch (error) {
193
- console.error('❌ UI flow failed:', error);
194
- await page.screenshot({ path: 'error-state.png' });
195
- } finally {
196
- await browser.close();
197
- }
198
- }
199
- ```
200
-
201
- **Advanced Playwright with Multiple Button Selectors:**
202
- ```typescript
203
- // Look for multiple possible button selectors
204
- const buttonSelectors = [
205
- 'button:has-text("Continue")',
206
- 'button:has-text("Allow")',
207
- 'button:has-text("Accept")',
208
- 'button:has-text("Authorize")',
209
- 'button[type="submit"]',
210
- 'button[jsname="LgbsSe"]:has-text("Continue")'
211
- ];
212
-
213
- let buttonClicked = false;
214
- for (const selector of buttonSelectors) {
215
- try {
216
- const button = await page.waitForSelector(selector, { timeout: 3000 });
217
- if (button && await button.isVisible()) {
218
- console.log(`🎯 Clicking button: ${selector}`);
219
- await button.click();
220
- buttonClicked = true;
221
- break;
222
- }
223
- } catch (e) {
224
- // Continue to next selector
225
- }
226
- }
227
- ```
228
-
229
- ### 3. Database Validation Scripts
230
-
231
- **MongoDB Token Validation:**
232
- ```typescript
233
- const { DatabaseFactory } = require('./src/databases/database-factory');
234
-
235
- async function checkDatabaseState() {
236
- console.log('🔍 Checking database state...');
237
- const dbService = await DatabaseFactory.createCalendarDatabaseService();
238
- await dbService.initialize();
239
-
240
- try {
241
- // Check for tokens
242
- const tokens = await dbService.loadCalendarTokens('primary');
243
- console.log('📋 Tokens found:', !!tokens);
244
-
245
- // Check for calendars
246
- const calendars = await dbService.getAllCalendars();
247
- console.log('📅 Calendars found:', calendars.length);
248
-
249
- // Check for specific data
250
- const credentials = await dbService.loadCredential('APP_CLIENT_ID');
251
- console.log('🔑 Credentials found:', !!credentials);
252
-
253
- } catch (error) {
254
- console.error('❌ Database check failed:', error);
255
- } finally {
256
- await dbService.close();
257
- }
258
- }
259
- ```
260
-
261
- **API Endpoint Testing:**
262
- ```typescript
263
- async function testAPIEndpoints() {
264
- const baseUrl = 'http://localhost:8333';
265
-
266
- // Test calendar API
267
- try {
268
- const response = await fetch(`${baseUrl}/calendar/events?timerange_start=2024-01-01T00:00:00.000Z&timerange_end=2024-01-02T00:00:00.000Z`);
269
- const data = await response.json();
270
- console.log('📅 Calendar API:', response.status, data);
271
- } catch (error) {
272
- console.error('❌ Calendar API failed:', error);
273
- }
274
-
275
- // Test conversation API
276
- try {
277
- const response = await fetch(`${baseUrl}/conversation/threads`);
278
- const data = await response.json();
279
- console.log('💬 Conversation API:', response.status, data);
280
- } catch (error) {
281
- console.error('❌ Conversation API failed:', error);
282
- }
283
- }
284
- ```
285
-
286
- ### 4. OAuth Flow Debugging Scripts
287
-
288
- **Complete OAuth Flow with Debugging:**
289
- ```typescript
290
- async function debugOAuthFlow() {
291
- const browser = await chromium.launch({ headless: false, slowMo: 3000 });
292
-
293
- try {
294
- const page = await browser.newPage();
295
- const oauthUrl = 'https://accounts.google.com/o/oauth2/v2/auth?client_id=...';
296
-
297
- // Step 1: Navigate and take screenshot
298
- await page.goto(oauthUrl);
299
- await page.waitForLoadState('networkidle');
300
- await page.screenshot({ path: 'oauth-step-1.png' });
301
-
302
- // Step 2: Email
303
- await page.fill('input[type="email"]', 'test@example.com');
304
- await page.click('button:has-text("Next")');
305
- await page.screenshot({ path: 'oauth-step-2.png' });
306
-
307
- // Step 3: Password
308
- await page.waitForSelector('input[type="password"]');
309
- await page.fill('input[type="password"]', 'password');
310
- await page.click('button:has-text("Next")');
311
- await page.screenshot({ path: 'oauth-step-3.png' });
312
-
313
- // Step 4: Consent page
314
- await page.waitForLoadState('networkidle');
315
- await page.screenshot({ path: 'consent-page.png' });
316
-
317
- // Step 5: Click continue with multiple selectors
318
- const continueSelectors = [
319
- 'button:has-text("Continue")',
320
- 'button:has-text("Allow")',
321
- 'button[type="submit"]'
322
- ];
323
-
324
- for (const selector of continueSelectors) {
325
- try {
326
- const button = await page.waitForSelector(selector, { timeout: 3000 });
327
- if (button && await button.isVisible()) {
328
- await button.click();
329
- break;
330
- }
331
- } catch (e) {}
332
- }
333
-
334
- // Step 6: Wait for callback
335
- await page.waitForURL('**/oauth/callback**', { timeout: 20000 });
336
- console.log('✅ OAuth flow completed!');
337
-
338
- } catch (error) {
339
- console.error(' OAuth flow failed:', error);
340
- await page.screenshot({ path: 'oauth-error.png' });
341
- } finally {
342
- await browser.close();
343
- }
344
- }
345
- ```
346
-
347
- ### 5. Timeout Management Commands
348
-
349
- **CRITICAL: Always Use Timeouts for Test Execution**
350
- Following the established pattern from memory, ALWAYS use timeout commands to prevent hanging:
351
-
352
- **Quick Operations (30s timeout):**
353
- ```bash
354
- npx tsx .ai-agents/scripts/exec-with-timeout.ts --timeout 30 -- <command>
355
- ```
356
-
357
- **Medium Operations (120s timeout):**
358
- ```bash
359
- npx tsx .ai-agents/scripts/exec-with-timeout.ts --timeout 120 -- <command>
360
- ```
361
-
362
- **Always run tests with timeout**
363
- ```
364
- npx tsx .ai-agents/scripts/exec-with-timeout.ts --timeout 30 -- npm run test <test-suite>
365
- ```
366
-
367
- **Always examine test results after running tests**
368
- ```
369
- npx tsx .ai-agents/scripts/exec-with-timeout.ts --timeout 30 -- cat test.log
370
- ```
371
-
372
- ## DEBUGGING WORKFLOW
373
-
374
- ### 1. **Initial Setup**
375
- ```bash
376
- # Start server with long timeout
377
- npx tsx .ai-agents/scripts/exec-with-timeout.ts --timeout 3600 -- npm run dev &
378
-
379
- # Wait for startup
380
- sleep 3
381
-
382
- # Check server logs
383
- tail -20 server.log
384
- ```
385
-
386
- ### 2. **UI Automation with Visual Debugging**
387
- ```bash
388
- # Run Playwright script with medium timeout
389
- npx tsx .ai-agents/scripts/exec-with-timeout.ts --timeout 120 -- npx tsx debug-ui-flow.ts
390
- ```
391
-
392
- ### 3. **Database Validation**
393
- ```bash
394
- # Check database state
395
- npx tsx .ai-agents/scripts/exec-with-timeout.ts --timeout 30 -- npx tsx check-database-state.ts
396
- ```
397
-
398
- ### 4. **API Testing**
399
- ```bash
400
- # Test API endpoints
401
- npx tsx .ai-agents/scripts/exec-with-timeout.ts --timeout 30 -- npx tsx test-api-endpoints.ts
402
- ```
403
-
404
- ### 5. **Log Analysis**
405
- ```bash
406
- # Check recent logs
407
- npx tsx .ai-agents/scripts/exec-with-timeout.ts --timeout 30 -- tail -30 server.log
408
- ```
409
-
410
- ## COMMON PATTERNS
411
-
412
- ### Pattern 1: OAuth Flow Debugging
413
- 1. Start server with long timeout
414
- 2. Create Playwright script with screenshots
415
- 3. Run OAuth flow with visual debugging
416
- 4. Check database for token storage
417
- 5. Test API with stored tokens
418
- 6. Analyze logs for any errors
419
-
420
- ### Pattern 2: API Integration Debugging
421
- 1. Start server and verify it's running
422
- 2. Test API endpoints with curl
423
- 3. Check database for data persistence
424
- 4. Monitor server logs for errors
425
- 5. Fix issues and retest
426
-
427
- ### Pattern 3: UI Feature Debugging
428
- 1. Navigate to feature in browser
429
- 2. Take screenshots at each step
430
- 3. Perform actions and capture results
431
- 4. Check backend state changes
432
- 5. Verify end-to-end functionality
433
-
434
- ## ERROR DETECTION
435
-
436
- ### Server Log Errors to Watch For:
437
- - `OAuth callback error:`
438
- - `Database connection failed`
439
- - `Missing credentials`
440
- - `Port conflict errors`
441
- - `TypeScript compilation errors`
442
- - `API endpoint errors`
443
-
444
- ### Database State Validation:
445
- - Check for expected data after operations
446
- - Verify token storage and expiration
447
- - Confirm calendar/thread creation
448
- - Validate credential loading
449
-
450
- ### API Response Validation:
451
- - Check HTTP status codes
452
- - Verify response data structure
453
- - Test error handling
454
- - Confirm authentication
455
-
456
- ## SUCCESS INDICATORS
457
-
458
- ### OAuth Flow Success:
459
- - Screenshots show successful page transitions
460
- - Database contains valid tokens
461
- - API calls return 200 OK with real data
462
- - Server logs show successful token exchange
463
-
464
- ### API Integration Success:
465
- - All endpoints return expected status codes
466
- - Database contains persisted data
467
- - No errors in server logs
468
- - End-to-end functionality works
469
-
470
- ### UI Feature Success:
471
- - Screenshots show correct UI state
472
- - Actions produce expected results
473
- - Backend state changes correctly
474
- - No JavaScript errors in browser console
475
-
476
- ## CONCLUSION
477
-
478
- These patterns provide a systematic approach to debugging complex integrations. The key is combining multiple validation layers (UI, API, Database) with appropriate timeout management and real-time monitoring. Always take screenshots, check database state, and monitor logs to get a complete picture of what's happening.
1
+ # Successful Debugging Patterns for Complex Integrations
2
+
3
+ ## INTENT
4
+ To provide agents with proven patterns for debugging complex integrations, especially OAuth flows, API integrations, and multi-layer systems that require both UI automation and backend validation.
5
+
6
+ ## PRINCIPLES
7
+ - **Multi-Layer Validation**: Always validate at UI, API, and Database layers
8
+ - **Iterative Enhancement**: Continuously refine approaches based on real-time feedback
9
+ - **Appropriate Timeout Management**: Use different timeouts for different operation types
10
+ - **Real-Time Monitoring**: Monitor logs and database state during complex operations
11
+ - **Visual Debugging**: Use screenshots and visual feedback to understand UI state
12
+ - **Prefer User-Visible Truth**: For UI flows, validate what the user sees/does (DOM + persisted state), not the order/timing of background requests
13
+
14
+ ## CORE DEBUGGING PATTERN
15
+
16
+ ### The "Repro -> Analyze → Implement → Test → Validate → Document → VERIFY COMPLETENESS" Pattern
17
+
18
+ ```
19
+ 1. REPRO: Reproduce the issue in a controlled environment. This can be manual using Playwright for UI issues, Curl for API issues, etc; or it can be through existing test cases. Run only the test case that fails. Mark it with tag `failing`, then run `npm run test-failing <test-suite>`
20
+ 2. ANALYZE: Use tools to examine actual codebase (grep_search, Read)
21
+ 3. IMPLEMENT: Make targeted changes based on real code analysis
22
+ 4. TEST: Run the single test and ensure it passes. Then run comprehensive tests for evidence
23
+ 5. VALIDATE: Verify functionality works end-to-end
24
+ 6. DOCUMENT: Create test cases that replicate the flow and validate end state
25
+ 7. VERIFY COMPLETENESS: Run comprehensive verification checklist (NEW CRITICAL STEP)
26
+ 8. ITERATE: Refine based on real feedback and evidence
27
+ ```
28
+
29
+ ### **NEW: Mandatory Completeness Verification Pattern**
30
+
31
+ Before declaring ANY work complete, **MUST** follow this systematic verification:
32
+
33
+ ```bash
34
+ # Step 1: Compilation Verification
35
+ timeout 30s npx tsc --noEmit --skipLibCheck
36
+ # MUST show 0 errors - fix any errors before proceeding
37
+
38
+ # Step 2: Build Verification (if build script exists)
39
+ timeout 60s npm run build
40
+ # MUST complete successfully
41
+
42
+ # Step 3: Comprehensive Search Verification
43
+ # Search for ALL possible references using multiple patterns:
44
+ grep_search --SearchPath . --Query "OldClassName" --MatchPerLine true
45
+ grep_search --SearchPath . --Query "import.*OldClassName" --IsRegex true --MatchPerLine true
46
+ grep_search --SearchPath . --Query "old-filename" --MatchPerLine true
47
+ grep_search --SearchPath . --Query "oldMethodName" --MatchPerLine true
48
+
49
+ # Step 4: Test Execution with Timeout
50
+ timeout 30s npx tsx --test --test-reporter tap test-relevant-file.ts
51
+
52
+ # Step 5: End-to-End Functionality Check
53
+ # Verify main application workflows still work
54
+ ```
55
+
56
+ ### Enhanced Multi-Layer Debugging Pattern
57
+
58
+ ```
59
+ 1. Code Analysis (grep_search, find_by_name to understand current state)
60
+ 2. UI Action (Playwright automation with screenshots)
61
+ 3. Database Check (verify persistence and state changes)
62
+ 4. Log Analysis (check server logs for errors/success)
63
+ 5. API Testing (verify endpoints work correctly)
64
+ 6. Integration Testing (test full workflows)
65
+ 7. Evidence Collection (screenshots, logs, test results)
66
+ 8. Refine Approach (improve based on findings)
67
+ 9. Repeat (iterate until success with evidence)
68
+ ```
69
+
70
+ ## UI DEBUGGING WITH PLAYWRIGHT (AND PLAYWRIGHT MCP)
71
+
72
+ When the bug is user-visible (empty UI, wrong modal opens, buttons do nothing), treat the browser as the source of truth.
73
+
74
+ ### Evidence-first UI debugging loop
75
+ 1. **Reproduce in the browser** (manual or Playwright).
76
+ 2. **Capture evidence**:
77
+ - Browser console output (errors + warnings)
78
+ - DOM snapshot (preferred) and/or screenshot
79
+ - The exact URL + the exact click sequence
80
+ 3. **Instrument to make failures obvious**:
81
+ - Log `requestfailed` URLs and error text
82
+ - Log HTTP >= 400 responses (method + URL)
83
+ 4. **Fix the root cause** (DOM wiring, event binding, auth headers, data mapping).
84
+ 5. **Re-run the same click path** to prove the UI behaves correctly.
85
+
86
+ ### Playwright MCP usage (required when asked to "pop the browser")
87
+ If you are asked to confirm a fix visually:
88
+ - Use Playwright MCP tools to `navigate`, `click`, and capture a `browser_snapshot`.
89
+ - Validate the specific UI element/state changed (e.g., form opens, list renders, “No meetings” disappears).
90
+
91
+ ### E2E test stabilization checklist (when tests time out)
92
+ - Prefer waiting on UI state (`waitForSelector`, text visible, DOM class changes) over `waitForResponse` predicates.
93
+ - Avoid coupling to background requests that can vary (telemetry, analysis triggers, service worker, polling).
94
+ - If UI is optional/feature-flagged, **do not re-enable product UI just to satisfy tests**; gate the test sub-flow or validate via API/DB.
95
+ - Ensure the server is up (or auto-start it) and clean up reliably (use `after()` hooks).
96
+
97
+ ## SPECIFIC SCRIPTS AND COMMANDS
98
+
99
+ > [!NOTE]
100
+ > Ensure you have retrieved necessary scripts before running these commands.
101
+ > For example: `get_fraim_file({ path: "tmp/exec-with-timeout.ts" })` and save to `tmp/exec-with-timeout.ts`.
102
+
103
+ ### 1. Long-Running Server Management
104
+
105
+ **Start Server with Proper Timeout:**
106
+ ```bash
107
+ # Use 1-hour timeout for server processes
108
+ npx tsx tmp/exec-with-timeout.ts --timeout 3600 -- npm run dev &
109
+ ```
110
+
111
+ **Monitor Server Logs in Real-Time:**
112
+ ```bash
113
+ # Real-time monitoring
114
+ npx tsx tmp/exec-with-timeout.ts --timeout 30 -- tail -f server.log
115
+
116
+ # Historical log analysis
117
+ npx tsx tmp/exec-with-timeout.ts --timeout 30 -- tail -100 server.log
118
+
119
+ # Look for errors in logs
120
+ npx tsx tmp/exec-with-timeout.ts --timeout 30 -- grep error server.log
121
+ ```
122
+
123
+ **Check Server Status:**
124
+ ```bash
125
+ # Verify server is running on correct port
126
+ npx tsx tmp/exec-with-timeout.ts --timeout 30 -- netstat -ano | findstr :<port>
127
+
128
+ # Test API endpoints
129
+ npx tsx tmp/exec-with-timeout.ts --timeout 30 -- curl -s "http://localhost:<port>/<endpoint>"
130
+ ```
131
+
132
+ ### 2. Code Analysis and Understanding
133
+
134
+ **CRITICAL: Always Analyze Before Implementing**
135
+ Before making any changes, use tools to understand the current codebase:
136
+
137
+ ```bash
138
+ # Find all files that import a specific module
139
+ grep_search --SearchPath src --Query "import.*GmailService" --IsRegex true --MatchPerLine true
140
+
141
+ # Find files by pattern
142
+ find_by_name --SearchDirectory src --Pattern "*email*" --Type file
143
+
144
+ # Read specific files to understand implementation
145
+ Read --file_path src/email/email-service.ts
146
+ ```
147
+
148
+ **Pattern Analysis Requirements:**
149
+ 1. **Examine existing patterns** in the codebase (e.g., CalendarService pattern)
150
+ 2. **Use grep_search** to find all dependencies and usage
151
+ 3. **Read actual implementations** to understand current architecture
152
+ 4. **Document findings** with real code examples and line numbers
153
+
154
+ ### 3. Playwright UI Automation with Visual Debugging
155
+
156
+ **IMPORTANT: Tool Troubleshooting Pattern**
157
+ When MCP Playwright tools fail with errors like `TypeError: (0 , import_server2.firstRootPath) is not a function`:
158
+
159
+ 1. **Check for existing working Playwright tests** in the project
160
+ 2. **Use direct Playwright library** instead of MCP tools
161
+ 3. **Look for test files** like `test-dashboard-ui.ts`, `test-hitl-ui.ts` as templates
162
+ 4. **Create custom test scripts** using the direct library approach
163
+
164
+ **Basic Playwright Script Template:**
165
+ ```typescript
166
+ import { chromium } from 'playwright';
167
+
168
+ async function debugUIFlow() {
169
+ const browser = await chromium.launch({
170
+ headless: false,
171
+ slowMo: 2000 // Human-like delays
172
+ });
173
+
174
+ try {
175
+ const page = await browser.newPage();
176
+
177
+ // Step 1: Navigate
178
+ await page.goto(targetUrl);
179
+ await page.waitForLoadState('networkidle');
180
+
181
+ // Step 2: Take screenshot for debugging
182
+ await page.screenshot({ path: 'debug-step-1.png' });
183
+ console.log('📸 Screenshot saved: debug-step-1.png');
184
+
185
+ // Step 3: Perform action
186
+ await page.fill('input[type="email"]', 'test@example.com');
187
+ await page.click('button:has-text("Next")');
188
+
189
+ // Step 4: Take another screenshot
190
+ await page.screenshot({ path: 'debug-step-2.png' });
191
+ console.log('📸 Screenshot saved: debug-step-2.png');
192
+
193
+ // Step 5-N: Iterate on above until scenario is fully validated
194
+
195
+
196
+ } catch (error) {
197
+ console.error('❌ UI flow failed:', error);
198
+ await page.screenshot({ path: 'error-state.png' });
199
+ } finally {
200
+ await browser.close();
201
+ }
202
+ }
203
+ ```
204
+
205
+ **Advanced Playwright with Multiple Button Selectors:**
206
+ ```typescript
207
+ // Look for multiple possible button selectors
208
+ const buttonSelectors = [
209
+ 'button:has-text("Continue")',
210
+ 'button:has-text("Allow")',
211
+ 'button:has-text("Accept")',
212
+ 'button:has-text("Authorize")',
213
+ 'button[type="submit"]',
214
+ 'button[jsname="LgbsSe"]:has-text("Continue")'
215
+ ];
216
+
217
+ let buttonClicked = false;
218
+ for (const selector of buttonSelectors) {
219
+ try {
220
+ const button = await page.waitForSelector(selector, { timeout: 3000 });
221
+ if (button && await button.isVisible()) {
222
+ console.log(`🎯 Clicking button: ${selector}`);
223
+ await button.click();
224
+ buttonClicked = true;
225
+ break;
226
+ }
227
+ } catch (e) {
228
+ // Continue to next selector
229
+ }
230
+ }
231
+ ```
232
+
233
+ ### 3. Database Validation Scripts
234
+
235
+ **MongoDB Token Validation:**
236
+ ```typescript
237
+ const { DatabaseFactory } = require('./src/databases/database-factory');
238
+
239
+ async function checkDatabaseState() {
240
+ console.log('🔍 Checking database state...');
241
+ const dbService = await DatabaseFactory.createCalendarDatabaseService();
242
+ await dbService.initialize();
243
+
244
+ try {
245
+ // Check for tokens
246
+ const tokens = await dbService.loadCalendarTokens('primary');
247
+ console.log('📋 Tokens found:', !!tokens);
248
+
249
+ // Check for calendars
250
+ const calendars = await dbService.getAllCalendars();
251
+ console.log('📅 Calendars found:', calendars.length);
252
+
253
+ // Check for specific data
254
+ const credentials = await dbService.loadCredential('APP_CLIENT_ID');
255
+ console.log('🔑 Credentials found:', !!credentials);
256
+
257
+ } catch (error) {
258
+ console.error('❌ Database check failed:', error);
259
+ } finally {
260
+ await dbService.close();
261
+ }
262
+ }
263
+ ```
264
+
265
+ **API Endpoint Testing:**
266
+ ```typescript
267
+ async function testAPIEndpoints() {
268
+ const baseUrl = 'http://localhost:8333';
269
+
270
+ // Test calendar API
271
+ try {
272
+ const response = await fetch(`${baseUrl}/calendar/events?timerange_start=2024-01-01T00:00:00.000Z&timerange_end=2024-01-02T00:00:00.000Z`);
273
+ const data = await response.json();
274
+ console.log('📅 Calendar API:', response.status, data);
275
+ } catch (error) {
276
+ console.error('❌ Calendar API failed:', error);
277
+ }
278
+
279
+ // Test conversation API
280
+ try {
281
+ const response = await fetch(`${baseUrl}/conversation/threads`);
282
+ const data = await response.json();
283
+ console.log('💬 Conversation API:', response.status, data);
284
+ } catch (error) {
285
+ console.error('❌ Conversation API failed:', error);
286
+ }
287
+ }
288
+ ```
289
+
290
+ ### 4. OAuth Flow Debugging Scripts
291
+
292
+ **Complete OAuth Flow with Debugging:**
293
+ ```typescript
294
+ async function debugOAuthFlow() {
295
+ const browser = await chromium.launch({ headless: false, slowMo: 3000 });
296
+
297
+ try {
298
+ const page = await browser.newPage();
299
+ const oauthUrl = 'https://accounts.google.com/o/oauth2/v2/auth?client_id=...';
300
+
301
+ // Step 1: Navigate and take screenshot
302
+ await page.goto(oauthUrl);
303
+ await page.waitForLoadState('networkidle');
304
+ await page.screenshot({ path: 'oauth-step-1.png' });
305
+
306
+ // Step 2: Email
307
+ await page.fill('input[type="email"]', 'test@example.com');
308
+ await page.click('button:has-text("Next")');
309
+ await page.screenshot({ path: 'oauth-step-2.png' });
310
+
311
+ // Step 3: Password
312
+ await page.waitForSelector('input[type="password"]');
313
+ await page.fill('input[type="password"]', 'password');
314
+ await page.click('button:has-text("Next")');
315
+ await page.screenshot({ path: 'oauth-step-3.png' });
316
+
317
+ // Step 4: Consent page
318
+ await page.waitForLoadState('networkidle');
319
+ await page.screenshot({ path: 'consent-page.png' });
320
+
321
+ // Step 5: Click continue with multiple selectors
322
+ const continueSelectors = [
323
+ 'button:has-text("Continue")',
324
+ 'button:has-text("Allow")',
325
+ 'button[type="submit"]'
326
+ ];
327
+
328
+ for (const selector of continueSelectors) {
329
+ try {
330
+ const button = await page.waitForSelector(selector, { timeout: 3000 });
331
+ if (button && await button.isVisible()) {
332
+ await button.click();
333
+ break;
334
+ }
335
+ } catch (e) {}
336
+ }
337
+
338
+ // Step 6: Wait for callback
339
+ await page.waitForURL('**/oauth/callback**', { timeout: 20000 });
340
+ console.log('✅ OAuth flow completed!');
341
+
342
+ } catch (error) {
343
+ console.error('❌ OAuth flow failed:', error);
344
+ await page.screenshot({ path: 'oauth-error.png' });
345
+ } finally {
346
+ await browser.close();
347
+ }
348
+ }
349
+ ```
350
+
351
+ ### 5. Timeout Management Commands
352
+
353
+ **CRITICAL: Always Use Timeouts for Test Execution**
354
+ Following the established pattern from memory, ALWAYS use timeout commands to prevent hanging:
355
+
356
+ **Quick Operations (30s timeout):**
357
+ ```bash
358
+ npx tsx tmp/exec-with-timeout.ts --timeout 30 -- <command>
359
+ ```
360
+
361
+ **Medium Operations (120s timeout):**
362
+ ```bash
363
+ npx tsx tmp/exec-with-timeout.ts --timeout 120 -- <command>
364
+ ```
365
+
366
+ **Always run tests with timeout**
367
+ ```
368
+ npx tsx tmp/exec-with-timeout.ts --timeout 30 -- npm run test <test-suite>
369
+ ```
370
+
371
+ **Always examine test results after running tests**
372
+ ```
373
+ npx tsx tmp/exec-with-timeout.ts --timeout 30 -- cat test.log
374
+ ```
375
+
376
+ ## DEBUGGING WORKFLOW
377
+
378
+ ### 1. **Initial Setup**
379
+ ```bash
380
+ # Start server with long timeout
381
+ npx tsx tmp/exec-with-timeout.ts --timeout 3600 -- npm run dev &
382
+
383
+ # Wait for startup
384
+ sleep 3
385
+
386
+ # Check server logs
387
+ tail -20 server.log
388
+ ```
389
+
390
+ ### 2. **UI Automation with Visual Debugging**
391
+ ```bash
392
+ # Run Playwright script with medium timeout
393
+ npx tsx tmp/exec-with-timeout.ts --timeout 120 -- npx tsx debug-ui-flow.ts
394
+ ```
395
+
396
+ ### 3. **Database Validation**
397
+ ```bash
398
+ # Check database state
399
+ npx tsx tmp/exec-with-timeout.ts --timeout 30 -- npx tsx check-database-state.ts
400
+ ```
401
+
402
+ ### 4. **API Testing**
403
+ ```bash
404
+ # Test API endpoints
405
+ npx tsx tmp/exec-with-timeout.ts --timeout 30 -- npx tsx test-api-endpoints.ts
406
+ ```
407
+
408
+ ### 5. **Log Analysis**
409
+ ```bash
410
+ # Check recent logs
411
+ npx tsx tmp/exec-with-timeout.ts --timeout 30 -- tail -30 server.log
412
+ ```
413
+
414
+ ## COMMON PATTERNS
415
+
416
+ ### Pattern 1: OAuth Flow Debugging
417
+ 1. Start server with long timeout
418
+ 2. Create Playwright script with screenshots
419
+ 3. Run OAuth flow with visual debugging
420
+ 4. Check database for token storage
421
+ 5. Test API with stored tokens
422
+ 6. Analyze logs for any errors
423
+
424
+ ### Pattern 2: API Integration Debugging
425
+ 1. Start server and verify it's running
426
+ 2. Test API endpoints with curl
427
+ 3. Check database for data persistence
428
+ 4. Monitor server logs for errors
429
+ 5. Fix issues and retest
430
+
431
+ ### Pattern 3: UI Feature Debugging
432
+ 1. Navigate to feature in browser
433
+ 2. Take screenshots at each step
434
+ 3. Perform actions and capture results
435
+ 4. Check backend state changes
436
+ 5. Verify end-to-end functionality
437
+
438
+ ## ERROR DETECTION
439
+
440
+ ### Server Log Errors to Watch For:
441
+ - `OAuth callback error:`
442
+ - `Database connection failed`
443
+ - `Missing credentials`
444
+ - `Port conflict errors`
445
+ - `TypeScript compilation errors`
446
+ - `API endpoint errors`
447
+
448
+ ### Database State Validation:
449
+ - Check for expected data after operations
450
+ - Verify token storage and expiration
451
+ - Confirm calendar/thread creation
452
+ - Validate credential loading
453
+
454
+ ### API Response Validation:
455
+ - Check HTTP status codes
456
+ - Verify response data structure
457
+ - Test error handling
458
+ - Confirm authentication
459
+
460
+ ## SUCCESS INDICATORS
461
+
462
+ ### OAuth Flow Success:
463
+ - Screenshots show successful page transitions
464
+ - Database contains valid tokens
465
+ - API calls return 200 OK with real data
466
+ - Server logs show successful token exchange
467
+
468
+ ### API Integration Success:
469
+ - All endpoints return expected status codes
470
+ - Database contains persisted data
471
+ - No errors in server logs
472
+ - End-to-end functionality works
473
+
474
+ ### UI Feature Success:
475
+ - Screenshots show correct UI state
476
+ - Actions produce expected results
477
+ - Backend state changes correctly
478
+ - No JavaScript errors in browser console
479
+
480
+ ## CONCLUSION
481
+
482
+ These patterns provide a systematic approach to debugging complex integrations. The key is combining multiple validation layers (UI, API, Database) with appropriate timeout management and real-time monitoring. Always take screenshots, check database state, and monitor logs to get a complete picture of what's happening.