feagi-brain-development 0.0.21

Brain Development Utilities - Synaptogenesis and Connectivity
Documentation
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
// Copyright 2025 Neuraville Inc.
// SPDX-License-Identifier: Apache-2.0

/*!
Synaptogenesis Integration Tests

Tests the synaptogenesis process through ConnectomeManager, covering:
- Core morphology applications (projector, centered_projector, block_to_block, vectors, patterns, expander)
- Integration path (apply_cortical_mapping -> apply_cortical_mapping_for_pair -> apply_single_morphology_rule)
- Edge cases (empty areas, no neurons, dimensions mismatch)
- Parameter validation (weight, psp, synapse_attractivity)

NOTE: These tests require morphologies to be registered in the morphology registry.
Morphologies are typically loaded from genome files. For these tests to work, morphologies
need to be set up first (e.g., using feagi_evolutionary::add_core_morphologies).

TODO: Add helper function to set up morphologies in test manager, or use genome loading
path for more realistic integration tests.
*/

use feagi_brain_development::{ConnectomeManager, CorticalArea, CorticalID};
use feagi_npu_burst_engine::{DynamicNPU, RustNPU, TracingMutex};
use feagi_structures::genomic::cortical_area::CorticalAreaDimensions;
use serde_json::json;
use std::sync::Arc;

/// Helper to create an isolated test manager with NPU
///
/// Sets up core morphologies (projector, block_to_block, etc.) required for synaptogenesis tests.
fn create_test_manager() -> ConnectomeManager {
    let runtime = feagi_npu_runtime::StdRuntime;
    let backend = feagi_npu_burst_engine::backend::CPUBackend::new();
    let npu_result =
        RustNPU::new(runtime, backend, 1_000_000, 10_000_000, 10).expect("Failed to create NPU");
    let npu = Arc::new(TracingMutex::new(
        feagi_npu_burst_engine::DynamicNPU::F32(npu_result),
        "TestNPU",
    ));

    let mut manager = ConnectomeManager::new_for_testing_with_npu(npu);
    // Set up core morphologies required for synaptogenesis
    manager.setup_core_morphologies_for_testing();
    manager
}

/// Helper to create a cortical area with dimensions
///
/// Creates custom cortical areas using the same approach as other tests:
/// Custom cortical IDs are 8 bytes starting with 'c' (e.g., b"csrc0000").
fn create_test_area(
    name: &str,
    width: u32,
    height: u32,
    depth: u32,
    idx: u32,
) -> (CorticalArea, CorticalID) {
    use feagi_structures::genomic::cortical_area::{CorticalAreaType, CustomCorticalType};

    // Create custom cortical ID: 8 bytes starting with 'c', padded with nulls
    // Format: 'c' + up to 7 characters from name, padded to 8 bytes
    let mut id_bytes = [0u8; 8];
    id_bytes[0] = b'c';
    let name_bytes = name.as_bytes();
    let copy_len = name_bytes.len().min(7); // Leave first byte as 'c'
    id_bytes[1..1 + copy_len].copy_from_slice(&name_bytes[..copy_len]);

    let cortical_id =
        CorticalID::try_from_bytes(&id_bytes).expect("Failed to create custom cortical ID");
    let cortical_type = CorticalAreaType::Custom(CustomCorticalType::LeakyIntegrateFire);

    let area = CorticalArea::new(
        cortical_id,
        idx,
        format!("Test Area {}", name),
        CorticalAreaDimensions::new(width, height, depth).unwrap(),
        (0, 0, 0).into(),
        cortical_type,
    )
    .expect("Failed to create cortical area");
    (area, cortical_id)
}

/// Helper to create neurons in a grid pattern within an area
fn create_grid_neurons(
    manager: &mut ConnectomeManager,
    area_id: &CorticalID,
    width: usize,
    height: usize,
    depth: usize,
) -> Vec<u64> {
    let mut neuron_ids = Vec::new();
    for z in 0..depth {
        for y in 0..height {
            for x in 0..width {
                let neuron_id = manager
                    .add_neuron(
                        area_id, x as u32, y as u32, z as u32, 1.0,   // firing_threshold
                        1.0,   // firing_threshold_limit
                        0.1,   // leak_coefficient
                        0.0,   // resting_potential
                        0,     // neuron_type
                        2,     // refractory_period
                        1.0,   // excitability
                        3,     // consecutive_fire_limit
                        5,     // snooze_length
                        false, // mp_charge_accumulation
                    )
                    .expect("Failed to create neuron");
                neuron_ids.push(neuron_id);
            }
        }
    }
    neuron_ids
}

// ============================================================================
// TEST 1: Projector Morphology - Basic Functionality
// ============================================================================

#[test]
fn test_projector_morphology_basic() {
    let mut manager = create_test_manager();

    // Create source area (10x10x1 = 100 neurons)
    let (src_area, src_id) = create_test_area("src000", 10, 10, 1, 0);
    manager
        .add_cortical_area(src_area)
        .expect("Failed to add source area");

    // Create destination area (10x10x1 = 100 neurons)
    let (dst_area, dst_id) = create_test_area("dst000", 10, 10, 1, 1);
    manager
        .add_cortical_area(dst_area)
        .expect("Failed to add destination area");

    // Create neurons in both areas
    create_grid_neurons(&mut manager, &src_id, 10, 10, 1);
    create_grid_neurons(&mut manager, &dst_id, 10, 10, 1);

    // Create a mapping rule (projector morphology)
    let rule = json!({
        "morphology_id": "projector",
        "postSynapticCurrent_multiplier": 1.0,
        "synapse_attractivity": 100
    });

    // Set up cortical mapping using update_cortical_mapping
    manager
        .update_cortical_mapping(&src_id, &dst_id, vec![rule])
        .expect("Failed to update cortical mapping");

    // Apply cortical mapping
    let synapse_count = manager
        .regenerate_synapses_for_mapping(&src_id, &dst_id)
        .expect("Failed to apply cortical mapping");

    println!(
        "Created {} synapses via projector morphology",
        synapse_count
    );

    // Verify synapses were created (projector should create 1:1 mapping for same dimensions)
    // With 100% attractivity, should create approximately 100 synapses (one per source neuron)
    // Note: May create slightly more due to projection algorithm behavior
    assert!(synapse_count > 0, "Should have created some synapses");
    assert!(
        synapse_count <= 150,
        "Should create reasonable number of synapses (allowing for projection variations)"
    );

    println!("✅ Test 1: Projector morphology basic - PASSED");
}

#[test]
fn test_centered_projector_drops_out_of_bounds() {
    let mut manager = create_test_manager();

    // Source larger than destination so peripheral source voxels are dropped.
    let (src_area, src_id) = create_test_area("src_cpr", 5, 5, 1, 0);
    manager
        .add_cortical_area(src_area)
        .expect("Failed to add source area");
    let (dst_area, dst_id) = create_test_area("dst_cpr", 3, 3, 1, 1);
    manager
        .add_cortical_area(dst_area)
        .expect("Failed to add destination area");

    let src_neurons = create_grid_neurons(&mut manager, &src_id, 5, 5, 1);
    create_grid_neurons(&mut manager, &dst_id, 3, 3, 1);

    let rule = json!({
        "morphology_id": "centered_projector",
        "postSynapticCurrent_multiplier": 1.0,
        "synapse_attractivity": 100
    });

    manager
        .update_cortical_mapping(&src_id, &dst_id, vec![rule])
        .expect("Failed to update cortical mapping");

    let synapse_count = manager
        .regenerate_synapses_for_mapping(&src_id, &dst_id)
        .expect("Failed to apply cortical mapping");

    // Only centered 3x3 source region maps into 3x3 destination => 9 synapses.
    assert_eq!(
        synapse_count, 9,
        "Centered projector should map only in-bounds centered voxels"
    );

    let Some(npu_arc) = manager.get_npu() else {
        panic!("Test manager must have an attached NPU");
    };
    let mut npu_guard = npu_arc.lock().unwrap();

    let src_center_nid = src_neurons[(2 * 5 + 2) as usize] as u32; // (2,2,0)
    let src_corner_nid = src_neurons[0] as u32; // (0,0,0)

    match *npu_guard {
        DynamicNPU::F32(ref mut npu) => {
            let center_outgoing = npu.get_outgoing_synapses(src_center_nid);
            assert_eq!(
                center_outgoing.len(),
                1,
                "Center source voxel should map to exactly one destination voxel"
            );
            let center_target_coords = npu
                .get_neuron_coordinates(center_outgoing[0].0)
                .expect("Destination neuron coordinates should exist");
            assert_eq!(
                center_target_coords,
                (1, 1, 0),
                "Source center should map to destination center"
            );

            let corner_outgoing = npu.get_outgoing_synapses(src_corner_nid);
            assert!(
                corner_outgoing.is_empty(),
                "Out-of-bounds mapped source voxels should be dropped"
            );
        }
        DynamicNPU::INT8(ref mut npu) => {
            let center_outgoing = npu.get_outgoing_synapses(src_center_nid);
            assert_eq!(
                center_outgoing.len(),
                1,
                "Center source voxel should map to exactly one destination voxel"
            );
            let center_target_coords = npu
                .get_neuron_coordinates(center_outgoing[0].0)
                .expect("Destination neuron coordinates should exist");
            assert_eq!(
                center_target_coords,
                (1, 1, 0),
                "Source center should map to destination center"
            );

            let corner_outgoing = npu.get_outgoing_synapses(src_corner_nid);
            assert!(
                corner_outgoing.is_empty(),
                "Out-of-bounds mapped source voxels should be dropped"
            );
        }
    }
}

#[test]
fn test_centered_projector_even_dimensions_use_lower_center_anchor() {
    let mut manager = create_test_manager();

    // Even-sized areas validate the lower-center anchor contract:
    // src center at (1,1,0) in 4x4x1 maps to dst center at (2,2,0) in 6x6x1.
    let (src_area, src_id) = create_test_area("src_cpe", 4, 4, 1, 0);
    manager
        .add_cortical_area(src_area)
        .expect("Failed to add source area");
    let (dst_area, dst_id) = create_test_area("dst_cpe", 6, 6, 1, 1);
    manager
        .add_cortical_area(dst_area)
        .expect("Failed to add destination area");

    let src_neurons = create_grid_neurons(&mut manager, &src_id, 4, 4, 1);
    create_grid_neurons(&mut manager, &dst_id, 6, 6, 1);

    let rule = json!({
        "morphology_id": "centered_projector",
        "postSynapticCurrent_multiplier": 1.0,
        "synapse_attractivity": 100
    });

    manager
        .update_cortical_mapping(&src_id, &dst_id, vec![rule])
        .expect("Failed to update cortical mapping");

    let synapse_count = manager
        .regenerate_synapses_for_mapping(&src_id, &dst_id)
        .expect("Failed to apply cortical mapping");
    assert_eq!(
        synapse_count, 16,
        "All 4x4 source voxels should map in-bounds into 6x6 destination"
    );

    let Some(npu_arc) = manager.get_npu() else {
        panic!("Test manager must have an attached NPU");
    };
    let mut npu_guard = npu_arc.lock().unwrap();

    let src_lower_center_nid = src_neurons[5] as u32; // (1,1,0)
    let src_upper_center_nid = src_neurons[(2 * 4 + 2) as usize] as u32; // (2,2,0)

    match *npu_guard {
        DynamicNPU::F32(ref mut npu) => {
            let lower_center_outgoing = npu.get_outgoing_synapses(src_lower_center_nid);
            assert_eq!(lower_center_outgoing.len(), 1);
            assert_eq!(
                npu.get_neuron_coordinates(lower_center_outgoing[0].0),
                Some((2, 2, 0)),
                "Lower-center source voxel should map to lower-center destination voxel"
            );

            let upper_center_outgoing = npu.get_outgoing_synapses(src_upper_center_nid);
            assert_eq!(upper_center_outgoing.len(), 1);
            assert_eq!(
                npu.get_neuron_coordinates(upper_center_outgoing[0].0),
                Some((3, 3, 0)),
                "Adjacent upper-center source voxel should preserve +1 offset from center"
            );
        }
        DynamicNPU::INT8(ref mut npu) => {
            let lower_center_outgoing = npu.get_outgoing_synapses(src_lower_center_nid);
            assert_eq!(lower_center_outgoing.len(), 1);
            assert_eq!(
                npu.get_neuron_coordinates(lower_center_outgoing[0].0),
                Some((2, 2, 0)),
                "Lower-center source voxel should map to lower-center destination voxel"
            );

            let upper_center_outgoing = npu.get_outgoing_synapses(src_upper_center_nid);
            assert_eq!(upper_center_outgoing.len(), 1);
            assert_eq!(
                npu.get_neuron_coordinates(upper_center_outgoing[0].0),
                Some((3, 3, 0)),
                "Adjacent upper-center source voxel should preserve +1 offset from center"
            );
        }
    }
}

#[test]
fn test_transpose_morphologies_basic() {
    for morphology_id in ["transpose_xy", "transpose_yz", "transpose_xz"] {
        let mut manager = create_test_manager();

        // Keep dimensions small and asymmetric so axis swaps are exercised.
        let (src_area, src_id) = create_test_area("srctrx", 4, 3, 2, 0);
        manager
            .add_cortical_area(src_area)
            .expect("Failed to add source area");

        let (dst_area, dst_id) = create_test_area("dsttrx", 4, 3, 2, 1);
        manager
            .add_cortical_area(dst_area)
            .expect("Failed to add destination area");

        create_grid_neurons(&mut manager, &src_id, 4, 3, 2);
        create_grid_neurons(&mut manager, &dst_id, 4, 3, 2);

        let rule = json!({
            "morphology_id": morphology_id,
            "postSynapticCurrent_multiplier": 1.0,
            "synapse_attractivity": 100
        });

        manager
            .update_cortical_mapping(&src_id, &dst_id, vec![rule])
            .expect("Failed to update cortical mapping");

        let synapse_count = manager
            .regenerate_synapses_for_mapping(&src_id, &dst_id)
            .expect("Failed to apply cortical mapping");

        assert!(
            synapse_count > 0,
            "Morphology {} should create synapses",
            morphology_id
        );
    }

    println!("✅ Test 1a: Transpose morphologies basic - PASSED");
}

// ============================================================================
// TEST 1b: Inhibitory mapping produces inhibitory synapses (type=1) with abs(weight)
// ============================================================================
#[test]
fn test_inhibitory_mapping_creates_inhibitory_synapses() {
    let mut manager = create_test_manager();

    // Create source + destination areas (small, deterministic)
    let (src_area, src_id) = create_test_area("src_inh", 4, 4, 1, 0);
    manager
        .add_cortical_area(src_area)
        .expect("Failed to add source area");

    let (dst_area, dst_id) = create_test_area("dst_inh", 4, 4, 1, 1);
    manager
        .add_cortical_area(dst_area)
        .expect("Failed to add destination area");

    // Create neurons in both areas
    let src_neurons = create_grid_neurons(&mut manager, &src_id, 4, 4, 1);
    create_grid_neurons(&mut manager, &dst_id, 4, 4, 1);

    // Negative multiplier should produce inhibitory synapses with weight = abs(multiplier)
    let rule = json!({
        "morphology_id": "projector",
        "postSynapticCurrent_multiplier": -5,
        "synapse_attractivity": 100
    });

    manager
        .update_cortical_mapping(&src_id, &dst_id, vec![rule])
        .expect("Failed to update cortical mapping");

    let synapse_count = manager
        .apply_cortical_mapping(&src_id)
        .expect("Failed to apply cortical mapping");

    assert!(
        synapse_count > 0,
        "Should have created synapses for inhibitory mapping"
    );

    // Inspect outgoing synapses from a sample source neuron
    let Some(npu_arc) = manager.get_npu() else {
        panic!("Test manager must have an attached NPU");
    };

    let sample_src = src_neurons[0] as u32;
    let mut npu_guard = npu_arc.lock().unwrap();
    match *npu_guard {
        DynamicNPU::F32(ref mut npu) => {
            // Propagation index is rebuilt during mapping application; outgoing list should be non-empty.
            let outgoing = npu.get_outgoing_synapses(sample_src);
            assert!(
                !outgoing.is_empty(),
                "Expected outgoing synapses from source neuron"
            );

            // Validate sign encoding: synapse_type=1 (inhibitory) and weight=5
            for (_target, weight, _psp, syn_type) in outgoing {
                assert_eq!(weight, 5.0, "Expected abs(multiplier) to be used as weight");
                assert_eq!(
                    syn_type, 1,
                    "Expected inhibitory synapse_type=1 for negative multiplier"
                );
            }
        }
        DynamicNPU::INT8(ref mut npu) => {
            let outgoing = npu.get_outgoing_synapses(sample_src);
            assert!(
                !outgoing.is_empty(),
                "Expected outgoing synapses from source neuron"
            );
            for (_target, weight, _psp, syn_type) in outgoing {
                assert_eq!(weight, 5.0, "Expected abs(multiplier) to be used as weight");
                assert_eq!(
                    syn_type, 1,
                    "Expected inhibitory synapse_type=1 for negative multiplier"
                );
            }
        }
    }

    println!("✅ Test 1b: Inhibitory mapping produces inhibitory synapses - PASSED");
}

// ============================================================================
// TEST 1c: Pattern morphology (0-0-0_to_all) creates expected synapses
// ============================================================================
/// Validate that pattern morphology connects origin to all destinations.
#[test]
fn test_pattern_morphology_origin_to_all() {
    let mut manager = create_test_manager();

    // Create source + destination areas (small, deterministic)
    let (src_area, src_id) = create_test_area("src_pat", 2, 2, 1, 0);
    manager
        .add_cortical_area(src_area)
        .expect("Failed to add source area");

    let (dst_area, dst_id) = create_test_area("dst_pat", 2, 2, 1, 1);
    manager
        .add_cortical_area(dst_area)
        .expect("Failed to add destination area");

    // Create neurons in both areas
    let src_neurons = create_grid_neurons(&mut manager, &src_id, 2, 2, 1);
    let dst_neurons = create_grid_neurons(&mut manager, &dst_id, 2, 2, 1);

    // Pattern morphology: origin -> all
    let rule = json!({
        "morphology_id": "0-0-0_to_all",
        "postSynapticCurrent_multiplier": 1.0,
        "synapse_attractivity": 100
    });

    manager
        .update_cortical_mapping(&src_id, &dst_id, vec![rule])
        .expect("Failed to update cortical mapping");

    let synapse_count = manager
        .apply_cortical_mapping(&src_id)
        .expect("Failed to apply cortical mapping");

    let expected_count = u32::try_from(dst_neurons.len()).expect("Neuron count overflow");
    assert_eq!(
        synapse_count, expected_count,
        "Expected one synapse from origin to each destination neuron"
    );

    let Some(npu_arc) = manager.get_npu() else {
        panic!("Test manager must have an attached NPU");
    };
    let origin_src = src_neurons[0] as u32;
    let mut npu_guard = npu_arc.lock().unwrap();
    match *npu_guard {
        DynamicNPU::F32(ref mut npu) => {
            let outgoing = npu.get_outgoing_synapses(origin_src);
            assert_eq!(
                outgoing.len(),
                dst_neurons.len(),
                "Origin neuron should connect to all destination neurons"
            );
        }
        DynamicNPU::INT8(ref mut npu) => {
            let outgoing = npu.get_outgoing_synapses(origin_src);
            assert_eq!(
                outgoing.len(),
                dst_neurons.len(),
                "Origin neuron should connect to all destination neurons"
            );
        }
    }

    println!("✅ Test 1c: Pattern morphology origin to all - PASSED");
}

#[test]
fn test_first_to_last_morphology_maps_origin_to_destination_max() {
    let mut manager = create_test_manager();

    // Source and destination dimensions intentionally differ.
    let (src_area, src_id) = create_test_area("srcf2l", 3, 3, 2, 0);
    manager
        .add_cortical_area(src_area)
        .expect("Failed to add source area");

    let (dst_area, dst_id) = create_test_area("dstf2l", 4, 2, 2, 1);
    manager
        .add_cortical_area(dst_area)
        .expect("Failed to add destination area");

    let src_neurons = create_grid_neurons(&mut manager, &src_id, 3, 3, 2);
    create_grid_neurons(&mut manager, &dst_id, 4, 2, 2);

    let rule = json!({
        "morphology_id": "first_to_last",
        "postSynapticCurrent_multiplier": 1.0,
        "synapse_attractivity": 100
    });

    manager
        .update_cortical_mapping(&src_id, &dst_id, vec![rule])
        .expect("Failed to update cortical mapping");

    let synapse_count = manager
        .apply_cortical_mapping(&src_id)
        .expect("Failed to apply cortical mapping");
    assert_eq!(
        synapse_count, 1,
        "first_to_last should create exactly one synapse"
    );

    let Some(npu_arc) = manager.get_npu() else {
        panic!("Test manager must have an attached NPU");
    };
    let mut npu_guard = npu_arc.lock().unwrap();
    let expected_dst = (3u32, 1u32, 1u32);

    match *npu_guard {
        DynamicNPU::F32(ref mut npu) => {
            let src_origin = src_neurons
                .iter()
                .map(|nid| *nid as u32)
                .find(|nid| npu.get_neuron_coordinates(*nid) == Some((0, 0, 0)))
                .expect("Source origin neuron must exist");
            let outgoing = npu.get_outgoing_synapses(src_origin);
            assert_eq!(
                outgoing.len(),
                1,
                "Source origin should have exactly one outgoing synapse"
            );
            assert_eq!(
                npu.get_neuron_coordinates(outgoing[0].0),
                Some(expected_dst),
                "Source origin should map to destination max voxel"
            );
        }
        DynamicNPU::INT8(ref mut npu) => {
            let src_origin = src_neurons
                .iter()
                .map(|nid| *nid as u32)
                .find(|nid| npu.get_neuron_coordinates(*nid) == Some((0, 0, 0)))
                .expect("Source origin neuron must exist");
            let outgoing = npu.get_outgoing_synapses(src_origin);
            assert_eq!(
                outgoing.len(),
                1,
                "Source origin should have exactly one outgoing synapse"
            );
            assert_eq!(
                npu.get_neuron_coordinates(outgoing[0].0),
                Some(expected_dst),
                "Source origin should map to destination max voxel"
            );
        }
    }
}

// ============================================================================
// TEST 2: Block-to-Block Morphology - Basic Functionality
// ============================================================================

#[test]
fn test_block_to_block_morphology_basic() {
    let mut manager = create_test_manager();

    // Create source area (10x10x1 = 100 neurons)
    let (src_area, src_id) = create_test_area("src001", 10, 10, 1, 0);
    manager
        .add_cortical_area(src_area)
        .expect("Failed to add source area");

    // Create destination area (5x5x1 = 25 neurons)
    let (dst_area, dst_id) = create_test_area("dst001", 5, 5, 1, 1);
    manager
        .add_cortical_area(dst_area)
        .expect("Failed to add destination area");

    // Create neurons in both areas
    create_grid_neurons(&mut manager, &src_id, 10, 10, 1);
    create_grid_neurons(&mut manager, &dst_id, 5, 5, 1);

    // Create a mapping rule (block_to_block morphology)
    let rule = json!({
        "morphology_id": "block_to_block",
        "morphology_scalar": [1],
        "postSynapticCurrent_multiplier": 1.0,
        "synapse_attractivity": 100
    });

    // Set up cortical mapping using update_cortical_mapping
    manager
        .update_cortical_mapping(&src_id, &dst_id, vec![rule])
        .expect("Failed to update cortical mapping");

    // Apply cortical mapping
    let synapse_count = manager
        .apply_cortical_mapping(&src_id)
        .expect("Failed to apply cortical mapping");

    println!(
        "Created {} synapses via block_to_block morphology",
        synapse_count
    );

    // Verify synapses were created
    assert!(synapse_count > 0, "Should have created some synapses");

    println!("✅ Test 2: Block-to-block morphology basic - PASSED");
}

// ============================================================================
// TEST 2b: Composite tile morphology - fold and replicate directions
// ============================================================================
#[test]
fn test_tile_morphology_fold_and_replicate() {
    let mut manager = create_test_manager();

    // Fold case: source larger than destination
    let (src_fold_area, src_fold_id) = create_test_area("src_tlf", 4, 1, 1, 10);
    manager
        .add_cortical_area(src_fold_area)
        .expect("Failed to add fold source area");
    let (dst_fold_area, dst_fold_id) = create_test_area("dst_tlf", 2, 1, 1, 11);
    manager
        .add_cortical_area(dst_fold_area)
        .expect("Failed to add fold destination area");
    create_grid_neurons(&mut manager, &src_fold_id, 4, 1, 1);
    create_grid_neurons(&mut manager, &dst_fold_id, 2, 1, 1);

    let rule_fold = json!({
        "morphology_id": "tile",
        "postSynapticCurrent_multiplier": 1.0,
        "synapse_attractivity": 100
    });
    manager
        .update_cortical_mapping(&src_fold_id, &dst_fold_id, vec![rule_fold])
        .expect("Failed to update fold tile mapping");
    let fold_count = manager
        .regenerate_synapses_for_mapping(&src_fold_id, &dst_fold_id)
        .expect("Failed to apply fold tile mapping");
    assert_eq!(
        fold_count, 4,
        "Fold mode should map each of 4 source neurons into destination tile positions"
    );

    // Replicate case: source smaller than destination
    let (src_rep_area, src_rep_id) = create_test_area("src_tlr", 2, 1, 1, 12);
    manager
        .add_cortical_area(src_rep_area)
        .expect("Failed to add replicate source area");
    let (dst_rep_area, dst_rep_id) = create_test_area("dst_tlr", 5, 1, 1, 13);
    manager
        .add_cortical_area(dst_rep_area)
        .expect("Failed to add replicate destination area");
    create_grid_neurons(&mut manager, &src_rep_id, 2, 1, 1);
    create_grid_neurons(&mut manager, &dst_rep_id, 5, 1, 1);

    let rule_rep = json!({
        "morphology_id": "tile",
        "postSynapticCurrent_multiplier": 1.0,
        "synapse_attractivity": 100
    });
    manager
        .update_cortical_mapping(&src_rep_id, &dst_rep_id, vec![rule_rep])
        .expect("Failed to update replicate tile mapping");
    let rep_count = manager
        .regenerate_synapses_for_mapping(&src_rep_id, &dst_rep_id)
        .expect("Failed to apply replicate tile mapping");
    assert_eq!(
        rep_count, 5,
        "Replicate mode should tile source over destination (x=0,2,4 and x=1,3)"
    );
}

// ============================================================================
// TEST 3: Edge Case - Empty Source Area
// ============================================================================

#[test]
fn test_synaptogenesis_empty_source_area() {
    let mut manager = create_test_manager();

    // Create source area (but don't add neurons)
    let (src_area, src_id) = create_test_area("src002", 10, 10, 1, 0);
    manager
        .add_cortical_area(src_area)
        .expect("Failed to add source area");

    // Create destination area with neurons
    let (dst_area, dst_id) = create_test_area("dst002", 10, 10, 1, 1);
    manager
        .add_cortical_area(dst_area)
        .expect("Failed to add destination area");
    create_grid_neurons(&mut manager, &dst_id, 10, 10, 1);

    // Create a mapping rule
    let rule = json!({
        "morphology_id": "projector",
        "postSynapticCurrent_multiplier": 1.0,
        "synapse_attractivity": 100
    });

    // Set up cortical mapping using update_cortical_mapping
    manager
        .update_cortical_mapping(&src_id, &dst_id, vec![rule])
        .expect("Failed to update cortical mapping");

    // Apply cortical mapping (should return 0 synapses, not error)
    let synapse_count = manager
        .apply_cortical_mapping(&src_id)
        .expect("Should handle empty source area gracefully");

    assert_eq!(
        synapse_count, 0,
        "Should create 0 synapses when source area is empty"
    );

    println!("✅ Test 3: Empty source area - PASSED");
}

// ============================================================================
// TEST 4: Edge Case - Empty Destination Area
// ============================================================================

#[test]
fn test_synaptogenesis_empty_destination_area() {
    let mut manager = create_test_manager();

    // Create source area with neurons
    let (src_area, src_id) = create_test_area("src003", 10, 10, 1, 0);
    manager
        .add_cortical_area(src_area)
        .expect("Failed to add source area");
    create_grid_neurons(&mut manager, &src_id, 10, 10, 1);

    // Create destination area (but don't add neurons)
    let (dst_area, dst_id) = create_test_area("dst003", 10, 10, 1, 1);
    manager
        .add_cortical_area(dst_area)
        .expect("Failed to add destination area");

    // Create a mapping rule
    let rule = json!({
        "morphology_id": "projector",
        "postSynapticCurrent_multiplier": 1.0,
        "synapse_attractivity": 100
    });

    // Set up cortical mapping using update_cortical_mapping
    manager
        .update_cortical_mapping(&src_id, &dst_id, vec![rule])
        .expect("Failed to update cortical mapping");

    // Apply cortical mapping (should return 0 synapses, not error)
    let synapse_count = manager
        .apply_cortical_mapping(&src_id)
        .expect("Should handle empty destination area gracefully");

    assert_eq!(
        synapse_count, 0,
        "Should create 0 synapses when destination area is empty"
    );

    println!("✅ Test 4: Empty destination area - PASSED");
}

// ============================================================================
// TEST 5: Synapse Attractivity Parameter
// ============================================================================

#[test]
fn test_synapse_attractivity_parameter() {
    let mut manager = create_test_manager();

    // Create source and destination areas
    let (src_area, src_id) = create_test_area("src004", 10, 10, 1, 0);
    manager
        .add_cortical_area(src_area)
        .expect("Failed to add source area");

    let (dst_area, dst_id) = create_test_area("dst004", 10, 10, 1, 1);
    manager
        .add_cortical_area(dst_area)
        .expect("Failed to add destination area");

    // Create neurons in both areas
    create_grid_neurons(&mut manager, &src_id, 10, 10, 1);
    create_grid_neurons(&mut manager, &dst_id, 10, 10, 1);

    // Test with 0% attractivity (should create 0 synapses)
    let rule_zero = json!({
        "morphology_id": "projector",
        "postSynapticCurrent_multiplier": 1.0,
        "synapse_attractivity": 0
    });

    // Set up cortical mapping using update_cortical_mapping
    manager
        .update_cortical_mapping(&src_id, &dst_id, vec![rule_zero])
        .expect("Failed to update cortical mapping");

    let synapse_count_zero = manager
        .apply_cortical_mapping(&src_id)
        .expect("Failed to apply cortical mapping with 0% attractivity");

    assert_eq!(
        synapse_count_zero, 0,
        "0% attractivity should create 0 synapses"
    );

    println!("✅ Test 5: Synapse attractivity parameter - PASSED");
}

// ============================================================================
// TEST 6: Multiple Morphology Rules
// ============================================================================

#[test]
fn test_multiple_morphology_rules() {
    let mut manager = create_test_manager();

    // Create source area
    let (src_area, src_id) = create_test_area("src005", 10, 10, 1, 0);
    manager
        .add_cortical_area(src_area)
        .expect("Failed to add source area");

    // Create destination area
    let (dst_area, dst_id) = create_test_area("dst005", 10, 10, 1, 1);
    manager
        .add_cortical_area(dst_area)
        .expect("Failed to add destination area");

    // Create neurons in both areas
    create_grid_neurons(&mut manager, &src_id, 10, 10, 1);
    create_grid_neurons(&mut manager, &dst_id, 10, 10, 1);

    // Create multiple mapping rules (same morphology applied twice)
    let rule1 = json!({
        "morphology_id": "projector",
        "postSynapticCurrent_multiplier": 1.0,
        "synapse_attractivity": 50  // 50% to reduce stochastic variation
    });

    let rule2 = json!({
        "morphology_id": "projector",
        "postSynapticCurrent_multiplier": 1.0,
        "synapse_attractivity": 50
    });

    // Set up cortical mapping with multiple rules using update_cortical_mapping
    manager
        .update_cortical_mapping(&src_id, &dst_id, vec![rule1, rule2])
        .expect("Failed to update cortical mapping");

    // Apply cortical mapping
    let synapse_count = manager
        .apply_cortical_mapping(&src_id)
        .expect("Failed to apply cortical mapping with multiple rules");

    println!(
        "Created {} synapses via multiple morphology rules",
        synapse_count
    );

    // Verify synapses were created (should be more than 0, but exact count depends on randomness)
    // synapse_count is unsigned; non-negative is guaranteed.

    println!("✅ Test 6: Multiple morphology rules - PASSED");
}

// ============================================================================
// TEST 7: Parallel morphologies (projector + block_to_block) — bug regression
// ============================================================================
//
// Repro for the Counter -> Counter Register issue:
// - Area A (1x1x1, 1 neuron) with `projector` and `block_to_block` mappings to
//   Area B (1x1x10, 10 neurons).
// - Both morphologies target the same src/dst pair at voxel (0,0,0).
// - Expected: two PARALLEL synapses exist from A[0,0,0] to B[0,0,0]:
//     * projector: weight = 1  (psc_mult=1)
//     * block_to_block: weight = 10 (psc_mult=10)
// - The additional 9 synapses from `projector` (z=1..9) must also exist.
// - Before the fix, the vector-type dedup check skipped the `block_to_block`
//   synapse because the projector synapse was already present, losing the 10x
//   multiplier and preventing B[0,0,0] from reaching its firing threshold.
#[test]
fn test_parallel_projector_and_block_to_block_preserves_both() {
    let mut manager = create_test_manager();

    // 1x1x1 source
    let (src_area, src_id) = create_test_area("src_par", 1, 1, 1, 0);
    manager
        .add_cortical_area(src_area)
        .expect("Failed to add source area");

    // 1x1x10 destination
    let (dst_area, dst_id) = create_test_area("dst_par", 1, 1, 10, 1);
    manager
        .add_cortical_area(dst_area)
        .expect("Failed to add destination area");

    let src_neurons = create_grid_neurons(&mut manager, &src_id, 1, 1, 1);
    let dst_neurons = create_grid_neurons(&mut manager, &dst_id, 1, 1, 10);

    assert_eq!(src_neurons.len(), 1, "Source should have 1 neuron");
    assert_eq!(dst_neurons.len(), 10, "Destination should have 10 neurons");

    // Two parallel mapping rules from A -> B for the same voxel pair.
    // Order matters for the regression: `projector` is declared first (as in the
    // user's genome), which used to cause `block_to_block` to be dropped.
    let projector_rule = json!({
        "morphology_id": "projector",
        "morphology_scalar": [1, 1, 1],
        "postSynapticCurrent_multiplier": 1,
        "synapse_attractivity": 100,
        "plasticity_flag": false,
        "synaptic_delay_bursts": 1,
    });
    let block_to_block_rule = json!({
        "morphology_id": "block_to_block",
        "morphology_scalar": [1, 1, 1],
        "postSynapticCurrent_multiplier": 10,
        "synapse_attractivity": 100,
        "plasticity_flag": false,
        "synaptic_delay_bursts": 1,
    });

    manager
        .update_cortical_mapping(&src_id, &dst_id, vec![projector_rule, block_to_block_rule])
        .expect("Failed to update cortical mapping");

    let synapse_count = manager
        .apply_cortical_mapping(&src_id)
        .expect("Failed to apply cortical mapping");

    // projector => 10 synapses (z=0..9), block_to_block => 1 additional synapse at z=0
    assert_eq!(
        synapse_count, 11,
        "Expected 10 projector + 1 block_to_block synapse, got {}",
        synapse_count
    );

    // Validate the outgoing synapses from the single source neuron.
    let Some(npu_arc) = manager.get_npu() else {
        panic!("Test manager must have an attached NPU");
    };
    let src_nid = src_neurons[0] as u32;
    let mut npu_guard = npu_arc.lock().unwrap();

    let outgoing: Vec<(u32, f32, f32, u8)> = match *npu_guard {
        DynamicNPU::F32(ref mut npu) => npu.get_outgoing_synapses(src_nid),
        DynamicNPU::INT8(ref mut npu) => npu.get_outgoing_synapses(src_nid),
    };

    assert_eq!(
        outgoing.len(),
        11,
        "Source neuron should have exactly 11 outgoing synapses, found {}",
        outgoing.len()
    );

    // Validate: every target is a real destination neuron (no orphans).
    let dst_neuron_ids: std::collections::HashSet<u32> =
        dst_neurons.iter().map(|&id| id as u32).collect();
    for (target, _weight, _psp, _syn_type) in &outgoing {
        assert!(
            dst_neuron_ids.contains(target),
            "Outgoing synapse target {} is not a valid destination neuron",
            target
        );
    }

    // Validate the block_to_block synapse (weight=10) exists alongside the
    // projector synapse (weight=1) for the same src/dst pair at voxel (0,0,0).
    let target_at_z0 = dst_neurons[0] as u32;
    let synapses_to_z0: Vec<&(u32, f32, f32, u8)> = outgoing
        .iter()
        .filter(|(t, _, _, _)| *t == target_at_z0)
        .collect();

    assert_eq!(
        synapses_to_z0.len(),
        2,
        "Expected 2 parallel synapses to dst[0,0,0] (projector + block_to_block), found {}",
        synapses_to_z0.len()
    );

    let weights: Vec<f32> = synapses_to_z0.iter().map(|(_, w, _, _)| *w).collect();
    assert!(
        weights.contains(&1.0),
        "Expected a projector synapse (weight=1.0) to dst[0,0,0], found weights {:?}",
        weights
    );
    assert!(
        weights.contains(&10.0),
        "Expected a block_to_block synapse (weight=10.0) to dst[0,0,0] — \
         this is the regression: the 10x multiplier is dropped. Found weights {:?}",
        weights
    );

    println!("✅ Test 7: Parallel morphologies preserve both synapses - PASSED");
}

// ============================================================================
// TEST 8: End-to-end spike delivery via apply_cortical_mapping
//          (regression for cartpole detector silence)
// ============================================================================
//
// Regression for the cartpole R-STDP detector silence bug:
// Live FEAGI showed that after `update_cortical_mapping` + `apply_cortical_mapping`
// (or the equivalent dynamic build_reflex_mapping flow), `get_outgoing_synapses`
// correctly returned the synapses, but the per-burst spike-delivery loop never
// delivered any spikes across them. The destination neuron's membrane potential
// never increased and it never fired despite the source firing thousands of
// consecutive bursts.
//
// The other tests in this file only verify that synapses become visible via the
// propagation index after `apply_cortical_mapping`. They never run a burst chain
// to verify that spikes actually propagate across those synapses, so they cannot
// catch this regression.
//
// This test fills that gap: it exercises the same dynamic mapping flow used by
// the live REST API, then drives the source neuron via
// `inject_sensory_with_potentials` + `process_burst`, and asserts that the
// destination neuron fires within the expected synaptic-delay window.
#[test]
fn test_apply_cortical_mapping_delivers_spikes_to_target() {
    use feagi_npu_neural::types::NeuronId;

    let mut manager = create_test_manager();

    // Tiny 1x1x1 -> 1x1x1 graph: deterministic and rules out fan-out as a confounder.
    let (src_area, src_id) = create_test_area("src_e2e", 1, 1, 1, 0);
    manager
        .add_cortical_area(src_area)
        .expect("Failed to add source area");
    let (dst_area, dst_id) = create_test_area("dst_e2e", 1, 1, 1, 1);
    manager
        .add_cortical_area(dst_area)
        .expect("Failed to add destination area");

    // Use neuron parameters matching the canonical integration_burst_workflow tests
    // (mp_charge_accumulation=true, no consecutive-fire/snooze cap, no leak) so we
    // know the neuron itself is firing-capable. This isolates the test to the
    // mapping/propagation path rather than neuron dynamics tuning.
    let add_one = |manager: &mut ConnectomeManager, area: &CorticalID, x, y, z| -> u64 {
        manager
            .add_neuron(
                area,
                x,
                y,
                z,
                1.0,      // firing_threshold
                f32::MAX, // firing_threshold_limit (no cap)
                0.0,      // leak_coefficient
                0.0,      // resting_potential
                0,        // neuron_type
                5,        // refractory_period
                1.0,      // excitability
                0,        // consecutive_fire_limit (0 = no cap)
                0,        // snooze_length
                true,     // mp_charge_accumulation
            )
            .expect("add_neuron failed")
    };

    let src_neuron_id = add_one(&mut manager, &src_id, 0, 0, 0);
    let dst_neuron_id = add_one(&mut manager, &dst_id, 0, 0, 0);

    // Strong unconditional connection. PSC multiplier is generous so a single
    // spike from src must drive dst above threshold (default firing_threshold = 1.0
    // in `create_grid_neurons`).
    let rule = json!({
        "morphology_id": "projector",
        "morphology_scalar": [1, 1, 1],
        "postSynapticCurrent_multiplier": 5,
        "synapse_attractivity": 100,
        "plasticity_flag": false,
        "synaptic_delay_bursts": 1,
    });

    manager
        .update_cortical_mapping(&src_id, &dst_id, vec![rule])
        .expect("Failed to update cortical mapping");
    let synapse_count = manager
        .apply_cortical_mapping(&src_id)
        .expect("Failed to apply cortical mapping");
    assert_eq!(
        synapse_count, 1,
        "projector should produce exactly one src->dst synapse for matching 1x1x1 dims"
    );

    let src_nid = NeuronId(src_neuron_id as u32);
    let dst_nid = NeuronId(dst_neuron_id as u32);

    let npu_arc = manager
        .get_npu()
        .expect("Test manager must have an attached NPU");
    let mut npu_guard = npu_arc.lock().unwrap();

    match *npu_guard {
        DynamicNPU::F32(ref mut npu) => {
            // Sanity check: synapse is in the propagation engine's index.
            let outgoing = npu.get_outgoing_synapses(src_nid.0);
            assert_eq!(
                outgoing.len(),
                1,
                "Outgoing synapse should be visible via propagation index after apply_cortical_mapping"
            );
            assert_eq!(
                outgoing[0].0, dst_nid.0,
                "Outgoing synapse must target the dst neuron (got target_id={})",
                outgoing[0].0
            );

            // The actual regression check: drive src above threshold and verify
            // dst fires within the synaptic-delay window.
            npu.inject_sensory_with_potentials(&[(src_nid, 5.0)]);
            let burst1 = npu.process_burst().expect("burst 1 failed");
            assert!(
                burst1.fired_neurons.contains(&src_nid),
                "Source neuron must fire on burst 1 after sensory injection \
                 (fired={:?})",
                burst1.fired_neurons
            );

            // synaptic_delay_bursts=1 means the src spike from burst 1 arrives at
            // dst during burst 2 processing. dst should reach threshold and fire
            // on burst 2.
            let burst2 = npu.process_burst().expect("burst 2 failed");
            assert!(
                burst2.fired_neurons.contains(&dst_nid),
                "REGRESSION: destination neuron did not fire on burst 2 despite \
                 synapse being visible via propagation index. This is the cartpole \
                 detector silence bug. burst2.fired_neurons={:?}",
                burst2.fired_neurons
            );
        }
        DynamicNPU::INT8(_) => panic!("Test only configured for F32 NPU"),
    }

    println!("✅ Test 8: End-to-end spike delivery via apply_cortical_mapping - PASSED");
}

// ============================================================================
// TEST 9: Fan-out PSP dilution silences low-threshold targets
//          (regression for cartpole detector silence after adding R-STDP fan-out)
// ============================================================================
//
// In `synaptic_propagation.rs`, when a source area's `psp_uniform_distribution`
// is false (the default), the source neuron's per-burst contribution is divided
// across the total number of outgoing synapses:
//
//     final_contribution = base_contribution / source_meta.synapse_count
//
// This is the exact mechanism behind the cartpole detector silence:
//   - Initially, the encoder had 2 outgoing synapses (to detectors at z=0,9):
//       contribution per synapse = 1.0 / 2 = 0.5  → above detector threshold 0.1, fires.
//   - After adding 20 R-STDP synapses (encoder → motor), encoder fan-out = 21:
//       contribution per synapse = 1.0 / 21 = 0.048 → below 0.1, detector silent.
//
// This test reconstructs that exact topology and asserts the symptom. It is a
// behavioral regression test: any future change that silently alters fan-out
// dilution semantics (e.g., toggling the default of psp_uniform_distribution)
// will move this assertion. Owners are expected to update this test
// intentionally if they change the contract.
#[test]
fn test_fanout_psp_dilution_silences_low_threshold_target() {
    use feagi_npu_neural::types::NeuronId;

    let mut manager = create_test_manager();

    // Source: 1x1x10 (matches the cartpole encoder shape)
    let (src_area, src_id) = create_test_area("src_fan", 1, 1, 10, 0);
    manager
        .add_cortical_area(src_area)
        .expect("Failed to add source area");

    // Detector: 1x1x1 (matches pain_fallen / pleasure_upright)
    let (det_area, det_id) = create_test_area("det_fan", 1, 1, 1, 1);
    manager
        .add_cortical_area(det_area)
        .expect("Failed to add detector area");

    // Motor sink: 2x1x10 (matches ungrouped-1 fan-out target)
    let (mot_area, mot_id) = create_test_area("mot_fan", 2, 1, 10, 2);
    manager
        .add_cortical_area(mot_area)
        .expect("Failed to add motor area");

    // Add a single firing neuron at src[0,0,0] (encoder z=0 = "fallen" position).
    let src_neuron_id = manager
        .add_neuron(
            &src_id,
            0,
            0,
            0,
            1.0, // firing_threshold
            f32::MAX,
            0.0,
            0.0,
            0,
            5,
            1.0,
            0,
            0,
            true,
        )
        .expect("add encoder neuron failed");

    // Detector neuron with cartpole-matching threshold 0.1.
    let det_neuron_id = manager
        .add_neuron(
            &det_id,
            0,
            0,
            0,
            0.1, // firing_threshold = 0.1 (cartpole pain/pleasure threshold)
            f32::MAX,
            0.0,
            0.0,
            0,
            5,
            1.0,
            0,
            0,
            true,
        )
        .expect("add detector neuron failed");

    // Motor sink neurons (20 of them, 2x1x10 grid).
    for x in 0..2 {
        for z in 0..10 {
            manager
                .add_neuron(
                    &mot_id,
                    x,
                    0,
                    z,
                    1.0,
                    f32::MAX,
                    0.0,
                    0.0,
                    0,
                    5,
                    1.0,
                    0,
                    0,
                    true,
                )
                .expect("add motor neuron failed");
        }
    }

    // Mapping 1: src → detector, single synapse from src origin to dst origin.
    // morphology_scalar [0,0,0] for "0-0-0_to_all" pattern with 1x1x1 dst means a
    // single synapse src[0,0,0]→det[0,0,0] (matches cartpole detector wiring).
    let det_rule = json!({
        "morphology_id": "0-0-0_to_all",
        "morphology_scalar": [1, 1, 1],
        "postSynapticCurrent_multiplier": 1,
        "synapse_attractivity": 100,
        "plasticity_flag": false,
        "synaptic_delay_bursts": 1,
    });
    manager
        .update_cortical_mapping(&src_id, &det_id, vec![det_rule])
        .expect("update src→det mapping failed");

    // Mapping 2: src → motor, all_to_all with origin source = 20 synapses
    // from src[0,0,0] to all motor neurons (matches encoder→ungrouped-1 R-STDP fan-out).
    let mot_rule = json!({
        "morphology_id": "0-0-0_to_all",
        "morphology_scalar": [1, 1, 1],
        "postSynapticCurrent_multiplier": 1,
        "synapse_attractivity": 100,
        "plasticity_flag": false,
        "synaptic_delay_bursts": 1,
    });
    manager
        .update_cortical_mapping(&src_id, &mot_id, vec![mot_rule])
        .expect("update src→mot mapping failed");

    // Apply both mappings.
    let total_synapses = manager
        .apply_cortical_mapping(&src_id)
        .expect("apply_cortical_mapping failed");
    assert_eq!(
        total_synapses, 21,
        "Expected 21 total synapses (1 src→det + 20 src→mot)"
    );

    let src_nid = NeuronId(src_neuron_id as u32);
    let det_nid = NeuronId(det_neuron_id as u32);

    let npu_arc = manager
        .get_npu()
        .expect("Test manager must have an attached NPU");
    let mut npu_guard = npu_arc.lock().unwrap();

    match *npu_guard {
        DynamicNPU::F32(ref mut npu) => {
            // Sanity: src has exactly 21 outgoing synapses.
            let outgoing = npu.get_outgoing_synapses(src_nid.0);
            assert_eq!(
                outgoing.len(),
                21,
                "Expected encoder src to have 21 outgoing synapses (cartpole topology)"
            );

            // Drive src above its own threshold.
            npu.inject_sensory_with_potentials(&[(src_nid, 5.0)]);
            let burst1 = npu.process_burst().expect("burst 1 failed");
            assert!(
                burst1.fired_neurons.contains(&src_nid),
                "Source must fire on burst 1; fired={:?}",
                burst1.fired_neurons
            );

            // Burst 2: contribution to detector is base / 21 = 1.0/21 ≈ 0.048,
            // below detector threshold 0.1. Detector must therefore stay silent.
            let burst2 = npu.process_burst().expect("burst 2 failed");
            assert!(
                !burst2.fired_neurons.contains(&det_nid),
                "REGRESSION: detector fired on burst 2 — fan-out PSP dilution \
                 contract has changed. Either psp_uniform_distribution default \
                 flipped, or per-synapse division was removed. Update this test \
                 intentionally if the contract changed. burst2.fired={:?}",
                burst2.fired_neurons
            );
        }
        DynamicNPU::INT8(_) => panic!("Test only configured for F32 NPU"),
    }

    println!(
        "✅ Test 9: Fan-out PSP dilution silences low-threshold target - PASSED \
         (this confirms the cartpole detector silence root cause: 1/21 < 0.1)"
    );
}