File size: 56,318 Bytes
529090e
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
76b54f1
1d28c11
 
529090e
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1d28c11
529090e
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1d28c11
 
 
 
 
 
 
 
33f2414
1d28c11
 
529090e
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
33f2414
 
 
 
 
 
529090e
33f2414
529090e
33f2414
 
 
 
 
 
 
 
 
 
529090e
 
1d28c11
 
 
 
76b54f1
1d28c11
 
 
 
 
 
 
 
 
 
 
 
76b54f1
 
1d28c11
 
76b54f1
1d28c11
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
76b54f1
1d28c11
76b54f1
1d28c11
76b54f1
1d28c11
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
529090e
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
76b54f1
 
 
 
529090e
 
 
 
 
 
 
 
76b54f1
 
 
529090e
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
76b54f1
1d28c11
 
 
76b54f1
529090e
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
bbf18eb
 
 
 
 
529090e
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
f1a6f7e
 
 
529090e
 
 
 
 
f1a6f7e
 
 
 
 
 
 
 
 
 
 
 
529090e
f1a6f7e
 
529090e
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1d28c11
 
 
 
 
 
 
529090e
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1d28c11
 
 
 
 
 
529090e
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
// Load environment variables FIRST - before any other imports
import { config } from 'dotenv';
import { resolve } from 'path';
import { fileURLToPath } from 'url';

// Polyfills for PDF parsing environment (pdfjs-dist v4+ compatibility)
// @ts-ignore
if (typeof global.DOMMatrix === 'undefined') {
  // @ts-ignore
  global.DOMMatrix = class DOMMatrix {
    a = 1; b = 0; c = 0; d = 1; e = 0; f = 0;
    constructor() { }
  };
}
// @ts-ignore
if (typeof global.ImageData === 'undefined') {
  // @ts-ignore
  global.ImageData = class ImageData {
    data: Uint8ClampedArray;
    width: number;
    height: number;
    constructor(width: number, height: number) {
      this.width = width;
      this.height = height;
      this.data = new Uint8ClampedArray(width * height * 4);
    }
  };
}
// @ts-ignore
if (typeof global.Path2D === 'undefined') {
  // @ts-ignore
  global.Path2D = class Path2D { };
}

const __dirname = typeof import.meta !== 'undefined' && import.meta.url
  ? new URL('.', import.meta.url).pathname.replace(/^\/([A-Z]:)/, '$1')
  : process.cwd();
// Load .env from backend directory, or root if not found
config({ path: resolve(__dirname, '../.env') });
config({ path: resolve(__dirname, '../../../.env') });

// --- SAFETY CHECK: VISUAL CONFIRMATION ---
const ENV_MODE = process.env.NODE_ENV || 'unknown';
const DB_HOST = process.env.POSTGRES_HOST || 'unknown';
const NEO_URI = process.env.NEO4J_URI || 'unknown';

console.log('\n\n');
if (ENV_MODE === 'production') {
  console.error('╔══════════════════════════════════════════════════════════════╗');
  console.error('β•‘                    WARNING: PRODUCTION MODE                  β•‘');
  console.error('β•‘   You are running against LIVE DATA. Use extreme caution.    β•‘');
  console.error('β•šβ•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•');
} else {
  console.log('╔══════════════════════════════════════════════════════════════╗');
  console.log('β•‘                 SAFE MODE: LOCAL DEVELOPMENT                 β•‘');
  console.log('β•‘                                                              β•‘');
  console.log(`β•‘  β€’ Environment: ${ENV_MODE.padEnd(28)} β•‘`);
  console.log(`β•‘  β€’ Postgres:    ${DB_HOST.padEnd(28)} β•‘`);
  console.log(`β•‘  β€’ Neo4j:       ${NEO_URI.padEnd(28)} β•‘`);
  console.log('β•šβ•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•');
}
console.log('\n');
// -----------------------------------------

import express from 'express';
import cors from 'cors';
import path from 'path';
import { createServer } from 'http';
import { initializeDatabase } from './database/index.js';
import { mcpRouter } from './mcp/mcpRouter.js';
import { mcpRegistry } from './mcp/mcpRegistry.js';
import { MCPWebSocketServer } from './mcp/mcpWebsocketServer.js';
import { WebSocketServer as LogsWebSocketServer, WebSocket as LogsWebSocket } from 'ws';
import { memoryRouter } from './services/memory/memoryController.js';
import { sragRouter } from './services/srag/sragController.js';
import { evolutionRouter } from './services/evolution/evolutionController.js';
import { palRouter } from './services/pal/palController.js';
import datasourcesRouter from './routes/datasources.js';
import {
  cmaContextHandler,
  cmaIngestHandler,
  cmaMemoryStoreHandler,
  cmaMemoryRetrieveHandler,
  sragQueryHandler,
  sragGovernanceCheckHandler,
  evolutionReportHandler,
  evolutionGetPromptHandler,
  evolutionAnalyzePromptsHandler,
  palEventHandler,
  palBoardActionHandler,
  palOptimizeWorkflowHandler,
  palAnalyzeSentimentHandler,
  notesListHandler,
  notesCreateHandler,
  notesUpdateHandler,
  notesDeleteHandler,
  notesGetHandler,
  widgetsInvokeHandler,
  widgetsOsintInvestigateHandler,
  widgetsThreatHuntHandler,
  widgetsOrchestratorCoordinateHandler,
  widgetsUpdateStateHandler,
  visionaryGenerateHandler,
  dataAnalysisHandler
} from './mcp/toolHandlers.js';
import { securityRouter } from './services/security/securityController.js';
import { AgentOrchestratorServer } from './mcp/servers/AgentOrchestratorServer.js';
import {
  inputValidationMiddleware,
  csrfProtectionMiddleware,
  rateLimitingMiddleware
} from './middleware/inputValidation.js';
import { dataScheduler } from './services/ingestion/DataScheduler.js';

// 🧠 NEURAL ORGANS - Phase B: Knowledge Synthesis
import { neuralCompiler } from './services/NeuralCompiler.js';
import { neuralBus } from './services/NeuralBus.js';
import { vectorService } from './services/VectorService.js';

// 🐝 SWARM & EVOLUTION - Advanced Neural Systems
import { swarmControl } from './agents/SwarmControl.js';
import { handoverWatchdog } from './services/HandoverWatchdog.js';
import { AngelProxy } from './middleware/AngelProxy.js';
import { prometheus } from './services/Prometheus.js';
import { logStream } from './services/logging/logStream.js';

const app = express();
const PORT = parseInt(process.env.PORT || '7860', 10);

// CORS Configuration
const corsOrigin = process.env.CORS_ORIGIN || '*';
app.use(cors({
  origin: corsOrigin === '*' ? '*' : corsOrigin.split(',').map(o => o.trim()),
  credentials: true,
  methods: ['GET', 'POST', 'PUT', 'DELETE', 'PATCH', 'OPTIONS'],
  allowedHeaders: ['Content-Type', 'Authorization', 'X-Requested-With'],
}));
app.use(express.json({ limit: '10mb' }));
app.use(rateLimitingMiddleware);
app.use(inputValidationMiddleware);
app.use(csrfProtectionMiddleware);

// CRITICAL: Start server only after database is initialized
async function startServer() {
  try {
    // ═══════════════════════════════════════════════════════════════════
    // EARLY SERVER START - Start accepting connections ASAP
    // ═══════════════════════════════════════════════════════════════════
    const server = createServer(app);
    const wsServer = new MCPWebSocketServer(server);

    // Health check endpoint - FAST response
    app.get('/health', async (req, res) => {
      // Basic process health - registeredTools count fetched dynamically
      res.json({
        status: 'healthy', // Always return healthy if process is up
        timestamp: new Date().toISOString(),
        uptime: process.uptime(),
        environment: process.env.NODE_ENV,
        registeredTools: mcpRegistry.getRegisteredTools().length
      });
    });

    // Readiness/Liveness checks
    app.get('/ready', (req, res) => res.json({ ready: true }));
    app.get('/live', (req, res) => res.json({ live: true }));

    // Start server IMMEDIATELY
    // CRITICAL ARCHITECTURE DECISION:
    // We force PORT 3001 to match the NudgeService internal wiring.
    // Cloud defaults like 7860 break the internal reflex arc.
    const PORT = 3001;

    server.listen(PORT, '0.0.0.0', () => {
      console.log(`πŸš€ Backend server running on http://0.0.0.0:${PORT}`);
      console.log(`πŸ“‘ MCP WebSocket available at ws://0.0.0.0:${PORT}/mcp/ws`);
      console.log(`✨ [SYSTEM] Neural Singularity aligned on Port ${PORT}`);

      // ACTIVATING AUTONOMOUS REFLEXES
      handoverWatchdog.startWatch();

      // Listen for signals (This is where we hook into the Orchestrator later)
      handoverWatchdog.on('handover_signal', (signal) => {
        console.log(`πŸ”” [SYSTEM] ORCHESTRATOR ALERT: Activating ${signal.target}...`);
        // TODO: Integrate with agentOrchestrator.triggerAgent(signal.target);
      });
    });

    // ============================================
    // 🧠 NEURAL ORGANS INITIALIZATION
    // Phase B: Knowledge Synthesis
    // ============================================

    // 1. Initialize Vector Service (Dark Matter)
    vectorService.init().then(() => {
      console.log('πŸŒ‘ [DARK MATTER] Vector Engine Ready (384 dimensions)');
    }).catch(err => {
      console.warn('πŸŒ‘ [DARK MATTER] Vector init deferred:', err.message);
    });

    // 2. Attach Neural Bus (Telepathy) to HTTP server
    neuralBus.attach(server);
    console.log('🐝 [HIVE] Neural Telepathy Bus Attached');

    // 3. Start Knowledge Compiler (Brain) - Watch DropZone
    const DROPZONE_PATH = process.env.DROPZONE_PATH ||
      (process.platform === 'win32'
        ? 'C:\\Users\\claus\\Desktop\\WidgeTDC_DropZone'
        : '/app/data/dropzone');

    neuralCompiler.startWatching(DROPZONE_PATH).then(() => {
      console.log(`πŸ“š [BRAIN] Neural Compiler watching: ${DROPZONE_PATH}`);
    }).catch(err => {
      console.warn('πŸ“š [BRAIN] Neural Compiler deferred:', err.message);
    });

    console.log('✨ [OMEGA] Neural Singularity Sequence Initiated');

    // 4. Initialize Swarm Consciousness (The Borg)
    swarmControl.registerAgent('SYSTEM_CORE', 'ARCHITECT', 3);
    swarmControl.registerAgent('PROMETHEUS', 'ARCHITECT', 2);
    swarmControl.registerAgent('KNOWLEDGE_COMPILER', 'EXECUTOR', 1);
    swarmControl.registerAgent('ANGEL_PROXY', 'GUARDIAN', 2);
    console.log('🐝 [HIVE] Swarm Consciousness Initialized');

    // 5. Start Prometheus Code Scanner (every hour)
    const SCAN_INTERVAL = parseInt(process.env.PROMETHEUS_SCAN_INTERVAL || '3600000');
    setTimeout(() => {
      prometheus.scanAndPropose(path.join(__dirname, 'services')).catch(() => { });
    }, 10000); // Initial scan after 10s

    setInterval(() => {
      prometheus.scanAndPropose(path.join(__dirname, 'services')).catch(() => { });
    }, SCAN_INTERVAL);
    console.log('πŸ”₯ [PROMETHEUS] Code Evolution Scanner Active');

    console.log('');
    console.log('╔══════════════════════════════════════════════════════════════╗');
    console.log('β•‘          🧠 NEURAL SINGULARITY FULLY OPERATIONAL 🧠          β•‘');
    console.log('β•‘                                                              β•‘');
    console.log('β•‘  SEGA     βœ“  Knowledge Graph Active                          β•‘');
    console.log('β•‘  THG      βœ“  Temporal Hypergraphs Ready                       β•‘');
    console.log('β•‘  SCE      βœ“  Swarm Consciousness Online                       β•‘');
    console.log('β•‘  PTAM     βœ“  Angel Security Shield Active                     β•‘');
    console.log('β•‘  CDMM     βœ“  Vector Dark Matter Engine                        β•‘');
    console.log('β•‘  APD      βœ“  Prometheus Evolution Watching                    β•‘');
    console.log('β•‘  QEK      βœ“  Neural Telepathy Bus Connected                   β•‘');
    console.log('β•šβ•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•');
    console.log('');

    // Setup Logs WebSocket
    const logsWsServer = new LogsWebSocketServer({ server, path: '/api/logs/stream' });
    logsWsServer.on('connection', (socket: LogsWebSocket) => {
      try {
        // Send recent logs buffer
        socket.send(JSON.stringify({ type: 'bootstrap', entries: logStream.getRecent({ limit: 50 }) }));
      } catch (err) {
        console.error('Failed to send initial log buffer:', err);
      }

      const listener = (entry: any) => {
        if (socket.readyState === LogsWebSocket.OPEN) {
          socket.send(JSON.stringify({ type: 'log', entry }));
        }
      };
      logStream.on('log', listener);
      socket.on('close', () => logStream.off('log', listener));
    });

    // Wire up WebSocket (async)
    (async () => {
      try {
        const { setWebSocketServer } = await import('./mcp/autonomousRouter.js');
        setWebSocketServer(wsServer);
      } catch (err) { /* ignore */ }
    })();


    // Show environment banner
    const isProd = process.env.NODE_ENV === 'production';
    const neo4jUri = process.env.NEO4J_URI || 'bolt://localhost:7687';
    const isAuraDB = neo4jUri.includes('neo4j.io') || neo4jUri.startsWith('neo4j+s://');

    console.log('');
    console.log('═══════════════════════════════════════════════════════════');
    if (isProd || isAuraDB) {
      console.log('  πŸ”΄ WIDGETTDC - PRODUCTION MODE');
      console.log('  Neo4j: AuraDB Cloud');
    } else {
      console.log('  🟒 WIDGETTDC - DEVELOPMENT MODE');
      console.log('  Neo4j: Local Docker');
    }
    console.log(`  URI: ${neo4jUri}`);
    console.log('═══════════════════════════════════════════════════════════');
    console.log('');

    // Step 0: Always initialize sql.js (used by CognitiveMemory, etc)
    await initializeDatabase();
    console.log('πŸ—„οΈ  SQLite (sql.js) initialized for memory systems');

    // Step 1: Initialize Prisma (PostgreSQL + pgvector) - Primary database
    try {
      const { getDatabaseAdapter } = await import('./platform/db/PrismaDatabaseAdapter.js');
      const prismaAdapter = getDatabaseAdapter();
      await prismaAdapter.initialize();
      console.log('🐘 PostgreSQL + pgvector initialized via Prisma');
    } catch (prismaError) {
      console.warn('⚠️  Prisma/PostgreSQL not available:', prismaError);
      console.log('   Using SQLite (sql.js) as fallback for all storage');
    }

    // Step 1.5: Initialize Neo4j Graph Database
    try {
      const { getNeo4jGraphAdapter } = await import('./platform/graph/Neo4jGraphAdapter.js');
      const neo4jAdapter = getNeo4jGraphAdapter();
      await neo4jAdapter.initialize();
      console.log('πŸ•ΈοΈ  Neo4j Graph Database initialized');

      // Also connect Neo4jService (used by GraphMemoryService)
      const { neo4jService } = await import('./database/Neo4jService.js');
      await neo4jService.connect();
      console.log('πŸ•ΈοΈ  Neo4j Service connected');

      // Run initialization if database is empty
      const stats = await neo4jAdapter.getStatistics();
      if (stats.nodeCount < 5) {
        console.log('πŸ“¦ Neo4j database appears empty, running initialization...');
        const { initializeNeo4j } = await import('./scripts/initNeo4j.js');
        await initializeNeo4j();
      }
    } catch (error) {
      console.warn('⚠️  Neo4j not available (optional):', error);
      console.log('   Continuing without Neo4j - using implicit graph patterns');
    }

    // Step 1.6: Initialize Transformers.js Embeddings
    try {
      const { getTransformersEmbeddings } = await import('./platform/embeddings/TransformersEmbeddings.js');
      const embeddings = getTransformersEmbeddings();
      await embeddings.initialize();
      console.log('🧠 Transformers.js Embeddings initialized');
    } catch (error) {
      console.warn('⚠️  Transformers.js not available (optional):', error);
      console.log('   Continuing without local embeddings');
    }

    // Step 2: Register MCP tools (repositories can now safely use getDatabase())
    mcpRegistry.registerTool('cma.context', cmaContextHandler);
    mcpRegistry.registerTool('cma.ingest', cmaIngestHandler);
    mcpRegistry.registerTool('cma.memory.store', cmaMemoryStoreHandler);
    mcpRegistry.registerTool('cma.memory.retrieve', cmaMemoryRetrieveHandler);
    mcpRegistry.registerTool('srag.query', sragQueryHandler);
    mcpRegistry.registerTool('srag.governance-check', sragGovernanceCheckHandler);
    mcpRegistry.registerTool('evolution.report-run', evolutionReportHandler);
    mcpRegistry.registerTool('evolution.get-prompt', evolutionGetPromptHandler);
    mcpRegistry.registerTool('evolution.analyze-prompts', evolutionAnalyzePromptsHandler);
    mcpRegistry.registerTool('pal.event', palEventHandler);
    mcpRegistry.registerTool('pal.board-action', palBoardActionHandler);
    mcpRegistry.registerTool('pal.optimize-workflow', palOptimizeWorkflowHandler);
    mcpRegistry.registerTool('pal.analyze-sentiment', palAnalyzeSentimentHandler);
    mcpRegistry.registerTool('notes.list', notesListHandler);
    mcpRegistry.registerTool('notes.create', notesCreateHandler);
    mcpRegistry.registerTool('notes.update', notesUpdateHandler);
    mcpRegistry.registerTool('notes.delete', notesDeleteHandler);
    mcpRegistry.registerTool('notes.get', notesGetHandler);
    mcpRegistry.registerTool('widgets.invoke', widgetsInvokeHandler);
    mcpRegistry.registerTool('widgets.osint.investigate', widgetsOsintInvestigateHandler);
    mcpRegistry.registerTool('widgets.threat.hunt', widgetsThreatHuntHandler);
    mcpRegistry.registerTool('widgets.orchestrator.coordinate', widgetsOrchestratorCoordinateHandler);
    mcpRegistry.registerTool('widgets.update_state', widgetsUpdateStateHandler);
    mcpRegistry.registerTool('visionary.generate', visionaryGenerateHandler);
    mcpRegistry.registerTool('data.analysis', dataAnalysisHandler);

    // Project Memory tools
    const {
      projectMemoryLogEventHandler,
      projectMemoryGetEventsHandler,
      projectMemoryAddFeatureHandler,
      projectMemoryUpdateFeatureHandler,
      projectMemoryGetFeaturesHandler
    } = await import('./mcp/projectMemoryHandlers.js');

    mcpRegistry.registerTool('project.log_event', projectMemoryLogEventHandler);
    mcpRegistry.registerTool('project.get_events', projectMemoryGetEventsHandler);
    mcpRegistry.registerTool('project.add_feature', projectMemoryAddFeatureHandler);
    mcpRegistry.registerTool('project.update_feature', projectMemoryUpdateFeatureHandler);
    mcpRegistry.registerTool('project.get_features', projectMemoryGetFeaturesHandler);

    // Data Ingestion tools
    const {
      ingestionStartHandler,
      ingestionStatusHandler,
      ingestionConfigureHandler,
      ingestionCrawlHandler,
      ingestionHarvestHandler
    } = await import('./mcp/ingestionHandlers.js');

    mcpRegistry.registerTool('ingestion.start', ingestionStartHandler);
    mcpRegistry.registerTool('ingestion.status', ingestionStatusHandler);
    mcpRegistry.registerTool('ingestion.configure', ingestionConfigureHandler);
    mcpRegistry.registerTool('ingestion.crawl', ingestionCrawlHandler);
    mcpRegistry.registerTool('ingestion.harvest', ingestionHarvestHandler);

    // Autonomous Cognitive Tools
    const {
      autonomousGraphRAGHandler,
      autonomousStateGraphHandler,
      autonomousEvolutionHandler,
      autonomousAgentTeamHandler,
      autonomousAgentTeamCoordinateHandler
    } = await import('./mcp/toolHandlers.js');

    mcpRegistry.registerTool('autonomous.graphrag', autonomousGraphRAGHandler);
    mcpRegistry.registerTool('autonomous.stategraph', autonomousStateGraphHandler);
    mcpRegistry.registerTool('autonomous.evolve', autonomousEvolutionHandler);
    mcpRegistry.registerTool('autonomous.agentteam', autonomousAgentTeamHandler);
    mcpRegistry.registerTool('autonomous.agentteam.coordinate', autonomousAgentTeamCoordinateHandler);

    // Vidensarkiv (Knowledge Archive) Tools - Persistent vector database
    const {
      vidensarkivSearchHandler,
      vidensarkivAddHandler,
      vidensarkivBatchAddHandler,
      vidensarkivGetRelatedHandler,
      vidensarkivListHandler,
      vidensarkivStatsHandler,
      vidensarkivReadHandler,
      vidensarkivListFilesHandler,
      vidensarkivReadFileHandler
    } = await import('./mcp/toolHandlers.js');

    mcpRegistry.registerTool('vidensarkiv.search', vidensarkivSearchHandler);
    mcpRegistry.registerTool('vidensarkiv.add', vidensarkivAddHandler);
    mcpRegistry.registerTool('vidensarkiv.batch_add', vidensarkivBatchAddHandler);
    mcpRegistry.registerTool('vidensarkiv.get_related', vidensarkivGetRelatedHandler);
    mcpRegistry.registerTool('vidensarkiv.list', vidensarkivListHandler);
    mcpRegistry.registerTool('vidensarkiv.stats', vidensarkivStatsHandler);
    mcpRegistry.registerTool('vidensarkiv.read', vidensarkivReadHandler);
    mcpRegistry.registerTool('vidensarkiv.list_files', vidensarkivListFilesHandler);
    mcpRegistry.registerTool('vidensarkiv.read_file', vidensarkivReadFileHandler);

    // TaskRecorder Tools
    const {
      taskRecorderGetSuggestionsHandler,
      taskRecorderApproveHandler,
      taskRecorderRejectHandler,
      taskRecorderExecuteHandler,
      taskRecorderGetPatternsHandler,
      emailRagHandler
    } = await import('./mcp/toolHandlers.js');

    mcpRegistry.registerTool('taskrecorder.get_suggestions', taskRecorderGetSuggestionsHandler);
    mcpRegistry.registerTool('taskrecorder.approve', taskRecorderApproveHandler);
    mcpRegistry.registerTool('taskrecorder.reject', taskRecorderRejectHandler);
    mcpRegistry.registerTool('taskrecorder.execute', taskRecorderExecuteHandler);
    mcpRegistry.registerTool('taskrecorder.get_patterns', taskRecorderGetPatternsHandler);
    mcpRegistry.registerTool('email.rag', emailRagHandler);

    // Document Generator Tools
    const {
      docgenPowerpointCreateHandler,
      docgenWordCreateHandler,
      docgenExcelCreateHandler,
      docgenStatusHandler
    } = await import('./mcp/toolHandlers.js');

    mcpRegistry.registerTool('docgen.powerpoint.create', docgenPowerpointCreateHandler);
    mcpRegistry.registerTool('docgen.word.create', docgenWordCreateHandler);
    mcpRegistry.registerTool('docgen.excel.create', docgenExcelCreateHandler);
    mcpRegistry.registerTool('docgen.status', docgenStatusHandler);

    // DevTools Guardian Tools
    const { handleDevToolsRequest } = await import('./mcp/devToolsHandlers.js');
    mcpRegistry.registerTool('devtools-status', handleDevToolsRequest);
    mcpRegistry.registerTool('devtools-scan', handleDevToolsRequest);
    mcpRegistry.registerTool('devtools-validate', handleDevToolsRequest);

    const { tdcGeneratePresentationHandler } = await import('./mcp/tdcHandlers.js');
    mcpRegistry.registerTool('tdc.generate_presentation', tdcGeneratePresentationHandler);

    // Serve public files (for generated presentations)
    app.use(express.static('public'));

    // Step 3: Initialize Agent Orchestrator
    const orchestrator = new AgentOrchestratorServer();
    mcpRegistry.registerServer(orchestrator);
    console.log('πŸ€– Agent Orchestrator initialized');

    // Step 3.5: Initialize Autonomous Intelligence System
    const { initCognitiveMemory } = await import('./mcp/memory/CognitiveMemory.js');
    const { getSourceRegistry } = await import('./mcp/SourceRegistry.js');
    const { initAutonomousAgent, startAutonomousLearning } = await import('./mcp/autonomousRouter.js');
    const { autonomousRouter } = await import('./mcp/autonomousRouter.js');
    const { getSqlJsDatabase } = await import('./database/index.js');
    const { existsSync } = await import('fs');
    const { readFileSync } = await import('fs');
    const yaml = (await import('js-yaml')).default;

    // Use raw sql.js database for memory systems (they need exec() method)
    const sqlJsDb = getSqlJsDatabase();
    if (sqlJsDb) {
      initCognitiveMemory(sqlJsDb);
      console.log('🧠 Cognitive Memory initialized');
    } else {
      console.warn('⚠️ Cognitive Memory running in degraded mode (no sql.js database)');
      initCognitiveMemory();
    }

    // Initialize Unified Memory System
    const { unifiedMemorySystem } = await import('./mcp/cognitive/UnifiedMemorySystem.js');
    unifiedMemorySystem.init();
    console.log('🧠 Unified Memory System initialized');

    const registry = getSourceRegistry();

    // Register agents-yaml data source
    registry.registerSource({
      name: 'agents-yaml',
      type: 'file',
      capabilities: ['agents.*', 'agents.list', 'agents.get', 'agents.trigger'],
      isHealthy: async () => existsSync('agents/registry.yml'),
      estimatedLatency: 50,
      costPerQuery: 0,
      query: async (operation: string, params: any) => {
        const content = readFileSync('agents/registry.yml', 'utf-8');
        const data = yaml.load(content) as any;

        if (operation === 'list') {
          return data.agents || [];
        } else if (operation === 'get' && params?.id) {
          return data.agents?.find((a: any) => a.id === params.id);
        }

        return data.agents || [];
      }
    });

    // Step 3.6: Initialize MCP β†’ Autonomous Integration (non-blocking with timeout)
    const autonomousInitPromise = (async () => {
      try {
        const timeoutPromise = new Promise((_, reject) =>
          setTimeout(() => reject(new Error('Autonomous init timeout')), 5000)
        );
        const { initializeAutonomousSources } = await import('./mcp/autonomous/MCPIntegration.js');
        await Promise.race([initializeAutonomousSources(), timeoutPromise]);
        console.log('πŸ”— MCP tools registered as autonomous sources');

        const agent = initAutonomousAgent();
        console.log('πŸ€– Autonomous Agent initialized');

        startAutonomousLearning(agent, 300000);
        console.log('πŸ”„ Autonomous learning started (5min intervals)');
      } catch (err: any) {
        console.warn('⚠️ Autonomous sources initialization skipped:', err.message);
      }
    })();
    // Don't await - let it run in background

    // Step 3.7: Start HansPedder orchestrator (non-blocking)
    (async () => {
      try {
        const { startHansPedder } = await import('./orchestrator/hansPedder.js');
        await startHansPedder();
        console.log('πŸ‘” HansPedder orchestrator started');
      } catch (err) {
        console.error('⚠️ Failed to start HansPedder:', err);
      }
    })();

    // Step 3.8: Start Data Ingestion Scheduler
    dataScheduler.start();
    console.log('⏰ Data Ingestion Scheduler started');

    // Step 3.8.5: Start NudgeService (aggressive data generation every 15 min)
    const { nudgeService } = await import('./services/NudgeService.js');
    nudgeService.start();

    // Step 3.9: Start HansPedder Agent Controller (non-blocking)
    (async () => {
      try {
        const { hansPedderAgent } = await import('./services/agent/HansPedderAgentController.js');
        hansPedderAgent.start();
        console.log('πŸ€– HansPedder Agent Controller started (continuous testing + nudges)');
      } catch (err) {
        console.error('⚠️ Failed to start HansPedder Agent Controller:', err);
      }
    })();

    // Step 4: Setup routes

    // πŸ›‘οΈ ANGEL PROXY: Security Shield on all API routes
    app.use('/api', AngelProxy.cortexFirewall);
    console.log('πŸ›‘οΈ [ANGEL] Cortex Firewall Active on /api/*');

    app.use('/api/mcp', mcpRouter);
    app.use('/api/mcp/autonomous', autonomousRouter);
    app.use('/api/memory', memoryRouter);
    app.use('/api/srag', sragRouter);
    app.use('/api/evolution', evolutionRouter);
    app.use('/api/harvest', (req, res, next) => {
      req.url = `/harvest${req.url}`;
      evolutionRouter(req, res, next);
    });
    app.use('/api/pal', palRouter);
    app.use('/api/security', securityRouter);

    // HansPedder Agent Controller routes
    const hanspedderRoutes = (await import('./routes/hanspedderRoutes.js')).default;
    app.use('/api/hanspedder', hanspedderRoutes);

    // Prototype Generation routes (PRD to Prototype)
    const prototypeRoutes = (await import('./routes/prototype.js')).default;
    app.use('/api/prototype', prototypeRoutes);

    // System Information routes (CPU, Memory, GPU, Network stats)
    const sysRoutes = (await import('./routes/sys.js')).default;
    app.use('/api/sys', sysRoutes);
    console.log('πŸ“Š System Info API mounted at /api/sys');

    // Neural Chat - Agent-to-Agent Communication
    const { neuralChatRouter } = await import('./services/NeuralChat/index.js');
    app.use('/api/neural-chat', neuralChatRouter);
    console.log('πŸ’¬ Neural Chat API mounted at /api/neural-chat');

    // Knowledge Compiler - System State Aggregation
    const knowledgeRoutes = (await import('./routes/knowledge.js')).default;
    app.use('/api/knowledge', knowledgeRoutes);
    console.log('🧠 Knowledge API mounted at /api/knowledge');

    // Knowledge Acquisition - The Omni-Harvester
    const acquisitionRoutes = (await import('./routes/acquisition.js')).default;
    app.use('/api/acquisition', acquisitionRoutes);
    console.log('🌾 Omni-Harvester API mounted at /api/acquisition');

    // Email API - Cloud-compatible email fetching via IMAP
    const emailRoutes = (await import('./routes/email.js')).default;
    app.use('/api/email', emailRoutes);
    console.log('πŸ“§ Email API mounted at /api/email');

    // Neo4j Sync API - Auto-sync between local and cloud
    const neo4jSyncRoutes = (await import('./routes/neo4j-sync.js')).default;
    app.use('/api/neo4j-sync', neo4jSyncRoutes);
    console.log('πŸ”„ Neo4j Sync API mounted at /api/neo4j-sync');

    // Start KnowledgeCompiler auto-compilation (every 60 seconds)
    const { knowledgeCompiler } = await import('./services/Knowledge/index.js');
    knowledgeCompiler.startAutoCompilation(60000);
    console.log('🧠 KnowledgeCompiler auto-compilation started');

    // ═══════════════════════════════════════════════════════════════════
    // πŸ›‘οΈ BOOTSTRAP HEALTH CHECKS now run inside BootstrapGate.init()
    // Prevents "Death on Startup" if Neo4j/DB unavailable
    // ═══════════════════════════════════════════════════════════════════
    const bootstrapHealthCheck = async (): Promise<{ ready: boolean; degraded: boolean; services: any[] }> => {
      const services: { name: string; status: 'healthy' | 'degraded' | 'unavailable'; latencyMs?: number }[] = [];
      let criticalFailure = false;

      // Check Neo4j
      try {
        const start = Date.now();
        const { neo4jAdapter } = await import('./adapters/Neo4jAdapter.js');
        await neo4jAdapter.executeQuery('RETURN 1 as ping');
        services.push({ name: 'Neo4j', status: 'healthy', latencyMs: Date.now() - start });
        console.log('βœ… Neo4j: HEALTHY');
      } catch (err: any) {
        services.push({ name: 'Neo4j', status: 'degraded' });
        console.warn('⚠️ Neo4j: DEGRADED - continuing without graph features');
      }

      // Check Prisma/PostgreSQL (already initialized above)
      try {
        const start = Date.now();
        // Prisma is already connected if we got here
        services.push({ name: 'PostgreSQL', status: 'healthy', latencyMs: Date.now() - start });
        console.log('βœ… PostgreSQL: HEALTHY (Prisma connected)');
      } catch (err: any) {
        services.push({ name: 'PostgreSQL', status: 'degraded' });
        console.warn('⚠️ PostgreSQL: DEGRADED - some features may be unavailable');
      }

      // Check filesystem (DropZone)
      try {
        const fs = await import('fs/promises');
        const { DROPZONE_PATH } = await import('./config.js');
        await fs.access(DROPZONE_PATH);
        services.push({ name: 'Filesystem', status: 'healthy' });
        console.log(`βœ… Filesystem: HEALTHY (${DROPZONE_PATH})`);
      } catch {
        services.push({ name: 'Filesystem', status: 'degraded' });
        console.warn('⚠️ Filesystem: DropZone not accessible');
      }

      const degraded = services.some(s => s.status === 'degraded');
      return { ready: !criticalFailure, degraded, services };
    };

    console.log('\nπŸ” Running Bootstrap Health Check...');
    const bootHealth = await bootstrapHealthCheck();

    if (!bootHealth.ready) {
      console.error('πŸ’€ CRITICAL: Bootstrap health check failed - aborting startup');
      process.exit(1);
    }

    if (bootHealth.degraded) {
      console.warn('⚠️ WARNING: Starting in DEGRADED MODE - some features may be unavailable\n');
    } else {
      console.log('βœ… All systems nominal - proceeding with startup\n');
    }

    // Server started early at top of startServer()

    // ═══════════════════════════════════════════════════════════════════
    // CONTINUING INITIALIZATION...
    // ═══════════════════════════════════════════════════════════════════

    // ============================================
    // KNOWLEDGE COMPILER API - System Intelligence
    // ============================================
    const knowledgeApi = (await import('./api/knowledge.js')).default;
    app.use('/api/knowledge', knowledgeApi);
    console.log('πŸ“š Knowledge Compiler API mounted at /api/knowledge');

    const logsRouter = (await import('./routes/logs.js')).default;
    app.use('/api/logs', logsRouter);
    console.log('πŸ“ Log API mounted at /api/logs');

    // HyperLog API - Real-time intelligence monitoring for NeuroLink widget
    app.get('/api/hyper/events', async (req, res) => {
      try {
        const { hyperLog } = await import('./services/hyper-log.js');
        const events = hyperLog.getHistory(50);
        const metrics = hyperLog.getMetrics();
        res.json({ events, metrics });
      } catch (error) {
        console.error('HyperLog error:', error);
        res.status(500).json({ error: 'HyperLog unavailable', events: [], metrics: { totalThoughts: 0, toolUsageRate: 0, activeAgents: 0 } });
      }
    });

    // ============================================
    // SEMANTIC BUS: Widget Telepathy API
    // ============================================

    // Dream API - Semantic search across collective memory
    app.post('/api/hyper/dream', async (req, res) => {
      try {
        const { hyperLog } = await import('./services/hyper-log.js');
        const { query, limit = 5, minScore = 0.6 } = req.body;

        if (!query) {
          return res.status(400).json({ error: 'Query is required' });
        }

        const results = await hyperLog.findRelatedThoughts(query, limit, minScore);
        const canDream = hyperLog.canDream();

        res.json({
          results,
          query,
          dreamMode: canDream ? 'semantic' : 'keyword',
          timestamp: Date.now()
        });
      } catch (error) {
        console.error('Dream API error:', error);
        res.status(500).json({ error: 'Dream failed', results: [] });
      }
    });

    // Broadcast API - Widget sends a thought into the collective
    app.post('/api/hyper/broadcast', async (req, res) => {
      try {
        const { hyperLog } = await import('./services/hyper-log.js');
        const { type, agent, content, metadata = {} } = req.body;

        if (!type || !agent || !content) {
          return res.status(400).json({ error: 'type, agent, and content are required' });
        }

        const eventId = await hyperLog.log(type, agent, content, metadata);

        res.json({
          success: true,
          eventId,
          timestamp: Date.now()
        });
      } catch (error) {
        console.error('Broadcast API error:', error);
        res.status(500).json({ error: 'Broadcast failed' });
      }
    });

    // Find similar thoughts to a specific event
    app.get('/api/hyper/similar/:eventId', async (req, res) => {
      try {
        const { hyperLog } = await import('./services/hyper-log.js');
        const { eventId } = req.params;
        const limit = parseInt(req.query.limit as string) || 5;

        const results = await hyperLog.findSimilarTo(eventId, limit);

        res.json({ results, eventId });
      } catch (error) {
        console.error('Similar API error:', error);
        res.status(500).json({ error: 'Similarity search failed', results: [] });
      }
    });

    // Get causal path leading to an event (rewind the brain)
    app.get('/api/hyper/rewind/:eventId', async (req, res) => {
      try {
        const { hyperLog } = await import('./services/hyper-log.js');
        const { eventId } = req.params;
        const maxDepth = parseInt(req.query.maxDepth as string) || 50;

        const path = await hyperLog.getCausalPath(eventId, maxDepth);

        res.json({ path, eventId, depth: path.length });
      } catch (error) {
        console.error('Rewind API error:', error);
        res.status(500).json({ error: 'Rewind failed', path: [] });
      }
    });

    // Start a new thought chain (correlation)
    app.post('/api/hyper/chain/start', async (req, res) => {
      try {
        const { hyperLog } = await import('./services/hyper-log.js');
        const { label } = req.body;

        const correlationId = hyperLog.startChain(label);

        res.json({ correlationId, label });
      } catch (error) {
        console.error('Chain start error:', error);
        res.status(500).json({ error: 'Failed to start chain' });
      }
    });

    // Get brain status (can it dream?)
    app.get('/api/hyper/status', async (req, res) => {
      try {
        const { hyperLog } = await import('./services/hyper-log.js');
        const metrics = hyperLog.getMetrics();
        const canDream = hyperLog.canDream();

        res.json({
          canDream,
          metrics,
          status: canDream ? 'dreaming' : 'awake',
          timestamp: Date.now()
        });
      } catch (error) {
        console.error('Status API error:', error);
        res.status(500).json({ error: 'Status unavailable' });
      }
    });

    // ============================================
    // THE STRATEGIST - Team Delegation API
    // ============================================

    /**
     * POST /api/team/delegate
     * The Strategist delegates tasks to team members (Architect, Visionary)
     */
    app.post('/api/team/delegate', async (req, res) => {
      try {
        const { hyperLog } = await import('./services/hyper-log.js');
        const {
          task,
          assignTo,
          priority = 'medium',
          context = {},
          parentTaskId
        } = req.body;

        if (!task || !assignTo) {
          return res.status(400).json({
            error: 'Missing required fields: task, assignTo'
          });
        }

        // Log the delegation event
        const eventId = await hyperLog.log(
          'DELEGATION',
          'TheStrategist',
          `Delegating to ${assignTo}: ${task}`,
          {
            assignedTo: assignTo,
            priority,
            context,
            parentTaskId,
            status: 'pending'
          }
        );

        // Broadcast the delegation for the assigned widget to pick up
        await hyperLog.log(
          'THOUGHT',
          assignTo,
          `Received task from Strategist: ${task}`,
          {
            delegationId: eventId,
            priority,
            context
          }
        );

        res.json({
          success: true,
          delegationId: eventId,
          message: `Task delegated to ${assignTo}`,
          task: {
            id: eventId,
            description: task,
            assignedTo: assignTo,
            priority,
            status: 'pending',
            createdAt: Date.now()
          }
        });

      } catch (error) {
        console.error('Delegation API error:', error);
        res.status(500).json({ error: 'Delegation failed' });
      }
    });

    /**
     * GET /api/team/tasks
     * Get all delegated tasks and their status
     */
    app.get('/api/team/tasks', async (req, res) => {
      try {
        const { hyperLog } = await import('./services/hyper-log.js');
        const { assignedTo, status } = req.query;

        // Search for delegation events
        const allEvents = hyperLog.getHistory(100);
        let tasks = allEvents.filter(e => e.type === 'DELEGATION');

        if (assignedTo) {
          tasks = tasks.filter(t => t.metadata?.assignedTo === assignedTo);
        }
        if (status) {
          tasks = tasks.filter(t => t.metadata?.status === status);
        }

        res.json({
          tasks: tasks.map(t => ({
            id: t.id,
            description: t.content,
            assignedTo: t.metadata?.assignedTo,
            priority: t.metadata?.priority,
            status: t.metadata?.status || 'pending',
            createdAt: t.timestamp,
            context: t.metadata?.context
          })),
          total: tasks.length
        });

      } catch (error) {
        console.error('Tasks API error:', error);
        res.status(500).json({ error: 'Failed to fetch tasks' });
      }
    });

    /**
     * PUT /api/team/tasks/:taskId/status
     * Update task status (e.g., in_progress, completed, blocked)
     */
    app.put('/api/team/tasks/:taskId/status', async (req, res) => {
      try {
        const { hyperLog } = await import('./services/hyper-log.js');
        const { taskId } = req.params;
        const { status, result, notes } = req.body;

        if (!status) {
          return res.status(400).json({ error: 'Status is required' });
        }

        // Log the status update
        const eventId = await hyperLog.log(
          'REASONING_UPDATE',
          'TheStrategist',
          `Task ${taskId} status updated to: ${status}`,
          {
            taskId,
            newStatus: status,
            result,
            notes,
            updatedAt: Date.now()
          }
        );

        res.json({
          success: true,
          taskId,
          status,
          updateEventId: eventId
        });

      } catch (error) {
        console.error('Task update API error:', error);
        res.status(500).json({ error: 'Failed to update task' });
      }
    });

    /**
     * POST /api/team/plan
     * The Strategist creates a multi-step plan with dependencies
     */
    app.post('/api/team/plan', async (req, res) => {
      try {
        const { hyperLog } = await import('./services/hyper-log.js');
        const {
          goal,
          steps,
          teamMembers = ['TheArchitect', 'TheVisionary']
        } = req.body;

        if (!goal || !steps || !Array.isArray(steps)) {
          return res.status(400).json({
            error: 'Missing required fields: goal, steps (array)'
          });
        }

        // Start a new correlation chain for this plan
        const planId = hyperLog.startChain(`Plan: ${goal.substring(0, 50)}`);

        // Log the plan creation
        await hyperLog.log(
          'CRITICAL_DECISION',
          'TheStrategist',
          `Created plan: ${goal}`,
          {
            planId,
            totalSteps: steps.length,
            teamMembers,
            steps: steps.map((s: any, i: number) => ({
              order: i + 1,
              ...s
            }))
          }
        );

        // Create delegation events for each step
        const delegations: { id: string; step: string }[] = [];
        for (let i = 0; i < steps.length; i++) {
          const step = steps[i];
          const eventId = await hyperLog.log(
            'DELEGATION',
            'TheStrategist',
            `Step ${i + 1}: ${step.task}`,
            {
              planId,
              stepOrder: i + 1,
              assignedTo: step.assignTo || teamMembers[i % teamMembers.length],
              dependsOn: step.dependsOn || (i > 0 ? [delegations[i - 1].id] : []),
              status: 'pending',
              priority: step.priority || 'medium'
            }
          );
          delegations.push({ id: eventId, step: step.task });
        }

        res.json({
          success: true,
          planId,
          goal,
          steps: delegations.map((d, i) => ({
            ...d,
            order: i + 1,
            assignedTo: steps[i].assignTo || teamMembers[i % teamMembers.length]
          })),
          totalSteps: steps.length
        });

      } catch (error) {
        console.error('Plan API error:', error);
        res.status(500).json({ error: 'Failed to create plan' });
      }
    });

    /**
     * GET /api/team/status
     * Get overall team status and workload
     */
    app.get('/api/team/status', async (req, res) => {
      try {
        const { hyperLog } = await import('./services/hyper-log.js');
        const allEvents = hyperLog.getHistory(200);

        const delegations = allEvents.filter(e => e.type === 'DELEGATION');
        const byAgent: Record<string, any> = {};

        // Aggregate by team member
        for (const d of delegations) {
          const agent = d.metadata?.assignedTo || 'Unassigned';
          if (!byAgent[agent]) {
            byAgent[agent] = {
              name: agent,
              pending: 0,
              inProgress: 0,
              completed: 0,
              blocked: 0,
              tasks: []
            };
          }

          const status = d.metadata?.status || 'pending';
          byAgent[agent][status === 'in_progress' ? 'inProgress' : status]++;
          byAgent[agent].tasks.push({
            id: d.id,
            task: d.content,
            status,
            priority: d.metadata?.priority
          });
        }

        res.json({
          team: Object.values(byAgent),
          summary: {
            totalTasks: delegations.length,
            pending: delegations.filter(d => d.metadata?.status === 'pending').length,
            inProgress: delegations.filter(d => d.metadata?.status === 'in_progress').length,
            completed: delegations.filter(d => d.metadata?.status === 'completed').length
          },
          lastUpdated: Date.now()
        });

      } catch (error) {
        console.error('Team status API error:', error);
        res.status(500).json({ error: 'Failed to fetch team status' });
      }
    });

    // ============================================
    // THE COLONIZER - API Assimilation Engine
    // ============================================

    /**
     * POST /api/evolution/colonize
     * Assimilate a new external API into the WidgeTDC swarm
     */
    app.post('/api/evolution/colonize', async (req, res) => {
      try {
        const { colonizerService } = await import('./services/colonizer-service.js');
        const { systemName, documentation, generateTests = false, dryRun = false } = req.body;

        if (!systemName || !documentation) {
          return res.status(400).json({
            error: 'Missing required fields: systemName, documentation'
          });
        }

        console.log(`πŸ›Έ [COLONIZER API] Received assimilation request for: ${systemName}`);

        const result = await colonizerService.assimilateSystem({
          systemName,
          apiSpecContent: documentation,
          generateTests,
          dryRun
        });

        res.json(result);

      } catch (error: any) {
        console.error('Colonizer API error:', error);
        res.status(500).json({ error: error.message || 'Assimilation failed' });
      }
    });

    /**
     * GET /api/evolution/systems
     * List all assimilated systems
     */
    app.get('/api/evolution/systems', async (req, res) => {
      try {
        const { colonizerService } = await import('./services/colonizer-service.js');
        const systems = await colonizerService.listAssimilatedSystems();

        res.json({
          systems,
          count: systems.length,
          toolsDirectory: 'apps/backend/src/tools/generated'
        });

      } catch (error: any) {
        console.error('Systems list API error:', error);
        res.status(500).json({ error: 'Failed to list systems' });
      }
    });

    /**
     * DELETE /api/evolution/systems/:systemName
     * Remove an assimilated system
     */
    app.delete('/api/evolution/systems/:systemName', async (req, res) => {
      try {
        const { colonizerService } = await import('./services/colonizer-service.js');
        const { systemName } = req.params;

        const success = await colonizerService.removeSystem(systemName);

        if (success) {
          res.json({
            success: true,
            message: `System ${systemName} removed. Restart server to complete removal.`
          });
        } else {
          res.status(404).json({
            success: false,
            message: `System ${systemName} not found`
          });
        }

      } catch (error: any) {
        console.error('System removal API error:', error);
        res.status(500).json({ error: 'Failed to remove system' });
      }
    });

    /**
     * GET /api/evolution/graph/stats
     * Get Neo4j graph statistics for 3D visualization
     * πŸ”— NEURAL LINK ENDPOINT
     *
     * OPTIMIZED: Uses separate lightweight queries to avoid memory overflow
     * on Neo4j AuraDB free tier (824 MiB limit)
     */
    app.get('/api/evolution/graph/stats', async (_req, res) => {
      try {
        const { neo4jService } = await import('./database/Neo4jService.js');

        // 1. Fetch Stats using memory-efficient separate queries
        // Note: The original MATCH (n) OPTIONAL MATCH ()-[r]->() creates a cross-product
        // that exceeds Neo4j AuraDB's memory limits on large graphs (150K+ nodes)
        const nodeCountQuery = `MATCH (n) RETURN count(n) as nodes`;
        const relCountQuery = `MATCH ()-[r]->() RETURN count(r) as relationships`;

        // Run queries in parallel for better performance
        const [nodeResult, relResult] = await Promise.all([
          neo4jService.runQuery(nodeCountQuery),
          neo4jService.runQuery(relCountQuery)
        ]);

        const stats = {
          nodes: nodeResult[0]?.nodes?.toNumber ? nodeResult[0].nodes.toNumber() : (nodeResult[0]?.nodes || 0),
          relationships: relResult[0]?.relationships?.toNumber ? relResult[0].relationships.toNumber() : (relResult[0]?.relationships || 0)
        };

        // 2. Fetch Sample Nodes for Visualization
        const vizQuery = `
          MATCH (n) 
          RETURN n, labels(n) as labels 
          LIMIT 100
        `;
        const vizResult = await neo4jService.runQuery(vizQuery);

        // Map Neo4j structure to clean JSON for Frontend
        const visualNodes = vizResult.map(row => {
          const node = row.n;
          return {
            id: node.elementId, // v6: use elementId instead of identity
            name: node.properties.name || node.properties.title || `Node ${node.elementId}`,
            labels: row.labels || node.labels,
            type: (row.labels && row.labels.includes('Directory')) ? 'directory' : 'file', // Simple heuristic
            properties: node.properties
          };
        });

        // 3. Fetch Sample Relationships
        const relQuery = `
          MATCH (n)-[r]->(m)
          RETURN r, elementId(n) as source, elementId(m) as target
          LIMIT 200
        `;
        const relResult = await neo4jService.runQuery(relQuery);

        const visualLinks = relResult.map(row => ({
          source: row.source, // elementId is string
          target: row.target, // elementId is string
          type: row.r.type,
          id: row.r.elementId // v6: use elementId
        }));

        // 4. Send Combined Payload
        res.json({
          timestamp: new Date().toISOString(),
          stats: stats,
          nodes: visualNodes,
          links: visualLinks,
          // Backwards compatibility fields
          totalNodes: stats.nodes,
          totalRelationships: stats.relationships,
          importGraph: visualLinks.map(l => ({ from: l.source, to: l.target }))
        });

      } catch (error: any) {
        console.error('❌ API Error in /graph/stats:', error);
        res.status(500).json({
          error: 'Failed to retrieve neural link data',
          details: error.message,
          nodes: [],
          links: []
        });
      }
    });

    /**
     * GET /api/codex/status
     * Get Codex Symbiosis status
     */
    app.get('/api/codex/status', async (_req, res) => {
      try {
        const { CODEX_VERSION } = await import('./config/codex.js');

        res.json({
          version: CODEX_VERSION,
          status: 'active',
          injectionPoint: 'LLM Service',
          principles: [
            'HUKOMMELSE - Check context before responding',
            'TRANSPARENS - Explain all actions',
            'SIKKERHED - Never leak PII without approval',
            'SAMARBEJDE - Compatible with team patterns',
            'VÆKST - Suggest improvements when seen',
            'YDMYGHED - Ask when uncertain',
            'LOYALITET - Serve The Executive'
          ],
          message: 'Codex Symbiosis is active. All AI responses are filtered through the ethical framework.'
        });

      } catch (error: any) {
        res.status(500).json({ error: 'Failed to get Codex status' });
      }
    });

    // ============================================
    // OMNI-HARVESTER - Knowledge Acquisition API
    // ============================================
    const acquisitionRouter = (await import('./routes/acquisition.js')).default;
    app.use('/api/acquisition', acquisitionRouter);
    console.log('🌾 Omni-Harvester API mounted at /api/acquisition');

    // ============================================
    // 🧠 NEURAL ORGANS API
    // ============================================
    const neuralRouter = (await import('./routes/neural.js')).default;
    app.use('/api/neural', neuralRouter);
    console.log('🧠 Neural Organs API mounted at /api/neural');

    // Graceful shutdown handler
    const gracefulShutdown = async (signal: string) => {
      console.log(`\nπŸ›‘ ${signal} received: starting graceful shutdown...`);

      // Stop accepting new connections
      server.close(() => {
        console.log('  βœ“ HTTP server closed');
      });

      // Stop scheduled tasks
      try {
        dataScheduler.stop();
        console.log('  βœ“ Data scheduler stopped');
      } catch { /* ignore */ }

      // Stop HansPedder agent
      try {
        const { hansPedderAgent } = await import('./services/agent/HansPedderAgentController.js');
        hansPedderAgent.stop();
        console.log('  βœ“ HansPedder agent stopped');
      } catch { /* ignore */ }

      // Close Neo4j connections
      try {
        const { neo4jService } = await import('./database/Neo4jService.js');
        await neo4jService.close();
        console.log('  βœ“ Neo4j connection closed');
      } catch { /* ignore */ }

      // Close SQLite database
      try {
        const { closeDatabase } = await import('./database/index.js');
        closeDatabase();
        console.log('  βœ“ SQLite database closed');
      } catch { /* ignore */ }

      // Stop Neural Compiler
      try {
        await neuralCompiler.stop();
        console.log('  βœ“ Neural Compiler stopped');
      } catch { /* ignore */ }

      console.log('βœ… Graceful shutdown complete');
      process.exit(0);
    };

    // Handle shutdown signals
    process.on('SIGTERM', () => gracefulShutdown('SIGTERM'));
    process.on('SIGINT', () => gracefulShutdown('SIGINT'));

    // Handle uncaught errors gracefully
    process.on('uncaughtException', (error) => {
      console.error('πŸ’₯ Uncaught Exception:', error);
      gracefulShutdown('uncaughtException');
    });

    process.on('unhandledRejection', (reason, promise) => {
      console.error('πŸ’₯ Unhandled Rejection at:', promise, 'reason:', reason);
      // Don't exit on unhandled rejections, just log
    });

  } catch (error) {
    console.error('❌ Failed to start server:', error);
    process.exit(1);
  }
}

// Start the application
startServer();