feagi-api 0.0.6

FEAGI REST API layer with HTTP and ZMQ transport adapters
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
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
// Copyright 2025 Neuraville Inc.
// SPDX-License-Identifier: Apache-2.0

#![allow(dead_code, unused_imports, unused_variables)] // TODO: Update tests to use new API

//! Contract Tests for FEAGI Rust API
//!
//! These tests ensure that the Rust API produces correct responses
//! and handles errors properly.
//!
//! NOTE: Currently disabled - tests need to be updated to use axum test utilities
//! instead of tower::util::ServiceExt (which requires the "util" feature).
use axum::body::Body;
use axum::http::{Request, StatusCode};
use base64::{engine::general_purpose, Engine as _};
#[cfg(feature = "feagi-agent")]
use feagi_agent::clients::{AgentRegistrationStatus, CommandControlAgent};
#[cfg(feature = "feagi-agent")]
use feagi_agent::command_and_control::FeagiMessage;
#[cfg(feature = "feagi-agent")]
use feagi_agent::server::auth::DummyAuth;
#[cfg(feature = "feagi-agent")]
use feagi_agent::server::{AgentLivenessConfig, FeagiAgentHandler};
#[cfg(feature = "feagi-agent")]
use feagi_agent::AgentCapabilities;
#[cfg(feature = "feagi-agent")]
use feagi_agent::{AgentDescriptor, AuthToken};
#[cfg(feature = "feagi-agent")]
use feagi_api::common::agent_registration::{
    auto_create_cortical_areas_from_device_registrations,
    derive_motor_cortical_ids_from_device_registrations,
    derive_sensory_cortical_ids_from_device_registrations,
};
use feagi_api::common::{Json as ApiJson, State as ApiStateExtract};
use feagi_api::endpoints::agent::register_agent;
#[cfg(feature = "feagi-agent")]
use feagi_api::endpoints::genome::post_upload;
use feagi_api::transports::http::server::{create_http_server, ApiState};
use feagi_api::v1::AgentRegistrationRequest;
use feagi_brain_development::ConnectomeManager;
use feagi_evolutionary::templates::create_genome_with_core_areas;
#[cfg(feature = "feagi-agent")]
use feagi_io::protocol_implementations::websocket::websocket_std::{
    FeagiWebSocketServerPublisherProperties, FeagiWebSocketServerPullerProperties,
    FeagiWebSocketServerRouterProperties,
};
#[cfg(feature = "feagi-agent")]
use feagi_io::traits_and_enums::client::{FeagiClient, FeagiClientPusher};
#[cfg(feature = "feagi-agent")]
use feagi_io::AgentID;
use feagi_npu_burst_engine::backend::CPUBackend;
use feagi_npu_burst_engine::TracingMutex;
use feagi_npu_burst_engine::{DynamicNPU, RustNPU};
use feagi_npu_runtime::StdRuntime;
#[cfg(feature = "feagi-agent")]
use feagi_serialization::FeagiByteContainer;
use feagi_services::impls::{
    AnalyticsServiceImpl, ConnectomeServiceImpl, GenomeServiceImpl, NeuronServiceImpl,
    SystemServiceImpl,
};
#[cfg(feature = "feagi-agent")]
use feagi_services::types::CreateCorticalAreaParams;
#[cfg(feature = "feagi-agent")]
use feagi_services::RuntimeService;
#[cfg(feature = "feagi-agent")]
use feagi_structures::genomic::cortical_area::descriptors::CorticalUnitIndex;
#[cfg(feature = "feagi-agent")]
use feagi_structures::genomic::cortical_area::io_cortical_area_configuration_flag::{
    FrameChangeHandling, PercentageNeuronPositioning,
};
#[cfg(feature = "feagi-agent")]
use feagi_structures::genomic::SensoryCorticalUnit;
use parking_lot::RwLock;
use serde_json::{json, Value};
use std::collections::HashMap;
#[cfg(feature = "feagi-agent")]
use std::collections::HashSet;
#[cfg(feature = "feagi-agent")]
use std::net::{Ipv4Addr, SocketAddr, TcpListener};
use std::sync::{Arc, Mutex, OnceLock};
#[cfg(feature = "feagi-agent")]
use std::time::{Duration, Instant};
use tower::ServiceExt;
// tower::util::ServiceExt requires the "util" feature which may not be enabled
// Using axum's test utilities instead

/// Build ApiState with initialized components.
/// Each test gets a fresh, isolated manager (no singleton conflicts)
fn build_test_state() -> ApiState {
    if std::env::var("FEAGI_CONFIG_PATH").is_err() {
        std::env::set_var(
            "FEAGI_CONFIG_PATH",
            "/Users/nadji/code/FEAGI-2.0/feagi-rs/feagi_configuration.toml",
        );
    }

    // Initialize NPU (fire_ledger_window=10)
    let runtime = StdRuntime;
    let backend = CPUBackend::new();
    let npu_result = RustNPU::new(runtime, backend, 1_000_000, 10_000_000, 10).unwrap();
    let npu = Arc::new(TracingMutex::new(
        DynamicNPU::F32(npu_result),
        "api-contract-test-npu",
    ));

    // Create isolated ConnectomeManager for testing (bypasses singleton)
    let manager = Arc::new(RwLock::new(ConnectomeManager::new_for_testing_with_npu(
        Arc::clone(&npu),
    )));

    // Create services
    let genome_service_impl = Arc::new(GenomeServiceImpl::new(Arc::clone(&manager)));
    let current_genome = genome_service_impl.get_current_genome_arc();
    {
        let mut genome_guard = current_genome.write();
        *genome_guard = Some(create_genome_with_core_areas(
            "test-genome".to_string(),
            "test".to_string(),
        ));
    }
    let genome_service = genome_service_impl;
    let connectome_service = Arc::new(ConnectomeServiceImpl::new(
        Arc::clone(&manager),
        current_genome.clone(),
    ));
    // For tests, use empty version info
    let version_info = feagi_services::types::VersionInfo::default();
    let system_service = Arc::new(SystemServiceImpl::new(
        Arc::clone(&manager),
        None, // No BurstLoopRunner for basic tests
        version_info,
    ));
    let analytics_service = Arc::new(AnalyticsServiceImpl::new(
        Arc::clone(&manager),
        None, // No BurstLoopRunner for basic tests
    ));
    let neuron_service = Arc::new(NeuronServiceImpl::new(Arc::clone(&manager)));

    // Create a mock RuntimeService that always returns NotImplemented
    // This is acceptable for tests that don't exercise runtime control
    struct MockRuntimeService;
    #[async_trait::async_trait]
    impl feagi_services::RuntimeService for MockRuntimeService {
        async fn start(&self) -> feagi_services::ServiceResult<()> {
            Err(feagi_services::ServiceError::NotImplemented(
                "MockRuntimeService".to_string(),
            ))
        }
        async fn stop(&self) -> feagi_services::ServiceResult<()> {
            Err(feagi_services::ServiceError::NotImplemented(
                "MockRuntimeService".to_string(),
            ))
        }
        async fn pause(&self) -> feagi_services::ServiceResult<()> {
            Err(feagi_services::ServiceError::NotImplemented(
                "MockRuntimeService".to_string(),
            ))
        }
        async fn resume(&self) -> feagi_services::ServiceResult<()> {
            Err(feagi_services::ServiceError::NotImplemented(
                "MockRuntimeService".to_string(),
            ))
        }
        async fn step(&self) -> feagi_services::ServiceResult<()> {
            Err(feagi_services::ServiceError::NotImplemented(
                "MockRuntimeService".to_string(),
            ))
        }
        async fn get_status(&self) -> feagi_services::ServiceResult<feagi_services::RuntimeStatus> {
            Ok(feagi_services::RuntimeStatus {
                is_running: false,
                is_paused: false,
                frequency_hz: 1000.0,
                burst_count: 0,
                current_rate_hz: 0.0,
                last_burst_neuron_count: 0,
                avg_burst_time_ms: 0.0,
            })
        }
        async fn set_frequency(&self, _frequency: f64) -> feagi_services::ServiceResult<()> {
            Err(feagi_services::ServiceError::NotImplemented(
                "MockRuntimeService".to_string(),
            ))
        }
        async fn get_burst_count(&self) -> feagi_services::ServiceResult<u64> {
            Ok(0)
        }
        async fn reset_burst_count(&self) -> feagi_services::ServiceResult<()> {
            Err(feagi_services::ServiceError::NotImplemented(
                "MockRuntimeService".to_string(),
            ))
        }
        async fn get_fcl_snapshot(&self) -> feagi_services::ServiceResult<Vec<(u64, f32)>> {
            Ok(vec![])
        }
        async fn get_fcl_snapshot_with_cortical_idx(
            &self,
        ) -> feagi_services::ServiceResult<Vec<(u64, u32, f32)>> {
            Ok(vec![])
        }
        async fn get_fire_queue_sample(
            &self,
        ) -> feagi_services::ServiceResult<
            std::collections::HashMap<u32, (Vec<u32>, Vec<u32>, Vec<u32>, Vec<u32>, Vec<f32>)>,
        > {
            Ok(std::collections::HashMap::new())
        }
        async fn get_fire_ledger_configs(
            &self,
        ) -> feagi_services::ServiceResult<Vec<(u32, usize)>> {
            Ok(vec![])
        }
        async fn configure_fire_ledger_window(
            &self,
            _cortical_id: u32,
            _window_size: usize,
        ) -> feagi_services::ServiceResult<()> {
            Err(feagi_services::ServiceError::NotImplemented(
                "MockRuntimeService".to_string(),
            ))
        }
        async fn get_fcl_sampler_config(&self) -> feagi_services::ServiceResult<(f64, u32)> {
            Ok((0.0, 0))
        }
        async fn set_fcl_sampler_config(
            &self,
            _sample_rate: Option<f64>,
            _max_samples: Option<u32>,
        ) -> feagi_services::ServiceResult<()> {
            Err(feagi_services::ServiceError::NotImplemented(
                "MockRuntimeService".to_string(),
            ))
        }
        async fn get_area_fcl_sample_rate(
            &self,
            _cortical_id: u32,
        ) -> feagi_services::ServiceResult<f64> {
            Ok(0.0)
        }
        async fn set_area_fcl_sample_rate(
            &self,
            _cortical_id: u32,
            _sample_rate: f64,
        ) -> feagi_services::ServiceResult<()> {
            Err(feagi_services::ServiceError::NotImplemented(
                "MockRuntimeService".to_string(),
            ))
        }
        async fn inject_sensory_by_coordinates(
            &self,
            _cortical_area_name: &str,
            _coordinates: &[(u32, u32, u32, f32)],
            _mode: feagi_services::traits::runtime_service::ManualStimulationMode,
        ) -> feagi_services::ServiceResult<usize> {
            Err(feagi_services::ServiceError::NotImplemented(
                "MockRuntimeService".to_string(),
            ))
        }

        async fn register_motor_subscriptions(
            &self,
            _agent_id: &str,
            _cortical_ids: Vec<String>,
            _rate_hz: f64,
        ) -> feagi_services::ServiceResult<()> {
            Ok(())
        }

        async fn register_visualization_subscriptions(
            &self,
            _agent_id: &str,
            _rate_hz: f64,
        ) -> feagi_services::ServiceResult<()> {
            Ok(())
        }
        fn unregister_motor_subscriptions(&self, _agent_id: &str) {}
        fn unregister_visualization_subscriptions(&self, _agent_id: &str) {}
        async fn reset_cortical_area_states(
            &self,
            cortical_indices: &[u32],
        ) -> feagi_services::ServiceResult<Vec<(u32, usize)>> {
            Ok(cortical_indices.iter().map(|&i| (i, 0)).collect())
        }
        fn clear_all_motor_subscriptions(&self) {}
        fn clear_all_visualization_subscriptions(&self) {}
    }

    let runtime_service =
        Arc::new(MockRuntimeService) as Arc<dyn feagi_services::RuntimeService + Send + Sync>;

    // Create API state
    // Get FEAGI session timestamp (when this instance started)
    let feagi_session_timestamp = std::time::SystemTime::now()
        .duration_since(std::time::UNIX_EPOCH)
        .map(|d| d.as_millis() as i64)
        .unwrap_or(0);

    let (genome_transition_lock, genome_transition_in_progress) =
        ApiState::init_genome_transition_controls();
    ApiState {
        network_connection_info_provider: None,
        agent_service: None,
        analytics_service,
        connectome_service,
        genome_service,
        neuron_service,
        runtime_service,
        system_service,
        snapshot_service: None,
        feagi_session_timestamp,
        memory_stats_cache: None,
        amalgamation_state: ApiState::init_amalgamation_state(),
        genome_transition_lock,
        genome_transition_in_progress,
        #[cfg(feature = "feagi-agent")]
        agent_handler: Some(ApiState::init_agent_registration_handler()),
    }
}

#[cfg(feature = "feagi-agent")]
#[derive(Default)]
struct RuntimeTransitionTracker {
    motor_subscriptions: Mutex<HashSet<String>>,
    visualization_subscriptions: Mutex<HashSet<String>>,
}

#[cfg(feature = "feagi-agent")]
struct TrackingRuntimeService {
    tracker: Arc<RuntimeTransitionTracker>,
}

#[cfg(feature = "feagi-agent")]
impl TrackingRuntimeService {
    fn new(tracker: Arc<RuntimeTransitionTracker>) -> Self {
        Self { tracker }
    }
}

#[cfg(feature = "feagi-agent")]
#[async_trait::async_trait]
impl feagi_services::RuntimeService for TrackingRuntimeService {
    async fn start(&self) -> feagi_services::ServiceResult<()> {
        Ok(())
    }
    async fn stop(&self) -> feagi_services::ServiceResult<()> {
        Ok(())
    }
    async fn pause(&self) -> feagi_services::ServiceResult<()> {
        Ok(())
    }
    async fn resume(&self) -> feagi_services::ServiceResult<()> {
        Ok(())
    }
    async fn step(&self) -> feagi_services::ServiceResult<()> {
        Ok(())
    }
    async fn get_status(&self) -> feagi_services::ServiceResult<feagi_services::RuntimeStatus> {
        Ok(feagi_services::RuntimeStatus {
            is_running: false,
            is_paused: false,
            frequency_hz: 1000.0,
            burst_count: 0,
            current_rate_hz: 0.0,
            last_burst_neuron_count: 0,
            avg_burst_time_ms: 0.0,
        })
    }
    async fn set_frequency(&self, _frequency: f64) -> feagi_services::ServiceResult<()> {
        Ok(())
    }
    async fn get_burst_count(&self) -> feagi_services::ServiceResult<u64> {
        Ok(0)
    }
    async fn reset_burst_count(&self) -> feagi_services::ServiceResult<()> {
        Ok(())
    }
    async fn get_fcl_snapshot(&self) -> feagi_services::ServiceResult<Vec<(u64, f32)>> {
        Ok(vec![])
    }
    async fn get_fcl_snapshot_with_cortical_idx(
        &self,
    ) -> feagi_services::ServiceResult<Vec<(u64, u32, f32)>> {
        Ok(vec![])
    }
    async fn get_fire_queue_sample(
        &self,
    ) -> feagi_services::ServiceResult<
        std::collections::HashMap<u32, (Vec<u32>, Vec<u32>, Vec<u32>, Vec<u32>, Vec<f32>)>,
    > {
        Ok(std::collections::HashMap::new())
    }
    async fn get_fire_ledger_configs(&self) -> feagi_services::ServiceResult<Vec<(u32, usize)>> {
        Ok(vec![])
    }
    async fn configure_fire_ledger_window(
        &self,
        _cortical_id: u32,
        _window_size: usize,
    ) -> feagi_services::ServiceResult<()> {
        Ok(())
    }
    async fn get_fcl_sampler_config(&self) -> feagi_services::ServiceResult<(f64, u32)> {
        Ok((0.0, 0))
    }
    async fn set_fcl_sampler_config(
        &self,
        _sample_rate: Option<f64>,
        _max_samples: Option<u32>,
    ) -> feagi_services::ServiceResult<()> {
        Ok(())
    }
    async fn get_area_fcl_sample_rate(
        &self,
        _cortical_id: u32,
    ) -> feagi_services::ServiceResult<f64> {
        Ok(0.0)
    }
    async fn set_area_fcl_sample_rate(
        &self,
        _cortical_id: u32,
        _sample_rate: f64,
    ) -> feagi_services::ServiceResult<()> {
        Ok(())
    }
    async fn inject_sensory_by_coordinates(
        &self,
        _cortical_area_name: &str,
        _coordinates: &[(u32, u32, u32, f32)],
        _mode: feagi_services::traits::runtime_service::ManualStimulationMode,
    ) -> feagi_services::ServiceResult<usize> {
        Ok(0)
    }
    async fn register_motor_subscriptions(
        &self,
        agent_id: &str,
        _cortical_ids: Vec<String>,
        _rate_hz: f64,
    ) -> feagi_services::ServiceResult<()> {
        self.tracker
            .motor_subscriptions
            .lock()
            .unwrap()
            .insert(agent_id.to_string());
        Ok(())
    }
    async fn register_visualization_subscriptions(
        &self,
        agent_id: &str,
        _rate_hz: f64,
    ) -> feagi_services::ServiceResult<()> {
        self.tracker
            .visualization_subscriptions
            .lock()
            .unwrap()
            .insert(agent_id.to_string());
        Ok(())
    }
    fn unregister_motor_subscriptions(&self, agent_id: &str) {
        self.tracker
            .motor_subscriptions
            .lock()
            .unwrap()
            .remove(agent_id);
    }
    fn unregister_visualization_subscriptions(&self, agent_id: &str) {
        self.tracker
            .visualization_subscriptions
            .lock()
            .unwrap()
            .remove(agent_id);
    }
    async fn reset_cortical_area_states(
        &self,
        cortical_indices: &[u32],
    ) -> feagi_services::ServiceResult<Vec<(u32, usize)>> {
        Ok(cortical_indices.iter().map(|&i| (i, 0)).collect())
    }
    fn clear_all_motor_subscriptions(&self) {
        self.tracker.motor_subscriptions.lock().unwrap().clear();
    }
    fn clear_all_visualization_subscriptions(&self) {
        self.tracker
            .visualization_subscriptions
            .lock()
            .unwrap()
            .clear();
    }
}

#[cfg(feature = "feagi-agent")]
fn wait_for_registered_agent(
    handler: &Arc<Mutex<FeagiAgentHandler>>,
    client: &mut CommandControlAgent,
    timeout: Duration,
) -> (
    String,
    feagi_io::traits_and_enums::shared::TransportProtocolEndpoint,
) {
    let deadline = Instant::now() + timeout;
    loop {
        {
            let mut guard = handler.lock().unwrap();
            guard
                .poll_command_and_control()
                .expect("command/control polling failed");
        }
        client
            .poll_for_messages()
            .expect("client poll_for_messages failed");
        if let AgentRegistrationStatus::Registered(session_id, endpoints) =
            client.registration_status()
        {
            let sensory_endpoint = endpoints
                .get(&AgentCapabilities::SendSensorData)
                .cloned()
                .expect("registration response missing sensory endpoint");
            return (session_id.to_base64(), sensory_endpoint);
        }
        assert!(
            Instant::now() < deadline,
            "timed out waiting for agent registration"
        );
        std::thread::sleep(Duration::from_millis(2));
    }
}

#[cfg(feature = "feagi-agent")]
fn wait_for_sensory_data(handler: &Arc<Mutex<FeagiAgentHandler>>, timeout: Duration) -> bool {
    let deadline = Instant::now() + timeout;
    loop {
        {
            let mut guard = handler.lock().unwrap();
            match guard.poll_agent_sensors() {
                Ok(Some(_)) => return true,
                Ok(None) => {}
                Err(_) => return false,
            }
        }
        if Instant::now() >= deadline {
            return false;
        }
        std::thread::sleep(Duration::from_millis(2));
    }
}

#[cfg(feature = "feagi-agent")]
fn reserve_free_port() -> u16 {
    let listener = TcpListener::bind(SocketAddr::from((Ipv4Addr::LOCALHOST, 0)))
        .expect("failed to bind ephemeral port");
    listener
        .local_addr()
        .expect("failed to read local addr")
        .port()
}

#[cfg(feature = "feagi-agent")]
/// Helper to create a test server with initialized components
async fn create_test_server() -> axum::Router {
    let state = build_test_state();
    create_http_server(state)
}

#[cfg(feature = "feagi-agent")]
static CONFIG_ENV_LOCK: OnceLock<Mutex<()>> = OnceLock::new();

#[cfg(feature = "feagi-agent")]
struct ConfigEnvGuard {
    previous: Option<String>,
    path: std::path::PathBuf,
}

#[cfg(feature = "feagi-agent")]
impl Drop for ConfigEnvGuard {
    fn drop(&mut self) {
        if let Some(value) = self.previous.take() {
            std::env::set_var("FEAGI_CONFIG_PATH", value);
        } else {
            std::env::remove_var("FEAGI_CONFIG_PATH");
        }
        let _ = std::fs::remove_file(&self.path);
    }
}

#[cfg(feature = "feagi-agent")]
fn set_temp_config(auto_create: bool) -> ConfigEnvGuard {
    let nanos = std::time::SystemTime::now()
        .duration_since(std::time::UNIX_EPOCH)
        .expect("Time went backwards")
        .as_nanos();
    let path = std::path::PathBuf::from(format!("/tmp/feagi-config-{nanos}--temp.toml"));
    let base_path =
        std::path::PathBuf::from("/Users/nadji/code/FEAGI-2.0/feagi-rs/feagi_configuration.toml");
    let base_contents =
        std::fs::read_to_string(&base_path).expect("Failed to read base FEAGI config");
    let mut contents = String::new();
    let mut in_agent = false;
    let mut injected = false;

    for line in base_contents.lines() {
        let trimmed = line.trim();
        if trimmed.starts_with("[agent]") {
            in_agent = true;
            contents.push_str(line);
            contents.push('\n');
            continue;
        }
        if in_agent && trimmed.starts_with('[') {
            if !injected {
                contents.push_str(&format!(
                    "auto_create_missing_cortical_areas = {}\n",
                    auto_create
                ));
                injected = true;
            }
            in_agent = false;
        }
        if in_agent && trimmed.starts_with("auto_create_missing_cortical_areas") {
            contents.push_str(&format!(
                "auto_create_missing_cortical_areas = {}\n",
                auto_create
            ));
            injected = true;
            continue;
        }
        contents.push_str(line);
        contents.push('\n');
    }

    if in_agent && !injected {
        contents.push_str(&format!(
            "auto_create_missing_cortical_areas = {}\n",
            auto_create
        ));
    }

    std::fs::write(&path, contents).expect("Failed to write temp config");

    let previous = std::env::var("FEAGI_CONFIG_PATH").ok();
    std::env::set_var("FEAGI_CONFIG_PATH", &path);

    ConfigEnvGuard { previous, path }
}

#[cfg(feature = "feagi-agent")]
fn sample_device_registrations() -> Value {
    json!({
        "input_units_and_encoder_properties": {
            "Vision": [
                [
                    {
                        "cortical_unit_index": 0,
                        "device_grouping": [{"id": 0}]
                    },
                    {}
                ]
            ]
        },
        "output_units_and_decoder_properties": {
            "RotaryMotor": [
                [
                    {
                        "cortical_unit_index": 0,
                        "device_grouping": [{"id": 0}]
                    },
                    {}
                ]
            ]
        },
        "feedbacks": {}
    })
}

/// Multi-limb device_registrations: 4 limbs (groups 0-3), 3 PositionalServo channels per limb.
#[cfg(feature = "feagi-agent")]
fn sample_multi_limb_device_registrations() -> Value {
    json!({
        "output_units_and_decoder_properties": {
            "PositionalServo": [
                [
                    {
                        "cortical_unit_index": 0,
                        "device_grouping": [{"id": 0}, {"id": 1}, {"id": 2}]
                    },
                    {}
                ],
                [
                    {
                        "cortical_unit_index": 1,
                        "device_grouping": [{"id": 0}, {"id": 1}, {"id": 2}]
                    },
                    {}
                ],
                [
                    {
                        "cortical_unit_index": 2,
                        "device_grouping": [{"id": 0}, {"id": 1}, {"id": 2}]
                    },
                    {}
                ],
                [
                    {
                        "cortical_unit_index": 3,
                        "device_grouping": [{"id": 0}, {"id": 1}, {"id": 2}]
                    },
                    {}
                ]
            ]
        },
        "feedbacks": {}
    })
}

#[cfg(feature = "feagi-agent")]
fn sample_named_motor_device_registrations() -> Value {
    json!({
        "output_units_and_decoder_properties": {
            "PositionalServo": [
                [
                    {
                        "friendly_name": "front_left_leg",
                        "cortical_unit_index": 0,
                        "device_grouping": [
                            {
                                "friendly_name": "front_left_hip",
                                "device_properties": {
                                    "bundle_id": "front_left_leg",
                                    "bundle_type": "leg"
                                }
                            },
                            {
                                "friendly_name": "front_left_knee",
                                "device_properties": {
                                    "bundle_id": "front_left_leg",
                                    "bundle_type": "leg"
                                }
                            }
                        ]
                    },
                    {}
                ]
            ]
        },
        "feedbacks": {}
    })
}

#[cfg(feature = "feagi-agent")]
fn sample_motor_device_registrations_with_io_flags() -> Value {
    json!({
        "output_units_and_decoder_properties": {
            "RotaryMotor": [
                [
                    {
                        "friendly_name": "arm_motor",
                        "cortical_unit_index": 0,
                        "device_grouping": [{"id": 0}, {"id": 1}],
                        "io_configuration_flags": {
                            "frame_change_handling": "Absolute",
                            "percentage_neuron_positioning": "Linear"
                        }
                    },
                    {}
                ]
            ]
        },
        "feedbacks": {}
    })
}

#[cfg(feature = "feagi-agent")]
fn sample_multi_segmented_vision_device_registrations() -> Value {
    json!({
        "input_units_and_encoder_properties": {
            "SegmentedVision": [
                [
                    {
                        "friendly_name": "front_camera_segmented",
                        "cortical_unit_index": 0,
                        "device_grouping": [{"id": 0}]
                    },
                    {
                        "segment_xy_resolutions": {
                            "lower_left": {"width": 32, "height": 32},
                            "lower_middle": {"width": 32, "height": 32},
                            "lower_right": {"width": 32, "height": 32},
                            "middle_left": {"width": 32, "height": 32},
                            "center": {"width": 128, "height": 128},
                            "middle_right": {"width": 32, "height": 32},
                            "upper_left": {"width": 32, "height": 32},
                            "upper_middle": {"width": 32, "height": 32},
                            "upper_right": {"width": 32, "height": 32}
                        },
                        "center_color_channel": "RGB",
                        "peripheral_color_channels": "GrayScale"
                    }
                ],
                [
                    {
                        "friendly_name": "rear_camera_segmented",
                        "cortical_unit_index": 1,
                        "device_grouping": [{"id": 0}]
                    },
                    {
                        "segment_xy_resolutions": {
                            "lower_left": {"width": 32, "height": 32},
                            "lower_middle": {"width": 32, "height": 32},
                            "lower_right": {"width": 32, "height": 32},
                            "middle_left": {"width": 32, "height": 32},
                            "center": {"width": 128, "height": 128},
                            "middle_right": {"width": 32, "height": 32},
                            "upper_left": {"width": 32, "height": 32},
                            "upper_middle": {"width": 32, "height": 32},
                            "upper_right": {"width": 32, "height": 32}
                        },
                        "center_color_channel": "RGB",
                        "peripheral_color_channels": "GrayScale"
                    }
                ]
            ]
        },
        "feedbacks": {}
    })
}

#[cfg(feature = "feagi-agent")]
fn sample_segmented_vision_group1_only_device_registrations() -> Value {
    json!({
        "input_units_and_encoder_properties": {
            "SegmentedVision": [
                [
                    {
                        "friendly_name": "rear_camera_segmented",
                        "cortical_unit_index": 1,
                        "device_grouping": [{"id": 0}]
                    },
                    {
                        "segment_xy_resolutions": {
                            "lower_left": {"width": 32, "height": 32},
                            "lower_middle": {"width": 32, "height": 32},
                            "lower_right": {"width": 32, "height": 32},
                            "middle_left": {"width": 32, "height": 32},
                            "center": {"width": 128, "height": 128},
                            "middle_right": {"width": 32, "height": 32},
                            "upper_left": {"width": 32, "height": 32},
                            "upper_middle": {"width": 32, "height": 32},
                            "upper_right": {"width": 32, "height": 32}
                        },
                        "center_color_channel": "RGB",
                        "peripheral_color_channels": "GrayScale"
                    }
                ]
            ]
        },
        "feedbacks": {}
    })
}

#[cfg(feature = "feagi-agent")]
fn sample_named_sensory_only_device_registrations() -> Value {
    json!({
        "input_units_and_encoder_properties": {
            "Vision": [
                [
                    {
                        "friendly_name": "head_camera",
                        "cortical_unit_index": 0,
                        "device_grouping": [
                            {
                                "friendly_name": "rgb_camera",
                                "device_properties": {
                                    "bundle_id": "head_camera",
                                    "bundle_type": "camera_rig"
                                }
                            }
                        ]
                    },
                    {}
                ]
            ]
        },
        "feedbacks": {}
    })
}

#[cfg(feature = "feagi-agent")]
fn sample_sensory_device_registrations_with_large_vision_encoder() -> Value {
    json!({
        "input_units_and_encoder_properties": {
            "Vision": [
                [
                    {
                        "friendly_name": "head_camera",
                        "cortical_unit_index": 0,
                        "device_grouping": [{"id": 0}]
                    },
                    {
                        "CartesianPlane": {
                            "image_resolution": {
                                "width": 128,
                                "height": 96
                            },
                            "color_space": "Gamma",
                            "color_channel_layout": "RGBA"
                        }
                    }
                ]
            ]
        },
        "feedbacks": {}
    })
}

/// Helper to make a request and get response as JSON
async fn request_json(
    app: axum::Router,
    method: &str,
    path: &str,
    body: Option<Value>,
) -> (StatusCode, Value) {
    let request_builder = Request::builder()
        .uri(path)
        .method(method)
        .header("content-type", "application/json");

    let request = if let Some(body_json) = body {
        request_builder
            .body(Body::from(serde_json::to_vec(&body_json).unwrap()))
            .unwrap()
    } else {
        request_builder.body(Body::empty()).unwrap()
    };

    let response = app.oneshot(request).await.unwrap();
    let status = response.status();

    let body_bytes = axum::body::to_bytes(response.into_body(), usize::MAX)
        .await
        .unwrap();

    let json: Value = if body_bytes.is_empty() {
        json!(null)
    } else {
        serde_json::from_slice(&body_bytes).unwrap_or(json!(null))
    };

    (status, json)
}

// ============================================================================
// HEALTH & SYSTEM TESTS
// ============================================================================

#[tokio::test]
async fn test_health_endpoint() {
    let app = create_test_server().await;

    let (status, response) = request_json(app, "GET", "/v1/system/health_check", None).await;

    assert_eq!(status, StatusCode::OK);
    assert!(response["status"].is_string() || !response.is_null());
}

#[tokio::test]
async fn test_system_status() {
    let app = create_test_server().await;

    let (status, response) = request_json(app, "GET", "/v1/monitoring/status", None).await;

    assert_eq!(status, StatusCode::OK);
    // Response should have burst_engine_active field
    assert!(response.is_object());
}

// ============================================================================
// AGENT REGISTRATION TESTS
// ============================================================================

#[cfg(feature = "feagi-agent")]
#[tokio::test]
async fn test_register_agent_returns_session_and_endpoints() {
    let _state = build_test_state();
    let _descriptor = AgentDescriptor::new("neuraville", "api-test", 1).unwrap();
    let agent_id = AgentID::new_random();
    let auth_token = AuthToken::new([1u8; 32]).to_base64();

    let device_registrations = json!({
        "input_units_and_encoder_properties": { "camera": [] },
        "output_units_and_decoder_properties": {},
        "feedbacks": {}
    });

    let mut capabilities: HashMap<String, Value> = HashMap::new();
    capabilities.insert("device_registrations".to_string(), device_registrations);

    let request = AgentRegistrationRequest {
        agent_type: "visualization".to_string(),
        agent_id: agent_id.to_base64(),
        agent_data_port: 0,
        agent_version: "0.0.0-test".to_string(),
        controller_version: "0.0.0-test".to_string(),
        capabilities,
        agent_ip: None,
        metadata: None,
        auth_token: Some(auth_token),
        chosen_transport: None,
    };

    let response = register_agent(ApiStateExtract(_state), ApiJson(request))
        .await
        .expect("Registration should succeed");
    let body = response.0;

    assert!(body.success);
    let transport = body.transport.expect("Expected transport payload");
    assert!(transport.contains_key("session_id"));
    let endpoints = transport
        .get("endpoints")
        .and_then(|value| value.as_object())
        .expect("Expected endpoints in transport payload");
    assert!(endpoints.contains_key("send_sensor_data"));
}

#[cfg(feature = "feagi-agent")]
#[tokio::test]
async fn test_register_visualization_only_agent_returns_session_and_endpoints() {
    let _state = build_test_state();
    let agent_id = AgentID::new_random();
    let auth_token = AuthToken::new([4u8; 32]).to_base64();

    let mut capabilities: HashMap<String, Value> = HashMap::new();
    capabilities.insert(
        "visualization".to_string(),
        json!({ "visualization_type": "3d_brain", "rate_hz": 20.0, "bridge_proxy": false }),
    );

    let request = AgentRegistrationRequest {
        agent_type: "visualization".to_string(),
        agent_id: agent_id.to_base64(),
        agent_data_port: 0,
        agent_version: "0.0.0-test".to_string(),
        controller_version: "0.0.0-test".to_string(),
        capabilities,
        agent_ip: None,
        metadata: None,
        auth_token: Some(auth_token),
        chosen_transport: None,
    };

    let response = register_agent(ApiStateExtract(_state), ApiJson(request))
        .await
        .expect("Visualization-only registration should succeed");
    let body = response.0;

    assert!(body.success);
    let transport = body.transport.expect("Expected transport payload");
    assert!(transport.contains_key("session_id"));
    let endpoints = transport
        .get("endpoints")
        .and_then(|value| value.as_object())
        .expect("Expected endpoints in transport payload");
    assert!(endpoints.contains_key("receive_neuron_visualizations"));
}

#[cfg(feature = "feagi-agent")]
#[tokio::test]
async fn test_register_agent_rejects_rate_above_burst_frequency() {
    let _state = build_test_state();
    let agent_id = AgentID::new_random();
    let auth_token = AuthToken::new([2u8; 32]).to_base64();

    let mut capabilities: HashMap<String, Value> = HashMap::new();
    capabilities.insert(
        "device_registrations".to_string(),
        sample_device_registrations(),
    );
    capabilities.insert("motor".to_string(), json!({ "rate_hz": 2000.0 }));

    let request = AgentRegistrationRequest {
        agent_type: "motor".to_string(),
        agent_id: agent_id.to_base64(),
        agent_data_port: 0,
        agent_version: "0.0.0-test".to_string(),
        controller_version: "0.0.0-test".to_string(),
        capabilities,
        agent_ip: None,
        metadata: None,
        auth_token: Some(auth_token),
        chosen_transport: None,
    };

    let result = register_agent(ApiStateExtract(_state), ApiJson(request)).await;
    assert!(result.is_err());
}

#[cfg(feature = "feagi-agent")]
#[tokio::test]
async fn test_register_agent_rejects_visualization_rate_above_burst_frequency() {
    let _state = build_test_state();
    let agent_id = AgentID::new_random();
    let auth_token = AuthToken::new([3u8; 32]).to_base64();

    let mut capabilities: HashMap<String, Value> = HashMap::new();
    capabilities.insert(
        "device_registrations".to_string(),
        sample_device_registrations(),
    );
    capabilities.insert("visualization".to_string(), json!({ "rate_hz": 2000.0 }));

    let request = AgentRegistrationRequest {
        agent_type: "visualization".to_string(),
        agent_id: agent_id.to_base64(),
        agent_data_port: 0,
        agent_version: "0.0.0-test".to_string(),
        controller_version: "0.0.0-test".to_string(),
        capabilities,
        agent_ip: None,
        metadata: None,
        auth_token: Some(auth_token),
        chosen_transport: None,
    };

    let result = register_agent(ApiStateExtract(_state), ApiJson(request)).await;
    assert!(result.is_err());
}

#[cfg(feature = "feagi-agent")]
#[tokio::test]
async fn test_auto_create_disabled_skips_creation() {
    let _guard = {
        let _lock = CONFIG_ENV_LOCK
            .get_or_init(|| Mutex::new(()))
            .lock()
            .expect("Failed to lock config env");
        set_temp_config(false)
    };
    let state = build_test_state();

    auto_create_cortical_areas_from_device_registrations(&state, &sample_device_registrations())
        .await;

    let areas = state
        .connectome_service
        .list_cortical_areas()
        .await
        .expect("Failed to list cortical areas");
    assert!(areas.is_empty());
}

#[cfg(feature = "feagi-agent")]
#[tokio::test]
async fn test_auto_create_enabled_creates_areas() {
    let _guard = {
        let _lock = CONFIG_ENV_LOCK
            .get_or_init(|| Mutex::new(()))
            .lock()
            .expect("Failed to lock config env");
        set_temp_config(true)
    };
    let state = build_test_state();

    auto_create_cortical_areas_from_device_registrations(&state, &sample_device_registrations())
        .await;

    let areas = state
        .connectome_service
        .list_cortical_areas()
        .await
        .expect("Failed to list cortical areas");
    assert!(!areas.is_empty());
}

#[cfg(feature = "feagi-agent")]
#[tokio::test]
async fn test_auto_create_creates_all_limb_cortical_areas() {
    let _guard = {
        let _lock = CONFIG_ENV_LOCK
            .get_or_init(|| Mutex::new(()))
            .lock()
            .expect("Failed to lock config env");
        set_temp_config(true)
    };
    let state = build_test_state();

    auto_create_cortical_areas_from_device_registrations(
        &state,
        &sample_multi_limb_device_registrations(),
    )
    .await;

    let areas = state
        .connectome_service
        .list_cortical_areas()
        .await
        .expect("Failed to list cortical areas");
    let motor_areas: Vec<_> = areas
        .iter()
        .filter(|a| a.area_type == "motor" || a.cortical_group == "OPU")
        .collect();
    assert_eq!(
        motor_areas.len(),
        8,
        "Expected 8 PositionalServo areas (abs+inc per limb), got {}",
        motor_areas.len()
    );
    let mut abs_width_count = 0;
    let mut inc_width_count = 0;
    for area in &motor_areas {
        if area.name.ends_with("-1") {
            assert_eq!(
                area.dimensions.0, 6,
                "Incremental subunit width should be 6"
            );
            inc_width_count += 1;
        } else if area.name.ends_with("-0") {
            assert_eq!(area.dimensions.0, 3, "Absolute subunit width should be 3");
            abs_width_count += 1;
        }
        assert_eq!(
            area.properties.get("dev_count").and_then(|v| v.as_u64()),
            Some(3),
            "Each limb area should have dev_count=3"
        );
    }
    assert_eq!(abs_width_count, 4, "Expected 4 absolute limb areas");
    assert_eq!(inc_width_count, 4, "Expected 4 incremental limb areas");
}

#[cfg(feature = "feagi-agent")]
#[tokio::test]
async fn test_auto_create_places_segmented_vision_groups_horizontally_by_unit_index() {
    let _guard = {
        let _lock = CONFIG_ENV_LOCK
            .get_or_init(|| Mutex::new(()))
            .lock()
            .expect("Failed to lock config env");
        set_temp_config(true)
    };
    let state = build_test_state();
    let registrations = sample_multi_segmented_vision_device_registrations();

    auto_create_cortical_areas_from_device_registrations(&state, &registrations).await;

    let areas = state
        .connectome_service
        .list_cortical_areas()
        .await
        .expect("Failed to list cortical areas");

    let mut group0_by_subunit: HashMap<u8, (i32, i32, i32)> = HashMap::new();
    let mut group1_by_subunit: HashMap<u8, (i32, i32, i32)> = HashMap::new();

    for area in &areas {
        let Ok(bytes) = general_purpose::STANDARD.decode(&area.cortical_id) else {
            continue;
        };
        if bytes.len() != 8 {
            continue;
        }
        if bytes[0] != b'i' || &bytes[1..4] != b"svi" {
            continue;
        }
        let subunit_index = bytes[6];
        let group_index = bytes[7];
        if group_index == 0 {
            group0_by_subunit.insert(subunit_index, area.position);
        } else if group_index == 1 {
            group1_by_subunit.insert(subunit_index, area.position);
        }
    }

    assert_eq!(
        group0_by_subunit.len(),
        9,
        "Expected 9 segmented-vision subunits for group 0"
    );
    assert_eq!(
        group1_by_subunit.len(),
        9,
        "Expected 9 segmented-vision subunits for group 1"
    );

    for subunit in 0u8..9u8 {
        let pos0 = group0_by_subunit
            .get(&subunit)
            .expect("Missing segmented-vision subunit in group 0");
        let pos1 = group1_by_subunit
            .get(&subunit)
            .expect("Missing segmented-vision subunit in group 1");

        assert_eq!(
            pos0.1, pos1.1,
            "Expected Y to match template for both segmented groups (subunit {})",
            subunit
        );
        assert_eq!(
            pos0.2, pos1.2,
            "Expected Z to match template for both segmented groups (subunit {})",
            subunit
        );
        assert!(
            pos1.0 > pos0.0,
            "Expected group 1 subunit {} to be to the right of group 0 (x1={}, x0={})",
            subunit,
            pos1.0,
            pos0.0
        );
    }

    let group0_max_x = group0_by_subunit
        .values()
        .map(|(x, _, _)| *x)
        .max()
        .expect("Group 0 should not be empty");
    let group1_min_x = group1_by_subunit
        .values()
        .map(|(x, _, _)| *x)
        .min()
        .expect("Group 1 should not be empty");
    assert!(
        group1_min_x > group0_max_x,
        "Expected segmented-vision group 1 assembly to be placed to the right of group 0 assembly"
    );
}

#[cfg(feature = "feagi-agent")]
#[tokio::test]
async fn test_auto_create_aligns_segmented_vision_yz_to_existing_scene_group() {
    let _guard = {
        let _lock = CONFIG_ENV_LOCK
            .get_or_init(|| Mutex::new(()))
            .lock()
            .expect("Failed to lock config env");
        set_temp_config(true)
    };
    let state = build_test_state();

    // Seed the scene with an existing segmented-vision group (group 0) at custom Y/Z positions.
    let mut config = serde_json::Map::new();
    config.insert(
        "frame_change_handling".to_string(),
        serde_json::to_value(FrameChangeHandling::Absolute).expect("Serialize frame handling"),
    );
    config.insert(
        "percentage_neuron_positioning".to_string(),
        serde_json::to_value(PercentageNeuronPositioning::Linear)
            .expect("Serialize percentage neuron positioning"),
    );

    let existing_ids = SensoryCorticalUnit::SegmentedVision
        .get_cortical_id_vector_from_index_and_serde_io_configuration_flags(
            CorticalUnitIndex::from(0u8),
            config,
        )
        .expect("Generate segmented-vision cortical IDs for group 0");

    let mut existing_params: Vec<CreateCorticalAreaParams> = Vec::new();
    for (subunit, cortical_id) in existing_ids.iter().enumerate() {
        let subunit_i32 = subunit as i32;
        existing_params.push(CreateCorticalAreaParams {
            cortical_id: cortical_id.as_base_64(),
            name: format!("seeded-segmented-{}", subunit),
            dimensions: if subunit == 4 {
                (128, 128, 3)
            } else {
                (32, 32, 1)
            },
            position: (-100 + subunit_i32, 200 + subunit_i32, -300 - subunit_i32),
            area_type: "sensory".to_string(),
            visible: None,
            sub_group: None,
            neurons_per_voxel: None,
            postsynaptic_current: None,
            plasticity_constant: None,
            degeneration: None,
            psp_uniform_distribution: None,
            firing_threshold_increment: None,
            firing_threshold_limit: None,
            consecutive_fire_count: None,
            snooze_period: None,
            refractory_period: None,
            leak_coefficient: None,
            leak_variability: None,
            burst_engine_active: None,
            properties: None,
        });
    }

    state
        .genome_service
        .create_cortical_areas(existing_params)
        .await
        .expect("Seed existing segmented-vision group");

    auto_create_cortical_areas_from_device_registrations(
        &state,
        &sample_segmented_vision_group1_only_device_registrations(),
    )
    .await;

    let areas = state
        .connectome_service
        .list_cortical_areas()
        .await
        .expect("Failed to list cortical areas");

    let mut group0_by_subunit: HashMap<u8, (i32, i32, i32)> = HashMap::new();
    let mut group1_by_subunit: HashMap<u8, (i32, i32, i32)> = HashMap::new();
    for area in &areas {
        let Ok(bytes) = general_purpose::STANDARD.decode(&area.cortical_id) else {
            continue;
        };
        if bytes.len() != 8 || bytes[0] != b'i' || &bytes[1..4] != b"svi" {
            continue;
        }
        let subunit_index = bytes[6];
        let group_index = bytes[7];
        if group_index == 0 {
            group0_by_subunit.insert(subunit_index, area.position);
        } else if group_index == 1 {
            group1_by_subunit.insert(subunit_index, area.position);
        }
    }

    assert_eq!(
        group0_by_subunit.len(),
        9,
        "Expected seeded group 0 subunits"
    );
    assert_eq!(
        group1_by_subunit.len(),
        9,
        "Expected newly created group 1 subunits"
    );

    for subunit in 0u8..9u8 {
        let pos0 = group0_by_subunit
            .get(&subunit)
            .expect("Missing seeded group 0 subunit");
        let pos1 = group1_by_subunit
            .get(&subunit)
            .expect("Missing created group 1 subunit");

        assert_eq!(
            pos1.1, pos0.1,
            "Expected group 1 subunit {} Y to align with existing segmented group",
            subunit
        );
        assert_eq!(
            pos1.2, pos0.2,
            "Expected group 1 subunit {} Z to align with existing segmented group",
            subunit
        );
        assert!(
            pos1.0 > pos0.0,
            "Expected group 1 subunit {} X to be to the right after horizontal expansion",
            subunit
        );
    }
}

#[cfg(feature = "feagi-agent")]
#[tokio::test]
async fn test_auto_create_segmented_vision_falls_back_to_template_yz_when_existing_anchor_incomplete(
) {
    let _guard = {
        let _lock = CONFIG_ENV_LOCK
            .get_or_init(|| Mutex::new(()))
            .lock()
            .expect("Failed to lock config env");
        set_temp_config(true)
    };
    let state = build_test_state();

    // Seed an INCOMPLETE existing segmented-vision group (group 0): only one subunit.
    let mut config = serde_json::Map::new();
    config.insert(
        "frame_change_handling".to_string(),
        serde_json::to_value(FrameChangeHandling::Absolute).expect("Serialize frame handling"),
    );
    config.insert(
        "percentage_neuron_positioning".to_string(),
        serde_json::to_value(PercentageNeuronPositioning::Linear)
            .expect("Serialize percentage neuron positioning"),
    );
    let existing_ids = SensoryCorticalUnit::SegmentedVision
        .get_cortical_id_vector_from_index_and_serde_io_configuration_flags(
            CorticalUnitIndex::from(0u8),
            config,
        )
        .expect("Generate segmented-vision cortical IDs for group 0");

    state
        .genome_service
        .create_cortical_areas(vec![CreateCorticalAreaParams {
            cortical_id: existing_ids[0].as_base_64(),
            name: "seeded-incomplete-segmented-0".to_string(),
            dimensions: (32, 32, 1),
            position: (999, 777, 555),
            area_type: "sensory".to_string(),
            visible: None,
            sub_group: None,
            neurons_per_voxel: None,
            postsynaptic_current: None,
            plasticity_constant: None,
            degeneration: None,
            psp_uniform_distribution: None,
            firing_threshold_increment: None,
            firing_threshold_limit: None,
            consecutive_fire_count: None,
            snooze_period: None,
            refractory_period: None,
            leak_coefficient: None,
            leak_variability: None,
            burst_engine_active: None,
            properties: None,
        }])
        .await
        .expect("Seed incomplete segmented-vision anchor");

    auto_create_cortical_areas_from_device_registrations(
        &state,
        &sample_segmented_vision_group1_only_device_registrations(),
    )
    .await;

    let areas = state
        .connectome_service
        .list_cortical_areas()
        .await
        .expect("Failed to list cortical areas");

    let mut group1_by_subunit: HashMap<u8, (i32, i32, i32)> = HashMap::new();
    for area in &areas {
        let Ok(bytes) = general_purpose::STANDARD.decode(&area.cortical_id) else {
            continue;
        };
        if bytes.len() != 8 || bytes[0] != b'i' || &bytes[1..4] != b"svi" {
            continue;
        }
        if bytes[7] == 1 {
            group1_by_subunit.insert(bytes[6], area.position);
        }
    }

    assert_eq!(
        group1_by_subunit.len(),
        9,
        "Expected complete group 1 segmented-vision creation"
    );

    // Subunit 0 template-relative Y/Z for segmented vision is (-70, 0) in sensory template.
    // With an incomplete anchor, Y/Z must come from template (not the seeded 777/555).
    let subunit0 = group1_by_subunit
        .get(&0)
        .expect("Missing group 1 subunit 0");
    assert_eq!(
        subunit0.1, -70,
        "Expected template Y when existing segmented anchor is incomplete"
    );
    assert_eq!(
        subunit0.2, 0,
        "Expected template Z when existing segmented anchor is incomplete"
    );
}

#[cfg(feature = "feagi-agent")]
#[tokio::test]
async fn test_auto_create_uses_registration_friendly_name_for_motor_areas() {
    let _guard = {
        let _lock = CONFIG_ENV_LOCK
            .get_or_init(|| Mutex::new(()))
            .lock()
            .expect("Failed to lock config env");
        set_temp_config(true)
    };
    let state = build_test_state();

    auto_create_cortical_areas_from_device_registrations(
        &state,
        &sample_named_motor_device_registrations(),
    )
    .await;

    let areas = state
        .connectome_service
        .list_cortical_areas()
        .await
        .expect("Failed to list cortical areas");
    assert!(
        areas
            .iter()
            .any(|area| area.name.starts_with("front_left_leg")),
        "Expected created motor area names to use registration friendly name"
    );
}

#[cfg(feature = "feagi-agent")]
#[tokio::test]
async fn test_auto_create_sets_firing_threshold_for_simple_vision() {
    let _guard = {
        let _lock = CONFIG_ENV_LOCK
            .get_or_init(|| Mutex::new(()))
            .lock()
            .expect("Failed to lock config env");
        set_temp_config(true)
    };
    let state = build_test_state();

    auto_create_cortical_areas_from_device_registrations(&state, &sample_device_registrations())
        .await;

    let areas = state
        .connectome_service
        .list_cortical_areas()
        .await
        .expect("Failed to list cortical areas");
    let vision_area = areas
        .iter()
        .find(|area| {
            general_purpose::STANDARD
                .decode(&area.cortical_id)
                .ok()
                .is_some_and(|bytes| bytes.len() == 8 && bytes[0] == b'i' && &bytes[1..4] == b"img")
        })
        .expect("Expected simple vision area to be auto-created");

    assert_eq!(
        vision_area.firing_threshold, 150.0,
        "Expected simple vision auto-created area firing_threshold=150.0"
    );
    assert!(
        !vision_area.mp_charge_accumulation,
        "Expected simple vision auto-created area mp_charge_accumulation=false"
    );
}

#[cfg(feature = "feagi-agent")]
#[tokio::test]
async fn test_auto_create_sets_firing_threshold_for_segmented_vision() {
    let _guard = {
        let _lock = CONFIG_ENV_LOCK
            .get_or_init(|| Mutex::new(()))
            .lock()
            .expect("Failed to lock config env");
        set_temp_config(true)
    };
    let state = build_test_state();

    auto_create_cortical_areas_from_device_registrations(
        &state,
        &sample_multi_segmented_vision_device_registrations(),
    )
    .await;

    let areas = state
        .connectome_service
        .list_cortical_areas()
        .await
        .expect("Failed to list cortical areas");

    let segmented_vision_areas: Vec<_> = areas
        .iter()
        .filter(|area| {
            general_purpose::STANDARD
                .decode(&area.cortical_id)
                .ok()
                .is_some_and(|bytes| bytes.len() == 8 && bytes[0] == b'i' && &bytes[1..4] == b"svi")
        })
        .collect();

    assert!(
        !segmented_vision_areas.is_empty(),
        "Expected segmented vision areas to be auto-created"
    );
    for area in segmented_vision_areas {
        assert_eq!(
            area.firing_threshold, 150.0,
            "Expected segmented vision area {} firing_threshold=150.0",
            area.cortical_id
        );
        assert!(
            !area.mp_charge_accumulation,
            "Expected segmented vision area {} mp_charge_accumulation=false",
            area.cortical_id
        );
    }
}

#[cfg(feature = "feagi-agent")]
#[tokio::test]
async fn test_auto_create_supports_sensory_only_registrations() {
    let _guard = {
        let _lock = CONFIG_ENV_LOCK
            .get_or_init(|| Mutex::new(()))
            .lock()
            .expect("Failed to lock config env");
        set_temp_config(true)
    };
    let state = build_test_state();

    auto_create_cortical_areas_from_device_registrations(
        &state,
        &sample_named_sensory_only_device_registrations(),
    )
    .await;

    let areas = state
        .connectome_service
        .list_cortical_areas()
        .await
        .expect("Failed to list cortical areas");
    assert!(
        areas.iter().any(|area| area.name == "head_camera"),
        "Expected sensory-only registration to create sensory area with registration name"
    );
}

#[cfg(feature = "feagi-agent")]
#[tokio::test]
async fn test_auto_create_updates_existing_sensory_area_dimensions_from_encoder_properties() {
    let _guard = {
        let _lock = CONFIG_ENV_LOCK
            .get_or_init(|| Mutex::new(()))
            .lock()
            .expect("Failed to lock config env");
        set_temp_config(true)
    };
    let state = build_test_state();
    let registrations = sample_sensory_device_registrations_with_large_vision_encoder();
    let sensory_ids = derive_sensory_cortical_ids_from_device_registrations(&registrations)
        .expect("Failed deriving sensory cortical IDs");
    let cortical_id = sensory_ids
        .into_iter()
        .next()
        .expect("Expected a vision cortical ID");

    // Pre-create an undersized sensory area to verify auto-create update logic expands it.
    state
        .genome_service
        .create_cortical_areas(vec![CreateCorticalAreaParams {
            cortical_id: cortical_id.clone(),
            name: "legacy_vision".to_string(),
            dimensions: (64, 64, 3),
            position: (-100, 30, 0),
            area_type: "sensory".to_string(),
            visible: None,
            sub_group: None,
            neurons_per_voxel: None,
            postsynaptic_current: None,
            plasticity_constant: None,
            degeneration: None,
            psp_uniform_distribution: None,
            firing_threshold_increment: None,
            firing_threshold_limit: None,
            consecutive_fire_count: None,
            snooze_period: None,
            refractory_period: None,
            leak_coefficient: None,
            leak_variability: None,
            burst_engine_active: None,
            properties: None,
        }])
        .await
        .expect("Failed to pre-create sensory area");

    auto_create_cortical_areas_from_device_registrations(&state, &registrations).await;

    let areas = state
        .connectome_service
        .list_cortical_areas()
        .await
        .expect("Failed to list cortical areas");
    let resized = areas
        .iter()
        .find(|area| area.cortical_id == cortical_id)
        .expect("Expected sensory area to exist after auto-create");

    assert_eq!(
        resized.dimensions,
        (128, 96, 4),
        "Expected sensory area dimensions to expand to encoder properties"
    );
    assert_eq!(
        resized.position,
        (-100, 30, 0),
        "Existing sensory area position must remain unchanged during auto-create reconciliation"
    );
}

#[cfg(feature = "feagi-agent")]
#[tokio::test]
async fn test_auto_create_preserves_existing_motor_area_position_while_reconciling_structure() {
    let _guard = {
        let _lock = CONFIG_ENV_LOCK
            .get_or_init(|| Mutex::new(()))
            .lock()
            .expect("Failed to lock config env");
        set_temp_config(true)
    };
    let state = build_test_state();
    let registrations = sample_motor_device_registrations_with_io_flags();
    let motor_ids = derive_motor_cortical_ids_from_device_registrations(&registrations)
        .expect("Failed deriving motor cortical IDs");
    let cortical_id = motor_ids
        .into_iter()
        .next()
        .expect("Expected at least one motor cortical ID");
    let preserved_position = (777, 888, 9);

    state
        .genome_service
        .create_cortical_areas(vec![CreateCorticalAreaParams {
            cortical_id: cortical_id.clone(),
            name: "legacy_motor".to_string(),
            dimensions: (1, 1, 1),
            position: preserved_position,
            area_type: "motor".to_string(),
            visible: None,
            sub_group: None,
            neurons_per_voxel: None,
            postsynaptic_current: None,
            plasticity_constant: None,
            degeneration: None,
            psp_uniform_distribution: None,
            firing_threshold_increment: None,
            firing_threshold_limit: None,
            consecutive_fire_count: None,
            snooze_period: None,
            refractory_period: None,
            leak_coefficient: None,
            leak_variability: None,
            burst_engine_active: None,
            properties: None,
        }])
        .await
        .expect("Failed to pre-create motor area");

    auto_create_cortical_areas_from_device_registrations(&state, &registrations).await;

    let areas = state
        .connectome_service
        .list_cortical_areas()
        .await
        .expect("Failed to list cortical areas");
    let reconciled = areas
        .iter()
        .find(|area| area.cortical_id == cortical_id)
        .expect("Expected motor area to exist after auto-create");

    assert_eq!(
        reconciled.position, preserved_position,
        "Existing motor area position must remain unchanged during auto-create reconciliation"
    );
    assert_ne!(
        reconciled.dimensions,
        (1, 1, 1),
        "Expected motor dimensions to reconcile from registration while preserving position"
    );
    assert_eq!(
        reconciled
            .properties
            .get("dev_count")
            .and_then(|v| v.as_u64()),
        Some(2),
        "Expected motor dev_count to reconcile from registration while preserving position"
    );
}

#[cfg(feature = "feagi-agent")]
#[tokio::test]
async fn test_genome_transition_clears_agents_subscriptions_and_blocks_sensory_until_reregister() {
    let tracker = Arc::new(RuntimeTransitionTracker::default());
    let runtime_service = Arc::new(TrackingRuntimeService::new(Arc::clone(&tracker)))
        as Arc<dyn RuntimeService + Send + Sync>;

    let mut state = build_test_state();
    state.runtime_service = runtime_service.clone();
    let handler = Arc::new(Mutex::new(feagi_agent::server::FeagiAgentHandler::new(
        Box::new(feagi_agent::server::auth::DummyAuth {}),
    )));
    state.agent_handler = Some(Arc::clone(&handler));

    let session_id = AgentID::new([7u8; AgentID::NUMBER_BYTES]);
    let descriptor = AgentDescriptor::new("neuraville", "transition-test-agent", 1)
        .expect("descriptor creation failed");
    {
        let mut guard = handler.lock().unwrap();
        guard.register_logical_agent(
            session_id,
            descriptor.clone(),
            vec![
                AgentCapabilities::SendSensorData,
                AgentCapabilities::ReceiveMotorData,
            ],
        );
    }
    let session_id_b64 = session_id.to_base64();
    assert_eq!(
        handler.lock().unwrap().get_all_registered_agents().len(),
        1,
        "expected an active registered agent before genome load"
    );

    runtime_service
        .register_motor_subscriptions(&session_id_b64, vec!["b21vdAUAAAA=".to_string()], 10.0)
        .await
        .expect("failed to seed motor subscriptions");
    runtime_service
        .register_visualization_subscriptions(&session_id_b64, 10.0)
        .await
        .expect("failed to seed visualization subscriptions");

    // Use a malformed genome payload so load fails fast while still exercising
    // strict transition teardown logic that runs before genome parsing/loading.
    let bad_genome_value = json!({"invalid": "payload"});
    let transition_result =
        post_upload(ApiStateExtract(state.clone()), ApiJson(bad_genome_value)).await;
    assert!(
        transition_result.is_err(),
        "expected malformed genome upload to fail"
    );

    assert_eq!(
        handler.lock().unwrap().get_all_registered_agents().len(),
        0,
        "agent list should be empty after genome transition"
    );
    assert!(
        tracker.motor_subscriptions.lock().unwrap().is_empty(),
        "motor subscriptions should be empty after genome transition"
    );
    assert!(
        tracker
            .visualization_subscriptions
            .lock()
            .unwrap()
            .is_empty(),
        "visualization subscriptions should be empty after genome transition"
    );

    // Before re-registration there is no active transport session, so handler
    // polling cannot consume sensory frames.
    {
        let mut guard = handler.lock().unwrap();
        assert!(
            guard
                .poll_agent_sensors()
                .expect("polling sensory should not fail")
                .is_none(),
            "sensory must not be consumed after genome transition before re-registration"
        );
    }

    // Re-registration path: a new logical session can be added after transition.
    let new_session_id = AgentID::new([9u8; AgentID::NUMBER_BYTES]);
    {
        let mut guard = handler.lock().unwrap();
        guard.register_logical_agent(
            new_session_id,
            descriptor,
            vec![
                AgentCapabilities::SendSensorData,
                AgentCapabilities::ReceiveMotorData,
            ],
        );
    }
    assert_eq!(
        handler.lock().unwrap().get_all_registered_agents().len(),
        1,
        "agent should reappear only after explicit re-registration"
    );
}

#[cfg(feature = "feagi-agent")]
#[tokio::test]
async fn test_force_deregister_preserves_descriptor_device_registrations_for_reconnect() {
    let mut handler = FeagiAgentHandler::new(Box::new(DummyAuth {}));
    let descriptor =
        AgentDescriptor::new("neuraville", "mujoco-agent", 1).expect("descriptor creation failed");
    let initial_session = AgentID::new([3u8; AgentID::NUMBER_BYTES]);

    handler.set_device_registrations_by_descriptor(
        initial_session.to_base64(),
        descriptor.clone(),
        json!({
            "outputs": {
                "servo": {
                    "type": "opu",
                    "properties": {"feagi_index": 0}
                }
            }
        }),
    );
    handler.register_logical_agent(
        initial_session,
        descriptor.clone(),
        vec![AgentCapabilities::ReceiveMotorData],
    );

    let removed = handler.force_deregister_all_agents("test transition");
    assert_eq!(removed.len(), 1, "expected one agent to be deregistered");
    assert!(
        handler.get_all_registered_agents().is_empty(),
        "all active agent sessions must be removed"
    );
    assert!(
        handler
            .get_device_registrations_by_descriptor(&descriptor)
            .is_some(),
        "descriptor device registrations should persist for reconnect mapping"
    );
}

#[cfg(feature = "feagi-agent")]
#[tokio::test]
#[ignore = "real transport path can hang in CI; run manually for websocket validation"]
async fn test_genome_transition_realtime_transport_requires_reregistration() {
    let tracker = Arc::new(RuntimeTransitionTracker::default());
    let runtime_service = Arc::new(TrackingRuntimeService::new(Arc::clone(&tracker)))
        as Arc<dyn RuntimeService + Send + Sync>;

    let mut state = build_test_state();
    state.runtime_service = runtime_service.clone();
    let host = Ipv4Addr::LOCALHOST.to_string();
    let registration_port = reserve_free_port();
    let sensory_port = reserve_free_port();
    let motor_port = reserve_free_port();
    let viz_port = reserve_free_port();
    let registration_bind = format!("{host}:{registration_port}");
    let registration_remote = format!("ws://{host}:{registration_port}");
    let sensory_bind = format!("{host}:{sensory_port}");
    let sensory_remote = format!("ws://{host}:{sensory_port}");
    let motor_bind = format!("{host}:{motor_port}");
    let motor_remote = format!("ws://{host}:{motor_port}");
    let viz_bind = format!("{host}:{viz_port}");
    let viz_remote = format!("ws://{host}:{viz_port}");

    let mut test_handler = FeagiAgentHandler::new_with_liveness_config(
        Box::new(DummyAuth {}),
        AgentLivenessConfig::default(),
    );
    test_handler
        .add_and_start_command_control_server(Box::new(
            FeagiWebSocketServerRouterProperties::new_with_remote(
                &registration_bind,
                &registration_remote,
            )
            .expect("failed to create websocket router properties"),
        ))
        .expect("failed to start websocket command/control router");
    test_handler.add_puller_server(Box::new(
        FeagiWebSocketServerPullerProperties::new_with_remote(&sensory_bind, &sensory_remote)
            .expect("failed to create websocket sensory puller properties"),
    ));
    test_handler.add_publisher_server(Box::new(
        FeagiWebSocketServerPublisherProperties::new(&motor_bind, &motor_remote)
            .expect("failed to create websocket motor publisher properties"),
    ));
    test_handler.add_publisher_server(Box::new(
        FeagiWebSocketServerPublisherProperties::new(&viz_bind, &viz_remote)
            .expect("failed to create websocket viz publisher properties"),
    ));
    let handler = Arc::new(Mutex::new(test_handler));
    state.agent_handler = Some(Arc::clone(&handler));

    let registration_endpoint = {
        let guard = handler.lock().unwrap();
        guard
            .get_command_control_server_info()
            .into_iter()
            .next()
            .expect("no command/control server available")
            .get_agent_endpoint()
    };

    let mut client = CommandControlAgent::new(
        registration_endpoint
            .try_create_boxed_client_requester_properties()
            .expect("failed to create requester properties"),
    );
    client.request_connect().expect("client connect failed");
    client
        .request_registration(
            AgentDescriptor::new("neuraville", "transition-rt-agent", 1)
                .expect("descriptor creation failed"),
            AuthToken::new([0u8; 32]),
            vec![
                AgentCapabilities::SendSensorData,
                AgentCapabilities::ReceiveMotorData,
            ],
        )
        .expect("registration request failed");

    let (session_id_b64, sensory_endpoint) =
        wait_for_registered_agent(&handler, &mut client, Duration::from_secs(5));
    assert_eq!(
        handler.lock().unwrap().get_all_registered_agents().len(),
        1,
        "expected an active registered agent before genome load"
    );

    runtime_service
        .register_motor_subscriptions(&session_id_b64, vec!["b21vdAUAAAA=".to_string()], 10.0)
        .await
        .expect("failed to seed motor subscriptions");
    runtime_service
        .register_visualization_subscriptions(&session_id_b64, 10.0)
        .await
        .expect("failed to seed visualization subscriptions");

    let pusher_props = sensory_endpoint
        .try_create_boxed_client_pusher_properties()
        .expect("failed to create sensory pusher properties");
    let mut sensory_pusher = pusher_props.as_boxed_client_pusher();
    sensory_pusher
        .request_connect()
        .expect("sensory pusher connect failed");
    let pre_payload: FeagiByteContainer = FeagiMessage::HeartBeat.into();
    sensory_pusher
        .publish_data(pre_payload.get_byte_ref())
        .expect("failed to publish pre-load sensory payload");
    assert!(
        wait_for_sensory_data(&handler, Duration::from_secs(2)),
        "expected sensory data to be consumed before genome transition"
    );

    let bad_genome_value = json!({"invalid": "payload"});
    let transition_result =
        post_upload(ApiStateExtract(state.clone()), ApiJson(bad_genome_value)).await;
    assert!(
        transition_result.is_err(),
        "expected malformed genome upload to fail"
    );

    assert_eq!(
        handler.lock().unwrap().get_all_registered_agents().len(),
        0,
        "agent list should be empty after genome transition"
    );
    assert!(
        tracker.motor_subscriptions.lock().unwrap().is_empty(),
        "motor subscriptions should be empty after genome transition"
    );
    assert!(
        tracker
            .visualization_subscriptions
            .lock()
            .unwrap()
            .is_empty(),
        "visualization subscriptions should be empty after genome transition"
    );

    let post_payload: FeagiByteContainer = FeagiMessage::HeartBeat.into();
    let _ = sensory_pusher.publish_data(post_payload.get_byte_ref());
    assert!(
        !wait_for_sensory_data(&handler, Duration::from_millis(500)),
        "sensory data must not be consumed after genome transition before re-registration"
    );

    let mut reconnected_client = CommandControlAgent::new(
        registration_endpoint
            .try_create_boxed_client_requester_properties()
            .expect("failed to create requester properties for reconnect"),
    );
    reconnected_client
        .request_connect()
        .expect("reconnect client connect failed");
    reconnected_client
        .request_registration(
            AgentDescriptor::new("neuraville", "transition-rt-agent", 1)
                .expect("descriptor creation failed on reconnect"),
            AuthToken::new([0u8; 32]),
            vec![
                AgentCapabilities::SendSensorData,
                AgentCapabilities::ReceiveMotorData,
            ],
        )
        .expect("reconnect registration request failed");
    let (_new_session, new_sensory_endpoint) =
        wait_for_registered_agent(&handler, &mut reconnected_client, Duration::from_secs(5));

    let new_pusher_props = new_sensory_endpoint
        .try_create_boxed_client_pusher_properties()
        .expect("failed to create new sensory pusher properties");
    let mut new_sensory_pusher = new_pusher_props.as_boxed_client_pusher();
    new_sensory_pusher
        .request_connect()
        .expect("new sensory pusher connect failed");
    let rereg_payload: FeagiByteContainer = FeagiMessage::HeartBeat.into();
    new_sensory_pusher
        .publish_data(rereg_payload.get_byte_ref())
        .expect("failed to publish sensory payload after re-registration");
    assert!(
        wait_for_sensory_data(&handler, Duration::from_secs(2)),
        "sensory data should be consumed again after re-registration"
    );
}

// ============================================================================
// CORTICAL AREA TESTS
// ============================================================================

#[tokio::test]
async fn test_create_cortical_area_success() {
    let app = create_test_server().await;

    let create_request = json!({
        "cortical_id": "iinf",
        "cortical_type": "IPU",
        "device_count": 1,
        "coordinates_3d": [0, 0, 0],
        "data_type_configs_by_subunit": {
            "0": 0
        },
        "neurons_per_voxel": 1
    });

    let (status, response) = request_json(
        app,
        "POST",
        "/v1/cortical_area/cortical_area",
        Some(create_request),
    )
    .await;

    assert_eq!(status, StatusCode::OK, "response: {}", response);
    assert!(response.get("cortical_id").is_some());
}

#[tokio::test]
async fn test_create_cortical_area_invalid_id() {
    let app = create_test_server().await;

    // Invalid ID (not 6 characters)
    let create_request = json!({
        "cortical_id": "invalid",
        "cortical_type": "IPU",
        "device_count": 1,
        "coordinates_3d": [0, 0, 0],
        "data_type_configs_by_subunit": {
            "0": 0
        },
        "neurons_per_voxel": 1
    });

    let (status, _response) = request_json(
        app,
        "POST",
        "/v1/cortical_area/cortical_area",
        Some(create_request),
    )
    .await;

    assert_eq!(status, StatusCode::BAD_REQUEST);
}

#[tokio::test]
async fn test_get_cortical_area_not_found() {
    let app = create_test_server().await;

    let (status, response) = request_json(
        app,
        "GET",
        "/v1/connectome/area_details?area_ids=notfnd",
        None,
    )
    .await;

    assert_eq!(status, StatusCode::OK, "response: {}", response);
    assert!(response.as_object().map(|o| o.is_empty()).unwrap_or(false));
}

#[tokio::test]
async fn test_list_cortical_areas_empty() {
    let app = create_test_server().await;

    let (status, response) =
        request_json(app, "GET", "/v1/cortical_area/cortical_area_id_list", None).await;

    assert_eq!(status, StatusCode::OK);
    let cortical_ids = response
        .get("cortical_ids")
        .and_then(|v| v.as_array())
        .expect("Expected cortical_ids array");
    assert!(cortical_ids.is_empty());
}

#[tokio::test]
async fn test_create_and_get_cortical_area() {
    let app = create_test_server().await;

    // Create
    let create_request = json!({
        "cortical_id": "iinf",
        "cortical_type": "IPU",
        "device_count": 1,
        "coordinates_3d": [0, 0, 0],
        "data_type_configs_by_subunit": {
            "0": 0
        },
        "neurons_per_voxel": 1
    });

    let (status, response) = request_json(
        app,
        "POST",
        "/v1/cortical_area/cortical_area",
        Some(create_request),
    )
    .await;
    assert_eq!(status, StatusCode::OK);
    let created_id = response
        .get("cortical_id")
        .and_then(|v| v.as_str())
        .expect("Expected cortical_id in response")
        .to_string();

    // Get - need to recreate app because oneshot consumes it
    let app2 = create_test_server().await;
    let (status2, response2) = request_json(
        app2,
        "GET",
        &format!("/v1/connectome/area_details?area_ids={}", created_id),
        None,
    )
    .await;

    // Fresh manager: created area not present
    assert_eq!(status2, StatusCode::OK);
    assert!(response2.as_object().map(|o| o.is_empty()).unwrap_or(false));
}

// ============================================================================
// GENOME TESTS
// ============================================================================

#[tokio::test]
async fn test_genome_validate_minimal() {
    let app = create_test_server().await;

    // Minimal valid genome
    let genome = json!({
        "blueprint": {
            "cortical_areas": {}
        }
    });

    let (status, response) = request_json(
        app,
        "POST",
        "/v1/genome/validate",
        Some(json!({ "genome_json": genome.to_string() })),
    )
    .await;

    assert_eq!(status, StatusCode::OK);
    // Response should indicate validation result
    assert!(response.is_object());
}

// ============================================================================
// ERROR FORMAT TESTS
// ============================================================================

#[tokio::test]
async fn test_error_format_consistency() {
    let app = create_test_server().await;

    // All error responses should have consistent format
    let (status, response) = request_json(
        app,
        "POST",
        "/v1/cortical_area/cortical_area",
        Some(json!({})),
    )
    .await;

    assert_eq!(status, StatusCode::BAD_REQUEST);
    // Should have some error information
    assert!(response.is_object() || response.is_string());
}

#[test]
fn test_compilation() {
    // This test just ensures the code compiles
}