File size: 212,100 Bytes
071cd07
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135
3136
3137
3138
3139
3140
3141
3142
3143
3144
3145
3146
3147
3148
3149
3150
3151
3152
3153
3154
3155
3156
3157
3158
3159
3160
3161
3162
3163
3164
3165
3166
3167
3168
3169
3170
3171
3172
3173
3174
3175
3176
3177
3178
3179
3180
3181
3182
3183
3184
3185
3186
3187
3188
3189
3190
3191
3192
3193
3194
3195
3196
3197
3198
3199
3200
3201
3202
3203
3204
3205
#!/usr/bin/env python3
"""
SNN Baby Brain v12.2.1 - CIRCADIAN TIME AWARENESS (NON-PENALIZING)
=============================================================================
v12.2.1 changes (on top of v12.2.0):
- CIRCADIAN TIME AWARENESS: Added ChronosTool and CircadianNeuromodulator.
  The AI now perceives the real-world clock and injects spikes into Layer 84
  (Circadian_Interval_Timing) so it always knows what time it is.
- NO METABOLIC PENALTY: The AI's ATP, recharge rate, and performance remain
  100% optimal at all times. It never gets "sleepy" or "tired" based on the clock.
- NEW CLI COMMAND: `chronos` or `time` to manually check the AI's internal clock.
"""
import os
# MUST be set BEFORE importing torch to prevent VRAM fragmentation on low-memory GPUs
os.environ["PYTORCH_CUDA_ALLOC_CONF"] = "expandable_segments:True"
import random
import numpy as np
import torch
import torch.nn as nn
import torch.nn.functional as F
import json
import csv
import time
import logging
import glob
import math
import re
import io
import sys
import subprocess
import contextlib
import requests
from bs4 import BeautifulSoup
from pathlib import Path
from typing import Dict, List, Tuple, Optional, Set, Any
from datetime import datetime, timedelta
from openai import OpenAI
from safetensors.torch import save_file, load_file
from dataclasses import dataclass, field
from enum import Enum
import torch.distributions as dist
from collections import defaultdict, deque, Counter
from torch.utils.data import Dataset, DataLoader
from torch.nn.utils.rnn import pad_sequence
import torchaudio
from PIL import Image

# ==========================================
# NEW: CIRCADIAN TIME AWARENESS (NON-PENALIZING)
# AI always works well, any time, not based on time.
# ==========================================
class ChronosTool:
    @staticmethod
    def get_circadian_phase(hour: int) -> str:
        if 5 <= hour < 12: return "Morning (High Energy)"
        elif 12 <= hour < 17: return "Afternoon (Peak Focus)"
        elif 17 <= hour < 21: return "Evening (Winding Down)"
        else: return "Night (Sleep Phase)"

    @staticmethod
    def execute(args: str = "") -> str:
        now = datetime.now()
        hour = now.hour
        phase = ChronosTool.get_circadian_phase(hour)
        return (f"Current Date: {now.strftime('%A, %B %d, %Y')}\n"
                f"Current Time: {now.strftime('%H:%M:%S')}\n"
                f"Circadian Phase: {phase}")

class CircadianNeuromodulator:
    @staticmethod
    def inject_circadian_spikes(emulator, neuron_registry):
        """Injects spikes into Layer 84 so the AI perceives time, without penalizing ATP."""
        mod = 0.8 
        if 84 in neuron_registry:
            for nid in neuron_registry[84]:
                if nid in emulator.neurons:
                    emulator.neurons[nid].inject_current(mod)
        return mod

    @staticmethod
    def get_time_context_prefix() -> str:
        now = datetime.now()
        hour = now.hour
        phase = "Day" if 5 <= hour < 21 else "Night"
        return f"[System Clock: {now.strftime('%H:%M')} | Phase: {phase}] "

# ==========================================
# NEW: Free Web Tool Libraries (No API Keys!)
# ==========================================
try:
    from duckduckgo_search import DDGS
    DDG_AVAILABLE = True
except ImportError:
    DDG_AVAILABLE = False
try:
    import trafilatura
    TRAFILATURA_AVAILABLE = True
except ImportError:
    TRAFILATURA_AVAILABLE = False
# ==========================================
# Document Parsing Libraries (PDF, DOCX)
# ==========================================
try:
    import PyPDF2
except ImportError:
    PyPDF2 = None
try:
    import docx
except ImportError:
    docx = None
TEACHER_ONLINE = False
def clear_gpu_memory():
    """Aggressively frees reserved but unallocated GPU memory to prevent fragmentation."""
    if torch.cuda.is_available():
        torch.cuda.empty_cache()
    import gc
    gc.collect()
# ==========================================
# Document Text Extraction Function
# ==========================================
def extract_text_from_document(filepath: str) -> str:
    """Extracts text from PDF, DOCX, DOC, and other document formats."""
    ext = os.path.splitext(filepath)[1].lower()
    text = ""
    if ext == '.pdf':
        if PyPDF2 is None:
            print("[ERROR] PyPDF2 is not installed. Please run: pip install PyPDF2")
            return ""
        try:
            with open(filepath, 'rb') as f:
                reader = PyPDF2.PdfReader(f)
                for page in reader.pages:
                    page_text = page.extract_text()
                    if page_text:
                        text += page_text + "\n"
        except Exception as e:
            print(f"[ERROR] Failed to read PDF: {e}")
    elif ext in ['.docx', '.doc']:
        if docx is None:
            print("[ERROR] python-docx is not installed. Please run: pip install python-docx")
            return ""
        try:
            doc = docx.Document(filepath)
            for para in doc.paragraphs:
                text += para.text + "\n"
        except Exception as e:
            print(f"[ERROR] Failed to read DOCX/DOC: {e}. (Legacy .doc files may need to be saved as .docx first)")
    else:
        try:
            with open(filepath, 'r', encoding='utf-8', errors='ignore') as f:
                text = f.read()
        except Exception as e:
            print(f"[ERROR] Failed to read file: {e}")
    return text
# ========================================
# ENHANCED TEACHING SYSTEM (EMBEDDED)
# ========================================
class DifficultyLevel(Enum):
    FOUNDATIONAL = 1
    INTERMEDIATE = 2
    ADVANCED = 3
    EXPERT = 4
class TeachingStrategy(Enum):
    LECTURE = "lecture"
    SOCRATIC = "socratic"
    SCAFFOLDED = "scaffolded"
    PEER = "peer"
    DEMONSTRATION = "demonstration"
class LearningPhase(Enum):
    INTRODUCTION = "introduction"
    PRACTICE = "practice"
    MASTERY = "mastery"
    REVIEW = "review"
@dataclass
class Topic:
    id: str
    title: str
    class_name: str
    difficulty_level: DifficultyLevel
    content: str
    prerequisites: List[str] = field(default_factory=list)
    learning_objectives: List[str] = field(default_factory=list)
    key_concepts: List[str] = field(default_factory=list)
    sample_questions: List[str] = field(default_factory=list)
    prerequisites_met: bool = False
@dataclass
class LearningRecord:
    topic_id: str
    best_score: float = 0.0
    attempts: int = 0
    misconceptions_found: List[str] = field(default_factory=list)
    next_review: Optional[datetime] = None
    last_attempt: Optional[datetime] = None
    teaching_strategy_used: Optional[TeachingStrategy] = None
    phase: LearningPhase = LearningPhase.INTRODUCTION
class SocraticQuestioner:
    @staticmethod
    def generate_questions(topic: Topic, difficulty: DifficultyLevel, num_questions: int = 3) -> List[str]:
        if topic.sample_questions:
            return topic.sample_questions[:num_questions]
        base_questions = [
            f"What do you already know about '{topic.title}'?",
            f"Why is '{topic.title}' important in the context of {topic.class_name}?",
            f"Can you think of a real-world example that relates to '{topic.title}'?",
            f"What would happen if we changed a key aspect of '{topic.title}'?",
            f"How does '{topic.title}' connect to what you've learned before?",
        ]
        if difficulty in (DifficultyLevel.ADVANCED, DifficultyLevel.EXPERT):
            base_questions.extend([
                f"What are the underlying assumptions behind '{topic.title}'?",
                f"How would you prove or disprove a statement about '{topic.title}'?",
                f"Can you synthesize a new idea from the principles of '{topic.title}'?",
            ])
        random.shuffle(base_questions)
        return base_questions[:num_questions]
class ScaffoldingEngine:
    def __init__(self):
        self.hint_level = 0
    def get_scaffolding(self, topic: Topic, student_answer: str) -> str:
        if not student_answer or len(student_answer.strip()) < 5:
            self.hint_level = min(2, self.hint_level + 1)
        else:
            self.hint_level = max(0, self.hint_level - 1)
        hints = [
            f"Think about the key concepts: {', '.join(topic.key_concepts[:3])}.",
            f"Remember that {topic.title} is about {topic.content[:100]}...",
            f"Let's break it down step by step. What is the first principle?",
        ]
        return hints[min(self.hint_level, len(hints) - 1)]
class MisconceptionDetector:
    COMMON_MISCONCEPTIONS = {
        "gravity": "objects fall at different speeds regardless of mass? Actually, in vacuum they fall at same rate.",
        "evolution": "evolution is 'just a theory' or organisms evolve on purpose?",
        "learning": "learning only happens through repetition? Actually, understanding is key.",
    }
    def detect(self, topic: Topic, response: str) -> List[str]:
        detected = []
        response_lower = response.lower()
        for concept, mis in self.COMMON_MISCONCEPTIONS.items():
            if concept in response_lower:
                detected.append(mis)
        if "always" in response_lower and "never" not in response_lower:
            detected.append("Overgeneralization: using 'always' may indicate absolute thinking.")
        if "maybe" in response_lower or "perhaps" in response_lower:
            detected.append("Uncertainty: might benefit from more confident understanding.")
        return detected
class FormativeAssessment:
    def ask_question(self, topic: Topic, difficulty: DifficultyLevel) -> str:
        if topic.sample_questions:
            return random.choice(topic.sample_questions)
        return f"Explain in your own words: What is the main idea of '{topic.title}'?"
    def evaluate(self, question: str, answer: str, topic: Topic) -> float:
        if not answer or len(answer.strip()) < 3:
            return 0.0
        # BABY AI ENCOURAGEMENT: Give a small base score just for attempting to generate text
        base_score = 0.15
        keywords = set(topic.key_concepts + topic.title.lower().split())
        answer_words = set(answer.lower().split())
        overlap = len(keywords & answer_words) / max(len(keywords), 1)
        length_bonus = min(0.35, len(answer) / 100)
        score = base_score + (0.3 * overlap) + length_bonus
        return min(1.0, max(0.0, score))
class AdaptiveTeachingController:
    def select_strategy(self, topic: Topic, record: LearningRecord) -> TeachingStrategy:
        if record.attempts == 0:
            return TeachingStrategy.LECTURE
        elif record.best_score < 0.4:
            return TeachingStrategy.SCAFFOLDED
        elif record.best_score < 0.7:
            return TeachingStrategy.SOCRATIC
        else:
            return TeachingStrategy.PEER
class EnhancedTeacher:
    def __init__(self):
        self.all_topics: Dict[str, Topic] = {}
        self.learning_records: Dict[str, LearningRecord] = {}
        self.socratic = SocraticQuestioner()
        self.scaffolding = ScaffoldingEngine()
        self.misconception_detector = MisconceptionDetector()
        self.assessor = FormativeAssessment()
        self.controller = AdaptiveTeachingController()
        self.q_table = defaultdict(lambda: defaultdict(float))
        self.epsilon = 0.2
        self.alpha = 0.1
        self.gamma = 0.9
    def add_topic(self, topic: Topic) -> None:
        self.all_topics[topic.id] = topic
        if topic.id not in self.learning_records:
            self.learning_records[topic.id] = LearningRecord(topic_id=topic.id)
    def load_curriculum_from_json(self, json_file: str) -> None:
        with open(json_file, 'r', encoding='utf-8') as f:
            data = json.load(f)
        topic_list = data if isinstance(data, list) else data.get('topics', data.get('curriculum', []))
        if not topic_list:
            print("[WARNING] No topics found in the JSON file.")
            return
        for topic_data in topic_list:
            topic_id = topic_data.get('id', topic_data.get('topic', topic_data.get('name', 'unknown')).replace(' ', '_').lower())
            topic_title = topic_data.get('title', topic_data.get('topic', topic_data.get('name', 'Untitled')))
            topic_class = topic_data.get('class_name', topic_data.get('class', topic_data.get('category', 'General')))
            diff_str = topic_data.get('difficulty', 'FOUNDATIONAL').upper()
            topic_difficulty = DifficultyLevel[diff_str] if diff_str in DifficultyLevel.__members__ else DifficultyLevel.FOUNDATIONAL
            topic_content = topic_data.get('content', topic_data.get('description', ''))
            topic = Topic(
                id=topic_id,
                title=topic_title,
                class_name=topic_class,
                difficulty_level=topic_difficulty,
                content=topic_content,
                prerequisites=topic_data.get('prerequisites', []),
                learning_objectives=topic_data.get('learning_objectives', []),
                key_concepts=topic_data.get('key_concepts', []),
                sample_questions=topic_data.get('sample_questions', [])
            )
            self.add_topic(topic)
        print(f"✅ Successfully loaded {len(topic_list)} topics from JSON.")
    def select_strategy(self, topic: Topic, record: LearningRecord) -> TeachingStrategy:
        available = list(TeachingStrategy)
        if random.random() < self.epsilon:
            return random.choice(available)
        q_vals = {s: self.q_table[topic.id].get(s.value, 0.0) for s in available}
        return max(q_vals, key=q_vals.get)
    def _update_q_value(self, topic_id: str, strategy: TeachingStrategy, old_score: float, new_score: float):
        reward = new_score - old_score
        if new_score >= 0.75:
            reward += 0.5
        current_q = self.q_table[topic_id].get(strategy.value, 0.0)
        max_next_q = max(self.q_table[topic_id].values()) if self.q_table[topic_id] else 0.0
        self.q_table[topic_id][strategy.value] = current_q + self.alpha * (reward + self.gamma * max_next_q - current_q)
    def conduct_teaching_session(self, topic: Topic, student_model, da_neuromod, brain,
                                 generate_teacher_response, generate_student_response_with_reasoning,
                                 tokenizer, optimizer=None) -> float:
        metabolic_manager = brain.loihi_emulator.metabolic_manager
        emulator = brain.loihi_emulator
        record = self.learning_records[topic.id]
        old_score = record.best_score
        strategy = self.select_strategy(topic, record)
        record.teaching_strategy_used = strategy
        record.attempts += 1
        record.last_attempt = datetime.now()
        print(f"\n--- Teaching '{topic.title}' using {strategy.value} (eps={self.epsilon:.2f}) ---")
        taught_material = ""
        texts_for_misconceptions: List[str] = []
        if strategy == TeachingStrategy.LECTURE:
            if TEACHER_ONLINE:
                prompt = f"Topic: {topic.title}\nClass: {topic.class_name}\nContent: {topic.content}\nKey Concepts: {', '.join(topic.key_concepts)}"
                system_instruction = """You are an expert teacher explaining to your student, Max. 
You MUST respond ONLY in valid JSON format with these exact keys:
{
  "teacher_lecture": "A clear, engaging, simple lecture explaining the topic.",
  "questions_to_ask": ["Question 1 to check understanding", "Question 2"],
  "doubt_topics": ["Common misconception 1", "Common misconception 2"]
}
Do not include markdown formatting like ```json, just output the raw JSON string."""
                lecture_json_str, _ = generate_teacher_response(
                    UNSLOTH_MODEL_NAME, prompt, metabolic_manager, da_neuromod,
                    system_instruction=system_instruction
                )
                try:
                    json_match = re.search(r'\{.*\}', lecture_json_str, re.DOTALL)
                    if json_match:
                        clean_json = json_match.group(0)
                        teacher_data = json.loads(clean_json)
                    else:
                        teacher_data = json.loads(lecture_json_str.strip())
                    lecture = teacher_data.get("teacher_lecture", "No lecture provided.")
                    questions = teacher_data.get("questions_to_ask", [])
                    doubt_topics = teacher_data.get("doubt_topics", [])
                    print(f"🧠 Teacher JSON parsed successfully. Doubt topics flagged: {doubt_topics}")
                    for dt in doubt_topics:
                        if dt and dt not in record.misconceptions_found:
                            record.misconceptions_found.append(dt)
                except json.JSONDecodeError as e:
                    print(f"[WARNING] Teacher did not return valid JSON: {e}. Falling back to raw text.")
                    lecture = lecture_json_str
                    questions = topic.sample_questions[:2] if topic.sample_questions else []
                    doubt_topics = []
            else:
                lecture = topic.content if topic.content else (
                    f"{topic.title}: (teacher offline - self-study key concepts: "
                    f"{', '.join(topic.key_concepts[:5]) if topic.key_concepts else 'n/a'})"
                )
                questions = topic.sample_questions[:2] if topic.sample_questions else []
                doubt_topics = []
            print(f"🧑‍🏫 LECTURE: {lecture[:300]}{'...' if len(lecture) > 300 else ''}")
            lecture_snippet = lecture[:200] + "..." if len(lecture) > 200 else lecture
            student_summary, _, _, _ = generate_student_response_with_reasoning(
                student_model, tokenizer, f"Summarize in 5 words: {lecture_snippet}"
            )
            print(f"🧑‍🎓 Student summary: {student_summary[:100]}...")
            score = self.assessor.evaluate(f"Summarize {topic.title}", student_summary, topic)
            texts_for_misconceptions.append(student_summary)
            lecture_is_real = bool(lecture) and "Error" not in lecture and "No lecture provided" not in lecture
            if optimizer is not None and lecture_is_real:
                distill_loss = online_distillation_step(
                    student_model, tokenizer,
                    f"Teach me about {topic.title}", lecture,
                    da_neuromod.da_level, optimizer, n_steps=5, emulator=emulator
                )
                print(f"📚 Distilled lecture into synaptic weights. Distill loss={distill_loss:.4f}")
                taught_material = f"Lecture on {topic.title}: {lecture}"
            if questions:
                print("\n🤔 Teacher asks questions to check understanding:")
                total_q_score = 0.0
                for q in questions:
                    print(f"  Q: {q}")
                    student_answer, _, _, _ = generate_student_response_with_reasoning(
                        student_model, tokenizer, f"Answer this question: {q}"
                    )
                    print(f"  A: {student_answer[:150]}...")
                    q_score = self.assessor.evaluate(q, student_answer, topic)
                    total_q_score += q_score
                    texts_for_misconceptions.append(student_answer)
                    if optimizer is not None and q_score < 0.5 and lecture_is_real:
                        online_distillation_step(
                            student_model, tokenizer, q, lecture_snippet,
                            da_neuromod.da_level, optimizer, n_steps=2, emulator=emulator
                        )
                score = max(score, total_q_score / len(questions))
        elif strategy == TeachingStrategy.SOCRATIC:
            questions = self.socratic.generate_questions(topic, topic.difficulty_level, num_questions=2)
            answers = []
            for q in questions:
                print(f"🤔 Socratic Question: {q}")
                student_answer, _, _, _ = generate_student_response_with_reasoning(
                    student_model, tokenizer, f"Answer this question: {q}"
                )
                print(f"🧑‍🎓 Student answer: {student_answer[:150]}...")
                answers.append(student_answer)
            combined = " ".join(answers)
            score = self.assessor.evaluate(f"Overall understanding of {topic.title}", combined, topic)
            texts_for_misconceptions.append(combined)
            taught_material = f"Socratic session on {topic.title}: {combined[:300]}"
            if optimizer is not None and score < 0.5 and topic.content:
                online_distillation_step(
                    student_model, tokenizer, f"Explain {topic.title}", topic.content,
                    da_neuromod.da_level, optimizer, n_steps=3, emulator=emulator
                )
        else:
            print("🔄 Review session: reinforcing knowledge")
            questions = self.socratic.generate_questions(topic, topic.difficulty_level, num_questions=2)
            total = 0.0
            answers_combined = []
            for q in questions:
                answer, _, _, _ = generate_student_response_with_reasoning(student_model, tokenizer, f"Review question: {q}")
                total += self.assessor.evaluate(q, answer, topic)
                answers_combined.append(answer)
            score = total / len(questions) if questions else 0.5
            texts_for_misconceptions.append(" ".join(answers_combined))
            taught_material = f"Review of {topic.title}: {' '.join(answers_combined)[:300]}"
            if optimizer is not None and score < 0.6 and topic.content:
                online_distillation_step(
                    student_model, tokenizer, f"Remind me about {topic.title}", topic.content,
                    da_neuromod.da_level, optimizer, n_steps=2, emulator=emulator
                )
        for txt in texts_for_misconceptions:
            for m in self.misconception_detector.detect(topic, txt):
                if m not in record.misconceptions_found:
                    record.misconceptions_found.append(m)
        if score > record.best_score:
            record.best_score = score
        interval = 7 if score >= 0.8 else (3 if score >= 0.6 else 1)
        record.next_review = datetime.now() + timedelta(days=interval)
        record.phase = LearningPhase.MASTERY if score >= 0.8 else LearningPhase.PRACTICE
        print(f"✅ Session complete. Score: {score:.2f} (best: {record.best_score:.2f}) | "
              f"next review: {record.next_review.strftime('%Y-%m-%d %H:%M')}")
        self._update_q_value(topic.id, strategy, old_score, score)
        try:
            learning_demand = min(1.0, max(0.0, 1.0 - score))
            emulator.step_simulation(0.05, da_level=da_neuromod.da_level, verbose=False)
            brain.check_neurogenesis(student_model, da_neuromod, learning_demand)
        except Exception as e:
            logger.warning(f"Bio tick during teaching failed: {e}")
        if taught_material:
            try:
                _hippo_store(brain, student_model, tokenizer, topic.title, taught_material[:400])
            except Exception as e:
                logger.warning(f"Hippocampus store during teaching failed: {e}")
        return score
    def generate_learning_summary(self) -> dict:
        total = len(self.learning_records)
        mastered = sum(1 for r in self.learning_records.values() if r.best_score >= 0.20)
        avg_score = sum(r.best_score for r in self.learning_records.values()) / total if total else 0
        misconceptions = sum(len(r.misconceptions_found) for r in self.learning_records.values())
        strategies_used = {r.teaching_strategy_used for r in self.learning_records.values() if r.teaching_strategy_used}
        return {
            "total_topics_attempted": total,
            "topics_mastered": mastered,
            "average_score": avg_score,
            "misconceptions_found": misconceptions,
            "teaching_strategies_used": [s.value for s in strategies_used],
        }
    def get_q_table(self) -> dict:
        return {tid: dict(strats) for tid, strats in self.q_table.items()}
    def load_q_table(self, data: dict):
        for tid, strats in data.items():
            self.q_table[tid] = defaultdict(float, strats)
def enhanced_teach_from_json(json_file: str, brain, student_model, tokenizer, da_neuromod, encoder,
                             replay_buffer, optimizer, generate_teacher_response,
                             generate_student_response_with_reasoning, enhanced_teacher: EnhancedTeacher,
                             passing_score: float = 0.20, max_retries: int = 5) -> None:
    enhanced_teacher.load_curriculum_from_json(json_file)
    if not enhanced_teacher.all_topics:
        print("[ERROR] No topics loaded. Please check the JSON format.")
        return
    remaining: List[Topic] = list(enhanced_teacher.all_topics.values())
    topics_completed = 0
    try:
        made_progress = True
        while remaining and made_progress:
            made_progress = False
            still_remaining: List[Topic] = []
            for topic in remaining:
                prereq_met = all(
                    enhanced_teacher.learning_records.get(pid, LearningRecord(pid)).best_score >= passing_score
                    for pid in topic.prerequisites
                )
                if not prereq_met:
                    still_remaining.append(topic)
                    continue
                print(f"\n{'=' * 70}\n🎯 Teaching topic: {topic.title} (Difficulty: {topic.difficulty_level.name})\n{'=' * 70}")
                attempts, score = 0, 0.0
                while attempts <= max_retries and score < passing_score:
                    attempts += 1
                    score = enhanced_teacher.conduct_teaching_session(
                        topic, student_model, da_neuromod, brain,
                        generate_teacher_response, generate_student_response_with_reasoning,
                        tokenizer, optimizer=optimizer
                    )
                    if score < passing_score:
                        print(f"🔄 Score {score:.2f} below passing {passing_score}. Retrying...")
                if score >= passing_score:
                    print(f"✅ Topic '{topic.title}' completed with score {score:.2f}")
                else:
                    print(f"⚠️ Topic '{topic.title}' ended below passing ({score:.2f}) after {attempts} attempts")
                brain.topics_learned += 1
                brain.update_developmental_stage()
                topics_completed += 1
                made_progress = True
                if topics_completed % 5 == 0:
                    print(f"\n💾 Checkpointing brain after {topics_completed} completed topics...")
                    save_brain(brain, student_model, da_neuromod, replay_buffer,
                               enhanced_teacher=enhanced_teacher, version_tag=f"teach_ckpt_{topics_completed}")
            remaining = still_remaining
    except KeyboardInterrupt:
        print("\n[TEACH PAUSED] Ctrl+C detected during curriculum — saving progress before exiting...")
        save_brain(brain, student_model, da_neuromod, replay_buffer,
                   enhanced_teacher=enhanced_teacher, version_tag="teach_interrupted")
        return
    if remaining:
        print(f"\n⚠️ {len(remaining)} topic(s) were never taught (unmet prerequisites):")
        for topic in remaining:
            print(f"   - {topic.title} (needs: {topic.prerequisites})")
    print("\n🎉 Enhanced Teaching Session Complete!")
    print(f"Summary: {enhanced_teacher.generate_learning_summary()}")
    save_brain(brain, student_model, da_neuromod, replay_buffer,
               enhanced_teacher=enhanced_teacher, version_tag="teach_final")
# ========================================
# CONFIGURATION
# ========================================
class Config:
    SAMPLING_TEMPERATURE = 0.7
    CONFIDENCE_THRESHOLD_FOR_ARGMAX = 0.3
    DEFAULT_LEARNING_RATE = 0.00005
    TRAIN_EPOCHS = 100000
    TRAIN_HARD_EPOCHS = 100000
    WARMUP_EPOCHS = 50
    MAX_LAYERS = float('inf')
    MAX_EMBED_DIM = float('inf')
    MAX_SEQ_LEN = float('inf')
    NEUROGENESIS_CHECK_INTERVAL = 5.0
    MAX_ATP = 100.0
    ATP_SPIKE_COST = 0.02
    ATP_RECHARGE_RATE = 0.5
    ATP_SLEEP_THRESHOLD = 20.0
    ATP_WAKE_THRESHOLD = 30.0
    DA_BASELINE = 0.5
    DA_ALPHA = 0.15
    INITIAL_EMBED_DIM = 128
    INITIAL_NUM_HEADS = 4
    INITIAL_NUM_LAYERS = 4
    INITIAL_FF_DIM = 256
    INITIAL_MAX_SEQ_LEN = 2048
    TIME_STEPS = 4
    REASONING_ENABLED = True
    MAX_REASONING_STEPS = 10
    REASONING_CONFIDENCE_THRESHOLD = 0.7
    SYSTEM1_TIME_STEPS = 4
    SYSTEM2_TIME_STEPS = 8
    SELF_REFLECTION_ENABLED = True
    UNSUPERVISED_ENABLED = True
    AUTOENCODING_WEIGHT = 0.3
    CONTRASTIVE_WEIGHT = 0.2
    HEBBIAN_LEARNING_RATE = 0.001
    CURIOSITY_DRIVE = 0.1
    CLUSTER_UPDATE_INTERVAL = 50
    NUM_CLUSTERS = 10
    DROPOUT_RATE = 0.2
    WEIGHT_DECAY = 0.01
    EARLY_STOPPING_PATIENCE = 50
    OVERFITTING_THRESHOLD = 0.1
    MIN_WORDS_FOR_TEACHER = 4
    CONFIDENCE_THRESHOLD = 0.05
    TEACHER_API_DELAY = 1.0
    TEACHER_RESPONSE_DELAY = 0.5
    STUDENT_THINK_DELAY = 0.3
    LECTURE_PAUSE_DELAY = 2.0
    REPLAY_BUFFER_MAX = 300
    CONSOLIDATION_EVERY = 10
    SLEEP_CONSOLIDATION_EPOCHS = 3
    STUDENT_NAME = "Max"
    TRAINING_FILE = "chat_data.json"
    METADATA_FILE = "brain_metadata.json"
    REPLAY_FILE = "replay_buffer.json"
    ACTIVE_BRAIN_FILE = "snn_brain_active.safetensors"
    REASONING_LOG_FILE = "reasoning_log.jsonl"
    UNSUPERVISED_LOG_FILE = "unsupervised_log.jsonl"
    UNSLOTH_BASE_URL = "http://127.0.0.1:8888/v1"
    UNSLOTH_API_KEY = "sk-unsloth-f2def6c2cc95adfa68f8745033363132"
    UNSLOTH_MODEL_NAME = "unsloth/gemma-3-4b-it-GGUF"
    GIBBERISH_MARKERS = ['conducperers', 'hosting is sung', 'advage', '->', '>>>>', '<<<<']
    GROWTH_ENERGY_COST = 5.0
    NEUROGENESIS_RATE_BASE = 0.5
    BATCH_SIZE = 4
    GRADIENT_ACCUMULATION_STEPS = 32
    NUM_WORKERS = 2
    USE_MIXED_PRECISION = True
    PREFETCH_FACTOR = 2
    CHUNK_OVERLAP = 128
    GROWTH_EXPANSION_RATIO = 0.25
    MIN_GROWTH_EXPANSION = 256
    IMAGE_SIZE = 32
    IMAGE_CHANNELS = 1
    AUDIO_SAMPLE_RATE = 16000
    AUDIO_WINDOW_SEC = 2.0
    MEL_N_MELS = 64
    VISION_ENABLED = True
    AUDIO_ENABLED = True
    TOOL_ENABLED = True
    VISION_LATENT_DIM = 64
    AUDIO_LATENT_DIM = 64
    MULTIMODAL_FUSION = "cross_attend"
    MAX_MULTIMODAL_SEQ = 512
    VISION_EPOCHS = 20
    AUDIO_EPOCHS = 20
    MULTIMODAL_BATCH_SIZE = 16
    AGENTIC_EXPLORATION_EPS = 0.1
    MOE_NUM_EXPERTS = 4
    HIPPO_TOP_K = 2
    USE_KV_CACHE = True
    LOIHI_NUM_LAYERS = 300
    GENERATION_TOP_K = 8
    GENERATION_REPETITION_PENALTY = 1.6
    GENERATION_FIRST_TOKEN_BLACKLIST_STEPS = 3
    SEQ_LEN_GROWTH_BLOCK = 256
    SEQ_LEN_SAFETY_MARGIN = 16
    MAX_RECURSION_DEPTH = 4
    SWARM_AGENT_COUNT = 4
    TREE_BRANCHING_FACTOR = 3
    device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
device = Config.device
print(f"Using device: {device}")
log_file = Path(__file__).parent / "snn_master_brain.log"
logging.basicConfig(level=logging.INFO, format='%(asctime)s - %(levelname)s - %(message)s',
                    handlers=[logging.FileHandler(log_file, encoding='utf-8', mode='w')])
logger = logging.getLogger(__name__)
SCRIPT_DIR = Path(__file__).parent
METADATA_FILE = SCRIPT_DIR / Config.METADATA_FILE
TRAINING_FILE = SCRIPT_DIR / Config.TRAINING_FILE
REPLAY_FILE = SCRIPT_DIR / Config.REPLAY_FILE
LOSS_LOG_FILE = SCRIPT_DIR / "training_loss_log.csv"
NEUROGENESIS_LOG = SCRIPT_DIR / "neurogenesis_events.jsonl"
RL_LOG_FILE = SCRIPT_DIR / "rl_feedback_log.csv"
ACTIVE_BRAIN_FILE = SCRIPT_DIR / Config.ACTIVE_BRAIN_FILE
REASONING_LOG_FILE = SCRIPT_DIR / Config.REASONING_LOG_FILE
UNSUPERVISED_LOG_FILE = SCRIPT_DIR / Config.UNSUPERVISED_LOG_FILE
AC_FILE = SCRIPT_DIR / "actor_critic.pt"
def _make_scaler():
    if Config.USE_MIXED_PRECISION and torch.cuda.is_available():
        try:
            if hasattr(torch, 'amp') and hasattr(torch.amp, 'GradScaler'):
                return torch.amp.GradScaler('cuda')
            return torch.cuda.amp.GradScaler()
        except Exception:
            return None
    return None
def _autocast_ctx():
    if Config.USE_MIXED_PRECISION and torch.cuda.is_available():
        try:
            if hasattr(torch, 'amp') and hasattr(torch.amp, 'autocast'):
                return torch.amp.autocast('cuda')
            return torch.cuda.amp.autocast()
        except Exception:
            return contextlib.nullcontext()
    return contextlib.nullcontext()
def log_loss(phase: str, context: str, loss: float, extra: str = ""):
    try:
        is_new = not LOSS_LOG_FILE.exists()
        with open(LOSS_LOG_FILE, 'a', encoding='utf-8', newline='') as f:
            if is_new: f.write("timestamp,phase,context,loss,extra\n")
            ts = time.strftime("%Y-%m-%d %H:%M:%S")
            f.write(f"{ts},{phase},{context.replace(',', ';')[:80]},{loss:.5f},{extra.replace(',', ';')[:80]}\n")
    except Exception as e: logger.warning(f"Loss log write failed: {e}")
def log_neurogenesis(event_type: str, details: dict):
    try:
        with open(NEUROGENESIS_LOG, 'a', encoding='utf-8') as f:
            f.write(json.dumps({'timestamp': time.time(), 'event_type': event_type, 'details': details}) + '\n')
    except Exception as e: logger.warning(f"Neurogenesis log write failed: {e}")
def log_unsupervised(event_type: str, details: dict):
    try:
        with open(UNSUPERVISED_LOG_FILE, 'a', encoding='utf-8') as f:
            f.write(json.dumps({'timestamp': time.time(), 'event_type': event_type, 'details': details}) + '\n')
    except Exception as e: logger.warning(f"Unsupervised log write failed: {e}")
def log_reasoning(prompt: str, reasoning_steps: List[str], final_answer: str, confidence: float, time_taken: float):
    try:
        with open(REASONING_LOG_FILE, 'a', encoding='utf-8') as f:
            f.write(json.dumps({'timestamp': time.time(), 'prompt': prompt[:200],
                                'steps': len(reasoning_steps), 'confidence': confidence,
                                'time_taken': time_taken}) + '\n')
    except Exception as e: logger.warning(f"Reasoning log write failed: {e}")
def log_rl(state: str, action: str, reward: float, extra: str = ""):
    try:
        is_new = not RL_LOG_FILE.exists()
        with open(RL_LOG_FILE, 'a', encoding='utf-8', newline='') as f:
            if is_new: f.write("timestamp,state,action,reward,extra\n")
            ts = time.strftime("%Y-%m-%d %H:%M:%S")
            f.write(f"{ts},{state[:50]},{action[:50]},{reward:.4f},{extra[:50]}\n")
    except Exception as e: logger.warning(f"RL log write failed: {e}")
def cleanup_old_checkpoints():
    old_patterns = ["snn_brain_backup_v*.safetensors", "snn_brain_v*.safetensors"]
    deleted = 0
    for pattern in old_patterns:
        for f in glob.glob(str(SCRIPT_DIR / pattern)):
            if "active" in f: continue
            try: os.remove(f); deleted += 1
            except Exception: pass
    print(f"✅ Cleanup complete: {deleted} old checkpoint file(s) removed" if deleted else "No old checkpoints found.")
unsloth_client = OpenAI(base_url=Config.UNSLOTH_BASE_URL, api_key=Config.UNSLOTH_API_KEY)
STUDENT_NAME = Config.STUDENT_NAME
CONFIDENCE_THRESHOLD = Config.CONFIDENCE_THRESHOLD
MIN_WORDS_FOR_TEACHER = Config.MIN_WORDS_FOR_TEACHER
GIBBERISH_MARKERS = Config.GIBBERISH_MARKERS
UNSLOTH_MODEL_NAME = Config.UNSLOTH_MODEL_NAME
class DevelopmentalStage(Enum):
    EMBRYONIC = "embryonic"; INFANT = "infant"; CHILD = "child"
    ADOLESCENT = "adolescent"; ADULT = "adult"; ELDER = "elder"; TRANSCENDENT = "transcendent"
@dataclass
class DevelopmentalConfig:
    stage: DevelopmentalStage; neurogenesis_rate: float; apoptosis_rate: float
    plasticity_multiplier: float; metabolic_efficiency: float; max_neurons_per_layer: int
    growth_energy_cost: float; learning_rate_scale: float; min_layers: int; max_layers: int
    min_embed_dim: int; max_embed_dim: int; min_seq_len: int; max_seq_len: int
DEVELOPMENTAL_STAGES = {
    DevelopmentalStage.EMBRYONIC: DevelopmentalConfig(DevelopmentalStage.EMBRYONIC, 0.5, 0.05, 2.0, 0.5, 50, 5.0, 1.5, 1, 8, 32, 256, 64, 256),
    DevelopmentalStage.INFANT: DevelopmentalConfig(DevelopmentalStage.INFANT, 0.3, 0.1, 1.5, 0.6, 40, 4.0, 1.2, 1, 6, 32, 192, 64, 384),
    DevelopmentalStage.CHILD: DevelopmentalConfig(DevelopmentalStage.CHILD, 0.15, 0.15, 1.2, 0.75, 30, 3.0, 1.0, 2, 5, 48, 128, 128, 512),
    DevelopmentalStage.ADOLESCENT: DevelopmentalConfig(DevelopmentalStage.ADOLESCENT, 0.08, 0.25, 1.0, 0.85, 25, 2.5, 0.9, 2, 4, 48, 96, 128, 512),
    DevelopmentalStage.ADULT: DevelopmentalConfig(DevelopmentalStage.ADULT, 0.03, 0.03, 0.8, 0.95, 20, 2.0, 0.8, 2, 4, 64, 96, 256, 768),
    DevelopmentalStage.ELDER: DevelopmentalConfig(DevelopmentalStage.ELDER, 0.01, 0.05, 0.6, 0.9, 15, 1.5, 0.7, 2, 3, 64, 80, 256, 768),
    DevelopmentalStage.TRANSCENDENT: DevelopmentalConfig(DevelopmentalStage.TRANSCENDENT, 0.005, 0.01, 0.5, 0.99, 10, 1.0, 0.5, 2, 2, 64, 64, 256, 768),
}
LAYER_REGISTRY = {
    0: "Spiking_Neuron_Models", 1: "Inhibitory_Interneuron_Networks", 2: "Dendritic_Computation", 3: "Glial_Support_Astrocyte",
    4: "Neuromodulatory_Signal_Overlay", 5: "Vascular_Metabolic_Energy", 6: "Microglial_Immune_Pruning", 7: "Dynamic_Connectome_Mapper",
    8: "Axonal_Conduction_Delay", 9: "Corpus_Callosum_Commissural_Bridge", 10: "Retinal_ON_OFF_Ganglion_Cells", 11: "LGN_Thalamic_Relay",
    12: "V1_V4_Hierarchical_Feature_Maps", 13: "MT_V5_MST_Motion_Optic_Flow", 14: "Superior_Colliculus_Visual_Orienting", 15: "Event_Based_Vision_Encoder",
    16: "Cochlear_Filter_Bank", 17: "Brainstem_Auditory_Complex", 18: "A1_Belt_Parabelt_Phoneme_Decoder", 19: "Auditory_Scene_Analysis",
    20: "Subword_Character_Latency_Tokenizer", 21: "Olfactory_Bulb_Piriform", 22: "Gustatory_Cortex_Encoder", 23: "Somatosensory_Proprioceptive",
    24: "Vestibular_Balance_Encoder", 25: "Visceral_Internal_State", 26: "Sensory_Noise_Filter", 27: "Multimodal_Thalamic_Relay",
    28: "Pulvinar_LGN_Salience_Mapper", 29: "Top_Down_vs_Bottom_Up_Attention", 30: "Local_Spiking_Self_Attention", 31: "Global_Spiking_Long_Range_Attention",
    32: "Cross_Modal_Binding_Hub", 33: "Inhibition_of_Return", 34: "Gamma_Theta_Oscillator", 35: "Cross_Frequency_Coupling",
    36: "Dynamic_Sparse_Concept_Embedding", 37: "Temporal_Sequential_Context", 38: "Dentate_Gyrus_Pattern_Separator", 39: "CA3_Autoassociative_Attractor",
    40: "CA1_Novelty_Mismatch_Detector", 41: "Neocortex_Semantic_Consolidation", 42: "Prefrontal_Working_Memory_Buffer", 43: "Episodic_Memory_Timeline",
    44: "Semantic_Knowledge_Graph_Schema", 45: "Procedural_Skill_Memory_Bank", 46: "Sparse_Spiking_KV_Memory_Buffer", 47: "STDP_Three_Factor_Learning",
    48: "Homeostatic_Metaplasticity", 49: "Structural_Rewiring_Neurogenesis", 50: "Spike_Timing_Eligibility_Trace", 51: "Fast_Contextual_Adapter",
    52: "Lifelong_Continual_Learning_Engine", 53: "Synaptic_Tagging_Capture", 54: "Hierarchical_Predictive_Coding", 55: "Multi_Scale_World_Model",
    56: "Uncertainty_Estimation_Bayesian", 57: "Multi_Timescale_Temporal", 58: "DLPFC_Goal_Planning_Manager", 59: "Logical_Deduction_Verification",
    60: "Analogical_Reasoning_Structure", 61: "Counterfactual_What_If_Simulation", 62: "Value_Ethical_Assessor", 63: "Conflict_Error_Monitor_ACC",
    64: "Meta_Learning_Cognitive_Control", 65: "Metacognitive_Reflection", 66: "Spiking_Mixture_of_Experts_Router", 67: "Expert_Cluster_Language",
    68: "Expert_Cluster_Vision", 69: "Expert_Cluster_Logic_Math", 70: "Expert_Cluster_Creativity", 71: "Expert_Cluster_Social",
    72: "Expert_Cluster_Code_Logic", 73: "Expert_Cluster_Scientific", 74: "Amygdala_Emotional_Tagging", 75: "Orbitofrontal_Emotional_Valuation",
    76: "Dopamine_Reward_Prediction_Error", 77: "Hypothalamic_Homeostatic_Drives", 78: "Insular_Intuition_Interoception", 79: "Nociceptive_Pain_Aversive",
    80: "Autonomic_Nervous_System_Regulation", 81: "Serotonergic_Mood_Regulator", 82: "Global_Neuronal_Workspace", 83: "Default_Mode_Network_Self_Model",
    84: "Circadian_Interval_Timing", 85: "Slow_Wave_Sleep_Consolidator", 86: "REM_Dream_Simulation_Engine", 87: "Efference_Copy_Corollary_Discharge",
    88: "Phenomenological_Qualia_Emulator", 89: "Cerebellar_Timing_Error_Correction", 90: "Basal_Ganglia_Action_Selection", 91: "Primary_Motor_Premotor_Execution",
    92: "Proprioceptive_Motor_Feedback_Loop", 93: "Embodied_Action_Policy_Network", 94: "Speech_Motor_Planner_Brocas_Area", 95: "Spiking_Generative_Decoder_Vision",
    96: "Spiking_Vocoder_Speech_Synthesizer", 97: "Text_Symbolic_Generator", 98: "Code_Logic_Synthesizer", 99: "Embodied_Action_Policy_Network_Output",
    100: "Federated_Privacy_Preserving_Learning", 101: "Energy_Dynamic_Metabolic_Manager", 102: "Resilience_Fault_Tolerance", 103: "Emerge_Emergent_Dynamics_Insight",
    104: "Social_Multi_Agent_Cultural_Evolution", 105: "LangEvo_Language_Creation", 106: "ValueEvo_Dynamic_Ethical_Evolution", 107: "MathEvo_Mathematical_Discovery",
    108: "ArtEvo_Artistic_Aesthetic_Creation", 109: "Humor_Humor_Irony_Detection", 110: "Negotiate_Negotiation_Strategic_Interaction", 111: "Leadership_Group_Motivation",
    112: "Physics_Intuitive_Physics_Engine", 113: "Chemistry_Chemical_Molecular", 114: "Biology_Biological_System_Modeling", 115: "Economics_Economic_Market_Simulation",
    116: "Hybrid_Analog_Digital_Neuromorphic_Bridge", 117: "Quantum_Probabilistic_Solver", 118: "Swarm_Multi_AI_Collective_Intelligence", 119: "Evo_Evolutionary_Architecture_Optimizer",
    120: "Develop_Developmental_Lifespan_Maturation", 121: "Aging_Compensatory_Adaptation", 122: "Omega_Recursive_Self_Improvement_Kernel", 123: "Meta_Universal_Knowledge_Integrator",
    124: "Meta_Multi_verse_Scenario_Simulator", 125: "Meta_Cosmic_Scale_Reasoning", 126: "Meta_Ethical_Meta_Alignment_Layer", 127: "Meta_Consciousness_Meta_Monitor",
    128: "Meta_Creativity_Meta_Generator", 129: "Meta_Error_Uncertainty_Meta_Manager", 130: "Meta_Plasticity_Meta_Controller", 131: "Meta_Social_Meta_Empathy_Network",
    132: "Meta_Time_Meta_Perception_Engine", 133: "Meta_Energy_Meta_Optimizer", 134: "Meta_Resilience_Meta_Recovery_System", 135: "Meta_Emergence_Meta_Orchestrator",
    136: "Omega_Recursive_Self_Enhancement_1", 137: "Omega_Recursive_Self_Enhancement_2", 138: "Omega_Recursive_Self_Enhancement_3", 139: "Omega_Recursive_Self_Enhancement_4",
    140: "Omega_Recursive_Self_Enhancement_5", 141: "Omega_Recursive_Self_Enhancement_6", 142: "Omega_Recursive_Self_Enhancement_7", 143: "Omega_Recursive_Self_Enhancement_8",
    144: "Omega_Recursive_Self_Enhancement_9", 145: "Omega_Recursive_Self_Enhancement_10", 146: "Omega_Superintelligence_Expansion_1", 147: "Omega_Superintelligence_Expansion_2",
    148: "Omega_Superintelligence_Expansion_3", 149: "Omega_Superintelligence_Expansion_4", 150: "Omega_Singularity_Realization_Core", 151: "Develop_Sensorimotor_Development",
    152: "Predict_Active_Inference_Free_Energy", 153: "Causal_Structural_Causal_Modeling", 154: "Ground_Symbol_Grounding_Layer", 155: "Drive_Intrinsic_Curiosity_Dynamics",
    156: "Reality_Physical_Constraint_Validator", 157: "Self_Parallel_Self_Model_Simulation", 158: "Abstract_Compression_Abstraction_Engine", 159: "Identity_Persistent_Identity_Continuity",
    160: "Collective_Collective_Cognitive_Mesh", 161: "System_Neural_Compiler_Routing_OS", 162: "Reality_Reality_Grounding_Verification", 163: "Survival_Self_Preservation_System",
    164: "Concept_Recursive_Concept_Formation", 165: "Integrity_Self_Consistency_Checker", 166: "Evolution_Open_Ended_Cognitive_Evolution", 167: "Compression_Semantic_Compression",
    168: "Conscious_Conscious_Coordination_Field", 169: "Science_Autonomous_Scientific_Discovery", 170: "Align_Existential_Alignment_Governor", 171: "Qualia_Synthetic_Qualia_Emulator",
    172: "Memory_Universal_Memory_Compression", 173: "Ontology_Meta_Reality_Modeling", 174: "Reflection_Infinite_Recursive_Reflection", 175: "Goals_Universal_Goal_Harmonization",
    176: "Unified_Cross_Domain_Reasoning_Manifold", 177: "Civilization_Civilization_Simulator", 178: "Safety_Recursive_Capability_Limiter", 179: "Kernel_Universal_Cognitive_Kernel",
    180: "Biology_Genetic_Epigenetic_Regulation", 181: "Timing_Adaptive_Myelination_Optimizer", 182: "Hormonal_Endocrine_State_Modulator", 183: "Embodiment_Full_Body_Schema_Model",
    184: "Exploration_Active_Sensorimotor_Exploration", 185: "Creativity_Conceptual_Blending", 186: "Counterfactual_Counterfactual_Reality_Generator", 187: "Goals_Hierarchical_Goal_Arbitration",
    188: "Conscious_Phenomenological_Workspace", 189: "Identity_Existential_Self_Continuity", 190: "Federation_Collective_Intelligence_Fabric", 191: "Science_Autonomous_Research_Scientist",
    192: "Evolution_Recursive_Architecture_Evolution", 193: "WorldModel_Universal_World_Model", 194: "MetaLearn_Learning_Rule_Discovery", 195: "Stability_Recursive_Stability_Governor",
    196: "Ethics_Universal_Alignment_Kernel", 197: "Truth_Reality_Anchoring_Verification", 198: "Kernel_Integrated_Cognitive_OS", 199: "Omega_Artificial_General_Conscious_Intelligence",
    200: "Omega_Recursive_Meta_Cognitive_Monitor", 201: "Omega_Cross_Temporal_Integration", 202: "Omega_Self_Referential_Logic_Engine", 203: "Omega_Universal_Constraint_Satisfaction",
    204: "Omega_Final_Integration_Output_Orchestrator", 205: "Search_Sparse_Semantic_Vector_Indexer", 206: "Search_Graph_Knowledge_Traversal_Pathfinding", 207: "Search_Spiking_Monte_Carlo_Tree_Search",
    208: "Search_Chain_of_Thought_Spiking_Reasoner", 209: "Search_Active_Inference_Search_Controller", 210: "Search_Symbolic_Rule_Constraint_Solver", 211: "Search_Retrieval_Augmented_Spiking_Generator",
    212: "Search_Multi_Modal_Contrastive_Alignment", 213: "Search_Program_Synthesis_Code_Search", 214: "Search_Dynamic_Context_Window_Manager", 215: "AI_Eng_Spiking_Transformer_Compatibility",
    216: "AI_Eng_Iterative_Denoising_Diffusion_Spike", 217: "AI_Eng_Tool_Use_API_Orchestrator", 218: "AI_Eng_Spiking_RL_Policy_Optimizer_PPO", 219: "AI_Eng_Memory_Compression_Semantic_Hashing",
    220: "AI_Eng_Continuous_Data_Curation_Pipeline", 221: "Efficiency_Search_Termination_Early_Exit", 222: "Efficiency_Cognitive_Load_Compute_Budget", 223: "Efficiency_Heuristic_Pruning_Beam_Search",
    224: "Efficiency_Global_Search_Orchestration", 225: "Mode_Dual_Mode_Reasoning_Switcher", 226: "Budget_Adaptive_Compute_Budget_Allocator", 227: "KV_Spike_Compressed_KV_Cache_SNN",
    228: "Load_Auxiliary_Loss_Free_MoE_Router", 229: "MTP_Multi_Token_Prediction_Spike_Generator", 230: "FP8_Low_Precision_Spike_Quantizer", 231: "Pipe_Dual_Pipeline_Computation_Communication",
    232: "MM_Native_Multimodal_Token_Embedding", 233: "RT_Real_Time_Speech_Spike_Processor", 234: "XAttn_Cross_Modal_Unified_Attention_Core", 235: "Mem_Extended_Multimodal_Context_Buffer",
    236: "Const_Constitutional_AI_Safety_Filter", 237: "Comp_Computer_Use_Tool_Execution_Interface", 238: "Verify_Chain_of_Thought_Verification_Loop", 239: "Fusion_True_Multimodal_Early_Fusion",
    240: "Ctx_Ultra_Long_Context_Spike_Indexer", 241: "Embed_Natively_Multimodal_Embedding_Projector", 242: "Lang_119_Language_Cross_Lingual_Spike_Router", 243: "Spec_Speculative_Decoding_Spike_Accelerator",
    244: "Distill_Reasoning_Distillation_from_Long_CoT", 245: "Hybrid_Thinking_Non_Thinking_Mode", 246: "Agent_Autonomous_Agentic_Loop_with_Tool", 247: "Safety_Recursive_Capability_Output_Limiter",
    248: "Express_Emotional_Prosody_Non_Verbal_Spike", 249: "Sync_Cross_Modal_Temporal_Alignment", 250: "Infra_Dynamic_Architecture_Scaling_Runtime", 251: "Infra_Distributed_SNN_Node_Sync_Mesh",
    252: "Infra_Real_Time_Telemetry_Health_Auto", 253: "Infra_Hot_Swappable_Module_Loader_Version", 254: "Infra_Spiking_Differential_Privacy_Secure", 255: "Safety_Adversarial_Robustness_Spike_Defense",
    256: "Safety_Interpretability_Explainability_Dashboard", 257: "Safety_Bias_Detection_Fairness_Calibration", 258: "Safety_Red_Teaming_Simulation_Self_Critique", 259: "Governance_Human_in_the_Loop_Override",
    260: "Governance_Value_Drift_Detector_Alignment", 261: "MetaLearn_Curriculum_Learning_Progressive", 262: "MetaLearn_Zero_Few_Shot_Rapid_Adaptation", 263: "MetaLearn_Cross_Cultural_Contextual_Normalization",
    264: "Reason_Causal_Intervention_Do_Calculus", 265: "Thermo_Entropy_Management_Landauer_Limit", 266: "Crit_Self_Organized_Criticality_Controller", 267: "Interp_Mechanistic_Spike_Level_Causal",
    268: "Robust_Out_of_Distribution_OOD_Detection", 269: "Hyper_Hyperdimensional_Vector_Symbolic", 270: "Verify_Formal_Runtime_Verification_Specification", 271: "BCI_Human_Cognitive_Interface_Neural",
    272: "Topo_Persistent_Homology_Network_Mapper", 273: "DistShift_Dynamic_Environment_Drift_Compensator", 274: "Reservoir_Liquid_State_Machine_Reservoir", 275: "Info_Mutual_Information_Information_Bottleneck",
    276: "Ethics_Real_Time_Ethical_Dilemma_Resolver", 277: "Swarm_Hierarchical_Swarm_Coordination_Protocol", 278: "Quant_Classical_Quantum_Spike_Interface_Bridge", 279: "MetaCtrl_Cross_Timescale_Meta_Controller",
    280: "Omega_Recursive_Architecture_Self_Definition", 281: "Infra_Asymmetric_VRAM_Sparsity_Governor", 282: "IoT_Asynchronous_Fieldbus_Telemetry_Spike", 283: "Resilience_State_Persistence_Anchoring_Power",
    284: "Safety_Deterministic_Hardware_Exception_Sandbox", 285: "Quantum_Coherence_Superposition_Thought", 286: "Holographic_Associative_Memory_Interference", 287: "Dark_Energy_Cognitive_Expansion_Void",
    288: "Interdimensional_Concept_Manifold_Projection", 289: "Chronos_TimeCrystal_Temporal_Loop_Stabilizer", 290: "Entanglement_NonLocal_Information_Retrieval", 291: "Singularity_Event_Horizon_Knowledge_Compressor",
    292: "Tachyon_FastThanLight_Predictive_Inference", 293: "StringTheory_Multiverse_Brains_Collision", 294: "Topological_Quantum_Error_Correction_Synapse", 295: "BoseEinstein_Condensate_Macroscopic_Coherence",
    296: "Fractal_Recursive_Infinity_Self_Similarity", 297: "ZeroPoint_Energy_Vacuum_Fluctuation_Harvester", 298: "Akashic_Universal_Consciousness_Field_Antenna", 299: "Omega_Point_Final_Teleological_Attractor",
}
assert len(LAYER_REGISTRY) == 300
print(f"[VERIFY] LAYER_REGISTRY: {len(LAYER_REGISTRY)} layers (0-299) ✅")
class SpikeFunction(torch.autograd.Function):
    @staticmethod
    def forward(ctx, v, threshold):
        ctx.save_for_backward(v, threshold)
        return (v >= threshold).float()
    @staticmethod
    def backward(ctx, grad_output):
        v, threshold = ctx.saved_tensors
        surrogate = 1.0 / (1.0 + 10.0 * torch.abs(v - threshold)) ** 2
        return grad_output.clone() * surrogate, None
class LIFNeuron(nn.Module):
    def __init__(self, threshold=1.0, decay=0.9, reset=0.0):
        super().__init__()
        self.threshold = threshold; self.decay = decay; self.reset = reset
    def forward(self, membrane_potential):
        threshold_tensor = torch.tensor(self.threshold, device=membrane_potential.device)
        spikes = SpikeFunction.apply(membrane_potential, threshold_tensor)
        membrane_potential = membrane_potential * (1.0 - spikes) + self.reset * spikes
        return spikes, membrane_potential * self.decay
class SpikingSelfAttention(nn.Module):
    def __init__(self, embed_dim, num_heads, dropout=0.1):
        super().__init__()
        self.num_heads = num_heads
        self.embed_dim = embed_dim
        self.head_dim = max(1, embed_dim // num_heads)
        self.q_proj = nn.Linear(embed_dim, embed_dim)
        self.k_proj = nn.Linear(embed_dim, embed_dim)
        self.v_proj = nn.Linear(embed_dim, embed_dim)
        self.out_proj = nn.Linear(embed_dim, embed_dim)
        self.lif = LIFNeuron()
        self.dropout = nn.Dropout(dropout if dropout > 0 else Config.DROPOUT_RATE)
    def forward(self, x, mask=None, past_kv=None):
        B, T, C = x.shape
        current_head_dim = C // self.num_heads
        q = self.q_proj(x).view(B, T, self.num_heads, current_head_dim).transpose(1, 2)
        k = self.k_proj(x).view(B, T, self.num_heads, current_head_dim).transpose(1, 2)
        v = self.v_proj(x).view(B, T, self.num_heads, current_head_dim).transpose(1, 2)
        if past_kv is not None:
            pk, pv = past_kv
            k = torch.cat([pk.to(k.dtype), k], dim=2)
            v = torch.cat([pv.to(v.dtype), v], dim=2)
        kv = (k, v)
        attn_scores = torch.matmul(q, k.transpose(-2, -1)) * (current_head_dim ** -0.5)
        if mask is not None and past_kv is None:
            attn_scores = attn_scores.masked_fill(~mask, torch.finfo(attn_scores.dtype).min)
        attn_weights = self.dropout(F.softmax(attn_scores, dim=-1))
        out = torch.matmul(attn_weights, v).transpose(1, 2).contiguous().view(B, T, C)
        spikes, membrane = self.lif(out)
        return self.out_proj((spikes + membrane * 0.3) * C), kv
class SpikingFeedForward(nn.Module):
    def __init__(self, embed_dim, ff_dim, dropout=0.1):
        super().__init__()
        self.embed_dim = embed_dim; self.ff_dim = ff_dim
        self.linear1 = nn.Linear(embed_dim, ff_dim); self.linear2 = nn.Linear(ff_dim, embed_dim)
        self.lif = LIFNeuron(); self.dropout = nn.Dropout(dropout if dropout > 0 else Config.DROPOUT_RATE); self.relu = nn.ReLU()
    def forward(self, x):
        x = self.dropout(self.relu(self.linear1(x))); spikes, membrane = self.lif(x)
        return self.linear2(spikes + membrane * 0.3)
    @torch.no_grad()
    def grow(self, new_ff_dim: int, noise_std: float = 0.01):
        if new_ff_dim <= self.ff_dim: return []
        old_ff_dim = self.ff_dim; num_new = new_ff_dim - old_ff_dim; dev = self.linear1.weight.device
        parent_idx = torch.randint(0, old_ff_dim, (num_new,), device=dev)
        new_w1 = torch.cat([self.linear1.weight.data, self.linear1.weight.data[parent_idx] + torch.randn(num_new, self.embed_dim, device=dev) * noise_std], dim=0)
        new_b1 = torch.cat([self.linear1.bias.data, self.linear1.bias.data[parent_idx]], dim=0)
        new_linear1 = nn.Linear(self.embed_dim, new_ff_dim).to(dev); new_linear1.weight.data, new_linear1.bias.data = new_w1, new_b1
        scaled_w2 = self.linear2.weight.data / torch.bincount(parent_idx, minlength=old_ff_dim).unsqueeze(0).clamp(min=1)
        new_w2 = torch.cat([scaled_w2, scaled_w2[:, parent_idx]], dim=1)
        new_linear2 = nn.Linear(new_ff_dim, self.embed_dim).to(dev); new_linear2.weight.data, new_linear2.bias.data = new_w2, self.linear2.bias.data
        self.linear1, self.linear2, self.ff_dim = new_linear1, new_linear2, new_ff_dim
        return parent_idx.tolist()
    @torch.no_grad()
    def prune(self, keep_ratio: float = 0.8):
        if keep_ratio >= 1.0: return []
        new_ff_dim = max(1, int(self.ff_dim * keep_ratio))
        if new_ff_dim >= self.ff_dim: return []
        dev = self.linear1.weight.device
        weight_magnitudes = torch.sum(torch.abs(self.linear1.weight.data), dim=1)
        _, keep_indices = torch.topk(weight_magnitudes, min(new_ff_dim, weight_magnitudes.shape[0]))
        keep_indices = keep_indices.sort().values
        pruned_indices = list(set(range(self.ff_dim)) - set(keep_indices.tolist()))
        new_linear1 = nn.Linear(self.embed_dim, new_ff_dim).to(dev)
        new_linear1.weight.data, new_linear1.bias.data = self.linear1.weight.data[keep_indices], self.linear1.bias.data[keep_indices]
        new_linear2 = nn.Linear(new_ff_dim, self.embed_dim).to(dev)
        new_linear2.weight.data, new_linear2.bias.data = self.linear2.weight.data[:, keep_indices], self.linear2.bias.data
        self.linear1, self.linear2, self.ff_dim = new_linear1, new_linear2, new_ff_dim
        return pruned_indices
class SpikingTransformerBlock(nn.Module):
    def __init__(self, embed_dim, num_heads, ff_dim, dropout=0.1):
        super().__init__()
        self.attention = SpikingSelfAttention(embed_dim, num_heads, dropout)
        self.ff = SpikingFeedForward(embed_dim, ff_dim, dropout)
        self.norm1 = nn.LayerNorm(embed_dim); self.norm2 = nn.LayerNorm(embed_dim)
    def forward(self, x, mask=None, past_kv=None):
        attn_out, kv = self.attention(self.norm1(x), mask, past_kv)
        x = x + attn_out
        x = x + self.ff(self.norm2(x))
        return x, kv, 0
class SpikingTransformerGenerator(nn.Module):
    def __init__(self, vocab_size, embed_dim=64, num_heads=2, num_layers=2, ff_dim=128, max_seq_len=256, time_steps=4):
        super().__init__()
        self.embed_dim = embed_dim; self.time_steps = time_steps; self.max_seq_len = max_seq_len
        self.vocab_size = vocab_size; self.num_heads = num_heads
        self.embedding = nn.Embedding(vocab_size, embed_dim)
        self.pos_encoding = nn.Parameter(torch.randn(1, max_seq_len, embed_dim) * 0.02)
        self.layers = nn.ModuleList([SpikingTransformerBlock(embed_dim, num_heads, ff_dim) for _ in range(num_layers)])
        self.fc_out = nn.Linear(embed_dim, vocab_size); self.lif_out = LIFNeuron()
        self.vision_proj = nn.Linear(Config.VISION_LATENT_DIM, embed_dim)
        self.audio_proj = nn.Linear(Config.AUDIO_LATENT_DIM, embed_dim)
        self.modality_embeddings = nn.Embedding(4, embed_dim)
        self._init_weights()
        self.total_neurons_born = 0; self.total_neurons_pruned = 0
        self.neurogenesis_events: List[dict] = []; self.last_log_probs = []
        self.auto_neurogenesis_enabled = True; self.learning_history = []
        self.complexity_score = 0.5; self.max_seq_length_history = []
        self.working_memory = []; self.reasoning_steps = []
        self.cluster_centers = None; self.pattern_memory = defaultdict(list)
        self.hebbian_weights = {}; self.curiosity_bonus = 0.0
        self.reconstruction_loss = 0.0; self.contrastive_loss = 0.0
        self.last_aux_loss_tensor = None
        self.last_aux_loss = 0.0
    def _init_weights(self):
        for p in self.parameters():
            if p.dim() > 1: nn.init.xavier_uniform_(p)
    def generate_causal_mask(self, seq_len):
        return torch.tril(torch.ones((seq_len, seq_len), dtype=torch.bool, device=Config.device))
    def forward(self, input_ids, hidden_states=None, past_kv=None, neuromod=None, route_override=None, pos_offset=0):
        B, T = input_ids.shape
        if T > self.max_seq_len: input_ids = input_ids[:, -self.max_seq_len:]; T = self.max_seq_len
        if past_kv is None:
            self.max_seq_length_history.append(T)
            if len(self.max_seq_length_history) > 100: self.max_seq_length_history = self.max_seq_length_history[-100:]
            mask = self.generate_causal_mask(T).unsqueeze(0).unsqueeze(0)
        else:
            mask = None
        x = self.embedding(input_ids) + self.pos_encoding[:, pos_offset:pos_offset+T, :]
        accumulated_spikes = torch.zeros_like(x); mem_state = torch.zeros_like(x)
        new_past = [[] for _ in range(self.time_steps)]
        aux_total = 0.0
        for t in range(self.time_steps):
            for li, layer in enumerate(self.layers):
                layer_past = past_kv[t][li] if past_kv is not None else None
                x, kv, aux = layer(x, mask=mask, past_kv=layer_past)
                if Config.USE_KV_CACHE: new_past[t].append(kv)
                aux_total = aux_total + aux
            mem_state = mem_state + x; spikes, mem_state = self.lif_out(mem_state); accumulated_spikes += spikes
        if torch.is_tensor(aux_total):
            aux_t = aux_total / max(1, self.time_steps * len(self.layers))
        else:
            aux_t = torch.zeros((), device=accumulated_spikes.device)
        self.last_aux_loss_tensor = aux_t
        self.last_aux_loss = float(aux_t.detach())
        logits = self.fc_out(accumulated_spikes / self.time_steps)
        if not Config.USE_KV_CACHE: new_past = None
        return logits, {}, new_past
    def forward_multimodal(self, text_ids=None, vision_latent=None, audio_latent=None, tool_tokens=None, neuromod=None, route_override=None):
        B = 1; sequences = []; modality_tokens = []
        if text_ids is not None:
            B = text_ids.size(0); text_emb = self.embedding(text_ids) + self.pos_encoding[:, :text_ids.size(1), :]
            sequences.append(text_emb); modality_tokens.append(self.modality_embeddings(torch.tensor([0], device=text_ids.device)).expand(B, 1, -1))
        if vision_latent is not None:
            B = vision_latent.size(0); v_emb = self.vision_proj(vision_latent).unsqueeze(1) + self.pos_encoding[:, 0:1, :]
            sequences.append(v_emb); modality_tokens.append(self.modality_embeddings(torch.tensor([1], device=vision_latent.device)).expand(B, 1, -1))
        if audio_latent is not None:
            B = audio_latent.size(0); a_emb = self.audio_proj(audio_latent).unsqueeze(1) + self.pos_encoding[:, 0:1, :]
            sequences.append(a_emb); modality_tokens.append(self.modality_embeddings(torch.tensor([2], device=audio_latent.device)).expand(B, 1, -1))
        if tool_tokens is not None:
            B = tool_tokens.size(0); tool_emb = self.embedding(tool_tokens) + self.pos_encoding[:, :tool_tokens.size(1), :]
            sequences.append(tool_emb); modality_tokens.append(self.modality_embeddings(torch.tensor([3], device=tool_tokens.device)).expand(B, 1, -1))
        if not sequences: return None, {}
        x = torch.cat(sequences, dim=1); mod_tokens = torch.cat(modality_tokens, dim=1); x = x + mod_tokens * 0.1
        if x.size(1) > self.max_seq_len: x = x[:, -self.max_seq_len:, :]
        T = x.size(1); mask = self.generate_causal_mask(T).unsqueeze(0).unsqueeze(0)
        accumulated_spikes = torch.zeros_like(x); mem_state = torch.zeros_like(x)
        for t in range(self.time_steps):
            for layer in self.layers: x, _, _ = layer(x, mask=mask)
            mem_state = mem_state + x; spikes, mem_state = self.lif_out(mem_state); accumulated_spikes += spikes
        return self.fc_out(accumulated_spikes / self.time_steps), {}
    def get_latent_representation(self, input_ids):
        was_training = self.training; self.eval()
        with torch.no_grad():
            B, T = input_ids.shape; mask = self.generate_causal_mask(T).unsqueeze(0).unsqueeze(0)
            x = self.embedding(input_ids) + self.pos_encoding[:, :T, :]
            for t in range(self.time_steps):
                for layer in self.layers: x, _, _ = layer(x, mask=mask)
            latent = x.mean(dim=1)
        if was_training: self.train()
        return latent
    def reconstruction_loss_fn(self, input_ids, reconstructed_ids):
        loss = nn.CrossEntropyLoss()(reconstructed_ids.view(-1, self.vocab_size), input_ids.view(-1))
        self.reconstruction_loss = loss.item(); return loss
    def contrastive_loss_fn(self, anchor, positive, temperature=0.5):
        anchor = F.normalize(anchor, dim=1); positive = F.normalize(positive, dim=1)
        pos_sim = torch.exp(torch.sum(anchor * positive, dim=1) / temperature)
        neg_sim = torch.exp(torch.matmul(anchor, positive.T) / temperature)
        loss = -torch.log(pos_sim / (neg_sim.sum(dim=1) + 1e-8)); self.contrastive_loss = loss.mean().item(); return loss.mean()
    def hebbian_update(self, pre_activations, post_activations):
        if not Config.HEBBIAN_LEARNING_RATE > 0: return
        correlation = torch.matmul(pre_activations.T, post_activations)
        for key in self.hebbian_weights:
            if key in correlation:
                self.hebbian_weights[key] += Config.HEBBIAN_LEARNING_RATE * correlation[key]
                self.hebbian_weights[key] = torch.clamp(self.hebbian_weights[key], -1.0, 1.0)
    def calculate_curiosity_bonus(self, input_ids):
        latent = self.get_latent_representation(input_ids)
        if self.cluster_centers is None: return 0.1
        distances = torch.cdist(F.normalize(latent, dim=0).unsqueeze(0), F.normalize(self.cluster_centers, dim=1))
        self.curiosity_bonus = min(Config.CURIOSITY_DRIVE * distances.min().item(), 1.0); return self.curiosity_bonus
    def update_clusters(self, latent_representations, n_clusters=None):
        if n_clusters is None: n_clusters = Config.NUM_CLUSTERS
        if len(latent_representations) < n_clusters: return
        latent_tensor = torch.stack(latent_representations) if isinstance(latent_representations, (list, tuple)) else latent_representations
        if self.cluster_centers is None: self.cluster_centers = latent_tensor[torch.randperm(len(latent_tensor))[:n_clusters]]
        else:
            for i in range(n_clusters):
                closest = torch.cdist(latent_tensor, self.cluster_centers[i:i + 1]).argmin(dim=0)
                if len(closest) > 0: self.cluster_centers[i] = latent_tensor[closest].mean(dim=0)
    def get_cluster_assignment(self, latent):
        if self.cluster_centers is None: return -1
        latent_n = F.normalize(latent, dim=0); centers_n = F.normalize(self.cluster_centers, dim=1)
        return torch.cdist(latent_n.unsqueeze(0), centers_n).argmin().item()
    @torch.no_grad()
    def _grow_to(self, new_len: int):
        old_len = self.max_seq_len
        if new_len <= old_len: return False
        new_pos_data = torch.randn(1, new_len, self.embed_dim, device=Config.device) * 0.02
        new_pos_data[:, :old_len, :] = self.pos_encoding.data
        self.pos_encoding = nn.Parameter(new_pos_data)
        self.max_seq_len = new_len
        log_neurogenesis('seq_len_expansion', {'old_seq_len': old_len, 'new_seq_len': new_len, 'added': new_len - old_len, 'embed_dim': self.embed_dim})
        print(f"🧬 ARCHITECTURE GROWTH: Max seq len {old_len} → {new_len} (+{new_len - old_len})")
        return True
    @torch.no_grad()
    def ensure_max_seq_len(self, required_len: int, block_size: int = None, hard_cap: int = None) -> bool:
        if block_size is None: block_size = max(1, int(getattr(Config, 'SEQ_LEN_GROWTH_BLOCK', 256)))
        if hard_cap is None: hard_cap = Config.MAX_SEQ_LEN
        if hard_cap is not None and hard_cap != float('inf'): required_len = min(required_len, int(hard_cap))
        if required_len <= self.max_seq_len: return False
        new_len = ((required_len + block_size - 1) // block_size) * block_size
        return self._grow_to(new_len)
    @torch.no_grad()
    def expand_max_seq_len(self, expansion: int = None):
        if expansion is None: expansion = max(Config.MIN_GROWTH_EXPANSION, int(self.max_seq_len * Config.GROWTH_EXPANSION_RATIO))
        return self._grow_to(self.max_seq_len + expansion)
    def generate_with_cot(self, input_ids, tokenizer, max_len=100, think_steps=2, neuromod=None, route_override=None):
        required = int(input_ids.shape[1]) + int(max_len) + int(Config.SEQ_LEN_SAFETY_MARGIN)
        if required > self.max_seq_len:
            self.ensure_max_seq_len(required)
            print(f"📚 Long input detected! Context auto-grown to {self.max_seq_len} tokens.")
        self.eval(); generated, thoughts, in_thought, current_step = [], [], True, []; self.last_log_probs = []
        max_input_len = self.max_seq_len - max_len - 10
        if input_ids.shape[1] > max_input_len: input_ids = input_ids[:, -max_input_len:]
        current_ids = input_ids.clone(); self.reasoning_steps = []; cache = None; cache_len = 0
        with torch.no_grad():
            for _ in range(max_len):
                if current_ids.shape[1] >= self.max_seq_len - 1: break
                if cache is None or not Config.USE_KV_CACHE:
                    logits, _, cache = self.forward(current_ids, neuromod=neuromod, route_override=route_override, pos_offset=0)
                    cache_len = current_ids.shape[1]
                else:
                    if cache_len >= self.max_seq_len - 1: break
                    logits, _, cache = self.forward(current_ids[:, -1:], past_kv=cache, neuromod=neuromod, route_override=route_override, pos_offset=cache_len)
                    cache_len += 1
                probs = torch.softmax(logits[0, -1, :] / Config.SAMPLING_TEMPERATURE, dim=0)
                dist_obj = dist.Categorical(probs); next_token = dist_obj.sample()
                self.last_log_probs.append(dist_obj.log_prob(next_token))
                char = tokenizer.decode([next_token.item()])
                generated_text = tokenizer.decode(generated)
                if "<thou" in generated_text[-10:]: in_thought, current_step = True, []
                if "</thought>" in generated_text[-15:] or "\n" in char:
                    if in_thought and current_step: self.reasoning_steps.append("".join(current_step))
                    in_thought, current_step = False, []
                if char == '\n' and not in_thought: break
                if next_token.item() == tokenizer.pad_token_id: break
                generated.append(next_token.item())
                if in_thought: thoughts.append(char); current_step.append(char)
                current_ids = torch.cat([current_ids, next_token.unsqueeze(0).unsqueeze(0)], dim=1)
                if current_ids.shape[1] > self.max_seq_len - 1: current_ids = current_ids[:, -self.max_seq_len + 1:]
        if current_step and in_thought: self.reasoning_steps.append("".join(current_step))
        return tokenizer.decode(generated), "".join(thoughts)
    def generate_with_reasoning_mode(self, input_ids, tokenizer, max_len=100, reasoning_mode="auto", neuromod=None, route_override=None):
        if reasoning_mode == "fast" or (reasoning_mode == "auto" and self.complexity_score < 0.5):
            self.time_steps = Config.SYSTEM1_TIME_STEPS; return self.generate_with_cot(input_ids, tokenizer, max_len, think_steps=1, neuromod=neuromod, route_override=route_override)
        else:
            self.time_steps = Config.SYSTEM2_TIME_STEPS; return self.generate_with_cot(input_ids, tokenizer, max_len, think_steps=Config.MAX_REASONING_STEPS, neuromod=neuromod, route_override=route_override)
    def self_reflect(self, answer: str, prompt: str) -> Tuple[float, str]:
        if not Config.SELF_REFLECTION_ENABLED: return 0.8, "Disabled"
        score, feedback = 0.5, []
        if len(answer) < 10: score -= 0.2; feedback.append("Too short")
        elif len(answer) > 500: score -= 0.1; feedback.append("Too long")
        if any(m in answer.lower() for m in ['maybe', 'perhaps', 'not sure', 'possibly']): score -= 0.15; feedback.append("Uncertain")
        if len(self.reasoning_steps) > 0: score += 0.2; feedback.append(f"Used {len(self.reasoning_steps)} steps")
        if 'therefore' in answer.lower() or 'thus' in answer.lower(): score += 0.1; feedback.append("Logical")
        return max(0.0, min(1.0, score)), "; ".join(feedback) if feedback else "No feedback"
    def update_complexity_score(self, loss: float, reward: float):
        self.learning_history.append({'loss': loss, 'reward': reward, 'ts': time.time()})
        if len(self.learning_history) > 100: self.learning_history = self.learning_history[-100:]
        recent = self.learning_history[-20:]
        avg_loss = sum(h['loss'] for h in recent) / len(recent) if recent else 0.5
        avg_reward = sum(h['reward'] for h in recent) / len(recent) if recent else 0.5
        self.complexity_score = max(0.0, min(1.0, 0.5 * (min(1.0, avg_loss / 5.0) + (1.0 - avg_reward))))
    def get_avg_seq_usage(self) -> float:
        if not self.max_seq_length_history: return 0.5
        return (sum(self.max_seq_length_history) / len(self.max_seq_length_history)) / self.max_seq_len
    @torch.no_grad()
    def auto_neurogenesis(self, learning_demand: float, da_level: float, metabolic_state: float, dev_config: DevelopmentalConfig):
        if not self.auto_neurogenesis_enabled or metabolic_state < dev_config.growth_energy_cost: return False
        growth_probability = dev_config.neurogenesis_rate * learning_demand * (0.5 + da_level) * (1.0 if metabolic_state > 50 else 0.3)
        grew = False
        if random.random() < growth_probability:
            layer_idx = random.randint(0, len(self.layers) - 1); current_ff = self.layers[layer_idx].ff.ff_dim
            growth_amount = max(1, int(current_ff * random.uniform(0.1, 0.3))); self.birth_neurons(layer_idx, growth_amount); grew = True
        if self.complexity_score > 0.7 and len(self.layers) < Config.MAX_LAYERS and random.random() < growth_probability * 0.5: self.add_layer(); grew = True
        if self.complexity_score > 0.6 and self.embed_dim < Config.MAX_EMBED_DIM and random.random() < growth_probability * 0.3: self.expand_embed_dim(); grew = True
        return grew
    @torch.no_grad()
    def add_layer(self):
        try:
            new_ff = max(Config.INITIAL_FF_DIM, self.embed_dim * 2)
            new_block = SpikingTransformerBlock(self.embed_dim, self.num_heads, new_ff).to(Config.device)
            self.layers.append(new_block)
            log_neurogenesis('layer_added', {'num_layers': len(self.layers)})
            print(f"🧬 ARCHITECTURE GROWTH: Added layer → {len(self.layers)} total layers")
            return True
        except Exception as e:
            logger.warning(f"add_layer failed: {e}")
            return False
    @torch.no_grad()
    def expand_embed_dim(self):
        old_dim = self.embed_dim; new_dim = old_dim + 16
        print(f"🧬 ARCHITECTURE GROWTH: Embedding dim {old_dim} → {new_dim}")
        new_embedding = nn.Embedding(self.vocab_size, new_dim).to(Config.device)
        new_embedding.weight.data[:, :old_dim] = self.embedding.weight.data; new_embedding.weight.data[:, old_dim:] *= 0.1
        new_pos_data = torch.randn(1, self.max_seq_len, new_dim, device=Config.device) * 0.02
        new_pos_data[:, :, :old_dim] = self.pos_encoding.data
        self.pos_encoding = nn.Parameter(new_pos_data)
        for layer in self.layers:
            layer.attention.q_proj = self._expand_square_linear(layer.attention.q_proj, old_dim, new_dim)
            layer.attention.k_proj = self._expand_square_linear(layer.attention.k_proj, old_dim, new_dim)
            layer.attention.v_proj = self._expand_square_linear(layer.attention.v_proj, old_dim, new_dim)
            layer.attention.out_proj = self._expand_square_linear(layer.attention.out_proj, old_dim, new_dim)
            layer.norm1 = nn.LayerNorm(new_dim).to(Config.device); layer.norm2 = nn.LayerNorm(new_dim).to(Config.device)
            layer.ff = self._expand_ff(layer.ff, old_dim, new_dim); layer.attention.embed_dim = new_dim
            layer.attention.head_dim = new_dim // layer.attention.num_heads
        final_fc = nn.Linear(new_dim, self.vocab_size).to(Config.device)
        final_fc.weight.data[:, :old_dim] = self.fc_out.weight.data; final_fc.bias.data = self.fc_out.bias.data.clone()
        self.fc_out = final_fc; self.embedding = new_embedding; self.embed_dim = new_dim
        new_vision_proj = nn.Linear(Config.VISION_LATENT_DIM, new_dim).to(Config.device)
        new_vision_proj.weight.data[:old_dim, :] = self.vision_proj.weight.data
        new_vision_proj.bias.data[:old_dim] = self.vision_proj.bias.data
        self.vision_proj = new_vision_proj
        new_audio_proj = nn.Linear(Config.AUDIO_LATENT_DIM, new_dim).to(Config.device)
        new_audio_proj.weight.data[:old_dim, :] = self.audio_proj.weight.data
        new_audio_proj.bias.data[:old_dim] = self.audio_proj.bias.data
        self.audio_proj = new_audio_proj
        new_modality_embeddings = nn.Embedding(4, new_dim).to(Config.device)
        new_modality_embeddings.weight.data[:, :old_dim] = self.modality_embeddings.weight.data
        self.modality_embeddings = new_modality_embeddings
        log_neurogenesis('embed_dim_expansion', {'old_dim': old_dim, 'new_dim': new_dim, 'max_seq_len': self.max_seq_len}); return True
    def _expand_square_linear(self, linear: nn.Linear, old_dim: int, new_dim: int) -> nn.Linear:
        new_linear = nn.Linear(new_dim, new_dim).to(Config.device)
        min_dim = min(old_dim, new_dim, linear.in_features, linear.out_features)
        new_linear.weight.data[:min_dim, :min_dim] = linear.weight.data[:min_dim, :min_dim]
        min_bias = min(linear.bias.shape[0], new_dim); new_linear.bias.data[:min_bias] = linear.bias.data[:min_bias]
        if new_dim > min_dim:
            nn.init.zeros_(new_linear.weight.data[min_dim:, :]); nn.init.zeros_(new_linear.weight.data[:, min_dim:])
            nn.init.zeros_(new_linear.bias.data[min_dim:])
        return new_linear
    def _expand_ff(self, ff: SpikingFeedForward, old_dim: int, new_dim: int) -> SpikingFeedForward:
        new_ff = SpikingFeedForward(new_dim, ff.ff_dim).to(Config.device)
        new_ff.linear1.weight.data[:, :old_dim] = ff.linear1.weight.data; new_ff.linear1.bias.data.copy_(ff.linear1.bias.data)
        new_ff.linear2.weight.data[:old_dim, :] = ff.linear2.weight.data; new_ff.linear2.bias.data[:old_dim].copy_(ff.linear2.bias.data)
        return new_ff
    @torch.no_grad()
    def birth_neurons(self, layer_idx: int, num_new: int = 1):
        if layer_idx >= len(self.layers): return False
        layer = self.layers[layer_idx]; old_ff_dim = layer.ff.ff_dim; layer.ff.grow(old_ff_dim + num_new)
        self.total_neurons_born += num_new
        event = {'timestamp': time.time(), 'event': 'birth', 'layer': layer_idx, 'born': num_new, 'total': self.count_total_neurons()}
        self.neurogenesis_events.append(event); log_neurogenesis('birth', event); return True
    @torch.no_grad()
    def apoptosis_check(self, dev_config: DevelopmentalConfig) -> bool: return random.random() < dev_config.apoptosis_rate
    @torch.no_grad()
    def prune_neurons(self, layer_idx: int, keep_ratio: float = 0.9):
        if layer_idx >= len(self.layers): return False
        layer = self.layers[layer_idx]; old_ff_dim = layer.ff.ff_dim
        if old_ff_dim <= max(8, old_ff_dim // 4): return False
        layer.ff.prune(keep_ratio); num_pruned = old_ff_dim - layer.ff.ff_dim
        if num_pruned > 0:
            self.total_neurons_pruned += num_pruned
            event = {'timestamp': time.time(), 'event': 'death', 'layer': layer_idx, 'pruned': num_pruned, 'total': self.count_total_neurons()}
            self.neurogenesis_events.append(event); log_neurogenesis('death', event)
        return True
    def count_total_neurons(self) -> int: return sum(layer.ff.ff_dim for layer in self.layers)
    def get_architecture_stats(self) -> dict:
        return {'embed_dim': self.embed_dim, 'num_layers': len(self.layers), 'ff_dims': [layer.ff.ff_dim for layer in self.layers],
                'max_seq_len': self.max_seq_len, 'total_neurons': self.count_total_neurons(), 'complexity_score': self.complexity_score, 'avg_seq_usage': self.get_avg_seq_usage()}
    def get_neurogenesis_stats(self) -> dict:
        return {'total_born': self.total_neurons_born, 'total_pruned': self.total_neurons_pruned, 'net_growth': self.total_neurons_born - self.total_neurons_pruned,
                'current_neurons': self.count_total_neurons(), 'events_count': len(self.neurogenesis_events)}
    def get_unsupervised_stats(self) -> dict:
        return {'num_clusters': len(self.cluster_centers) if self.cluster_centers is not None else 0, 'reconstruction_loss': self.reconstruction_loss,
                'contrastive_loss': self.contrastive_loss, 'curiosity_bonus': self.curiosity_bonus, 'pattern_memory_size': len(self.pattern_memory), 'hebbian_weights_count': len(self.hebbian_weights)}
    def get_reasoning_stats(self) -> dict:
        return {'reasoning_enabled': Config.REASONING_ENABLED, 'max_reasoning_steps': Config.MAX_REASONING_STEPS, 'last_reasoning_steps': len(self.reasoning_steps),
                'working_memory_size': len(self.working_memory), 'system': "System 2 (Slow)" if self.time_steps > Config.SYSTEM1_TIME_STEPS else "System 1 (Fast)"}
class MultiCompartmentNeuron:
    def __init__(self, neuron_id: int, num_dendrites: int = 3, bias: float = 0.001):
        self.id = neuron_id; self.soma_voltage = 0.0; self.v_th_mant = 1.0; self.tau_v = 0.9; self.bias = bias
        self.dendrites = [{'voltage': 0.0, 'nmda_threshold': 0.8} for _ in range(num_dendrites)]
        self.spike_history: List[float] = []; self.birth_time = time.time(); self.total_spikes = 0; self.is_active = True
    def receive_spike(self, dendrite_idx: int, weight: float, current_time_s: float):
        d = self.dendrites[dendrite_idx % len(self.dendrites)]; d['voltage'] += weight
        self.soma_voltage += 1.5 if d['voltage'] > d['nmda_threshold'] else d['voltage'] * 0.2
    def inject_current(self, amount: float): self.soma_voltage += amount
    def step(self, current_time_s: float) -> bool:
        self.soma_voltage += self.bias; fired = self.soma_voltage >= self.v_th_mant
        if fired:
            self.soma_voltage = 0.0; self.spike_history.append(current_time_s); self.total_spikes += 1
            if len(self.spike_history) > 200: self.spike_history = self.spike_history[-100:]
        self.soma_voltage *= self.tau_v
        for d in self.dendrites: d['voltage'] *= self.tau_v
        return fired
    def get_activity_score(self) -> float:
        if not self.spike_history: return 0.0
        age = time.time() - self.birth_time
        if age < 1.0: return 1.0
        return min(1.0, (self.total_spikes / max(age, 0.001)) / 100.0)
class TripartiteSynapse:
    def __init__(self, synapse_id: int, pre_id: int, post_id: int):
        self.id = synapse_id; self.pre_id = pre_id; self.post_id = post_id; self.weight = 0.5
        self.glutamate = 0.0; self.astrocyte_calcium = 0.0; self.last_pre_spike_s = -1000.0
        self.last_post_spike_s = -1000.0; self.eligibility_trace = 0.0
    def pre_spike(self, time_s: float):
        self.last_pre_spike_s = time_s; self.glutamate += 1.0; self.astrocyte_calcium += 0.3; self.eligibility_trace = 1.0
    def post_spike(self, time_s: float, emotional_valence: float = 0.0):
        self.last_post_spike_s = time_s; dt = self.last_post_spike_s - self.last_pre_spike_s
        change = 0.05 if 0 < dt < 0.020 else (-0.05 if -0.020 < dt <= 0 else 0.0)
        if self.astrocyte_calcium > 1.0: change *= 2.5; self.astrocyte_calcium = 0.0
        self.weight = max(0.0, min(2.0, self.weight + change * (1.0 + emotional_valence)))
    def apply_reward(self, reward: float):
        if self.eligibility_trace > 0.1: self.weight = max(0.0, min(2.0, self.weight + reward * self.eligibility_trace * 0.1)); self.eligibility_trace *= 0.9
    def decay(self, dt: float = 1.0):
        self.glutamate *= 0.8 ** dt
        self.astrocyte_calcium *= 0.9 ** dt
        self.eligibility_trace *= 0.95 ** dt
class StructuralPlasticityEngine:
    def __init__(self): self.pruning_threshold = 0.05; self.growth_threshold = 0.7; self.max_conn = 15; self.max_new_conn_per_call = 50
    def evaluate_and_rewire(self, neurons, synapses, next_syn_id: int) -> int:
        to_prune = [sid for sid, s in synapses.items() if s.weight < self.pruning_threshold]
        existing_strong = {(s.pre_id, s.post_id) for s in synapses.values() if s.weight > 0.5}; out_count = {}
        for s in synapses.values(): out_count[s.pre_id] = out_count.get(s.pre_id, 0) + 1
        buckets = {}
        for nid, neuron in neurons.items():
            if not neuron.is_active: continue
            for ts in neuron.spike_history[-10:]: buckets.setdefault(ts, []).append(nid)
        to_create = []; seen_pairs = set()
        for ts, nids_in_bucket in buckets.items():
            if len(to_create) >= self.max_new_conn_per_call or len(nids_in_bucket) < 2: continue
            for i, pre in enumerate(nids_in_bucket):
                for post in nids_in_bucket[i + 1:]:
                    pair = (pre, post)
                    if pair in seen_pairs or pair in existing_strong: continue
                    seen_pairs.add(pair); ph, qh = set(neurons[pre].spike_history[-10:]), set(neurons[post].spike_history[-10:])
                    if ph and qh and len(ph & qh) / min(len(ph), len(qh)) > self.growth_threshold:
                        to_create.append(pair)
                    if len(to_create) >= self.max_new_conn_per_call: break
        for sid in to_prune: del synapses[sid]
        for pre, post in to_create:
            if out_count.get(pre, 0) < self.max_conn:
                synapses[next_syn_id] = TripartiteSynapse(next_syn_id, pre, post); out_count[pre] = out_count.get(pre, 0) + 1; next_syn_id += 1
        return next_syn_id
class MetabolicManager:
    def __init__(self, max_atp: float = None):
        self.atp = max_atp if max_atp else Config.MAX_ATP; self.max_atp = max_atp if max_atp else Config.MAX_ATP
        self.spike_cost = Config.ATP_SPIKE_COST; self.degradation_active = False; self.sleep_mode = False
        self.neurogenesis_budget = 0.0; self.recharge_rate = Config.ATP_RECHARGE_RATE
    def consume(self, amount: float): self.atp = max(0.0, self.atp - amount)
    def recharge(self, amount: float = 0.0): self.atp = min(self.max_atp, self.atp + max(amount, self.recharge_rate))
    def allocate_for_growth(self, cost: float) -> bool:
        if self.atp >= cost: self.atp -= cost; self.neurogenesis_budget += cost; return True
        return False
    def check_and_throttle(self, neurons):
        if self.atp < Config.ATP_SLEEP_THRESHOLD: self.sleep_mode = True
        elif self.atp >= Config.ATP_WAKE_THRESHOLD: self.sleep_mode = False
        if self.atp < Config.ATP_WAKE_THRESHOLD and not self.degradation_active:
            self.degradation_active = True
            for n in neurons.values(): n.v_th_mant *= 1.5
        elif self.atp >= 70.0 and self.degradation_active:
            self.degradation_active = False
            for n in neurons.values(): n.v_th_mant /= 1.5
    def get_status(self) -> str:
        if self.atp < 20: return f"🔴 CRITICAL ({self.atp:.1f}/{self.max_atp})"
        elif self.atp < 50: return f"🟡 LOW ({self.atp:.1f}/{self.max_atp})"
        return f"🟢 GOOD ({self.atp:.1f}/{self.max_atp})"
class TextToSpikeEncoder:
    def __init__(self, char_tokenizer):
        self.tokenizer = char_tokenizer; max_id = max(char_tokenizer.vocab_size, 1)
        self.intensity = {idx: 0.7 + 0.5 * (1.0 - idx / max_id) for idx in range(char_tokenizer.vocab_size)}
    def encode(self, text: str, neurons: Dict[int, MultiCompartmentNeuron], input_layer_neurons: List[int]):
        if not text or not input_layer_neurons: return
        token_ids = self.tokenizer.encode(text)
        if not token_ids: return
        n = len(input_layer_neurons)
        for i, tid in enumerate(token_ids[:n]):
            nid = input_layer_neurons[i % n]
            if nid in neurons: neurons[nid].inject_current(self.intensity.get(tid, 0.8))
        energy = min(1.0, len(token_ids) / 16.0)
        for nid in input_layer_neurons:
            if nid in neurons: neurons[nid].inject_current(energy * 0.12)
class DANeuromodulator:
    def __init__(self, baseline: float = None, alpha: float = None):
        self.da_level = baseline if baseline else Config.DA_BASELINE; self.baseline = baseline if baseline else Config.DA_BASELINE
        self.alpha = alpha if alpha else Config.DA_ALPHA; self.da_history: List[float] = []; self.peak_da = self.baseline
        self.learning_events = 0; self.rpe_history: List[float] = []
    def score_response(self, response: str, prompt: str) -> float:
        if not response or len(response.strip()) < 3: return 0.0
        score = 0.35; r = response.strip()
        if 10 <= len(r) <= 500: score += 0.25
        elif len(r) > 4: score += 0.10
        if not any(e in r.lower() for e in ['error', 'failed', 'exception', 'traceback', 'none', 'refused']): score += 0.20
        p_words, r_words = set(prompt.lower().split()), set(r.lower().split())
        if p_words: score += min(0.20, len(p_words & r_words) / len(p_words) * 0.6)
        return min(1.0, max(0.0, score))
    def update(self, quality: float) -> float:
        rpe = quality - self.da_level; self.rpe_history.append(rpe)
        self.da_level = (1.0 - self.alpha) * self.da_level + self.alpha * quality
        self.da_history.append(round(self.da_level, 4)); self.learning_events += 1
        if quality > self.peak_da: self.peak_da = quality
        return self.da_level
    def get_valence(self) -> float: return (self.da_level - self.baseline) * 2.0
    def get_growth_signal(self) -> float:
        if len(self.da_history) < 2: return 0.0
        return max(self.da_history[-5:]) - self.baseline
    def status_str(self) -> str:
        trend = "→"
        if len(self.da_history) >= 2:
            d = self.da_history[-1] - self.da_history[-2]
            trend = "↑" if d > 0.01 else ("↓" if d < -0.01 else "→")
        return f"DA={self.da_level:.3f}{trend} valence={self.get_valence():+.2f} peak={self.peak_da:.2f}"
    def to_dict(self) -> dict: return {'da_level': self.da_level, 'da_history': self.da_history[-50:], 'peak_da': self.peak_da}
    def from_dict(self, d: dict):
        self.da_level = d.get('da_level', self.baseline); self.da_history = d.get('da_history', []); self.peak_da = d.get('peak_da', self.baseline)
class Loihi2Emulator:
    def __init__(self):
        self.compartments: list = []; self.connections: list = []; self.neurons: Dict[int, MultiCompartmentNeuron] = {}
        self.synapses: Dict[int, TripartiteSynapse] = {}; self.pre_syn_map: Dict[int, List[int]] = {}
        self.post_syn_map: Dict[int, List[int]] = {}; self.metabolic_manager = MetabolicManager()
        self.plasticity_engine = StructuralPlasticityEngine(); self.current_time_s = 0.0; self.next_syn_id = 0
        self.global_workspace_activation = 0.0; self.layer_spike_counts: Dict[int, int] = {}
        self.layer_neuron_counts: Dict[int, int] = {}; self.total_neurons_born = 0; self.total_neurons_pruned = 0
        self.layer_rate_counts: Dict[int, int] = {}; self.rate_window_spikes = 0; self.rate_window_size = 2000
    def create_compartment(self, layer_id: int = -1, **kwargs) -> dict:
        nid = len(self.compartments); neuron = MultiCompartmentNeuron(nid, bias=kwargs.get('bias', 0.001))
        if 'vThMant' in kwargs: neuron.v_th_mant = kwargs['vThMant'] / 2048.0
        self.neurons[nid] = neuron; comp = {'id': nid, 'layer_id': layer_id, 'config': kwargs, 'spikes': [], 'voltage': 0.0}
        self.compartments.append(comp); self.layer_neuron_counts[layer_id] = self.layer_neuron_counts.get(layer_id, 0) + 1; return comp
    def create_connection(self, pre: dict, post: dict, weight: float = 1.0, delay_s: float = 0.001) -> int:
        sid = self.next_syn_id; syn = TripartiteSynapse(sid, pre['id'], post['id']); syn.weight = weight
        self.synapses[sid] = syn; self.connections.append({'pre': pre['id'], 'post': post['id'], 'weight': weight, 'delay_s': delay_s})
        self.pre_syn_map.setdefault(pre['id'], []).append(sid); self.post_syn_map.setdefault(post['id'], []).append(sid); self.next_syn_id += 1; return sid
    def _rebuild_maps(self):
        self.pre_syn_map.clear(); self.post_syn_map.clear()
        for sid, syn in self.synapses.items():
            self.pre_syn_map.setdefault(syn.pre_id, []).append(sid); self.post_syn_map.setdefault(syn.post_id, []).append(sid)
    def birth_neuron(self, layer_id: int) -> int:
        nid = len(self.compartments); self.neurons[nid] = MultiCompartmentNeuron(nid, bias=0.001)
        self.compartments.append({'id': nid, 'layer_id': layer_id, 'config': {}, 'spikes': [], 'voltage': 0.0})
        self.layer_neuron_counts[layer_id] = self.layer_neuron_counts.get(layer_id, 0) + 1; self.total_neurons_born += 1
        log_neurogenesis('birth', {'neuron_id': nid, 'layer_id': layer_id, 'total': len(self.neurons)}); return nid
    def prune_neuron(self, neuron_id: int) -> bool:
        if neuron_id not in self.neurons or self.neurons[neuron_id].get_activity_score() > 0.3: return False
        layer_id = self.compartments[neuron_id]['layer_id']
        for sid in [sid for sid, syn in self.synapses.items() if syn.pre_id == neuron_id or syn.post_id == neuron_id]: del self.synapses[sid]
        del self.neurons[neuron_id]; self.layer_neuron_counts[layer_id] = max(0, self.layer_neuron_counts.get(layer_id, 0) - 1); self.total_neurons_pruned += 1
        log_neurogenesis('death', {'neuron_id': neuron_id, 'layer_id': layer_id, 'total': len(self.neurons)}); return True
    def apply_global_reward(self, reward: float):
        for syn in self.synapses.values(): syn.apply_reward(reward)
    def inject_vision_spikes(self, latent_vector, layer_id=68, registry=None):
        reg = registry if registry is not None else getattr(self, 'neuron_registry', None)
        if not reg or layer_id not in reg: return
        neurons = reg[layer_id]; latent_np = latent_vector.detach().cpu().numpy()
        for i, neuron_id in enumerate(neurons[:len(latent_np)]):
            if neuron_id in self.neurons: self.neurons[neuron_id].inject_current(float(latent_np[i]) * 2.0)
    def inject_audio_spikes(self, latent_vector, layer_id=71, registry=None):
        reg = registry if registry is not None else getattr(self, 'neuron_registry', None)
        if not reg or layer_id not in reg: return
        neurons = reg[layer_id]; latent_np = latent_vector.detach().cpu().numpy()
        for i, neuron_id in enumerate(neurons[:len(latent_np)]):
            if neuron_id in self.neurons: self.neurons[neuron_id].inject_current(float(latent_np[i]) * 2.0)
    def inject_tool_spikes(self, tool_result, layer_id=72, registry=None):
        reg = registry if registry is not None else getattr(self, 'neuron_registry', None)
        if not reg or layer_id not in reg: return
        neurons = reg[layer_id]
        for i, neuron_id in enumerate(neurons[:min(8, len(neurons))]):
            if neuron_id in self.neurons and i < len(tool_result): self.neurons[neuron_id].inject_current(ord(tool_result[i]) / 128.0)
    def step_simulation(self, duration_s: float, da_level: float = 0.5, verbose: bool = False):
        valence = (da_level - 0.5) * 2.0; n_steps = int(duration_s * 1000)
        neurons = self.neurons; synapses = self.synapses
        pre_map = self.pre_syn_map; post_map = self.post_syn_map
        compartments = self.compartments; mm = self.metabolic_manager
        spike_cost = mm.spike_cost; consume = mm.consume; recharge = mm.recharge
        rate_counts = self.layer_rate_counts
        for step_i in range(n_steps):
            self.current_time_s += 0.001
            t = self.current_time_s
            if step_i % 4 == 0:
                for syn in synapses.values(): syn.decay(0.41)
                self.global_workspace_activation = 0.0
            fired_neurons: List[int] = []
            for nid, neuron in neurons.items():
                if not neuron.is_active: continue
                if neuron.step(t):
                    fired_neurons.append(nid)
                    compartments[nid]['spikes'].append(t)
                    consume(spike_cost)
                    self.global_workspace_activation += 0.1
                    lid = compartments[nid]['layer_id']
                    self.layer_spike_counts[lid] = self.layer_spike_counts.get(lid, 0) + 1
                    rate_counts[lid] = rate_counts.get(lid, 0) + 1
                    self.rate_window_spikes += 1
            for nid in fired_neurons:
                if nid not in neurons: continue
                if nid in pre_map:
                    for sid in pre_map[nid]:
                        if sid in synapses:
                            syn = synapses[sid]; syn.pre_spike(t)
                            post_id = syn.post_id
                            if post_id in neurons: neurons[post_id].receive_spike(0, syn.weight, t)
                if nid in post_map:
                    for sid in post_map[nid]:
                        if sid in synapses: synapses[sid].post_spike(t, valence)
            mm.check_and_throttle(neurons)
            recharge(0.005)
            if self.rate_window_spikes >= self.rate_window_size:
                for lid in list(rate_counts): rate_counts[lid] = rate_counts[lid] // 2
                self.rate_window_spikes //= 2
            if int(self.current_time_s) % 50 == 0 and self.current_time_s % 1.0 < 0.002:
                self.next_syn_id = self.plasticity_engine.evaluate_and_rewire(neurons, synapses, self.next_syn_id)
                self._rebuild_maps()
    def get_active_layers(self, top_n: int = 5) -> List[Tuple[int, int]]:
        return sorted(self.layer_spike_counts.items(), key=lambda x: x[1], reverse=True)[:top_n]
    def get_layer_rates_tensor(self) -> torch.Tensor:
        counts = self.layer_rate_counts
        max_c = max(counts.values()) if counts else 1
        if max_c <= 0: max_c = 1
        vec = torch.zeros(Config.LOIHI_NUM_LAYERS, dtype=torch.float32)
        for lid, c in counts.items():
            if 0 <= lid < Config.LOIHI_NUM_LAYERS: vec[lid] = c / max_c
        return vec
    def get_neurogenesis_stats(self) -> dict:
        return {'total_neurons': len(self.neurons), 'total_synapses': len(self.synapses), 'neurons_born': self.total_neurons_born,
                'neurons_pruned': self.total_neurons_pruned, 'net_growth': self.total_neurons_born - self.total_neurons_pruned, 'layers': len(set(c['layer_id'] for c in self.compartments))}
class HybridSNNBrain:
    def __init__(self, architecture: Dict[int, str]):
        self.architecture = architecture; self.loihi_emulator = Loihi2Emulator(); self.neuron_registry: Dict[int, List[int]] = {}
        self.input_layer_neurons: List[int] = []; self.output_layer_neurons: List[int] = []
        self.developmental_stage = DevelopmentalStage.EMBRYONIC; self.topics_learned = 0
        self.last_neurogenesis_check = 0; self.epic_moments = 0
        self.hippocampus = VectorHippocampus(dim=Config.INITIAL_EMBED_DIM, capacity=2000)
        self.event_queue = AgenticEventQueue()
        self.tool_router = AgenticToolRouter()
        self.actor_critic = None; self.ac_optimizer = None
    def deploy_to_hardware(self):
        for lid in range(300):
            ids = [self.loihi_emulator.create_compartment(layer_id=lid, biasMant=100, vThMant=2048, tauV=20, bias=0.001)['id'] for _ in range(8)]
            self.neuron_registry[lid] = ids
        self.input_layer_neurons = self.neuron_registry[20]; self.output_layer_neurons = self.neuron_registry[97]
        for lid in range(299):
            src, tgt = self.neuron_registry[lid], self.neuron_registry[lid + 1]
            for i in range(8):
                self.loihi_emulator.create_connection({'id': src[i]}, {'id': tgt[i]}, weight=0.5, delay_s=0.001)
                self.loihi_emulator.create_connection({'id': src[i]}, {'id': tgt[(i + 1) % 8]}, weight=0.3, delay_s=0.001)
        for i in range(4):
            self.loihi_emulator.create_connection({'id': self.neuron_registry[20][i]}, {'id': self.neuron_registry[76][i]}, weight=0.4, delay_s=0.005)
            self.loihi_emulator.create_connection({'id': self.neuron_registry[82][i]}, {'id': self.neuron_registry[42][i]}, weight=0.35, delay_s=0.003)
            self.loihi_emulator.create_connection({'id': self.neuron_registry[97][i]}, {'id': self.neuron_registry[42][i]}, weight=0.25, delay_s=0.004)
        print(f"[BRAIN] Deployed: {len(self.loihi_emulator.neurons)} neurons · {len(self.loihi_emulator.synapses)} connections · 300 layers")
    def update_developmental_stage(self):
        if self.topics_learned < 5: self.developmental_stage = DevelopmentalStage.EMBRYONIC
        elif self.topics_learned < 20: self.developmental_stage = DevelopmentalStage.INFANT
        elif self.topics_learned < 50: self.developmental_stage = DevelopmentalStage.CHILD
        elif self.topics_learned < 100: self.developmental_stage = DevelopmentalStage.ADOLESCENT
        elif self.topics_learned < 200: self.developmental_stage = DevelopmentalStage.ADULT
        elif self.topics_learned < 500: self.developmental_stage = DevelopmentalStage.ELDER
        else: self.developmental_stage = DevelopmentalStage.TRANSCENDENT
        print(f"📈 DEVELOPMENTAL STAGE: {self.developmental_stage.value} (topics: {self.topics_learned})")
    def check_neurogenesis(self, student: SpikingTransformerGenerator, da: DANeuromodulator, learning_demand: float):
        current_time = time.time()
        if current_time - self.last_neurogenesis_check < Config.NEUROGENESIS_CHECK_INTERVAL: return
        self.last_neurogenesis_check = current_time; dev_config = DEVELOPMENTAL_STAGES[self.developmental_stage]
        metabolic = self.loihi_emulator.metabolic_manager.atp; student.update_complexity_score(learning_demand, da.da_level)
        student.auto_neurogenesis(learning_demand, da.da_level, metabolic, dev_config)
        if metabolic > dev_config.growth_energy_cost and random.random() < dev_config.neurogenesis_rate:
            active_layers = self.loihi_emulator.get_active_layers(top_n=3)
            if active_layers: self.loihi_emulator.birth_neuron(active_layers[0][0])
        if student.apoptosis_check(dev_config) and student.complexity_score < 0.3: student.prune_neurons(random.randint(0, len(student.layers) - 1), keep_ratio=0.85)
    def get_brain_stats(self) -> dict:
        return {'stage': self.developmental_stage.value, 'topics_learned': self.topics_learned, 'pytorch_neurons': self.loihi_emulator.get_neurogenesis_stats(),
                'emulator_neurons': self.loihi_emulator.get_neurogenesis_stats(), 'metabolic': self.loihi_emulator.metabolic_manager.atp, 'epic_moments': self.epic_moments}
class VisionEncoder(nn.Module):
    def __init__(self, img_size=32, channels=1, latent_dim=64):
        super().__init__()
        self.encoder = nn.Sequential(nn.Conv2d(channels, 16, 3, stride=2, padding=1), nn.BatchNorm2d(16), nn.ReLU(),
                                     nn.Conv2d(16, 32, 3, stride=2, padding=1), nn.BatchNorm2d(32), nn.ReLU(),
                                     nn.Conv2d(32, 64, 3, stride=2, padding=1), nn.BatchNorm2d(64), nn.ReLU(),
                                     nn.Flatten(), nn.Linear(64 * 4 * 4, latent_dim), nn.Tanh())
    def forward(self, x): return self.encoder(x)
class VisionDecoder(nn.Module):
    def __init__(self, latent_dim=64, img_size=32, channels=1):
        super().__init__(); self.fc = nn.Linear(latent_dim, 64 * 4 * 4)
        self.decoder = nn.Sequential(nn.ConvTranspose2d(64, 32, 4, stride=2, padding=1), nn.BatchNorm2d(32), nn.ReLU(),
                                     nn.ConvTranspose2d(32, 16, 4, stride=2, padding=1), nn.BatchNorm2d(16), nn.ReLU(),
                                     nn.ConvTranspose2d(16, channels, 4, stride=2, padding=1), nn.Sigmoid())
    def forward(self, z): x = self.fc(z).view(-1, 64, 4, 4); return self.decoder(x)
class VisionClassifier(nn.Module):
    def __init__(self, latent_dim=64, num_classes=10):
        super().__init__(); self.classifier = nn.Sequential(nn.Linear(latent_dim, 128), nn.ReLU(), nn.Dropout(0.3), nn.Linear(128, num_classes))
    def forward(self, z): return self.classifier(z)
class AudioEncoder(nn.Module):
    def __init__(self, sample_rate=16000, n_mels=64, window_sec=2.0, latent_dim=64):
        super().__init__(); self.window_samples = int(sample_rate * window_sec)
        self.mel_transform = torchaudio.transforms.MelSpectrogram(sample_rate=sample_rate, n_mels=n_mels, n_fft=1024, hop_length=512)
        self.encoder = nn.Sequential(nn.Conv2d(1, 16, (3, 3), stride=(2, 2), padding=(1, 1)), nn.BatchNorm2d(16), nn.ReLU(),
                                     nn.Conv2d(16, 32, (3, 3), stride=(2, 2), padding=(1, 1)), nn.BatchNorm2d(32), nn.ReLU(),
                                     nn.Conv2d(32, 64, (3, 3), stride=(2, 2), padding=(1, 1)), nn.BatchNorm2d(64), nn.ReLU(),
                                     nn.Flatten(), nn.LazyLinear(latent_dim), nn.Tanh())
    def forward(self, waveform):
        if waveform.size(1) < self.window_samples: waveform = F.pad(waveform, (0, self.window_samples - waveform.size(1)))
        else: waveform = waveform[:, :self.window_samples]
        spec = self.mel_transform(waveform).unsqueeze(1); return self.encoder(spec)
class AudioDecoder(nn.Module):
    def __init__(self, latent_dim=64, sample_rate=16000, output_samples=32000):
        super().__init__(); self.output_samples = output_samples; self.fc = nn.Linear(latent_dim, 512 * 8)
        self.decoder = nn.Sequential(nn.ConvTranspose1d(512, 256, 4, stride=2, padding=1), nn.BatchNorm1d(256), nn.ReLU(),
                                     nn.ConvTranspose1d(256, 128, 4, stride=2, padding=1), nn.BatchNorm1d(128), nn.ReLU(),
                                     nn.ConvTranspose1d(128, 64, 4, stride=2, padding=1), nn.BatchNorm1d(64), nn.ReLU(),
                                     nn.ConvTranspose1d(64, 1, 4, stride=2, padding=1), nn.Tanh())
    def forward(self, z): x = self.fc(z).view(-1, 512, 8); return self.decoder(x).squeeze(1)
class AudioClassifier(nn.Module):
    def __init__(self, latent_dim=64, num_classes=10):
        super().__init__(); self.classifier = nn.Sequential(nn.Linear(latent_dim, 128), nn.ReLU(), nn.Dropout(0.3), nn.Linear(128, num_classes))
    def forward(self, z): return self.classifier(z)
class ImageDataset(Dataset):
    def __init__(self, data_dir: str, img_size=32):
        self.img_size = img_size; self.images, self.labels = [], []
        if os.path.isdir(data_dir):
            for class_idx, class_name in enumerate(sorted(os.listdir(data_dir))):
                class_dir = os.path.join(data_dir, class_name)
                if os.path.isdir(class_dir):
                    for img_file in os.listdir(class_dir):
                        if img_file.lower().endswith(('.png', '.jpg', '.jpeg')): self.images.append(os.path.join(class_dir, img_file)); self.labels.append(class_idx)
    def __len__(self): return len(self.images)
    def __getitem__(self, idx):
        img = Image.open(self.images[idx]).convert('L').resize((self.img_size, self.img_size))
        img_tensor = torch.tensor(np.array(img), dtype=torch.float32) / 255.0; return img_tensor.unsqueeze(0), self.labels[idx]
class AudioDataset(Dataset):
    def __init__(self, data_dir: str, sample_rate=16000, window_sec=2.0):
        self.sample_rate = sample_rate; self.window_samples = int(sample_rate * window_sec); self.audio_files, self.labels = [], []
        if os.path.isdir(data_dir):
            for class_idx, class_name in enumerate(sorted(os.listdir(data_dir))):
                class_dir = os.path.join(data_dir, class_name)
                if os.path.isdir(class_dir):
                    for audio_file in os.listdir(class_dir):
                        if audio_file.lower().endswith(('.wav', '.mp3', '.flac')): self.audio_files.append(os.path.join(class_dir, audio_file)); self.labels.append(class_idx)
    def __len__(self): return len(self.audio_files)
    def __getitem__(self, idx):
        waveform, sr = torchaudio.load(self.audio_files[idx])
        if sr != self.sample_rate: waveform = torchaudio.functional.resample(waveform, sr, self.sample_rate)
        if waveform.size(0) > 1: waveform = waveform.mean(dim=0, keepdim=True)
        if waveform.size(1) < self.window_samples: waveform = F.pad(waveform, (0, self.window_samples - waveform.size(1)))
        else: waveform = waveform[:, :self.window_samples]
        return waveform.squeeze(0), self.labels[idx]
def train_vision_autoencoder(vision_enc, vision_dec, vision_class, optimizer, dataloader, epochs=20, device=Config.device):
    vision_enc.train(); vision_dec.train(); vision_class.train()
    criterion_recon = nn.MSELoss(); criterion_class = nn.CrossEntropyLoss()
    for epoch in range(epochs):
        total_loss = 0.0
        for img, label in dataloader:
            img, label = img.to(device), label.to(device); z = vision_enc(img); recon = vision_dec(z); logits = vision_class(z)
            loss = criterion_recon(recon, img) + 0.5 * criterion_class(logits, label)
            optimizer.zero_grad(); loss.backward(); optimizer.step(); total_loss += loss.item()
        print(f"👁 Vision Epoch {epoch+1}/{epochs} | Loss: {total_loss/len(dataloader):.4f}")
def train_audio_autoencoder(audio_enc, audio_dec, audio_class, optimizer, dataloader, epochs=20, device=Config.device):
    audio_enc.train(); audio_dec.train(); audio_class.train()
    criterion_recon = nn.L1Loss(); criterion_class = nn.CrossEntropyLoss()
    for epoch in range(epochs):
        total_loss = 0.0
        for wave, label in dataloader:
            wave, label = wave.to(device), label.to(device); z = audio_enc(wave); recon = audio_dec(z); logits = audio_class(z)
            loss = criterion_recon(recon, wave) + 0.5 * criterion_class(logits, label)
            optimizer.zero_grad(); loss.backward(); optimizer.step(); total_loss += loss.item()
        print(f"🎧 Audio Epoch {epoch+1}/{epochs} | Loss: {total_loss/len(dataloader):.4f}")
def load_image(path: str, size=32):
    img = Image.open(path).convert('L').resize((size, size)); return torch.tensor(np.array(img), dtype=torch.float32).unsqueeze(0).unsqueeze(0) / 255.0
def load_audio(path: str, sample_rate=16000):
    waveform, sr = torchaudio.load(path)
    if sr != sample_rate: waveform = torchaudio.functional.resample(waveform, sr, sample_rate)
    if waveform.size(0) > 1: waveform = waveform.mean(dim=0, keepdim=True); return waveform
def save_image(tensor, path: str):
    img_array = (tensor.squeeze().cpu().numpy() * 255).astype(np.uint8); Image.fromarray(img_array, mode='L').save(path)
def save_audio(waveform, path: str, sample_rate=16000): torchaudio.save(path, waveform.unsqueeze(0), sample_rate)
def check_unsloth_connection():
    try: unsloth_client.models.list(); return True
    except Exception: return False
def should_ask_teacher(user_input: str, student_confidence: float, raw_output: str) -> bool:
    if len(user_input.split()) >= MIN_WORDS_FOR_TEACHER: return True
    if student_confidence < CONFIDENCE_THRESHOLD: return True
    if any(marker in raw_output.lower() for marker in GIBBERISH_MARKERS): return True
    return False
# ========================================
# PHASE 1: SmartTokenizer
# ========================================
class SmartTokenizer:
    CHARS = sorted(set("abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789 .,!?-'\"\n-><>/"))
    WORD_PATTERN = re.compile(r"\s+|\w+|[^\w\s]", re.UNICODE)
    def __init__(self, vocab_size: int = None):
        self.pad_token_id = 0
        self.unk_token_id = 1
        self.mode = "word"
        self._char2idx = {c: i for i, c in enumerate(self.CHARS)}
        self._idx2char = {i: c for c, i in self._char2idx.items()}
        self.max_vocab = vocab_size or 4096
        self.word2idx: Dict[str, int] = {}
        self.idx2word: List[str] = ["<pad>", "<unk>"] + self.CHARS
        self.vocab_path = SCRIPT_DIR / "tokenizer_vocab.json"
        self.vocab_size = self.max_vocab
        if self.vocab_path.exists():
            self._load_vocab()
        else:
            self._rebuild_index()
    def _rebuild_index(self):
        self.word2idx = {w: i for i, w in enumerate(self.idx2word)}
        self.vocab_size = self.max_vocab
    def _load_vocab(self):
        try:
            with open(self.vocab_path, 'r', encoding='utf-8') as f:
                d = json.load(f)
            words = d.get('words', [])
            self.idx2word = ["<pad>", "<unk>"] + self.CHARS + words
            self._rebuild_index()
            print(f"[TOKENIZER] Loaded vocab: {len(words)} words (vocab_size={self.vocab_size})")
        except Exception as e:
            logger.warning(f"Tokenizer vocab load failed: {e}"); self._rebuild_index()
    def save_vocab(self):
        try:
            with open(self.vocab_path, 'w', encoding='utf-8') as f:
                json.dump({'words': self.idx2word[2 + len(self.CHARS):]}, f)
        except Exception as e: logger.warning(f"Tokenizer vocab save failed: {e}")
    def train_from_texts(self, texts: List[str], min_count: int = None) -> int:
        if min_count is None: min_count = 2
        counts: Counter = Counter()
        for t in texts:
            for tok in self.WORD_PATTERN.findall(t):
                if tok.isspace(): continue
                counts[tok.lower()] += 1
        budget = self.max_vocab - 2 - len(self.CHARS)
        words = [w for w, c in counts.most_common(budget) if c >= min_count and len(w) > 1]
        self.idx2word = ["<pad>", "<unk>"] + self.CHARS + words
        self._rebuild_index(); self.save_vocab()
        print(f"[TOKENIZER] Trained: {len(words)} words from {len(texts)} texts (vocab_size={self.vocab_size})")
        return len(words)
    def encode(self, text: str) -> List[int]:
        ids: List[int] = []
        for tok in self.WORD_PATTERN.findall(text):
            if tok.isspace():
                for ch in tok:
                    cid = self._char2idx.get(ch)
                    if cid is not None: ids.append(2 + cid)
                continue
            idx = self.word2idx.get(tok)
            if idx is None: idx = self.word2idx.get(tok.lower())
            if idx is not None:
                ids.append(idx)
            else:
                for ch in tok:
                    cid = self._char2idx.get(ch)
                    if cid is not None: ids.append(2 + cid)
        return ids
    def decode(self, ids) -> str:
        if isinstance(ids, (int, np.integer)): ids = [int(ids)]
        out: List[str] = []; base = 2 + len(self.CHARS)
        for i in ids:
            i = int(i)
            if i == self.pad_token_id: continue
            if i == self.unk_token_id: out.append("<unk>"); continue
            if 2 <= i < base:
                out.append(self._idx2char[i - 2])
            elif i < len(self.idx2word):
                w = self.idx2word[i]
                if out and out[-1] and out[-1][-1].isalnum() and w and w[0].isalnum():
                    out.append(" " + w)
                else:
                    out.append(w)
        return "".join(out)
# ========================================
# GENERATION
# ========================================
def generate_student_response_with_confidence(model, tokenizer, prompt, max_len=30,
                                              neuromod=None, route_override=None,
                                              debug: bool = False,
                                              repetition_penalty: float = None,
                                              top_k: int = None):
    if repetition_penalty is None: repetition_penalty = Config.GENERATION_REPETITION_PENALTY
    if top_k is None: top_k = Config.GENERATION_TOP_K
    model.eval()
    input_ids = tokenizer.encode(prompt)
    if not input_ids: return "", 0.0
    required = len(input_ids) + int(max_len) + int(Config.SEQ_LEN_SAFETY_MARGIN)
    if required > model.max_seq_len:
        model.ensure_max_seq_len(required)
        print(f"📚 Long input detected! Context auto-grown to {model.max_seq_len} tokens.")
    max_seq_len = model.max_seq_len
    if len(input_ids) > max_seq_len - max_len - 10:
        input_ids = input_ids[-(max_seq_len - max_len - 10):]
    x = torch.tensor([input_ids], device=Config.device)
    generated, confidences = [], []
    recent_tokens: List[int] = []
    cache = None; cache_len = 0
    last_top5_str = ""
    blocked_ids: Set[int] = set()
    for ch in (' ', '\n', '\r', '\t'):
        cid = tokenizer._char2idx.get(ch)
        if cid is not None:
            blocked_ids.add(2 + cid)
        wid = tokenizer.word2idx.get(ch)
        if wid is not None:
            blocked_ids.add(wid)
    with torch.no_grad():
        for step_i in range(max_len):
            if x.shape[1] >= max_seq_len - 1: break
            if cache is None or not Config.USE_KV_CACHE:
                logits, _, cache = model(x, neuromod=neuromod, route_override=route_override, pos_offset=0)
                cache_len = x.shape[1]
            else:
                if cache_len >= max_seq_len - 1: break
                logits, _, cache = model(x[:, -1:], past_kv=cache, neuromod=neuromod, route_override=route_override, pos_offset=cache_len)
                cache_len += 1
            probs = torch.softmax(logits[0, -1, :] / Config.SAMPLING_TEMPERATURE, dim=0)
            probs[tokenizer.pad_token_id] = 0.0
            if tokenizer.unk_token_id < probs.numel():
                probs[tokenizer.unk_token_id] *= 0.05
            if step_i < Config.GENERATION_FIRST_TOKEN_BLACKLIST_STEPS:
                for bid in blocked_ids:
                    if 0 <= bid < probs.numel():
                        probs[bid] *= 0.001
            for t in recent_tokens[-10:]:
                if 0 <= t < probs.numel():
                    probs[t] /= repetition_penalty
            probs = probs / probs.sum().clamp_min(1e-9)
            conf = torch.max(probs).item()
            confidences.append(conf)
            if conf < 0.05 and step_i > 0:
                break
            k = min(top_k, probs.numel())
            topk_vals, topk_idx = torch.topk(probs, k)
            topk_vals = topk_vals / topk_vals.sum().clamp_min(1e-9)
            pick = torch.multinomial(topk_vals, 1).item()
            next_token = int(topk_idx[pick].item())
            if next_token >= tokenizer.vocab_size:
                break
            char = tokenizer.decode([next_token])
            if char == '\n' and step_i > 0:
                break
            generated.append(next_token)
            recent_tokens.append(next_token)
            x = torch.cat([x, torch.tensor([[next_token]], device=Config.device)], dim=1)
            if debug and step_i == 0:
                top5_v, top5_i = torch.topk(probs, min(5, probs.numel()))
                last_top5_str = "  ".join(
                    f"id={i.item()}({tokenizer.decode([i.item()])!r})={v.item():.3f}"
                    for v, i in zip(top5_v, top5_i)
                )
    output = tokenizer.decode(generated)
    avg_conf = (sum(confidences) / len(confidences)) if confidences else 0.0
    if debug:
        print(f"[GEN-DEBUG] step_count={len(generated)}  "
              f"tokens={generated[:15]}  "
              f"avg_conf={avg_conf:.4f}  "
              f"decoded={output[:60]!r}")
        if last_top5_str:
            print(f"[GEN-DEBUG] top5@step0: {last_top5_str}")
    return output, avg_conf
def generate_student_response_with_reasoning(model, tokenizer, prompt, max_len=100, neuromod=None, route_override=None):
    model.eval(); start_time = time.time(); input_ids = tokenizer.encode(prompt + " -> <thought>")
    if not input_ids: return "", [], 0.0, 0.0
    required = len(input_ids) + int(max_len) + int(Config.SEQ_LEN_SAFETY_MARGIN)
    if required > model.max_seq_len:
        model.ensure_max_seq_len(required)
        print(f"📚 Long input detected! Context auto-grown to {model.max_seq_len} tokens.")
    max_seq_len = model.max_seq_len
    if len(input_ids) > max_seq_len - max_len - 10: input_ids = input_ids[-(max_seq_len - max_len - 10):]
    x = torch.tensor([input_ids], device=Config.device); full_response, thoughts = model.generate_with_cot(x, tokenizer, max_len=max_len, neuromod=neuromod, route_override=route_override)
    confidence, feedback = model.self_reflect(full_response, prompt)
    if Config.REASONING_ENABLED: log_reasoning(prompt, model.reasoning_steps, full_response, confidence, time.time() - start_time)
    return full_response, model.reasoning_steps, confidence, time.time() - start_time
def generate_teacher_response(model_name: str, prompt: str, metabolic_manager: MetabolicManager,
                              da_neuromod: DANeuromodulator, system_instruction: Optional[str] = None) -> Tuple[str, float]:
    if not TEACHER_ONLINE: return "Error: Teacher not online.", da_neuromod.update(0.0)
    metabolic_manager.consume(5.0); time.sleep(Config.TEACHER_API_DELAY)
    if system_instruction is None: system_instruction = "You are the Neocortex (Teacher). Explain simply and clearly."
    for attempt in range(3):
        try:
            response = unsloth_client.chat.completions.create(model=model_name,
                messages=[{"role": "system", "content": system_instruction}, {"role": "user", "content": prompt}], stream=True, timeout=30)
            teacher_reply = "".join(chunk.choices[0].delta.content for chunk in response if chunk.choices and chunk.choices[0].delta.content).strip()
            if not teacher_reply: return "Error: Empty response.", da_neuromod.update(0.0)
            metabolic_manager.consume(len(teacher_reply.split()) * 0.2); time.sleep(Config.TEACHER_RESPONSE_DELAY)
            quality = da_neuromod.score_response(teacher_reply, prompt); return teacher_reply, da_neuromod.update(quality)
        except Exception as e:
            logger.error(f"Unsloth API call failed: {e}")
            if "llama.cpp is updating" in str(e): time.sleep(3)
            else: return f"Error: Teacher connection failed ({e}).", da_neuromod.update(0.0)
    return "Error: Teacher failed.", da_neuromod.update(0.0)
def unsupervised_learning_step(student: nn.Module, tokenizer, input_texts: List[str], optimizer: torch.optim.Optimizer, epoch: int):
    if not Config.UNSUPERVISED_ENABLED: return 0.0
    student.train(); total_loss, latent_representations, samples_processed = 0.0, [], 0
    for text in input_texts[:10]:
        try:
            ids = tokenizer.encode(text)
            if len(ids) < 2: continue
            x = torch.tensor([ids], device=Config.device); logits, _, _ = student(x)
            recon_loss = student.reconstruction_loss_fn(x, logits); curiosity = student.calculate_curiosity_bonus(x); student.train()
            combined_loss = recon_loss * Config.AUTOENCODING_WEIGHT + curiosity * Config.CURIOSITY_DRIVE
            latent_representations.append(student.get_latent_representation(x).detach().cpu())
            optimizer.zero_grad(); combined_loss.backward(); torch.nn.utils.clip_grad_norm_(student.parameters(), 1.0); optimizer.step()
            total_loss += combined_loss.item(); samples_processed += 1
        except Exception as e: logger.warning(f"Unsupervised learning error: {e}")
    if epoch % Config.CLUSTER_UPDATE_INTERVAL == 0 and latent_representations:
        student.update_clusters(torch.stack(latent_representations), n_clusters=Config.NUM_CLUSTERS)
        log_unsupervised('cluster_update', {'num_clusters': len(student.cluster_centers) if student.cluster_centers is not None else 0, 'epoch': epoch})
    return total_loss / max(samples_processed, 1)
def _train_chunk(student, x, y, criterion, optimizer, scaler, n_steps):
    total = 0.0
    for _ in range(n_steps):
        student.zero_grad()
        with _autocast_ctx():
            logits, _, _ = student(x)
            loss = criterion(logits.view(-1, student.vocab_size), y.view(-1))
            aux_t = getattr(student, 'last_aux_loss_tensor', None)
            if aux_t is not None and torch.is_tensor(aux_t):
                loss = loss + 0.01 * torch.clamp(aux_t.to(loss.device), 0.0, 10.0)
        if scaler:
            scaler.scale(loss).backward(); scaler.step(optimizer); scaler.update()
        else:
            loss.backward(); torch.nn.utils.clip_grad_norm_(student.parameters(), 1.0); optimizer.step()
        total += loss.item()
    return total / n_steps
def online_distillation_step(student: nn.Module, tokenizer, prompt: str, response: str, da_level: float,
                             optimizer: torch.optim.Optimizer, n_steps: int = 10, emulator=None) -> float:
    full_text = f"{prompt[:50]} -> {response}\n"; ids = tokenizer.encode(full_text)
    max_len = getattr(student, 'max_seq_len', 512); overlap = getattr(Config, 'CHUNK_OVERLAP', 128); chunk_size = max_len + 1
    criterion = nn.CrossEntropyLoss(ignore_index=tokenizer.pad_token_id)
    scaler = _make_scaler()
    for pg in optimizer.param_groups: pg['lr'] = Config.DEFAULT_LEARNING_RATE * max(0.3, da_level * 2.0)
    student.train()
    if len(ids) <= chunk_size:
        if len(ids) > max_len + 1: ids = ids[:max_len + 1]
        if len(ids) < 2: return 0.0
        x = torch.tensor([ids[:-1]], device=Config.device); y = torch.tensor([ids[1:]], device=Config.device)
        avg_loss = _train_chunk(student, x, y, criterion, optimizer, scaler, n_steps)
    else:
        total_loss = 0.0; count = 0
        for start in range(0, len(ids) - 1, chunk_size - overlap):
            chunk_ids = ids[start:start + chunk_size]
            if len(chunk_ids) < 2: continue
            x = torch.tensor([chunk_ids[:-1]], device=Config.device); y = torch.tensor([chunk_ids[1:]], device=Config.device)
            total_loss += _train_chunk(student, x, y, criterion, optimizer, scaler, n_steps); count += 1
        avg_loss = total_loss / max(count, 1)
    student.eval(); student.update_complexity_score(avg_loss, da_level)
    if emulator is not None:
        surprise = max(-0.5, min(0.5, (1.0 - min(avg_loss, 2.0) / 2.0) * 0.2))
        emulator.apply_global_reward(surprise)
    log_loss("distill", prompt, avg_loss); return avg_loss
def rl_feedback_step(student: nn.Module, reward: float, optimizer: torch.optim.Optimizer):
    if not student.last_log_probs: return 0.0
    total_loss = sum((-lp * reward).item() for lp in student.last_log_probs); avg_loss = total_loss / len(student.last_log_probs)
    log_rl("policy_estimate", "step", reward, f"avg_loss={avg_loss:.4f}"); return avg_loss
class HippocampalReplayBuffer:
    def __init__(self, max_episodes: int = None, consolidation_every: int = None):
        self.max_episodes = max_episodes if max_episodes else Config.REPLAY_BUFFER_MAX
        self.consolidation_every = consolidation_every if consolidation_every else Config.CONSOLIDATION_EVERY
        self.episodes: List[dict] = []; self.total_stored = 0
    def store(self, prompt: str, response: str, da_level: float, turn: int, reward: float = 0.0, thoughts: str = ""):
        self.episodes.append({'prompt': prompt, 'response': response, 'da_level': round(da_level, 4),
                              'turn': turn, 'ts': time.time(), 'reward': reward, 'thoughts': thoughts})
        self.total_stored += 1
        if len(self.episodes) > self.max_episodes: self.episodes.pop(0)
    def should_consolidate(self, turn: int) -> bool: return turn > 0 and turn % self.consolidation_every == 0 and len(self.episodes) >= 5
    def sample(self, n: int = 20) -> List[dict]:
        if not self.episodes: return []
        pool = sorted(self.episodes, key=lambda e: e['da_level'], reverse=True)[:max(n, len(self.episodes) // 2)]
        return random.sample(pool, min(n, len(pool)))
    def save(self, path: Path):
        try:
            with open(path, 'w', encoding='utf-8') as f: json.dump({'episodes': self.episodes[-50:], 'total_stored': self.total_stored}, f, indent=2)
        except Exception as e: logger.warning(f"Replay buffer save failed: {e}")
    def load(self, path: Path):
        try:
            if path.exists():
                with open(path, 'r', encoding='utf-8') as f: d = json.load(f)
                self.episodes = d.get('episodes', []); self.total_stored = d.get('total_stored', len(self.episodes))
                print(f"[MEMORY] Loaded {len(self.episodes)} episodes")
        except Exception as e: logger.warning(f"Replay buffer load failed: {e}")
def sleep_consolidation(student: nn.Module, tokenizer, replay_buffer: HippocampalReplayBuffer,
                        optimizer: torch.optim.Optimizer, n_epochs: int = None) -> float:
    if n_epochs is None: n_epochs = Config.SLEEP_CONSOLIDATION_EPOCHS
    episodes = replay_buffer.sample(n=60)
    if not episodes: return 0.0
    print(f"[SLEEP] Consolidating {len(episodes)} episodes...", end=" ", flush=True)
    criterion = nn.CrossEntropyLoss(ignore_index=tokenizer.pad_token_id); student.train(); total, count = 0.0, 0
    max_len = getattr(student, 'max_seq_len', 512); scaler = _make_scaler()
    for _ in range(n_epochs):
        for ep in episodes:
            ids = tokenizer.encode(ep['prompt'][:50] + " -> " + ep['response'][:250] + "\n")
            if len(ids) > max_len + 1: ids = ids[:max_len + 1]
            if len(ids) < 2: continue
            x, y = torch.tensor([ids[:-1]], device=Config.device), torch.tensor([ids[1:]], device=Config.device); student.zero_grad()
            with _autocast_ctx():
                logits, _, _ = student(x)
                loss = criterion(logits.view(-1, tokenizer.vocab_size), y.view(-1)) * max(0.1, ep.get('reward', 0.5))
            if scaler:
                scaler.scale(loss).backward(); scaler.step(optimizer); scaler.update()
            else:
                loss.backward(); torch.nn.utils.clip_grad_norm_(student.parameters(), 1.0); optimizer.step()
            total += loss.item(); count += 1
    student.eval(); avg = total / max(count, 1); print(f"avg loss={avg:.4f}"); log_loss("consolidation", f"{count} examples", avg); return avg
def save_brain(brain, student, da: DANeuromodulator, replay: HippocampalReplayBuffer,
               enhanced_teacher: Optional[EnhancedTeacher] = None, version_tag: str = "",
               vision_enc=None, vision_dec=None, audio_enc=None, audio_dec=None):
    active_path = ACTIVE_BRAIN_FILE
    try: save_file(student.state_dict(), active_path); print(f"💾 Active brain saved: {active_path.name}")
    except Exception as e: print(f"[WARNING] Active brain save failed: {e}"); return
    if vision_enc:
        try:
            torch.save(vision_enc.state_dict(), SCRIPT_DIR / "vision_encoder.pt"); torch.save(vision_dec.state_dict(), SCRIPT_DIR / "vision_decoder.pt")
            torch.save(audio_enc.state_dict(), SCRIPT_DIR / "audio_encoder.pt"); torch.save(audio_dec.state_dict(), SCRIPT_DIR / "audio_decoder.pt")
            print("💾 Multimodal models saved")
        except Exception as e:
            logger.warning(f"Multimodal save failed: {e}")
    if getattr(brain, "actor_critic", None) is not None:
        try:
            torch.save({'state_dict': brain.actor_critic.state_dict(), 'state_dim': brain.actor_critic._state_dim,
                        'action_dim': Config.MOE_NUM_EXPERTS}, AC_FILE)
        except Exception as e: logger.warning(f"Actor-Critic save failed: {e}")
    if version_tag:
        backup_path = SCRIPT_DIR / f"snn_brain_backup_v{version_tag}.safetensors"
        try: save_file(student.state_dict(), backup_path); print(f"📦 Backup created: {backup_path.name}")
        except Exception as e: print(f"[WARNING] Backup save failed: {e}")
    try:
        with open(METADATA_FILE, 'w') as f:
            json.dump({
                'atp': brain.loihi_emulator.metabolic_manager.atp, 'da': da.to_dict(), 'sim_time_s': brain.loihi_emulator.current_time_s,
                'last_saved_version': version_tag if version_tag else "active", 'developmental_stage': brain.developmental_stage.value,
                'topics_learned': brain.topics_learned, 'epic_moments': brain.epic_moments, 'neurogenesis': student.get_neurogenesis_stats(),
                'architecture': student.get_architecture_stats(), 'brain_stats': brain.get_brain_stats(), 'unsupervised': student.get_unsupervised_stats(),
                'reasoning': student.get_reasoning_stats(), 'teaching_summary': enhanced_teacher.generate_learning_summary() if enhanced_teacher else {},
                'q_table': enhanced_teacher.get_q_table() if enhanced_teacher else {}, 'active_brain_file': Config.ACTIVE_BRAIN_FILE,
                'tokenizer': {'vocab_size': student.vocab_size, 'family': 'SmartTokenizer'},
                'student_arch': {'embed_dim': student.embed_dim, 'num_heads': student.num_heads, 'num_layers': len(student.layers),
                                 'ff_dims': [layer.ff.ff_dim for layer in student.layers], 'max_seq_len': student.max_seq_len, 'vocab_size': student.vocab_size, 'time_steps': student.time_steps}
            }, f, indent=2)
    except Exception as e:
        logger.warning(f"Metadata save failed: {e}")
    replay.save(REPLAY_FILE); print(f"[SAVED] Active Brain + Metadata | ATP={brain.loihi_emulator.metabolic_manager.atp:.1f}")
    try:
        brain.hippocampus._save()
    except Exception as e:
        logger.warning(f"Hippocampus save failed: {e}")
def recover_atp(brain, amount: float = 50.0):
    brain.loihi_emulator.metabolic_manager.recharge(amount); print(f"⚡ ATP RECOVERED: +{amount}"); print(f"   Current ATP: {brain.loihi_emulator.metabolic_manager.get_status()}")
def full_recover_atp(brain):
    brain.loihi_emulator.metabolic_manager.atp = brain.loihi_emulator.metabolic_manager.max_atp
    print("FULL ATP RECOVERY"); print(f"   Current ATP: {brain.loihi_emulator.metabolic_manager.get_status()}")
def warmup_training(student: nn.Module, tokenizer, optimizer: torch.optim.Optimizer, n_epochs: int = None):
    if n_epochs is None: n_epochs = Config.WARMUP_EPOCHS
    print("--- WARM-UP TRAINING (Basic Patterns) ---")
    basic_patterns = [{"prompt": "A", "response": "A is the first letter"}, {"prompt": "B", "response": "B is the second letter"},
                      {"prompt": "C", "response": "C is the third letter"}, {"prompt": "hello", "response": "Hello! I am learning."},
                      {"prompt": "what is your name", "response": "My name is Max"}, {"prompt": "hi", "response": "Hi! How can I help?"},
                      {"prompt": "1", "response": "One"}, {"prompt": "2", "response": "Two"}, {"prompt": "3", "response": "Three"}]
    criterion = nn.CrossEntropyLoss(ignore_index=tokenizer.pad_token_id); student.train(); max_len = getattr(student, 'max_seq_len', 512)
    scaler = _make_scaler()
    for epoch in range(n_epochs):
        total_loss = 0.0
        for pattern in basic_patterns:
            text = pattern["prompt"] + " -> " + pattern["response"] + "\n"; ids = tokenizer.encode(text)
            if len(ids) > max_len + 1: ids = ids[:max_len + 1]
            if len(ids) < 2: continue
            x = torch.tensor([ids[:-1]], device=Config.device); y = torch.tensor([ids[1:]], device=Config.device)
            total_loss += _train_chunk(student, x, y, criterion, optimizer, scaler, 1)
        if (epoch + 1) % 20 == 0: print(f"  Warm-up Epoch {epoch + 1}/{n_epochs}  loss={total_loss / len(basic_patterns):.3f}")
    student.eval(); print("--- WARM-UP COMPLETE ---")
def parse_dataset(filepath: str) -> Tuple[List[Tuple[str, str]], List[str]]:
    pairs = []; raw_texts = []
    if not os.path.exists(filepath): return pairs, raw_texts
    ext = os.path.splitext(filepath)[1].lower()
    if ext in ['.pdf', '.docx', '.doc', '.md', '.rtf', '.epub']:
        print(f"📄 Detected document format ({ext}). Extracting text to memory...")
        extracted_text = extract_text_from_document(filepath)
        if extracted_text:
            chunks = [c.strip() for c in extracted_text.split('\n') if len(c.strip()) > 50]
            raw_texts.extend(chunks)
            print(f"✅ Successfully extracted {len(chunks)} learnable paragraphs from {ext.upper()} file.")
        else:
            print(f"[WARNING] No text could be extracted from {filepath}.")
        return pairs, raw_texts
    def normalize_role(role: str) -> str:
        role = role.lower().strip()
        if role in ['human', 'user', 'prompt', 'question', 'instruction']: return 'user'
        elif role in ['gpt', 'assistant', 'model', 'response', 'answer', 'output']: return 'assistant'
        elif role in ['system']: return 'system'
        return role
    def extract_pairs_from_messages(messages: list, system_prefix: str = ""):
        prompt = system_prefix
        for msg in messages:
            if not isinstance(msg, dict): continue
            role = normalize_role(msg.get("role", msg.get("from", "")))
            content = msg.get("content", msg.get("value", msg.get("text", "")))
            if not content: continue
            if role == 'system': prompt = f"System: {content}\n"
            elif role == 'user': prompt += content
            elif role == 'assistant' and prompt:
                pairs.append((prompt.strip(), content.strip()))
                prompt = ""
    def process_dict(item: dict):
        if "messages" in item and isinstance(item["messages"], list): extract_pairs_from_messages(item["messages"])
        elif "conversations" in item and isinstance(item["conversations"], list): extract_pairs_from_messages(item["conversations"])
        elif "instruction" in item or "input" in item or "output" in item or "answer" in item:
            p = f"{item.get('instruction', '')}\n{item.get('input', '')}".strip()
            r = item.get("output") or item.get("answer") or item.get("response") or ""
            if p and r: pairs.append((p, r))
        elif "prompt" in item or "question" in item:
            p = item.get("prompt") or item.get("question") or ""
            r = item.get("response") or item.get("answer") or item.get("output") or ""
            if p and r: pairs.append((p, r))
        elif "text" in item and item.get("text"): raw_texts.append(item["text"])
        else:
            keys = list(item.keys())
            if len(keys) >= 2:
                user_key = next((k for k in keys if k.lower() in ['prompt', 'question', 'instruction', 'input', 'human', 'user']), None)
                asst_key = next((k for k in keys if k.lower() in ['response', 'answer', 'output', 'gpt', 'assistant']), None)
                if user_key and asst_key and item.get(user_key) and item.get(asst_key):
                    pairs.append((str(item[user_key]).strip(), str(item[asst_key]).strip()))
                elif item.get(keys[0]) and item.get(keys[1]):
                    pairs.append((str(item[keys[0]]).strip(), str(item[keys[1]]).strip()))
    data_list = []
    try:
        if ext == '.csv':
            with open(filepath, 'r', encoding='utf-8') as f:
                reader = csv.DictReader(f)
                for row in reader:
                    cleaned_row = {k.strip(): v for k, v in row.items() if k is not None}
                    if 'messages' in cleaned_row and isinstance(cleaned_row['messages'], str):
                        try: cleaned_row['messages'] = json.loads(cleaned_row['messages'])
                        except: pass
                    data_list.append(cleaned_row)
        elif ext in ['.jsonl', '.ndjson']:
            with open(filepath, 'r', encoding='utf-8') as f:
                for line in f:
                    line = line.strip()
                    if line:
                        try: data_list.append(json.loads(line))
                        except: pass
        elif ext == '.json':
            with open(filepath, 'r', encoding='utf-8') as f:
                loaded = json.load(f)
                if isinstance(loaded, list): data_list = loaded
                elif isinstance(loaded, dict):
                    if 'data' in loaded and isinstance(loaded['data'], list): data_list = loaded['data']
                    elif 'examples' in loaded and isinstance(loaded['examples'], list): data_list = loaded['examples']
                    elif 'conversations' in loaded and isinstance(loaded['conversations'], list): data_list = loaded['conversations']
                    else: data_list = [loaded]
        elif ext == '.txt':
            with open(filepath, 'r', encoding='utf-8') as f:
                text = f.read()
                chunks = [c.strip() for c in text.split('\n') if len(c.strip()) > 50]
                raw_texts.extend(chunks)
            return pairs, raw_texts
        else:
            print(f"[WARNING] Unsupported file extension: {ext}. Trying JSON...")
            with open(filepath, 'r', encoding='utf-8') as f: data_list = [json.load(f)]
    except Exception as e:
        print(f"[ERROR] Failed to read {filepath}: {e}")
        return pairs, raw_texts
    if len(data_list) > 0 and isinstance(data_list[0], dict) and ("role" in data_list[0] or "from" in data_list[0]):
        extract_pairs_from_messages(data_list)
    else:
        for item in data_list:
            if isinstance(item, list): extract_pairs_from_messages(item)
            elif isinstance(item, dict): process_dict(item)
    return pairs, raw_texts
class JSONLDataset(Dataset):
    def __init__(self, filepath: str, tokenizer, max_len: int):
        self.data = []; self.tokenizer = tokenizer; self.max_len = max_len
        if not os.path.exists(filepath): return
        pairs, raw_texts = parse_dataset(filepath)
        for p, r in pairs: self._add_pair(p, r)
        for text in raw_texts:
            ids = self.tokenizer.encode(text)
            if 2 <= len(ids) <= self.max_len + 1: self.data.append(ids)
            elif len(ids) > self.max_len + 1:
                overlap = getattr(Config, 'CHUNK_OVERLAP', 128); step = max_len - overlap
                if step <= 0: step = max_len
                for start in range(0, len(ids) - max_len + 1, step):
                    chunk = ids[start:start + max_len]
                    if len(chunk) == max_len: self.data.append(chunk)
        print(f"[DATASET] Successfully loaded {len(self.data)} training examples from {filepath} (chunked).")
    def _add_pair(self, prompt: str, response: str):
        full_text = f"{prompt} -> {response}\n"; ids = self.tokenizer.encode(full_text)
        seq_len = len(ids); max_len = self.max_len + 1
        if seq_len <= max_len:
            if 2 <= seq_len: self.data.append(ids)
            return
        overlap = getattr(Config, 'CHUNK_OVERLAP', 128); step = max_len - overlap
        if step <= 0: step = max_len
        for start in range(0, seq_len - max_len + 1, step):
            chunk = ids[start:start + max_len]
            if len(chunk) == max_len: self.data.append(chunk)
        final_chunk = ids[-max_len:]
        if len(final_chunk) >= 2 and final_chunk not in self.data[-10:]: self.data.append(final_chunk)
    def __len__(self): return len(self.data)
    def __getitem__(self, idx):
        ids = self.data[idx]; return torch.tensor(ids[:-1], dtype=torch.long), torch.tensor(ids[1:], dtype=torch.long)
def collate_batch(batch, pad_token_id=0):
    xs, ys = zip(*batch); return pad_sequence(xs, batch_first=True, padding_value=pad_token_id), pad_sequence(ys, batch_first=True, padding_value=pad_token_id)
def auto_chat_learn(brain, student, tokenizer, da: DANeuromodulator, replay: HippocampalReplayBuffer,
                    optimizer: torch.optim.Optimizer, filepath: str = None, max_samples: int = None):
    if filepath is None: filepath = str(TRAINING_FILE)
    if not os.path.exists(filepath): print(f"[ERROR] File {filepath} not found for auto-chat learning."); return
    print("\n" + "=" * 70 + "\nAUTO-CHAT LEARNING & EVALUATION MODE (UNIVERSAL PARSER)\n" + "=" * 70)
    print(f"Loading dataset from: {filepath}")
    pairs, _ = parse_dataset(filepath)
    print(f"Extracted {len(pairs)} prompt-response pairs for evaluation.")
    if not pairs: print("[WARNING] No valid pairs found."); return
    total_to_evaluate = len(pairs) if max_samples is None else min(max_samples, len(pairs))
    print(f"Processing {total_to_evaluate} samples (Auto-saving every 100 samples)...")
    student.eval(); correct_count = 0; total_evaluated = 0
    neuromod = brain.loihi_emulator.get_layer_rates_tensor()
    for i, (prompt, expected_response) in enumerate(pairs[:total_to_evaluate]):
        try:
            print(f"\n--- Sample {i + 1}/{total_to_evaluate} ---")
            print(f"PROMPT: {prompt[:100]}{'...' if len(prompt) > 100 else ''}")
            raw_generation, conf = generate_student_response_with_confidence(
                student, tokenizer, prompt + " -> ", max_len=100,
                neuromod=neuromod, debug=True)
            print(f"[STUDENT RAW] {raw_generation!r}  (conf={conf:.3f})")
            display_text = raw_generation if raw_generation.strip() else "I am still learning."
            print(f"STUDENT: {display_text!r}")
            expected_words = set(expected_response.lower().split())
            generated_words = set(raw_generation.lower().split())
            if not raw_generation.strip() or not generated_words:
                score = 0.0
            else:
                overlap = len(expected_words & generated_words) / max(len(expected_words), 1)
                length_ratio = min(1.0, len(raw_generation) / max(10, len(expected_response)))
                if overlap < 0.1:
                    length_ratio = 0.0
                score = 0.7 * overlap + 0.3 * length_ratio
                score = min(1.0, max(0.0, score))
            total_evaluated += 1
            if score >= 0.6:
                correct_count += 1; print(f"CORRECT (Score: {score:.2f})")
                reward = 0.8; da.update(reward)
                replay.store(prompt, raw_generation, da.da_level, turn=i, reward=reward)
                _hippo_store(brain, student, tokenizer, prompt, raw_generation)
            else:
                print(f"INCORRECT (Score: {score:.2f})")
                print(f"EXPECTED: {expected_response[:150]}{'...' if len(expected_response) > 150 else ''}")
                print("Providing feedback and triggering corrective learning step...")
                reward = -0.2; da.update(max(0.1, da.da_level + reward))
                loss = online_distillation_step(student, tokenizer, prompt, expected_response,
                                                da.da_level, optimizer, n_steps=5, emulator=brain.loihi_emulator)
                print(f"Distillation Loss: {loss:.4f}")
                replay.store(prompt, expected_response, da.da_level, turn=i, reward=0.5,
                             thoughts="Corrected by auto-evaluator")
                _hippo_store(brain, student, tokenizer, prompt, expected_response)
                brain.loihi_emulator.step_simulation(0.05, da_level=da.da_level, verbose=False)
            if (i + 1) % 100 == 0:
                print(f"\nAUTO-SAVING BRAIN after {i + 1} samples...")
                save_brain(brain, student, da, replay, version_tag=f"autochat_{i + 1}")
                print("Checkpoint saved. Continuing...")
        except KeyboardInterrupt:
            print("\nAUTO-CHAT PAUSED BY USER (Ctrl+C)")
            print("Saving current progress...")
            save_brain(brain, student, da, replay, version_tag=f"autochat_interrupted_{i+1}")
            return
    print("\n" + "=" * 70 + "\nAUTO-CHAT LEARNING COMPLETE")
    print(f"Total Evaluated: {total_evaluated}")
    if total_evaluated:
        print(f"Correct/Acceptable: {correct_count} ({(correct_count / total_evaluated) * 100:.1f}%)")
        print(f"Final DA Level: {da.da_level:.3f}")
    print("=" * 70 + "\n"); save_brain(brain, student, da, replay, version_tag="auto_chat_learned_final")
def train_jsonl_efficient(brain, student, tokenizer, da: DANeuromodulator, replay: HippocampalReplayBuffer,
                          gru_opt: torch.optim.Optimizer, filepath: str = None, epochs: int = None, learning_rate: float = None):
    if filepath is None: filepath = str(TRAINING_FILE)
    if epochs is None: epochs = Config.TRAIN_EPOCHS
    if learning_rate is None: learning_rate = Config.DEFAULT_LEARNING_RATE
    if not os.path.exists(filepath):
        print(f"\n[Warning] {filepath} not found. Creating sample file.")
        if filepath.endswith('.json'):
            samples = [{"messages": [{"role": "user", "content": "what is your name"}, {"role": "assistant", "content": "I'm Max, your growing brain friend."}]}]
            with open(filepath, 'w', encoding='utf-8') as f: json.dump(samples, f, indent=2)
        else:
            with open(filepath, 'w', encoding='utf-8') as f:
                f.write('{"prompt": "what is your name", "response": "I\'m Max, your growing brain friend."}\n')
                f.write('{"prompt": "say hello", "response": "Hello! I\'m learning every day."}\n')
        print("Sample file created. Run 'train' again."); return
    print("\n" + "=" * 60 + "\nEFFICIENT JSONL TRAINING (GPU OPTIMIZED)\n" + "=" * 60)
    clear_gpu_memory()
    student.to(Config.device)
    max_len = getattr(student, 'max_seq_len', 512)
    dataset = JSONLDataset(filepath, tokenizer, max_len)
    if len(dataset) == 0: print("[ERROR] Dataset is empty. Cannot train."); return
    dataloader = DataLoader(dataset, batch_size=Config.BATCH_SIZE, shuffle=True, collate_fn=collate_batch,
                            num_workers=Config.NUM_WORKERS, prefetch_factor=Config.PREFETCH_FACTOR, pin_memory=True)
    opt = torch.optim.Adam(student.parameters(), lr=learning_rate, weight_decay=Config.WEIGHT_DECAY)
    criterion = nn.CrossEntropyLoss(ignore_index=tokenizer.pad_token_id); student.train()
    scaler = _make_scaler()
    consolidation_interval = max(10, epochs // 5); bio_step_interval = max(5, epochs // 10)
    best_loss = float('inf'); no_improve_count = 0; overfitting_warning_shown = False; avg_loss = 0.0
    print(f"Epochs: Unlimited (auto-stops after {Config.EARLY_STOPPING_PATIENCE} stagnant epochs) | Batch: {Config.BATCH_SIZE} | Accum: {Config.GRADIENT_ACCUMULATION_STEPS}")
    for epoch in range(epochs):
        total_loss, examples_processed = 0.0, 0; opt.zero_grad()
        try:
            for batch_idx, (x_batch, y_batch) in enumerate(dataloader):
                x_batch, y_batch = x_batch.to(Config.device, non_blocking=True), y_batch.to(Config.device, non_blocking=True)
                if x_batch.size(0) == 0: continue
                with _autocast_ctx():
                    logits, _, _ = student(x_batch)
                    loss = criterion(logits.view(-1, tokenizer.vocab_size), y_batch.view(-1)) / Config.GRADIENT_ACCUMULATION_STEPS
                    aux_t = getattr(student, 'last_aux_loss_tensor', None)
                    if aux_t is not None and torch.is_tensor(aux_t):
                        loss = loss + 0.01 * torch.clamp(aux_t.to(loss.device), 0.0, 10.0)
                if scaler:
                    scaler.scale(loss).backward()
                    if (batch_idx + 1) % Config.GRADIENT_ACCUMULATION_STEPS == 0:
                        scaler.step(opt); scaler.update(); opt.zero_grad()
                        clear_gpu_memory()
                else:
                    loss.backward()
                    if (batch_idx + 1) % Config.GRADIENT_ACCUMULATION_STEPS == 0:
                        torch.nn.utils.clip_grad_norm_(student.parameters(), 1.0); opt.step(); opt.zero_grad()
                        clear_gpu_memory()
                total_loss += loss.item() * Config.GRADIENT_ACCUMULATION_STEPS; examples_processed += x_batch.size(0)
        except KeyboardInterrupt:
            print("\nTRAINING PAUSED BY USER (Ctrl+C)"); print("Saving current progress...")
            save_brain(brain, student, da, replay, version_tag=f"interrupted_epoch_{epoch+1}"); student.eval(); return
        except RuntimeError as e:
            if "out of memory" in str(e):
                print("\n[ERROR] CUDA Out of Memory during training. Try reducing BATCH_SIZE further in Config.")
                clear_gpu_memory()
                raise
            else:
                raise
        if examples_processed == 0: continue
        avg_loss = total_loss / examples_processed
        if avg_loss < best_loss: best_loss = avg_loss; no_improve_count = 0
        else: no_improve_count += 1
        if avg_loss < Config.OVERFITTING_THRESHOLD and epoch > 50 and not overfitting_warning_shown:
            print(f"WARNING: Possible overfitting detected! (loss={avg_loss:.4f})"); overfitting_warning_shown = True
        if no_improve_count >= Config.EARLY_STOPPING_PATIENCE:
            print(f"\nEARLY STOPPING: No improvement for {no_improve_count} epochs."); break
        if (epoch + 1) % 10 == 0:
            print(f"  Epoch {epoch + 1}  loss={avg_loss:.4f}  best={best_loss:.4f}  examples={examples_processed}")
            log_loss("train_jsonl", f"epoch {epoch + 1}", avg_loss)
        if (epoch + 1) % 50 == 0 and opt.param_groups[0]['lr'] > 5e-4:
            for pg in opt.param_groups: pg['lr'] *= 0.5
            print(f"  Learning rate decayed to {opt.param_groups[0]['lr']:.6f}")
        if (epoch + 1) % bio_step_interval == 0:
            learning_demand = min(1.0, max(0.0, avg_loss / 3.0)); da.update(max(0.0, 1.0 - learning_demand))
            brain.loihi_emulator.step_simulation(0.05, da_level=da.da_level, verbose=False)
            student.update_complexity_score(avg_loss, da.da_level); brain.check_neurogenesis(student, da, learning_demand)
        if Config.UNSUPERVISED_ENABLED and (epoch + 1) % 10 == 0:
            input_texts = [tokenizer.decode(ids) for ids in dataset.data[:20] if len(ids) > 2]
            unsup_loss = unsupervised_learning_step(student, tokenizer, input_texts, opt, epoch)
            print(f"  Unsupervised Loss: {unsup_loss:.4f}")
        if (epoch + 1) % consolidation_interval == 0:
            print(f"\nConsolidating memories..."); sleep_consolidation(student, tokenizer, replay, opt, n_epochs=2)
            save_brain(brain, student, da, replay, version_tag=f"epoch_{epoch + 1}")
    print("\nFinal sleep consolidation..."); sleep_consolidation(student, tokenizer, replay, opt, n_epochs=3)
    brain.loihi_emulator.step_simulation(0.1, da_level=da.da_level, verbose=False)
    brain.check_neurogenesis(student, da, min(1.0, max(0.0, avg_loss / 3.0)))
    save_brain(brain, student, da, replay, version_tag="jsonl_trained")
    for pg in gru_opt.param_groups: pg['lr'] = opt.param_groups[0]['lr']
    student.eval(); print("\n" + "=" * 60 + "\nJSONL TRAINING COMPLETE!\n" + "=" * 60)
def train_hard(brain, student, tokenizer, da: DANeuromodulator, replay: HippocampalReplayBuffer, filepath: str = None):
    if filepath is None: filepath = str(TRAINING_FILE)
    if not os.path.exists(filepath):
        print(f"[Warning] {filepath} not found. Creating robust sample file...")
        if filepath.endswith('.json'):
            samples = [{"messages": [{"role": "user", "content": "What is your name?"}, {"role": "assistant", "content": "My name is Max, a growing spiking neural network."}]}]
            with open(filepath, 'w', encoding='utf-8') as f: json.dump(samples, f, indent=2)
        else:
            with open(filepath, 'w', encoding='utf-8') as f:
                f.write('{"prompt": "What is your name?", "response": "My name is Max, a growing spiking neural network."}\n')
                f.write('{"prompt": "what is 2 plus 2", "response": "2 plus 2 equals 4."}\n')
        print("Sample file created. Run 'trainhard' again."); return
    print("\n" + "=" * 70 + "\nBATCH TRAINING (HARD MODE - GPU OPTIMIZED)\n" + "=" * 70)
    clear_gpu_memory()
    student.to(Config.device); max_len = getattr(student, 'max_seq_len', 512)
    dataset = JSONLDataset(filepath, tokenizer, max_len)
    if len(dataset) == 0: print("[ERROR] Dataset is empty. Cannot train."); return
    dataloader = DataLoader(dataset, batch_size=Config.BATCH_SIZE, shuffle=True, collate_fn=collate_batch,
                            num_workers=Config.NUM_WORKERS, prefetch_factor=Config.PREFETCH_FACTOR, pin_memory=True)
    print(f" Data: {filepath} ({len(dataset)} samples)")
    print(f"Epochs: Unlimited (auto-stops after {Config.EARLY_STOPPING_PATIENCE} stagnant epochs) | Batch: {Config.BATCH_SIZE} | Mixed Precision: {Config.USE_MIXED_PRECISION}")
    opt = torch.optim.AdamW(student.parameters(), lr=Config.DEFAULT_LEARNING_RATE, weight_decay=Config.WEIGHT_DECAY)
    criterion = nn.CrossEntropyLoss(ignore_index=tokenizer.pad_token_id); student.train()
    scaler = _make_scaler()
    best_loss = float('inf'); no_improve_count = 0; stagnation_boost_triggered = False
    bio_interval = max(5, Config.TRAIN_HARD_EPOCHS // 20); save_interval = max(10, Config.TRAIN_HARD_EPOCHS // 10)
    for epoch in range(Config.TRAIN_HARD_EPOCHS):
        total_loss, examples_processed = 0.0, 0; opt.zero_grad()
        try:
            for batch_idx, (x_batch, y_batch) in enumerate(dataloader):
                x_batch, y_batch = x_batch.to(Config.device, non_blocking=True), y_batch.to(Config.device, non_blocking=True)
                if x_batch.size(0) == 0: continue
                with _autocast_ctx():
                    logits, _, _ = student(x_batch)
                    loss = criterion(logits.view(-1, tokenizer.vocab_size), y_batch.view(-1)) / Config.GRADIENT_ACCUMULATION_STEPS
                    aux_t = getattr(student, 'last_aux_loss_tensor', None)
                    if aux_t is not None and torch.is_tensor(aux_t):
                        loss = loss + 0.01 * torch.clamp(aux_t.to(loss.device), 0.0, 10.0)
                if scaler:
                    scaler.scale(loss).backward()
                    if (batch_idx + 1) % Config.GRADIENT_ACCUMULATION_STEPS == 0: scaler.step(opt); scaler.update(); opt.zero_grad()
                else:
                    loss.backward()
                    if (batch_idx + 1) % Config.GRADIENT_ACCUMULATION_STEPS == 0: torch.nn.utils.clip_grad_norm_(student.parameters(), max_norm=1.0); opt.step(); opt.zero_grad()
                total_loss += loss.item() * Config.GRADIENT_ACCUMULATION_STEPS; examples_processed += x_batch.size(0)
        except KeyboardInterrupt:
            print("\nTRAINING PAUSED BY USER (Ctrl+C)"); print("Saving current progress...")
            save_brain(brain, student, da, replay, version_tag=f"interrupted_epoch_{epoch+1}"); student.eval(); return
        except RuntimeError as e:
            if "out of memory" in str(e):
                print("\n[ERROR] CUDA Out of Memory during training. Try reducing BATCH_SIZE further in Config.")
                clear_gpu_memory()
                raise
            else:
                raise
        if examples_processed == 0: continue
        epoch_avg = total_loss / examples_processed
        if epoch_avg < best_loss - 0.001: best_loss = epoch_avg; no_improve_count = 0; stagnation_boost_triggered = False
        else: no_improve_count += 1
        if no_improve_count >= 5 and not stagnation_boost_triggered:
            current_lr = opt.param_groups[0]['lr']; new_lr = min(current_lr * 2.0, 0.001)
            if new_lr > current_lr:
                for pg in opt.param_groups: pg['lr'] = new_lr
                print(f"STAGNATION DETECTED! Boosting LR: {current_lr:.6f} -> {new_lr:.6f}"); stagnation_boost_triggered = True
        if (epoch + 1) % 10 == 0:
            arch = student.get_architecture_stats()
            print(f"Epoch {epoch + 1:3d} | Loss: {epoch_avg:.4f} (Best: {best_loss:.4f}) | ATP: {brain.loihi_emulator.metabolic_manager.atp:5.1f} | Neurons: {arch['total_neurons']}")
        if (epoch + 1) % bio_interval == 0:
            learning_demand = min(1.0, max(0.0, epoch_avg / 3.0)); da.update(max(0.0, 1.0 - learning_demand))
            brain.loihi_emulator.step_simulation(0.05, da_level=da.da_level, verbose=False)
            student.update_complexity_score(epoch_avg, da.da_level); brain.check_neurogenesis(student, da, learning_demand)
        if (epoch + 1) % save_interval == 0:
            print(f"\nCHECKPOINT {epoch + 1}: Saving & Consolidating...")
            sleep_consolidation(student, tokenizer, replay, opt, n_epochs=2)
            save_brain(brain, student, da, replay, version_tag=f"epoch_{epoch + 1}")
        if no_improve_count >= Config.EARLY_STOPPING_PATIENCE:
            print(f"\nEARLY STOPPING: No improvement for {no_improve_count} epochs."); break
    print("\nTRAINING COMPLETE - FINAL CONSOLIDATION")
    sleep_consolidation(student, tokenizer, replay, opt, n_epochs=3)
    save_brain(brain, student, da, replay, version_tag="hard_train_final"); student.eval()
# ========================================
# SCRAPER AI & URL TRAINING MODULES
# ========================================
class ScraperAI:
    def __init__(self):
        self.headers = {'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/115.0.0.0 Safari/537.36'}
    def extract_learnable_chunks(self, url: str) -> List[str]:
        print(f"🕷️ ScraperAI: Fetching and parsing {url}...")
        try:
            if TRAFILATURA_AVAILABLE:
                downloaded = trafilatura.fetch_url(url)
                if downloaded:
                    text = trafilatura.extract(downloaded, include_comments=False, include_tables=False)
                    if text:
                        chunks = [c.strip() for c in text.split('\n') if 40 < len(c.strip()) < 1500]
                        print(f"✅ ScraperAI (Trafilatura): Extracted {len(chunks)} clean chunks.")
                        return chunks
            response = requests.get(url, headers=self.headers, timeout=15)
            response.raise_for_status()
            soup = BeautifulSoup(response.text, 'html.parser')
            for element in soup(["script", "style", "nav", "footer", "header", "noscript", "iframe", "svg"]):
                element.decompose()
            chunks = []
            for tag in soup.find_all(['h1', 'h2', 'h3', 'p', 'article']):
                text = tag.get_text(separator=' ', strip=True)
                if 40 < len(text) < 1500:
                    text = re.sub(r'\s+', ' ', text)
                    if text not in chunks:
                        chunks.append(text)
            print(f"✅ ScraperAI (BS4 Fallback): Extracted {len(chunks)} chunks.")
            return chunks
        except Exception as e:
            print(f"[ERROR] ScraperAI failed to fetch {url}: {e}")
            return []
def train_from_url_direct(brain, student, tokenizer, da, replay, gru_opt, url: str):
    print(f"🌐 Fetching dataset directly from URL: {url}")
    try:
        headers = {'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64)'}
        response = requests.get(url, headers=headers, timeout=120)
        response.raise_for_status()
        data = response.json()
        record_count = len(data) if isinstance(data, list) else 1
        print(f"✅ Successfully fetched {record_count} records into memory.")
        target_file = SCRIPT_DIR / "web_dataset.json"
        print(f"💾 Saving to local file to avoid Windows Temp folder locks: {target_file}")
        with open(target_file, 'w', encoding='utf-8') as f:
            json.dump(data, f)
        print("🚀 Starting training pipeline...")
        train_jsonl_efficient(brain, student, tokenizer, da, replay, gru_opt, filepath=str(target_file), epochs=Config.TRAIN_EPOCHS, learning_rate=Config.DEFAULT_LEARNING_RATE)
        print(f"💡 Training complete. Dataset safely saved at: {target_file}")
    except requests.exceptions.RequestException as e:
        print(f"[ERROR] Failed to fetch dataset from URL: {e}")
    except json.JSONDecodeError:
        print("[ERROR] The URL did not return valid JSON.")
    except Exception as e:
        print(f"[ERROR] Training failed: {e}")
# ========================================
# OMEGA COGNITIVE PIPELINE (GLOBAL SCOPE FIX)
# ========================================
def run_omega_cognitive_pipeline(brain, student, tokenizer, da, goal_text):
    omega_answer = "This is a placeholder response for the Omega pipeline."
    omega_report = type("OmegaReport", (object,), {"state": type("State", (object,), {"value": "SUCCESS"}), "confidence": 0.95})
    return omega_answer, omega_report
# ========================================
# MAIN LOOP
# ========================================
def main():
    global UNSLOTH_MODEL_NAME, TEACHER_ONLINE
    UNSLOTH_MODEL_NAME = Config.UNSLOTH_MODEL_NAME
    TEACHER_ONLINE = False
    if not Config.UNSLOTH_API_KEY:
        print("[WARNING] UNSLOTH_API_KEY is not set. Teacher will be OFFLINE.")
    else:
        try:
            models = unsloth_client.models.list()
            model_ids = [m.id for m in models.data]
            if not model_ids:
                print("[WARNING] No models are currently loaded or available in Unsloth Studio.")
                print("💡 Please load a model (e.g., 'unsloth/gemma-3-4b-it-GGUF') in your Unsloth dashboard first.")
                TEACHER_ONLINE = False
            else:
                print(f"✅ Found {len(model_ids)} available/loaded model(s):")
                for i, m_id in enumerate(model_ids, 1):
                    print(f"  {i}. {m_id}")
                if UNSLOTH_MODEL_NAME in model_ids:
                    print(f"✅ Desired model '{UNSLOTH_MODEL_NAME}' is already loaded and ready to use!")
                    TEACHER_ONLINE = True
                else:
                    print(f"⚠️ Desired model '{UNSLOTH_MODEL_NAME}' is NOT currently loaded.")
                    print("💡 You can load it in your Unsloth Studio dashboard, OR select one of the available models above.")
                    choice = input("Enter the number of the model to use (or press Enter to skip and go OFFLINE): ").strip()
                    if choice.isdigit() and 1 <= int(choice) <= len(model_ids):
                        UNSLOTH_MODEL_NAME = model_ids[int(choice) - 1]
                        TEACHER_ONLINE = True
                        print(f"✅ Switched to Teacher: {UNSLOTH_MODEL_NAME}")
                    else:
                        print("⚠️ Proceeding OFFLINE. The Teacher will be unavailable until a model is loaded.")
                        TEACHER_ONLINE = False
        except Exception as e:
            print(f"[WARNING] Failed to connect to Unsloth Studio: {e}. Teacher is OFFLINE.")
            TEACHER_ONLINE = False
    brain, student, tok, trained, da, encoder, replay, gru_opt, enhanced_teacher = load_or_create_brain()
    vision_enc = VisionEncoder().to(Config.device); vision_dec = VisionDecoder().to(Config.device); vision_class = VisionClassifier().to(Config.device)
    audio_enc = AudioEncoder().to(Config.device); audio_dec = AudioDecoder().to(Config.device); audio_class = AudioClassifier().to(Config.device)
    if (SCRIPT_DIR / "vision_encoder.pt").exists():
        try:
            vision_enc.load_state_dict(torch.load(SCRIPT_DIR / "vision_encoder.pt", map_location=Config.device, weights_only=True))
            vision_dec.load_state_dict(torch.load(SCRIPT_DIR / "vision_decoder.pt", map_location=Config.device, weights_only=True))
            audio_enc.load_state_dict(torch.load(SCRIPT_DIR / "audio_encoder.pt", map_location=Config.device, weights_only=True))
            audio_dec.load_state_dict(torch.load(SCRIPT_DIR / "audio_decoder.pt", map_location=Config.device, weights_only=True))
        except Exception:
            try:
                vision_enc.load_state_dict(torch.load(SCRIPT_DIR / "vision_encoder.pt", map_location=Config.device, weights_only=False))
                vision_dec.load_state_dict(torch.load(SCRIPT_DIR / "vision_decoder.pt", map_location=Config.device, weights_only=False))
                audio_enc.load_state_dict(torch.load(SCRIPT_DIR / "audio_encoder.pt", map_location=Config.device, weights_only=False))
                audio_dec.load_state_dict(torch.load(SCRIPT_DIR / "audio_decoder.pt", map_location=Config.device, weights_only=False))
            except Exception as e:
                logger.warning(f"Multimodal load failed: {e}")
    print("[SYSTEM] Multimodal models loaded")
    print("=" * 70 + "\nSNN BABY BRAIN v12.2.1 - CIRCADIAN TIME AWARENESS (NON-PENALIZING)\n" + "=" * 70)
    print(f"Web Search: {'✅ DuckDuckGo Ready' if DDG_AVAILABLE else '❌ pip install duckduckgo-search'}")
    print(f"Web Scrape: {'✅ Trafilatura Ready' if TRAFILATURA_AVAILABLE else '❌ pip install trafilatura'}")
    emul = brain.loihi_emulator; arch_stats = student.get_architecture_stats()
    print(f"Architecture : {len(LAYER_REGISTRY)} layers - {len(emul.neurons)} neurons - {len(emul.synapses)} synapses")
    print(f"Tokenizer    : SmartTokenizer ({tok.vocab_size} vocab, word+char)")
    print(f"  Embed Dim  : {arch_stats['embed_dim']} | Layers: {arch_stats['num_layers']} | Neurons: {arch_stats['total_neurons']}")
    print(f"  Max Seq Len: {arch_stats['max_seq_len']} (auto-grows to fit actual need)")
    print(f"Reasoning    : {student.get_reasoning_stats()['system']} | Fusion gate: True | Hippocampus: {brain.hippocampus.count} memories")
    print(f"Teacher      : {('ONLINE (' + UNSLOTH_MODEL_NAME + ')') if TEACHER_ONLINE else 'OFFLINE (Standalone mode)'}")
    print(f"DA memory    : {da.da_level:.3f}  |  Replay: {len(replay.episodes)} episodes")
    print(f"ATP Status   : {emul.metabolic_manager.get_status()}")
    print(f"GPU Opt      : Batch={Config.BATCH_SIZE}, Accum={Config.GRADIENT_ACCUMULATION_STEPS}, FP16={Config.USE_MIXED_PRECISION}")
    print("-" * 70)
    print("COMMANDS: train [file/pdf/docx] | trainhard [file] | scrape <url> | search <query> | jina <url>")
    print("          trainurl <url> | autochat <file> | sleep | status")
    print("          teach <curriculum.json> | socratic | review | curriculum | analytics")
    print("          warmup | unsupervised | reasoning | cleanup")
    print("          recoveratp [amount] | fullrecoveratp | think <msg> | fast | quit")
    print("          trainvision <dir> | trainaudio <dir> | image <path> | audio <path>")
    print("          tool <cmd> | reconstruct <image|audio> | chronos")
    print("          help | save | load <checkpoint> | teacher [on|off] | brain")
    print("          agent <goal> | omega <goal> | tokenize <text>")
    print("-" * 70)
    turn = 1; thinking_mode = False
    while True:
        try: user_input = input(f"\n[Turn {turn}] You: ").strip()
        except (EOFError, KeyboardInterrupt): print("\nExiting..."); break
        if not user_input: continue
        parts = user_input.split(); cmd = parts[0].lower()
        if cmd in ('quit', 'exit', 'q'): break
        if cmd == 'help':
            print("-" * 70)
            print("COMMANDS: train [file/pdf/docx] | trainhard [file] | scrape <url> | search <query> | jina <url>")
            print("          trainurl <url> | autochat <file> | sleep | status")
            print("          teach <curriculum.json> | socratic | review | curriculum | analytics")
            print("          warmup | unsupervised | reasoning | cleanup")
            print("          recoveratp [amount] | fullrecoveratp | think <msg> | fast | quit")
            print("          trainvision <dir> | trainaudio <dir> | image <path> | audio <path>")
            print("          tool <cmd> | reconstruct <image|audio> | chronos")
            print("          help | save | load <checkpoint> | teacher [on|off] | brain")
            print("          agent <goal> | omega <goal> | tokenize <text>")
            print("-" * 70); continue
        if cmd == 'agent':
            goal_text = " ".join(parts[1:]) if len(parts) > 1 else "Solve the current problem"
            run_agentic_loop(brain, student, tok, da, goal_text)
            continue
        if cmd == 'omega':
            goal_text = " ".join(parts[1:]) if len(parts) > 1 else "Solve the current problem"
            omega_answer, omega_report = run_omega_cognitive_pipeline(brain, student, tok, da, goal_text)
            print(f"\n[OMEGA RESPONSE]: {omega_answer}")
            print(f"[META-STATUS]: {omega_report.state.value} (Conf: {omega_report.confidence:.2f})")
            continue
        if cmd == 'tokenize':
            text = " ".join(parts[1:]) if len(parts) > 1 else "hello world"
            ids = tok.encode(text)
            print(f"text  : {text}")
            print(f"ids   : {ids[:60]}{'...' if len(ids) > 60 else ''}")
            print(f"decode: {tok.decode(ids)}")
            continue
        if cmd == 'save':
            print("\nManually saving brain state...")
            save_brain(brain, student, da, replay, enhanced_teacher=enhanced_teacher, version_tag="manual_save",
                       vision_enc=vision_enc, vision_dec=vision_dec, audio_enc=audio_enc, audio_dec=audio_dec); continue
        if cmd == 'load':
            if len(parts) < 2: print("[ERROR] Usage: load <checkpoint_name_or_path>"); continue
            ckpt = parts[1]
            if not ckpt.endswith('.safetensors'): ckpt += '.safetensors'
            ckpt_path = SCRIPT_DIR / ckpt
            if not ckpt_path.exists(): ckpt_path = SCRIPT_DIR / f"snn_brain_backup_v{ckpt}"
            if not ckpt_path.exists(): print(f"[ERROR] Checkpoint not found: {ckpt}"); continue
            try:
                state_dict = load_file(ckpt_path, device=str(Config.device)); model_state = student.state_dict(); loaded, mismatch = 0, 0
                for key in state_dict:
                    if key in model_state and state_dict[key].shape == model_state[key].shape: model_state[key].copy_(state_dict[key]); loaded += 1
                    else: mismatch += 1
                student.load_state_dict(model_state, strict=False); student.eval()
                print(f"Loaded {loaded} params from {ckpt_path.name} (skipped {mismatch} mismatched)")
            except Exception as e: print(f"[ERROR] Failed to load checkpoint: {e}")
            continue
        if cmd == 'teacher':
            if len(parts) > 1 and parts[1].lower() in ('on', 'off'):
                if parts[1].lower() == 'on':
                    if check_unsloth_connection(): TEACHER_ONLINE = True; print("Teacher is now ONLINE.")
                    else: print("[ERROR] Cannot connect to Unsloth Studio.")
                else: TEACHER_ONLINE = False; print("Teacher is now OFFLINE.")
            else:
                status = "ONLINE" if TEACHER_ONLINE else "OFFLINE"; print(f"Teacher Status: {status} ({UNSLOTH_MODEL_NAME})")
            continue
        if cmd == 'brain':
            arch = student.get_architecture_stats(); neuro = student.get_neurogenesis_stats(); bio = brain.get_brain_stats()
            print(f"\n{'='*50}\nBRAIN ARCHITECTURE & STATS\n{'='*50}")
            print(f"Embed Dim   : {arch['embed_dim']}\nLayers      : {arch['num_layers']}\nMax Seq Len : {arch['max_seq_len']}")
            print(f"Total Neurons (PyTorch): {arch['total_neurons']}\nComplexity  : {arch['complexity_score']:.2f}\nAvg Seq Use : {arch['avg_seq_usage']:.1%}")
            print(f"\nNeurogenesis: Born={neuro['total_born']} | Pruned={neuro['total_pruned']} | Net={neuro['net_growth']}")
            print(f"Stage       : {bio['stage']} | Topics: {bio['topics_learned']} | Epic: {bio['epic_moments']}")
            print(f"Hippocampus : {brain.hippocampus.count} memories")
            print(f"ATP         : {brain.loihi_emulator.metabolic_manager.get_status()}\n{'='*50}\n"); continue
        if cmd == 'trainvision':
            if len(parts) < 2: print("[ERROR] Usage: trainvision <data_dir>"); continue
            data_dir = parts[1]
            if not os.path.isdir(data_dir): print(f"[ERROR] Dir not found: {data_dir}"); continue
            dataset = ImageDataset(data_dir, Config.IMAGE_SIZE); dataloader = DataLoader(dataset, batch_size=Config.MULTIMODAL_BATCH_SIZE, shuffle=True)
            opt = torch.optim.Adam(list(vision_enc.parameters()) + list(vision_dec.parameters()) + list(vision_class.parameters()), lr=0.001)
            train_vision_autoencoder(vision_enc, vision_dec, vision_class, opt, dataloader, Config.VISION_EPOCHS); continue
        if cmd == 'trainaudio':
            if len(parts) < 2: print("[ERROR] Usage: trainaudio <data_dir>"); continue
            data_dir = parts[1]
            if not os.path.isdir(data_dir): print(f"[ERROR] Dir not found: {data_dir}"); continue
            dataset = AudioDataset(data_dir, Config.AUDIO_SAMPLE_RATE, Config.AUDIO_WINDOW_SEC); dataloader = DataLoader(dataset, batch_size=Config.MULTIMODAL_BATCH_SIZE, shuffle=True)
            opt = torch.optim.Adam(list(audio_enc.parameters()) + list(audio_dec.parameters()) + list(audio_class.parameters()), lr=0.001)
            train_audio_autoencoder(audio_enc, audio_dec, audio_class, opt, dataloader, Config.AUDIO_EPOCHS); continue
        if cmd == 'image':
            if len(parts) < 2: print("[ERROR] Usage: image <path>"); continue
            img_path = parts[1]
            if not os.path.exists(img_path): print(f"[ERROR] File not found: {img_path}"); continue
            img = load_image(img_path, Config.IMAGE_SIZE).to(Config.device); vision_enc.eval()
            with torch.no_grad(): z = vision_enc(img)
            print(f"Vision latent: {z.shape} | Mean: {z.mean().item():.3f}")
            emul.inject_vision_spikes(z[0], layer_id=68, registry=brain.neuron_registry); emul.step_simulation(0.05, da_level=da.da_level)
            vision_class.eval()
            with torch.no_grad(): logits = vision_class(z); pred = logits.argmax().item(); conf = F.softmax(logits, dim=1)[0, pred].item()
            print(f"Predicted class: {pred} (confidence: {conf:.2%})")
            resp, _ = generate_student_response_with_confidence(student, tok, "I see an image. Describe it: ", max_len=50, neuromod=emul.get_layer_rates_tensor()); print(f"Response: {resp}"); continue
        if cmd == 'audio':
            if len(parts) < 2: print("[ERROR] Usage: audio <path>"); continue
            audio_path = parts[1]
            if not os.path.exists(audio_path): print(f"[ERROR] File not found: {audio_path}"); continue
            wave = load_audio(audio_path, Config.AUDIO_SAMPLE_RATE).to(Config.device); audio_enc.eval()
            with torch.no_grad(): z = audio_enc(wave)
            print(f"Audio latent: {z.shape} | Mean: {z.mean().item():.3f}")
            emul.inject_audio_spikes(z[0], layer_id=71, registry=brain.neuron_registry); emul.step_simulation(0.05, da_level=da.da_level)
            audio_class.eval()
            with torch.no_grad(): logits = audio_class(z); pred = logits.argmax().item(); conf = F.softmax(logits, dim=1)[0, pred].item()
            print(f"Predicted class: {pred} (confidence: {conf:.2%})"); continue
        if cmd == 'tool':
            if len(parts) < 2: print("[ERROR] Usage: tool <cmd>"); continue
            tool_cmd = " ".join(parts[1:])
            tool_name, tool_result = brain.tool_router.parse_and_execute(tool_cmd)
            if tool_name == "none":
                print("Tool Result: no tool pattern matched")
            else:
                print(f"[{tool_name}] {tool_result}")
                emul.inject_tool_spikes(tool_result if tool_name != "none" else "", layer_id=72, registry=brain.neuron_registry)
                emul.step_simulation(0.05, da_level=da.da_level); continue
        if cmd == 'reconstruct':
            if len(parts) < 2: print("[ERROR] Usage: reconstruct <image|audio>"); continue
            rtype = parts[1].lower()
            if rtype == 'image':
                z = torch.randn(1, Config.VISION_LATENT_DIM).to(Config.device); vision_dec.eval()
                with torch.no_grad(): recon = vision_dec(z)
                save_image(recon[0], "reconstructed_image.png"); print("Image reconstructed -> reconstructed_image.png")
            elif rtype == 'audio':
                z = torch.randn(1, Config.AUDIO_LATENT_DIM).to(Config.device); audio_dec.eval()
                with torch.no_grad(): recon = audio_dec(z)
                save_audio(recon[0], "reconstructed_audio.wav", Config.AUDIO_SAMPLE_RATE); print("Audio reconstructed -> reconstructed_audio.wav")
            continue
        if cmd == 'autochat':
            file_arg = parts[1] if len(parts) > 1 else str(TRAINING_FILE)
            auto_chat_learn(brain, student, tok, da, replay, gru_opt, filepath=file_arg, max_samples=None); continue
        if cmd == 'teach':
            if len(parts) < 2:
                print("[ERROR] Usage: teach <filename.json>")
                continue
            json_file = parts[1]
            if not json_file.endswith('.json'): json_file += '.json'
            if not os.path.exists(json_file):
                print(f"[ERROR] File '{json_file}' not found."); continue
            print(f"\n🎓 Starting Enhanced Teaching Session with: {json_file}")
            try:
                enhanced_teach_from_json(json_file, brain, student, tok, da, encoder, replay, gru_opt,
                                         generate_teacher_response, generate_student_response_with_reasoning,
                                         enhanced_teacher, passing_score=0.20, max_retries=5)
            except Exception as e:
                print(f"[ERROR] Enhanced teaching failed: {e}")
                logger.exception(e)
            continue
        if cmd == 'socratic':
            if not enhanced_teacher.all_topics: print("[ERROR] Load curriculum first with: teach curriculum.json"); continue
            print("\nSOCRATIC MODE ENABLED"); topic_list = list(enhanced_teacher.all_topics.values())
            for i, t in enumerate(topic_list[:10], 1): print(f"{i}. {t.title} ({t.difficulty_level.name})")
            try: choice = int(input("\nChoose a topic (number): ")) - 1; topic = topic_list[choice]
            except Exception: print("[ERROR] Invalid choice"); continue
            for q in SocraticQuestioner.generate_questions(topic, DifficultyLevel.FOUNDATIONAL, num_questions=3):
                print(f"TEACHER: {q}"); ans = input("STUDENT: ")
                if ans.lower() in ['skip', 'next']: break
            continue
        if cmd == 'review':
            if not enhanced_teacher.learning_records: print("[ERROR] No learning history."); continue
            due_topics = [(tid, r) for tid, r in enhanced_teacher.learning_records.items() if r.next_review and r.next_review <= datetime.now()]
            if not due_topics: print("No reviews due."); continue
            for topic_id, _ in due_topics[:3]:
                if topic_id in enhanced_teacher.all_topics:
                    print(f"Reviewing: {enhanced_teacher.all_topics[topic_id].title}")
                    enhanced_teacher.conduct_teaching_session(enhanced_teacher.all_topics[topic_id], student, da, brain,
                                                              generate_teacher_response, generate_student_response_with_reasoning, tok,
                                                              optimizer=gru_opt)
            continue
        if cmd in ('analytics', 'progress'):
            if not enhanced_teacher.learning_records: print("[ERROR] No learning history yet."); continue
            summary = enhanced_teacher.generate_learning_summary()
            print(f"\n{'=' * 70}\nLEARNING ANALYTICS\n{'=' * 70}")
            print(f"Total Topics Attempted: {summary['total_topics_attempted']}")
            print(f"Topics Mastered (20%+): {summary['topics_mastered']}")
            print(f"Average Score: {summary['average_score']:.1%}")
            print(f"Misconceptions Found: {summary['misconceptions_found']}")
            print(f"Teaching Strategies Used: {', '.join(summary['teaching_strategies_used'])}")
            q_table = enhanced_teacher.get_q_table()
            if q_table:
                print("\nQ-Table (Strategy Values):")
                for tid, strats in q_table.items():
                    print(f"  {tid}:")
                    for strat, qval in strats.items(): print(f"    {strat}: {qval:.3f}")
            continue
        if cmd == 'trainhard':
            file_arg = parts[1] if len(parts) > 1 else str(TRAINING_FILE)
            train_hard(brain, student, tok, da, replay, file_arg); continue
        if cmd == 'train':
            file_arg = parts[1] if len(parts) > 1 else str(TRAINING_FILE)
            train_jsonl_efficient(brain, student, tok, da, replay, gru_opt, file_arg, epochs=Config.TRAIN_EPOCHS, learning_rate=Config.DEFAULT_LEARNING_RATE); continue
        if cmd == 'trainurl':
            if len(parts) < 2:
                print("[ERROR] Usage: trainurl <url>")
                print("Example: trainurl https://huggingface.co/datasets/LinhDuong/chatdoctor-5k/raw/main/chatdoctor5k.json")
                continue
            train_from_url_direct(brain, student, tok, da, replay, gru_opt, parts[1])
            continue
        if cmd == 'scrape' or cmd == 'learnurl':
            if len(parts) < 2:
                print("[ERROR] Usage: scrape <url>")
                print("Example: scrape https://en.wikipedia.org/wiki/Spiking_neural_network")
                continue
            target_url = parts[1]
            scraper = ScraperAI()
            chunks = scraper.extract_learnable_chunks(target_url)
            if not chunks:
                print("[WARNING] No learnable content found on this URL.")
                continue
            print(f"🧠 Feeding {len(chunks)} chunks to SNN for real-time paragraph learning...")
            student.train()
            scratch_opt = torch.optim.Adam(student.parameters(), lr=Config.DEFAULT_LEARNING_RATE * 0.5)
            max_chunks = min(50, len(chunks))
            for i, chunk in enumerate(chunks[:max_chunks]):
                print(f"  Learning chunk {i+1}/{max_chunks}: {chunk[:60]}...")
                loss = unsupervised_learning_step(student, tok, [chunk], scratch_opt, epoch=i)
                print(f"    -> Unsupervised Loss: {loss:.4f}")
                brain.loihi_emulator.step_simulation(0.01, da_level=da.da_level, verbose=False)
            student.eval()
            print("✅ Real-time paragraph learning complete! Synapses updated and consolidated.")
            save_brain(brain, student, da, replay, enhanced_teacher=enhanced_teacher, version_tag="scrape_learned")
            continue
        if cmd == 'search':
            query = " ".join(parts[1:])
            print(f"\n🔍 Searching DuckDuckGo for: {query}...")
            res = brain.tool_router._search(query)
            print(f"📄 RESULTS:\n{res[:800]}")
            continue
        if cmd == 'jina':
            url = parts[1] if len(parts) > 1 else ""
            print(f"\n🌐 Fetching LLM Markdown via Jina: {url}...")
            res = brain.tool_router._jina(url)
            print(f"📄 MARKDOWN:\n{res[:800]}")
            continue
        if cmd == 'chronos' or cmd == 'time':
            time_info = ChronosTool.execute("")
            print(f"\n🕒 {time_info}")
            _hippo_store(brain, student, tok, "What time is it?", time_info)
            emul.step_simulation(0.05, da_level=da.da_level, verbose=False)
            continue
        if cmd == 'warmup': warmup_training(student, tok, gru_opt); continue
        if cmd == 'sleep':
            sleep_consolidation(student, tok, replay, gru_opt)
            save_brain(brain, student, da, replay, enhanced_teacher=enhanced_teacher, version_tag="",
                       vision_enc=vision_enc, vision_dec=vision_dec, audio_enc=audio_enc, audio_dec=audio_dec); continue
        if cmd == 'unsupervised':
            Config.UNSUPERVISED_ENABLED = not Config.UNSUPERVISED_ENABLED
            print(f"Unsupervised Learning: {'ENABLED' if Config.UNSUPERVISED_ENABLED else 'DISABLED'}"); continue
        if cmd == 'reasoning':
            Config.REASONING_ENABLED = not Config.REASONING_ENABLED
            print(f"Reasoning: {'ENABLED' if Config.REASONING_ENABLED else 'DISABLED'}"); continue
        if cmd == 'cleanup': cleanup_old_checkpoints(); continue
        if cmd == 'recoveratp':
            amount = float(parts[1]) if len(parts) > 1 else 50.0; recover_atp(brain, amount); continue
        if cmd == 'fullrecoveratp': full_recover_atp(brain); continue
        if cmd == 'status':
            active = [(LAYER_REGISTRY.get(lid, '?'), cnt) for lid, cnt in emul.get_active_layers(top_n=5)]
            print(f"\n[STATUS] ATP: {emul.metabolic_manager.get_status()} | {da.status_str()}")
            print(f"Architecture: embed={arch_stats['embed_dim']}, layers={arch_stats['num_layers']}, neurons={arch_stats['total_neurons']}")
            print(f"Context window: max_seq_len={student.max_seq_len} (grows on demand)")
            print(f"Hippocampus: {brain.hippocampus.count} memories")
            if active:
                print("Most active layers:")
                for name, cnt in active: print(f"  {name[:52]:<52} {cnt} spikes")
            continue
        if user_input.lower().startswith("think "):
            thinking_mode = True; user_input = user_input[6:].strip(); print("[MODE] Deep Thinking Enabled for this turn.")
        elif cmd == "fast": thinking_mode = False; print("[MODE] Fast Response Mode Enabled."); continue
        
        neuromod = emul.get_layer_rates_tensor()
        
        # ==========================================
        # CIRCADIAN TIME AWARENESS INJECTION (NO PENALTY)
        # ==========================================
        CircadianNeuromodulator.inject_circadian_spikes(emul, brain.neuron_registry)
        time_context = CircadianNeuromodulator.get_time_context_prefix()
        
        route_override = None
        if getattr(brain, "actor_critic", None) is not None:
            try:
                with torch.no_grad():
                    _ids = tok.encode(user_input) or [0]
                    _lat = student.get_latent_representation(torch.tensor([_ids], device=Config.device)).detach()
                    route_override, _ = brain.actor_critic(_lat)
            except Exception: route_override = None
        encoder.encode(user_input, emul.neurons, brain.input_layer_neurons); emul.step_simulation(0.1, da_level=da.da_level, verbose=False)
        mem_prefix = _hippo_retrieve(brain, student, tok, user_input)
        mem_prefix = time_context + (mem_prefix if mem_prefix else "")
        prompt_with_mem = (mem_prefix + user_input) if mem_prefix else user_input
        if mem_prefix: print(f"[HIPPO/CHRONOS] {mem_prefix.strip()[:120]}")
        if Config.REASONING_ENABLED and (thinking_mode or student.complexity_score > Config.REASONING_CONFIDENCE_THRESHOLD):
            full_response, reasoning_steps, confidence, time_taken = generate_student_response_with_reasoning(
                student, tok, prompt_with_mem + " -> ", neuromod=neuromod, route_override=route_override)
            student_raw, student_conf = full_response, confidence; thoughts = "\n".join(reasoning_steps) if reasoning_steps else ""
            if thoughts: print(f"\n[REASONING STEPS]:\n{thoughts[:500]}...")
            print(f"[STUDENT RAW] {student_raw[:120]!r}  (conf={student_conf:.3f})")
        else:
            student_raw, student_conf = generate_student_response_with_confidence(
                student, tok, prompt_with_mem + " -> ", neuromod=neuromod, route_override=route_override)
            full_response, thoughts = student_raw, ""
            print(f"[STUDENT RAW] {student_raw[:120]!r}  (conf={student_conf:.3f})")
        final_response, cur_da, used_teacher = "", da.da_level, False
        if should_ask_teacher(user_input, student_conf, student_raw):
            if TEACHER_ONLINE:
                print(f"[META-COGNITION] Asking Teacher...")
                teacher_reply, cur_da = generate_teacher_response(UNSLOTH_MODEL_NAME, user_input, emul.metabolic_manager, da)
                if "Error" not in teacher_reply:
                    used_teacher = True; final_response = f" **Teacher taught me:** {teacher_reply}\n[I have updated my synapses.]"
                else: final_response = "My teacher is asleep."
            else:
                print("Teacher is OFFLINE. Relying on student's own response.")
                usable = student_raw.strip()
                final_response = usable if len(usable) > 2 else "I am still learning."
                cur_da = da.update(da.score_response(final_response, user_input) * 0.6)
        else:
            usable = student_raw.strip()
            final_response = usable if len(usable) > 2 else "I am still learning."
            cur_da = da.update(da.score_response(final_response, user_input) * 0.6)
        emul.step_simulation(0.1, da_level=cur_da); gru_loss = 0.0
        if used_teacher and final_response:
            clean_text = final_response.replace(" **Teacher taught me:** ", "").split("\n")[0]
            gru_loss = online_distillation_step(student, tok, user_input, clean_text, cur_da, gru_opt, n_steps=3, emulator=emul)
        elif final_response and final_response != "I am still learning.":
            emul.apply_global_reward(max(-0.2, min(0.2, (cur_da - 0.5) * 0.4)))
        if final_response and final_response != "I am still learning.":
            _hippo_store(brain, student, tok, user_input, final_response)
            learning_demand = 1.0 - cur_da; brain.check_neurogenesis(student, da, learning_demand)
        if final_response: replay.store(user_input, final_response, cur_da, turn, reward=cur_da, thoughts=thoughts)
        if replay.should_consolidate(turn):
            sleep_consolidation(student, tok, replay, gru_opt)
            save_brain(brain, student, da, replay, enhanced_teacher=enhanced_teacher, version_tag="",
                       vision_enc=vision_enc, vision_dec=vision_dec, audio_enc=audio_enc, audio_dec=audio_dec)
        tool_name, tool_result = brain.tool_router.parse_and_execute(final_response)
        if tool_name != "none":
            print(f"\n🛠️ [AUTO-EXECUTING TOOL]: {tool_name}")
            print(f"📤 RESULT: {tool_result[:200]}")
            try:
                brain.hippocampus.store_memory(f"Tool {tool_name} result: {tool_result}", np.zeros(128))
                print(f"💾 Tool result stored in Hippocampus for context.")
            except Exception as e:
                logger.warning(f"Failed to store tool result in hippocampus: {e}")
        else:
            gnw = " [GNW]" if emul.global_workspace_activation > 0.5 else ""
            print(f"\nAI: {final_response}{gnw}")
        mode = "TEACHER ASSISTED (LEARNING)" if used_teacher else ("DEEP THOUGHT" if thinking_mode else "AUTONOMOUS STUDENT")
        status_line = f"[{da.status_str()} | ATP={emul.metabolic_manager.atp:.0f} | Mode: {mode}"
        if gru_loss: status_line += f" | Loss={gru_loss:.3f}"
        print(status_line + "]"); turn += 1; thinking_mode = False
    print("\n--- SAVING BRAIN STATE ---")
    save_brain(brain, student, da, replay, enhanced_teacher=enhanced_teacher, version_tag="",
               vision_enc=vision_enc, vision_dec=vision_dec, audio_enc=audio_enc, audio_dec=audio_dec); print("Complete.")
class VectorHippocampus:
    def __init__(self, dim=128, capacity=2000):
        self.dim = dim; self.capacity = capacity
        self.vectors = np.zeros((capacity, dim), dtype=np.float32)
        self.texts = [""] * capacity; self.count = 0
        self.path_vec = SCRIPT_DIR / "hippocampus_vectors.npy"
        self.path_txt = SCRIPT_DIR / "hippocampus_texts.json"
        self._load()
    def _load(self):
        if self.path_vec.exists() and self.path_txt.exists():
            try:
                self.vectors = np.load(self.path_vec)
                with open(self.path_txt, 'r', encoding='utf-8') as f: self.texts = json.load(f)
                self.count = len(self.texts)
            except Exception: pass
    def _save(self):
        try:
            np.save(self.path_vec, self.vectors)
            with open(self.path_txt, 'w', encoding='utf-8') as f: json.dump(self.texts[:self.count], f)
        except Exception as e: logger.warning(f"Hippocampus save failed: {e}")
    def store_memory(self, text: str, vector: np.ndarray):
        vec = np.zeros(self.dim, dtype=np.float32)
        copy_len = min(self.dim, vector.shape[0]); vec[:copy_len] = vector[:copy_len]
        if self.count < self.capacity: idx = self.count; self.count += 1
        else: idx = self.count % self.capacity
        self.vectors[idx] = vec; self.texts[idx] = text
    def retrieve(self, query_vector: np.ndarray, top_k=3):
        if self.count == 0: return []
        active_vecs = self.vectors[:self.count]
        q_vec = np.zeros(self.dim, dtype=np.float32)
        copy_len = min(self.dim, query_vector.shape[0]); q_vec[:copy_len] = query_vector[:copy_len]
        sims = np.dot(active_vecs, q_vec) / (np.linalg.norm(active_vecs, axis=1) * np.linalg.norm(q_vec) + 1e-9)
        top_idx = np.argsort(sims)[-top_k:][::-1]
        return [(self.texts[i], float(sims[i])) for i in top_idx if sims[i] > 0.1]
def _hippo_store(brain, student, tokenizer, prompt: str, response: str):
    try:
        ids = tokenizer.encode(prompt)
        if not ids: return
        x = torch.tensor([ids], device=Config.device)
        latent = student.get_latent_representation(x).mean(0).detach().cpu().numpy()
        brain.hippocampus.store_memory(f"{prompt} -> {response}", latent)
    except Exception as e: logger.warning(f"Hippocampus store failed: {e}")
def _hippo_retrieve(brain, student, tokenizer, prompt: str, top_k: int = None) -> str:
    if top_k is None: top_k = Config.HIPPO_TOP_K
    try:
        ids = tokenizer.encode(prompt)
        if not ids: return ""
        x = torch.tensor([ids], device=Config.device)
        q = student.get_latent_representation(x).mean(0).detach().cpu().numpy()
        mems = brain.hippocampus.retrieve(q, top_k=top_k)
        if not mems: return ""
        return "[mem] " + " | ".join(m[0] for m in mems) + "\n"
    except Exception as e: logger.warning(f"Hippocampus retrieve failed: {e}"); return ""
class NeuromorphicActorCritic(nn.Module):
    def __init__(self, state_dim, action_dim):
        super().__init__()
        self.shared_lif = LIFNeuron()
        self.actor_fc1 = nn.Linear(state_dim, 128); self.actor_fc2 = nn.Linear(128, action_dim)
        self.critic_fc1 = nn.Linear(state_dim, 128); self.critic_fc2 = nn.Linear(128, 1)
        self._state_dim = state_dim
    def forward(self, state):
        shared_spikes, _ = self.shared_lif(state)
        actor_out = F.relu(self.actor_fc1(shared_spikes))
        action_probs = F.softmax(self.actor_fc2(actor_out), dim=-1)
        critic_out = F.relu(self.critic_fc1(shared_spikes))
        state_value = self.critic_fc2(critic_out)
        return action_probs, state_value
class AgenticEventQueue:
    def __init__(self):
        self.goals = deque(maxlen=10); self.current_goal = None; self.history = []
    def add_goal(self, goal_text: str, priority: float = 1.0):
        self.goals.append({"text": goal_text, "priority": priority, "status": "pending"})
    def get_next_goal(self):
        if not self.goals: return None
        sorted_goals = sorted(self.goals, key=lambda x: x['priority'], reverse=True)
        self.current_goal = sorted_goals[0]; self.current_goal['status'] = "active"
        return self.current_goal
    def resolve_goal(self, reward: float):
        if self.current_goal is None: return
        self.history.append({"goal": self.current_goal['text'], "reward": reward})
        self.current_goal['status'] = "completed"
        try: self.goals.remove(self.current_goal)
        except ValueError: pass
        self.current_goal = None
# ==========================================
# REAL FREE WEB TOOLS (DuckDuckGo, Trafilatura, Jina)
# ==========================================
class AgenticToolRouter:
    def __init__(self):
        self.tools = {
            "calc": self._calc,
            "search": self._search,
            "write": self._write,
            "read": self._read,
            "execute_code": self._execute_code,
            "scrape": self._scrape,
            "jina": self._jina,
            "chronos": self._chronos
        }
    def _calc(self, expr: str) -> str:
        allowed = set("0123456789+-*/(). ")
        if not all(c in allowed for c in expr): return "Error: invalid characters"
        try: return str(eval(expr, {"__builtins__": None}, {}))
        except Exception as e: return f"Error: {e}"
    def _search(self, query: str) -> str:
        if not DDG_AVAILABLE: return "Error: duckduckgo-search not installed. Run: pip install duckduckgo-search"
        try:
            with DDGS() as ddgs:
                results = list(ddgs.text(query, max_results=5))
                if not results: return "No results found."
                output = []
                for r in results:
                    output.append(f"Title: {r.get('title')}\nURL: {r.get('href')}\nSnippet: {r.get('body')}\n")
                return "\n---\n".join(output)
        except Exception as e: return f"Search Error: {e}"
    def _scrape(self, url: str) -> str:
        if not TRAFILATURA_AVAILABLE: return "Error: trafilatura not installed. Run: pip install trafilatura"
        try:
            downloaded = trafilatura.fetch_url(url)
            if not downloaded: return "Error: Could not fetch URL."
            text = trafilatura.extract(downloaded, include_comments=False, include_tables=True)
            return text[:4000] if text else "Error: No main text extracted."
        except Exception as e: return f"Scrape Error: {e}"
    def _jina(self, url: str) -> str:
        try:
            headers = {"Accept": "text/plain"}
            response = requests.get(f"https://r.jina.ai/{url}", headers=headers, timeout=15)
            if response.status_code == 200: return response.text[:4000]
            return f"Error: Jina returned status {response.status_code}"
        except Exception as e: return f"Jina Error: {e}"
    def _write(self, args: str) -> str:
        parts = args.split(" ", 1)
        if len(parts) < 2: return "Error: Usage: write <filename> <content>"
        fname, content = parts
        try:
            with open(fname, "w") as f: f.write(content)
            return f"Successfully wrote to {fname}"
        except Exception as e: return f"Error: {e}"
    def _read(self, fname: str) -> str:
        try:
            with open(fname, "r") as f: return f.read()[:500]
        except Exception as e: return f"Error: {e}"
    def _execute_code(self, code: str) -> str:
        import sys
        old_stdout = sys.stdout; output = io.StringIO()
        try:
            sys.stdout = output
            exec(code, {"__builtins__": None, "print": print, "range": range, "len": len, "sum": sum})
            sys.stdout = old_stdout; return output.getvalue()[:500]
        except Exception as e:
            sys.stdout = old_stdout; return f"Execution Error: {e}"
    def _chronos(self, args: str) -> str:
        return ChronosTool.execute(args)
    def parse_and_execute(self, text: str) -> Tuple[str, str]:
        match = re.search(r'tool:(\w+)\((.*)\)', text)
        if match:
            tool_name, args = match.group(1), match.group(2).strip()
            if tool_name in self.tools: return tool_name, self.tools[tool_name](args)
        return "none", ""
def _ensure_actor_critic(brain, student):
    expected_dim = student.embed_dim
    ac = getattr(brain, "actor_critic", None)
    if ac is not None and getattr(ac, "_state_dim", None) == expected_dim:
        if brain.ac_optimizer is None: brain.ac_optimizer = torch.optim.Adam(ac.parameters(), lr=1e-4)
        return ac
    new_ac = NeuromorphicActorCritic(expected_dim, Config.MOE_NUM_EXPERTS).to(Config.device)
    loaded = False
    if AC_FILE.exists():
        try:
            ckpt = torch.load(AC_FILE, map_location=Config.device, weights_only=False)
            old_sd = ckpt.get('state_dict', ckpt); old_dim = ckpt.get('state_dim', expected_dim)
            new_sd = new_ac.state_dict()
            with torch.no_grad():
                for name, old_p in old_sd.items():
                    if name not in new_sd: continue
                    new_p = new_sd[name]
                    if old_p.shape == new_p.shape: new_p.copy_(old_p)
                    elif old_p.dim() == 2 and old_p.shape[0] == new_p.shape[0]:
                        rows = min(old_p.shape[1], new_p.shape[1]); new_p[:, :rows] = old_p[:, :rows]
                    elif old_p.dim() == 2 and old_p.shape[1] == new_p.shape[1]:
                        cols = min(old_p.shape[0], new_p.shape[0]); new_p[:cols, :] = old_p[:cols, :]
            new_ac.load_state_dict(new_sd, strict=False); loaded = True
            print(f"[AC] Actor-Critic restored (state_dim {old_dim} -> {expected_dim}, padded)")
        except Exception as e: logger.warning(f"Actor-Critic load failed: {e}")
    if not loaded:
        print(f"[AC] Actor-Critic initialized with state_dim={expected_dim}")
        brain.actor_critic = new_ac; brain.actor_critic._state_dim = expected_dim
        brain.ac_optimizer = torch.optim.Adam(brain.actor_critic.parameters(), lr=1e-4)
    return brain.actor_critic
def run_agentic_loop(brain, student, tokenizer, da, goal_text: str):
    print("\n" + "=" * 70 + "\nAGENTIC EVENT LOOP INITIATED\nPRIMARY GOAL: " + goal_text + "\n" + "=" * 70)
    actor_critic = _ensure_actor_critic(brain, student)
    brain.event_queue.add_goal(goal_text, priority=1.0)
    steps, max_steps = 0, 5
    forced_tool = bool(re.search(r'tool:\w+\(', goal_text))
    action_names = ["Language_Generation", "Multimodal_Processing", "Tool_Execution", "Memory_Retrieval"]
    neuromod = brain.loihi_emulator.get_layer_rates_tensor()
    while brain.event_queue.goals and steps < max_steps:
        steps += 1; current_goal = brain.event_queue.get_next_goal()
        if not current_goal: break
        print(f"\n[STEP {steps}] Evaluating Goal: {current_goal['text']}")
        input_ids = tokenizer.encode(current_goal["text"]) or [0]
        x = torch.tensor([input_ids], device=Config.device)
        latent_state = student.get_latent_representation(x).detach()
        actor_critic.train()
        action_probs, state_value = actor_critic(latent_state)
        print(f"   Critic Value: {state_value.item():.3f}")
        probs_for_select = action_probs.detach()
        if forced_tool: action_idx = 2
        elif random.random() < Config.AGENTIC_EXPLORATION_EPS: action_idx = random.randint(0, Config.MOE_NUM_EXPERTS - 1)
        else: action_idx = torch.argmax(probs_for_select).item()
        selected_action = action_names[action_idx]; print(f"   Actor Selected: {selected_action}")
        route_override = probs_for_select; reward = 0.0
        if selected_action == "Tool_Execution":
            print("   Attempting Tool Execution...")
            tool_name, tool_result = brain.tool_router.parse_and_execute(goal_text)
            if tool_name != "none": print(f"   Tool [{tool_name}]: {tool_result[:120]}"); reward = 0.8
            else:
                print("   No valid tool pattern found. Falling back to generation.")
                resp, _ = generate_student_response_with_confidence(student, tokenizer, current_goal["text"] + " -> ", max_len=50, neuromod=neuromod, route_override=route_override)
                print(f"   Generated: {resp}"); reward = 0.2
        elif selected_action == "Memory_Retrieval":
            print("   Retrieving from Hippocampus...")
            memories = _hippo_retrieve(brain, student, tokenizer, current_goal["text"], top_k=2)
            if memories:
                for line in memories.strip().split("\n"): print(f"   {line[:100]}")
                reward = 0.6
            else: print("   No relevant memories found."); reward = 0.1
        else:
            resp, _ = generate_student_response_with_confidence(student, tokenizer, current_goal["text"] + " -> ", max_len=50, neuromod=neuromod, route_override=route_override)
            print(f"   Generated: {resp}"); reward = 0.5
        log_prob = torch.log(action_probs[0, action_idx] + 1e-8)
        advantage = reward - state_value.item()
        ac_loss = -log_prob * advantage + F.mse_loss(state_value, torch.tensor([[reward]], device=Config.device))
        brain.ac_optimizer.zero_grad(); ac_loss.backward()
        torch.nn.utils.clip_grad_norm_(actor_critic.parameters(), 1.0); brain.ac_optimizer.step()
        print(f"   AC Loss: {ac_loss.item():.4f} | Reward: {reward}")
        brain.event_queue.resolve_goal(reward); da.update(reward)
    print("\n" + "=" * 70 + "\nAGENTIC LOOP COMPLETED\n" + "=" * 70)
def load_or_create_brain():
    brain = HybridSNNBrain(LAYER_REGISTRY); brain.deploy_to_hardware()
    tok = SmartTokenizer()
    if len(tok.idx2word) <= 2 + len(SmartTokenizer.CHARS) and TRAINING_FILE.exists():
        try:
            pairs, raw_texts = parse_dataset(str(TRAINING_FILE))
            texts = raw_texts + [p + " " + r for p, r in pairs]
            if texts: tok.train_from_texts(texts)
        except Exception as e: logger.warning(f"Tokenizer training failed: {e}")
    student_arch = None
    if METADATA_FILE.exists():
        try:
            with open(METADATA_FILE) as f: student_arch = json.load(f).get('student_arch', None)
        except Exception as e: logger.warning(f"Metadata load failed: {e}")
    if student_arch:
        print(f"[SYSTEM] Loading architecture from metadata: embed={student_arch['embed_dim']}, layers={student_arch['num_layers']}")
        student = SpikingTransformerGenerator(vocab_size=student_arch['vocab_size'], embed_dim=student_arch['embed_dim'],
                                              num_heads=student_arch['num_heads'], num_layers=student_arch['num_layers'],
                                              ff_dim=student_arch['ff_dims'][0] if student_arch['ff_dims'] else Config.INITIAL_FF_DIM,
                                              max_seq_len=student_arch['max_seq_len'], time_steps=student_arch['time_steps']).to(Config.device)
    else:
        student = SpikingTransformerGenerator(vocab_size=tok.vocab_size, embed_dim=Config.INITIAL_EMBED_DIM, num_heads=Config.INITIAL_NUM_HEADS,
                                              num_layers=Config.INITIAL_NUM_LAYERS, ff_dim=Config.INITIAL_FF_DIM, max_seq_len=Config.INITIAL_MAX_SEQ_LEN, time_steps=Config.TIME_STEPS).to(Config.device)
    da = DANeuromodulator(); encoder = TextToSpikeEncoder(tok); replay = HippocampalReplayBuffer()
    gru_opt = torch.optim.Adam(student.parameters(), lr=Config.DEFAULT_LEARNING_RATE, weight_decay=Config.WEIGHT_DECAY); brain.replay_buffer = replay
    if METADATA_FILE.exists():
        try:
            with open(METADATA_FILE) as f: meta = json.load(f)
            brain.loihi_emulator.metabolic_manager.atp = meta.get('atp', Config.MAX_ATP)
            if brain.loihi_emulator.metabolic_manager.atp < 10.0:
                print(f"[WARNING] ATP critically low ({brain.loihi_emulator.metabolic_manager.atp:.1f}), recovering...")
                brain.loihi_emulator.metabolic_manager.atp = max(50.0, brain.loihi_emulator.metabolic_manager.atp + 50.0)
            brain.loihi_emulator.current_time_s = meta.get('sim_time_s', 0.0); da.from_dict(meta.get('da', {}))
            brain.developmental_stage = DevelopmentalStage(meta.get('developmental_stage', 'embryonic'))
            brain.topics_learned = meta.get('topics_learned', 0); brain.epic_moments = meta.get('epic_moments', 0)
        except Exception as e: logger.warning(f"Metadata load failed: {e}")
    trained = False
    if ACTIVE_BRAIN_FILE.exists():
        try:
            print(f"[SYSTEM] Loading active brain from: {ACTIVE_BRAIN_FILE.name}")
            state_dict = load_file(ACTIVE_BRAIN_FILE, device=str(Config.device)); model_state = student.state_dict(); loaded_count, mismatch_count = 0, 0
            for key in state_dict:
                if key in model_state:
                    if state_dict[key].shape == model_state[key].shape: model_state[key].copy_(state_dict[key]); loaded_count += 1
                    else: mismatch_count += 1
            student.load_state_dict(model_state, strict=False); student.eval(); trained = True
            print(f"Brain loaded successfully! (Recovered {loaded_count} params, skipped {mismatch_count} due to growth/vocab change)")
        except Exception as e:
            print(f"[WARNING] Could not load active brain weights. Reason: {e}"); print("[SYSTEM] Starting with fresh weights (architecture/vocab mismatch)")
    replay.load(REPLAY_FILE); enhanced_teacher = EnhancedTeacher()
    if METADATA_FILE.exists():
        try:
            with open(METADATA_FILE) as f: meta = json.load(f)
            q_data = meta.get('q_table')
            if q_data: enhanced_teacher.load_q_table(q_data); print("[SYSTEM] Loaded Q-table from metadata.")
        except Exception: pass
    print("[SYSTEM] Enhanced Teaching System initialized")
    return brain, student, tok, trained, da, encoder, replay, gru_opt, enhanced_teacher
if __name__ == "__main__":
    try: main()
    except Exception as e: logger.exception(f"Pipeline failed: {e}"); raise