File size: 36,628 Bytes
5a81b95
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
/**
 * COMPREHENSIVE ERROR PATTERN INGESTION
 * =====================================
 * Ingests curated error patterns from authoritative sources:
 * - Node.js system errors
 * - HTTP status codes
 * - PostgreSQL error codes
 * - TypeScript compiler errors
 */

const API_BASE = 'http://localhost:3001/api/healing';

async function ingestPattern(pattern) {
  try {
    const res = await fetch(`${API_BASE}/knowledge/ingest`, {
      method: 'POST',
      headers: { 'Content-Type': 'application/json' },
      body: JSON.stringify(pattern)
    });
    const data = await res.json();
    return data.isNew;
  } catch (e) {
    console.error(`Failed to ingest: ${pattern.signature.substring(0, 50)}...`);
    return false;
  }
}

// ═══════════════════════════════════════════════════════════════════════════
// NODE.JS SYSTEM ERRORS
// ═══════════════════════════════════════════════════════════════════════════

const nodeErrors = [
  {
    source: 'nodejs-system',
    category: 'network',
    severity: 'high',
    signature: 'ECONNREFUSED',
    description: 'Connection refused - target service is not running or not accepting connections',
    solutions: [
      { description: 'Verify the target service is running', confidence: 0.95, source: 'nodejs-docs', verified: true },
      { description: 'Check if the port number is correct', confidence: 0.9, source: 'nodejs-docs', verified: true },
      { description: 'Ensure firewall allows the connection', confidence: 0.8, source: 'community', verified: true },
      { description: 'Use 127.0.0.1 instead of localhost for local connections', confidence: 0.75, source: 'stackoverflow', verified: true }
    ],
    tags: ['network', 'connection', 'socket', 'tcp']
  },
  {
    source: 'nodejs-system',
    category: 'network',
    severity: 'medium',
    signature: 'ETIMEDOUT',
    description: 'Operation timed out - connection or send request failed due to no response',
    solutions: [
      { description: 'Implement retry with exponential backoff', confidence: 0.9, source: 'best-practices', verified: true },
      { description: 'Increase timeout value in request options', confidence: 0.85, source: 'nodejs-docs', verified: true },
      { description: 'Check network connectivity and DNS resolution', confidence: 0.8, source: 'community', verified: true },
      { description: 'Ensure socket.end() is called properly', confidence: 0.7, source: 'nodejs-docs', verified: true }
    ],
    tags: ['network', 'timeout', 'socket']
  },
  {
    source: 'nodejs-system',
    category: 'network',
    severity: 'high',
    signature: 'ENOTFOUND',
    description: 'DNS lookup failed - hostname could not be resolved',
    solutions: [
      { description: 'Verify the hostname is spelled correctly', confidence: 0.95, source: 'nodejs-docs', verified: true },
      { description: 'Check DNS configuration and /etc/hosts', confidence: 0.85, source: 'community', verified: true },
      { description: 'Use IP address instead of hostname to test', confidence: 0.8, source: 'debugging', verified: true },
      { description: 'Remove protocol prefix (https://) from host property', confidence: 0.9, source: 'stackoverflow', verified: true }
    ],
    tags: ['network', 'dns', 'hostname']
  },
  {
    source: 'nodejs-system',
    category: 'network',
    severity: 'medium',
    signature: 'ECONNRESET',
    description: 'Connection reset by peer - remote side forcibly closed connection',
    solutions: [
      { description: 'Implement automatic retry logic', confidence: 0.85, source: 'best-practices', verified: true },
      { description: 'Check if server has connection timeout settings', confidence: 0.8, source: 'community', verified: true },
      { description: 'Ensure keep-alive is properly configured', confidence: 0.75, source: 'nodejs-docs', verified: true },
      { description: 'Check for network instability or proxy issues', confidence: 0.7, source: 'debugging', verified: true }
    ],
    tags: ['network', 'connection', 'reset']
  },
  {
    source: 'nodejs-system',
    category: 'network',
    severity: 'high',
    signature: 'EADDRINUSE',
    description: 'Address already in use - port is bound by another process',
    solutions: [
      { description: 'Use a different port number', confidence: 0.95, source: 'nodejs-docs', verified: true },
      { description: 'Find and kill the process using the port: lsof -i :PORT or netstat -anp | grep PORT', confidence: 0.9, source: 'linux-admin', verified: true },
      { description: 'Wait for TIME_WAIT to expire or enable SO_REUSEADDR', confidence: 0.8, source: 'networking', verified: true },
      { description: 'Check for zombie processes from previous runs', confidence: 0.75, source: 'debugging', verified: true }
    ],
    tags: ['network', 'port', 'binding']
  },
  {
    source: 'nodejs-system',
    category: 'runtime',
    severity: 'high',
    signature: 'EMFILE',
    description: 'Too many open files - system file descriptor limit reached',
    solutions: [
      { description: 'Increase system file descriptor limit: ulimit -n 65535', confidence: 0.9, source: 'linux-admin', verified: true },
      { description: 'Ensure file handles are properly closed after use', confidence: 0.95, source: 'best-practices', verified: true },
      { description: 'Use graceful-fs package for automatic retry', confidence: 0.85, source: 'npm', verified: true },
      { description: 'Implement connection pooling for databases', confidence: 0.8, source: 'best-practices', verified: true }
    ],
    tags: ['files', 'resources', 'limit']
  },
  {
    source: 'nodejs-system',
    category: 'network',
    severity: 'medium',
    signature: 'EPIPE',
    description: 'Broken pipe - write to a connection that has been closed',
    solutions: [
      { description: 'Handle the error event on the socket', confidence: 0.9, source: 'nodejs-docs', verified: true },
      { description: 'Check if connection is still open before writing', confidence: 0.85, source: 'best-practices', verified: true },
      { description: 'Implement proper connection state management', confidence: 0.8, source: 'community', verified: true }
    ],
    tags: ['network', 'pipe', 'socket']
  },
  {
    source: 'nodejs-system',
    category: 'network',
    severity: 'high',
    signature: 'EHOSTUNREACH',
    description: 'Host unreachable - no route to the specified host',
    solutions: [
      { description: 'Check network connectivity and routing tables', confidence: 0.9, source: 'networking', verified: true },
      { description: 'Verify the target host IP/hostname is correct', confidence: 0.85, source: 'debugging', verified: true },
      { description: 'Check VPN connection if accessing private network', confidence: 0.8, source: 'community', verified: true }
    ],
    tags: ['network', 'routing', 'host']
  },
  {
    source: 'nodejs-system',
    category: 'memory',
    severity: 'critical',
    signature: 'FATAL ERROR: CALL_AND_RETRY_LAST Allocation failed - JavaScript heap out of memory',
    description: 'Node.js ran out of heap memory',
    solutions: [
      { description: 'Increase heap size: node --max-old-space-size=4096', confidence: 0.95, source: 'nodejs-docs', verified: true },
      { description: 'Check for memory leaks using heapdump or memwatch', confidence: 0.9, source: 'best-practices', verified: true },
      { description: 'Stream large data instead of loading into memory', confidence: 0.85, source: 'best-practices', verified: true },
      { description: 'Use pagination for large database queries', confidence: 0.8, source: 'optimization', verified: true }
    ],
    tags: ['memory', 'heap', 'oom', 'critical']
  },
  {
    source: 'nodejs-system',
    category: 'performance',
    severity: 'high',
    signature: 'Event loop blocked',
    description: 'Synchronous operations blocking the event loop',
    solutions: [
      { description: 'Replace sync file operations with async versions', confidence: 0.95, source: 'nodejs-docs', verified: true },
      { description: 'Use Worker Threads for CPU-intensive tasks', confidence: 0.9, source: 'nodejs-docs', verified: true },
      { description: 'Break up large computations with setImmediate()', confidence: 0.85, source: 'best-practices', verified: true },
      { description: 'Profile with clinic.js to identify blockers', confidence: 0.8, source: 'tooling', verified: true }
    ],
    tags: ['performance', 'event-loop', 'blocking']
  }
];

// ═══════════════════════════════════════════════════════════════════════════
// HTTP STATUS CODE ERRORS
// ═══════════════════════════════════════════════════════════════════════════

const httpErrors = [
  {
    source: 'http-standards',
    category: 'api',
    severity: 'medium',
    signature: 'HTTP 400 Bad Request',
    description: 'Server could not understand the request due to invalid syntax',
    solutions: [
      { description: 'Validate request body against expected schema', confidence: 0.95, source: 'http-spec', verified: true },
      { description: 'Check Content-Type header matches body format', confidence: 0.9, source: 'http-spec', verified: true },
      { description: 'Ensure all required fields are present', confidence: 0.85, source: 'best-practices', verified: true },
      { description: 'URL-encode special characters in query parameters', confidence: 0.8, source: 'http-spec', verified: true }
    ],
    tags: ['http', 'client-error', 'validation']
  },
  {
    source: 'http-standards',
    category: 'authentication',
    severity: 'high',
    signature: 'HTTP 401 Unauthorized',
    description: 'Authentication credentials are missing or invalid',
    solutions: [
      { description: 'Check if auth token is present in request headers', confidence: 0.95, source: 'http-spec', verified: true },
      { description: 'Verify token has not expired', confidence: 0.9, source: 'security', verified: true },
      { description: 'Ensure correct authentication scheme (Bearer, Basic)', confidence: 0.85, source: 'http-spec', verified: true },
      { description: 'Refresh the access token if using OAuth', confidence: 0.8, source: 'oauth-spec', verified: true }
    ],
    tags: ['http', 'auth', 'security', '401']
  },
  {
    source: 'http-standards',
    category: 'authentication',
    severity: 'high',
    signature: 'HTTP 403 Forbidden',
    description: 'Server understood request but refuses to authorize it',
    solutions: [
      { description: 'Check user permissions/roles for the resource', confidence: 0.95, source: 'http-spec', verified: true },
      { description: 'Verify API key has correct scopes', confidence: 0.9, source: 'api-design', verified: true },
      { description: 'Check if IP is whitelisted if IP filtering is enabled', confidence: 0.8, source: 'security', verified: true },
      { description: 'Review access control policies', confidence: 0.75, source: 'security', verified: true }
    ],
    tags: ['http', 'authorization', 'security', '403']
  },
  {
    source: 'http-standards',
    category: 'api',
    severity: 'medium',
    signature: 'HTTP 404 Not Found',
    description: 'Server cannot find the requested resource',
    solutions: [
      { description: 'Verify the URL path is correct', confidence: 0.95, source: 'http-spec', verified: true },
      { description: 'Check if resource ID exists in database', confidence: 0.9, source: 'api-design', verified: true },
      { description: 'Ensure API version prefix is correct', confidence: 0.85, source: 'api-design', verified: true },
      { description: 'Check for trailing slashes in URL', confidence: 0.7, source: 'debugging', verified: true }
    ],
    tags: ['http', 'not-found', '404']
  },
  {
    source: 'http-standards',
    category: 'api',
    severity: 'medium',
    signature: 'HTTP 405 Method Not Allowed',
    description: 'HTTP method is not supported for this resource',
    solutions: [
      { description: 'Check Allow header for supported methods', confidence: 0.95, source: 'http-spec', verified: true },
      { description: 'Verify correct HTTP verb (GET/POST/PUT/DELETE)', confidence: 0.9, source: 'api-design', verified: true },
      { description: 'Check if route is registered for this method', confidence: 0.85, source: 'debugging', verified: true }
    ],
    tags: ['http', 'method', '405']
  },
  {
    source: 'http-standards',
    category: 'api',
    severity: 'high',
    signature: 'HTTP 429 Too Many Requests',
    description: 'Rate limit exceeded - too many requests sent',
    solutions: [
      { description: 'Implement exponential backoff retry logic', confidence: 0.95, source: 'best-practices', verified: true },
      { description: 'Check Retry-After header for wait time', confidence: 0.9, source: 'http-spec', verified: true },
      { description: 'Implement request queuing/throttling', confidence: 0.85, source: 'architecture', verified: true },
      { description: 'Consider upgrading API plan for higher limits', confidence: 0.6, source: 'business', verified: true }
    ],
    tags: ['http', 'rate-limit', '429', 'throttling']
  },
  {
    source: 'http-standards',
    category: 'runtime',
    severity: 'critical',
    signature: 'HTTP 500 Internal Server Error',
    description: 'Server encountered an unexpected condition',
    solutions: [
      { description: 'Check server logs for stack trace', confidence: 0.95, source: 'debugging', verified: true },
      { description: 'Add proper error handling middleware', confidence: 0.9, source: 'best-practices', verified: true },
      { description: 'Validate all inputs before processing', confidence: 0.85, source: 'security', verified: true },
      { description: 'Ensure database connections are available', confidence: 0.8, source: 'operations', verified: true }
    ],
    tags: ['http', 'server-error', '500', 'critical']
  },
  {
    source: 'http-standards',
    category: 'network',
    severity: 'high',
    signature: 'HTTP 502 Bad Gateway',
    description: 'Gateway/proxy received invalid response from upstream',
    solutions: [
      { description: 'Check if upstream service is running', confidence: 0.95, source: 'operations', verified: true },
      { description: 'Verify upstream service URL configuration', confidence: 0.9, source: 'configuration', verified: true },
      { description: 'Check network connectivity between services', confidence: 0.85, source: 'networking', verified: true },
      { description: 'Review proxy timeout settings', confidence: 0.8, source: 'configuration', verified: true }
    ],
    tags: ['http', 'gateway', 'proxy', '502']
  },
  {
    source: 'http-standards',
    category: 'runtime',
    severity: 'high',
    signature: 'HTTP 503 Service Unavailable',
    description: 'Server is not ready to handle request (overloaded or maintenance)',
    solutions: [
      { description: 'Implement circuit breaker pattern', confidence: 0.9, source: 'architecture', verified: true },
      { description: 'Check Retry-After header and retry later', confidence: 0.85, source: 'http-spec', verified: true },
      { description: 'Scale up server resources or add instances', confidence: 0.8, source: 'operations', verified: true },
      { description: 'Implement health checks and load balancing', confidence: 0.75, source: 'architecture', verified: true }
    ],
    tags: ['http', 'unavailable', '503', 'scaling']
  },
  {
    source: 'http-standards',
    category: 'network',
    severity: 'high',
    signature: 'HTTP 504 Gateway Timeout',
    description: 'Gateway/proxy did not receive timely response from upstream',
    solutions: [
      { description: 'Increase upstream service timeout', confidence: 0.9, source: 'configuration', verified: true },
      { description: 'Optimize slow backend operations', confidence: 0.85, source: 'optimization', verified: true },
      { description: 'Implement async processing for long operations', confidence: 0.8, source: 'architecture', verified: true },
      { description: 'Add caching layer to reduce backend load', confidence: 0.75, source: 'architecture', verified: true }
    ],
    tags: ['http', 'timeout', 'gateway', '504']
  }
];

// ═══════════════════════════════════════════════════════════════════════════
// POSTGRESQL ERRORS
// ═══════════════════════════════════════════════════════════════════════════

const postgresErrors = [
  {
    source: 'postgresql-official',
    category: 'database',
    severity: 'high',
    signature: 'SQLSTATE 08001',
    description: 'Connection attempt to database failed',
    solutions: [
      { description: 'Verify database server is running', confidence: 0.95, source: 'postgresql-docs', verified: true },
      { description: 'Check connection string parameters (host, port, database)', confidence: 0.9, source: 'postgresql-docs', verified: true },
      { description: 'Verify pg_hba.conf allows connection from client', confidence: 0.85, source: 'postgresql-docs', verified: true },
      { description: 'Check firewall rules allow connection', confidence: 0.8, source: 'networking', verified: true }
    ],
    tags: ['database', 'postgresql', 'connection']
  },
  {
    source: 'postgresql-official',
    category: 'database',
    severity: 'medium',
    signature: 'SQLSTATE 21000',
    description: 'Subquery result is not single row when single row expected',
    solutions: [
      { description: 'Add LIMIT 1 to subquery', confidence: 0.9, source: 'postgresql-docs', verified: true },
      { description: 'Use aggregate function (MAX, MIN) if single value needed', confidence: 0.85, source: 'sql-best-practices', verified: true },
      { description: 'Review data to understand why multiple rows returned', confidence: 0.8, source: 'debugging', verified: true }
    ],
    tags: ['database', 'postgresql', 'subquery']
  },
  {
    source: 'postgresql-official',
    category: 'database',
    severity: 'high',
    signature: 'SQLSTATE 23505',
    description: 'Duplicate key violation - unique constraint violated',
    solutions: [
      { description: 'Use ON CONFLICT DO UPDATE for upsert operations', confidence: 0.95, source: 'postgresql-docs', verified: true },
      { description: 'Check if record already exists before insert', confidence: 0.85, source: 'best-practices', verified: true },
      { description: 'Use INSERT ... ON CONFLICT DO NOTHING to skip duplicates', confidence: 0.8, source: 'postgresql-docs', verified: true },
      { description: 'Review unique constraint definition', confidence: 0.7, source: 'schema-design', verified: true }
    ],
    tags: ['database', 'postgresql', 'unique', 'constraint']
  },
  {
    source: 'postgresql-official',
    category: 'database',
    severity: 'high',
    signature: 'SQLSTATE 23503',
    description: 'Foreign key violation - referenced row does not exist',
    solutions: [
      { description: 'Ensure parent record exists before inserting child', confidence: 0.95, source: 'postgresql-docs', verified: true },
      { description: 'Use CASCADE on delete if orphans should be removed', confidence: 0.85, source: 'schema-design', verified: true },
      { description: 'Implement proper transaction ordering', confidence: 0.8, source: 'best-practices', verified: true }
    ],
    tags: ['database', 'postgresql', 'foreign-key', 'constraint']
  },
  {
    source: 'postgresql-official',
    category: 'database',
    severity: 'medium',
    signature: 'SQLSTATE 42601',
    description: 'SQL syntax error',
    solutions: [
      { description: 'Check query for missing/extra commas, parentheses', confidence: 0.9, source: 'debugging', verified: true },
      { description: 'Verify column and table names are correct', confidence: 0.85, source: 'debugging', verified: true },
      { description: 'Use parameterized queries to avoid injection issues', confidence: 0.95, source: 'security', verified: true },
      { description: 'Quote reserved words used as identifiers', confidence: 0.8, source: 'postgresql-docs', verified: true }
    ],
    tags: ['database', 'postgresql', 'syntax']
  },
  {
    source: 'postgresql-official',
    category: 'database',
    severity: 'medium',
    signature: 'SQLSTATE 42703',
    description: 'Undefined column - column does not exist',
    solutions: [
      { description: 'Check column name spelling and case', confidence: 0.95, source: 'postgresql-docs', verified: true },
      { description: 'Verify column exists in correct table (use table alias)', confidence: 0.9, source: 'debugging', verified: true },
      { description: 'Run pending migrations if column was recently added', confidence: 0.85, source: 'operations', verified: true }
    ],
    tags: ['database', 'postgresql', 'column']
  },
  {
    source: 'postgresql-official',
    category: 'database',
    severity: 'medium',
    signature: 'SQLSTATE 42P01',
    description: 'Undefined table - relation does not exist',
    solutions: [
      { description: 'Check table name spelling and schema prefix', confidence: 0.95, source: 'postgresql-docs', verified: true },
      { description: 'Verify search_path includes correct schema', confidence: 0.85, source: 'postgresql-docs', verified: true },
      { description: 'Run pending migrations if table was recently created', confidence: 0.9, source: 'operations', verified: true }
    ],
    tags: ['database', 'postgresql', 'table']
  },
  {
    source: 'postgresql-official',
    category: 'database',
    severity: 'critical',
    signature: 'SQLSTATE 53200',
    description: 'Out of memory - insufficient memory for operation',
    solutions: [
      { description: 'Increase work_mem configuration', confidence: 0.85, source: 'postgresql-docs', verified: true },
      { description: 'Optimize query to use less memory', confidence: 0.9, source: 'optimization', verified: true },
      { description: 'Add indexes to avoid large sorts', confidence: 0.8, source: 'optimization', verified: true },
      { description: 'Consider query pagination for large result sets', confidence: 0.85, source: 'best-practices', verified: true }
    ],
    tags: ['database', 'postgresql', 'memory', 'critical']
  },
  {
    source: 'postgresql-official',
    category: 'database',
    severity: 'high',
    signature: 'SQLSTATE 53300',
    description: 'Too many connections',
    solutions: [
      { description: 'Implement connection pooling (PgBouncer, built-in pool)', confidence: 0.95, source: 'best-practices', verified: true },
      { description: 'Increase max_connections in postgresql.conf', confidence: 0.8, source: 'postgresql-docs', verified: true },
      { description: 'Close idle connections promptly', confidence: 0.85, source: 'best-practices', verified: true },
      { description: 'Review application connection lifecycle', confidence: 0.8, source: 'debugging', verified: true }
    ],
    tags: ['database', 'postgresql', 'connections', 'pool']
  },
  {
    source: 'postgresql-official',
    category: 'concurrency',
    severity: 'high',
    signature: 'SQLSTATE 40P01',
    description: 'Deadlock detected',
    solutions: [
      { description: 'Order operations consistently across transactions', confidence: 0.9, source: 'postgresql-docs', verified: true },
      { description: 'Keep transactions short', confidence: 0.85, source: 'best-practices', verified: true },
      { description: 'Use SELECT FOR UPDATE NOWAIT to fail fast', confidence: 0.8, source: 'postgresql-docs', verified: true },
      { description: 'Implement retry logic with backoff', confidence: 0.85, source: 'best-practices', verified: true }
    ],
    tags: ['database', 'postgresql', 'deadlock', 'concurrency']
  }
];

// ═══════════════════════════════════════════════════════════════════════════
// TYPESCRIPT ERRORS
// ═══════════════════════════════════════════════════════════════════════════

const typescriptErrors = [
  {
    source: 'typescript-compiler',
    category: 'type',
    severity: 'medium',
    signature: "TS2322: Type 'X' is not assignable to type 'Y'",
    description: 'Type mismatch - attempting to assign incompatible type',
    solutions: [
      { description: 'Check variable type declaration matches assigned value', confidence: 0.95, source: 'typescript-docs', verified: true },
      { description: 'Use type assertion if types are compatible at runtime', confidence: 0.7, source: 'typescript-docs', verified: true },
      { description: 'Add proper type guard before assignment', confidence: 0.85, source: 'best-practices', verified: true },
      { description: 'Update type definition to accept both types (union type)', confidence: 0.8, source: 'typescript-docs', verified: true }
    ],
    tags: ['typescript', 'type', 'assignment']
  },
  {
    source: 'typescript-compiler',
    category: 'type',
    severity: 'medium',
    signature: "TS2339: Property 'X' does not exist on type 'Y'",
    description: 'Accessing property that does not exist on the type',
    solutions: [
      { description: 'Add the property to the interface/type definition', confidence: 0.9, source: 'typescript-docs', verified: true },
      { description: 'Use optional chaining (?.) if property might not exist', confidence: 0.85, source: 'typescript-docs', verified: true },
      { description: 'Check if accessing property on correct variable', confidence: 0.8, source: 'debugging', verified: true },
      { description: 'Use type assertion if property exists at runtime', confidence: 0.7, source: 'typescript-docs', verified: true }
    ],
    tags: ['typescript', 'type', 'property']
  },
  {
    source: 'typescript-compiler',
    category: 'type',
    severity: 'medium',
    signature: "TS2345: Argument of type 'X' is not assignable to parameter of type 'Y'",
    description: 'Function called with wrong argument type',
    solutions: [
      { description: 'Check function signature and provide correct types', confidence: 0.95, source: 'typescript-docs', verified: true },
      { description: 'Transform data to expected type before calling', confidence: 0.85, source: 'best-practices', verified: true },
      { description: 'Update function signature if it should accept more types', confidence: 0.8, source: 'typescript-docs', verified: true }
    ],
    tags: ['typescript', 'type', 'argument', 'function']
  },
  {
    source: 'typescript-compiler',
    category: 'type',
    severity: 'high',
    signature: "TS2531: Object is possibly 'null'",
    description: 'Accessing object that could be null without null check',
    solutions: [
      { description: 'Add null check before accessing: if (obj !== null)', confidence: 0.95, source: 'typescript-docs', verified: true },
      { description: 'Use optional chaining: obj?.property', confidence: 0.9, source: 'typescript-docs', verified: true },
      { description: 'Use non-null assertion if certain value exists: obj!', confidence: 0.7, source: 'typescript-docs', verified: true },
      { description: 'Use nullish coalescing for default: obj ?? defaultValue', confidence: 0.85, source: 'typescript-docs', verified: true }
    ],
    tags: ['typescript', 'null', 'strictNullChecks']
  },
  {
    source: 'typescript-compiler',
    category: 'type',
    severity: 'high',
    signature: "TS2532: Object is possibly 'undefined'",
    description: 'Accessing object that could be undefined without check',
    solutions: [
      { description: 'Add undefined check: if (obj !== undefined)', confidence: 0.95, source: 'typescript-docs', verified: true },
      { description: 'Use optional chaining: obj?.property', confidence: 0.9, source: 'typescript-docs', verified: true },
      { description: 'Provide default value: obj ?? defaultValue', confidence: 0.85, source: 'typescript-docs', verified: true }
    ],
    tags: ['typescript', 'undefined', 'strictNullChecks']
  },
  {
    source: 'typescript-compiler',
    category: 'type',
    severity: 'low',
    signature: 'TS7006: Parameter implicitly has an any type',
    description: 'Function parameter missing type annotation in strict mode',
    solutions: [
      { description: 'Add explicit type annotation to parameter', confidence: 0.95, source: 'typescript-docs', verified: true },
      { description: 'Set noImplicitAny: false in tsconfig (not recommended)', confidence: 0.5, source: 'typescript-docs', verified: true }
    ],
    tags: ['typescript', 'any', 'strict']
  },
  {
    source: 'typescript-compiler',
    category: 'dependency',
    severity: 'medium',
    signature: "TS2307: Cannot find module 'X' or its corresponding type declarations",
    description: 'Module or types not found',
    solutions: [
      { description: 'Install the package: npm install X', confidence: 0.9, source: 'npm', verified: true },
      { description: 'Install type definitions: npm install -D @types/X', confidence: 0.95, source: 'typescript-docs', verified: true },
      { description: 'Check module path is correct (relative vs package)', confidence: 0.85, source: 'debugging', verified: true },
      { description: 'Create declaration file: declare module "X"', confidence: 0.7, source: 'typescript-docs', verified: true }
    ],
    tags: ['typescript', 'module', 'types', 'import']
  },
  {
    source: 'typescript-compiler',
    category: 'syntax',
    severity: 'high',
    signature: 'TS1005: Expected X',
    description: 'Syntax error - expected token missing',
    solutions: [
      { description: 'Check for missing semicolons, brackets, or parentheses', confidence: 0.95, source: 'debugging', verified: true },
      { description: 'Verify arrow function syntax: () => {}', confidence: 0.85, source: 'typescript-docs', verified: true },
      { description: 'Check for unclosed string literals', confidence: 0.8, source: 'debugging', verified: true }
    ],
    tags: ['typescript', 'syntax', 'parsing']
  },
  {
    source: 'typescript-compiler',
    category: 'runtime',
    severity: 'critical',
    signature: "TypeError: Cannot read property 'X' of undefined",
    description: 'Runtime error accessing property on undefined value',
    solutions: [
      { description: 'Add null/undefined check before access', confidence: 0.95, source: 'best-practices', verified: true },
      { description: 'Use optional chaining: obj?.property', confidence: 0.9, source: 'javascript', verified: true },
      { description: 'Check data flow to find where undefined originates', confidence: 0.85, source: 'debugging', verified: true },
      { description: 'Initialize variables with default values', confidence: 0.8, source: 'best-practices', verified: true }
    ],
    tags: ['typescript', 'runtime', 'undefined', 'critical']
  },
  {
    source: 'typescript-compiler',
    category: 'runtime',
    severity: 'critical',
    signature: "TypeError: X is not a function",
    description: 'Attempting to call something that is not a function',
    solutions: [
      { description: 'Check variable is actually a function before calling', confidence: 0.95, source: 'debugging', verified: true },
      { description: 'Verify import statement brings in correct export', confidence: 0.9, source: 'debugging', verified: true },
      { description: 'Check this binding if method is passed as callback', confidence: 0.85, source: 'javascript', verified: true },
      { description: 'Ensure async functions are awaited properly', confidence: 0.8, source: 'best-practices', verified: true }
    ],
    tags: ['typescript', 'runtime', 'function', 'critical']
  }
];

// ═══════════════════════════════════════════════════════════════════════════
// MAIN INGESTION
// ═══════════════════════════════════════════════════════════════════════════

async function main() {
  console.log('╔═══════════════════════════════════════════════════════════════════════════╗');
  console.log('β•‘             COMPREHENSIVE ERROR PATTERN INGESTION                         β•‘');
  console.log('β•šβ•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•\n');

  const stats = { total: 0, new: 0, updated: 0 };

  // Ingest Node.js errors
  console.log('πŸ“¦ Ingesting Node.js system errors...');
  for (const pattern of nodeErrors) {
    stats.total++;
    const isNew = await ingestPattern(pattern);
    if (isNew) stats.new++; else stats.updated++;
    process.stdout.write('.');
  }
  console.log(` βœ“ ${nodeErrors.length} patterns`);

  // Ingest HTTP errors
  console.log('🌐 Ingesting HTTP status codes...');
  for (const pattern of httpErrors) {
    stats.total++;
    const isNew = await ingestPattern(pattern);
    if (isNew) stats.new++; else stats.updated++;
    process.stdout.write('.');
  }
  console.log(` βœ“ ${httpErrors.length} patterns`);

  // Ingest PostgreSQL errors
  console.log('🐘 Ingesting PostgreSQL errors...');
  for (const pattern of postgresErrors) {
    stats.total++;
    const isNew = await ingestPattern(pattern);
    if (isNew) stats.new++; else stats.updated++;
    process.stdout.write('.');
  }
  console.log(` βœ“ ${postgresErrors.length} patterns`);

  // Ingest TypeScript errors
  console.log('πŸ“˜ Ingesting TypeScript errors...');
  for (const pattern of typescriptErrors) {
    stats.total++;
    const isNew = await ingestPattern(pattern);
    if (isNew) stats.new++; else stats.updated++;
    process.stdout.write('.');
  }
  console.log(` βœ“ ${typescriptErrors.length} patterns`);

  console.log('\n═══════════════════════════════════════════════════════════════════════════');
  console.log(`βœ… COMPLETE: ${stats.total} patterns processed`);
  console.log(`   New: ${stats.new} | Updated: ${stats.updated}`);
  console.log('═══════════════════════════════════════════════════════════════════════════\n');

  // Persist to Neo4j
  console.log('πŸ’Ύ Persisting to Neo4j...');
  try {
    const res = await fetch(`${API_BASE}/persist`, { method: 'POST' });
    const data = await res.json();
    console.log(`   βœ“ ${data.success} patterns persisted to database\n`);
  } catch (e) {
    console.log('   ⚠ Neo4j persistence skipped (service not available)\n');
  }

  // Get final stats
  try {
    const res = await fetch(`${API_BASE}/knowledge/stats`);
    const stats = await res.json();
    console.log('πŸ“Š FINAL KNOWLEDGE BASE STATS:');
    console.log(`   Total patterns: ${stats.totalPatterns}`);
    console.log(`   Total solutions: ${stats.totalSolutions}`);
    console.log('   Sources:', Object.entries(stats.bySource || {}).map(([k,v]) => `${k}:${v}`).join(', '));
  } catch (e) {
    console.log('   Could not fetch final stats');
  }
}

main().catch(console.error);