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
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
"""Tests for core/graph.py — RoleGraph and dynamic operations."""

import json
import tempfile

import pytest
import rustworkx as rx
import torch

from core.graph import (
    GraphIntegrityError,
    RoleGraph,
    StateMigrationPolicy,
)
from utils.state_storage import FileStateStorage, InMemoryStateStorage


class TestRoleGraphCreation:
    def test_empty_graph(self):
        graph = RoleGraph()
        assert graph.num_nodes == 0
        assert graph.num_edges == 0
        assert graph.node_ids == []

    def test_graph_with_nodes(self):
        g = rx.PyDiGraph()
        g.add_node({"id": "a"})
        g.add_node({"id": "b"})

        graph = RoleGraph(
            node_ids=["a", "b"],
            graph=g,
        )

        assert graph.num_nodes == 2
        assert "a" in graph.node_ids
        assert "b" in graph.node_ids

    def test_graph_with_edges(self):
        g = rx.PyDiGraph()
        g.add_node({"id": "a"})
        g.add_node({"id": "b"})
        g.add_edge(0, 1, {"weight": 0.5})

        graph = RoleGraph(
            node_ids=["a", "b"],
            role_connections={"a": ["b"], "b": []},
            graph=g,
        )

        assert graph.num_edges == 1
        edges = graph.edges
        assert len(edges) == 1
        assert edges[0]["source"] == "a"
        assert edges[0]["target"] == "b"


class TestAddNode:
    def test_add_node_basic(self):
        from core.agent import AgentProfile

        graph = RoleGraph()
        agent = AgentProfile(agent_id="new_agent", display_name="Agent")

        result = graph.add_node(agent)

        assert result is True
        assert "new_agent" in graph.node_ids
        assert graph.num_nodes == 1

    def test_add_node_with_connections(self):
        from core.agent import AgentProfile

        g = rx.PyDiGraph()
        g.add_node({"id": "a"})

        agent_a = AgentProfile(agent_id="a", display_name="Agent A")
        graph = RoleGraph(
            node_ids=["a"],
            role_connections={"a": []},
            graph=g,
            A_com=torch.zeros((1, 1), dtype=torch.float32),
        )
        graph.agents = [agent_a]

        agent_b = AgentProfile(agent_id="b", display_name="Agent B")
        graph.add_node(agent_b, connections_to=["a"])

        assert "b" in graph.node_ids
        assert graph.A_com.shape == (2, 2)

    def test_add_duplicate_node_raises(self):
        from core.agent import AgentProfile

        g = rx.PyDiGraph()
        g.add_node({"id": "a"})

        agent_a = AgentProfile(agent_id="a", display_name="Agent A")
        graph = RoleGraph(
            node_ids=["a"],
            graph=g,
        )
        graph.agents = [agent_a]

        agent_a_dup = AgentProfile(agent_id="a", display_name="Agent A")
        result = graph.add_node(agent_a_dup)

        # add_node returns False for duplicates
        assert result is False

    def test_add_node_expands_matrices(self):
        from core.agent import AgentProfile

        agent_a = AgentProfile(agent_id="a", display_name="Agent A")
        agent_b = AgentProfile(agent_id="b", display_name="Agent B")

        graph = RoleGraph(
            node_ids=["a", "b"],
            A_com=torch.tensor([[0, 1], [0, 0]], dtype=torch.float32),
        )
        graph.agents = [agent_a, agent_b]
        original_shape = graph.A_com.shape

        agent_c = AgentProfile(agent_id="c", display_name="Agent C")
        graph.add_node(agent_c)

        assert graph.A_com.shape[0] == original_shape[0] + 1
        assert graph.A_com.shape[1] == original_shape[1] + 1


class TestRemoveNode:
    def test_remove_node_basic(self):
        from core.agent import AgentProfile

        g = rx.PyDiGraph()
        g.add_node({"id": "a"})
        g.add_node({"id": "b"})

        agent_a = AgentProfile(agent_id="a", display_name="Agent A")
        agent_b = AgentProfile(agent_id="b", display_name="Agent B")

        graph = RoleGraph(
            node_ids=["a", "b"],
            graph=g,
            A_com=torch.zeros((2, 2), dtype=torch.float32),
        )
        graph.agents = [agent_a, agent_b]

        graph.remove_node("b")

        assert "b" not in graph.node_ids
        assert graph.num_nodes == 1

    def test_remove_nonexistent_node_raises(self):
        graph = RoleGraph()

        # remove_node returns None for nonexistent nodes, doesn't raise
        result = graph.remove_node("nonexistent")
        assert result is None

    def test_remove_node_shrinks_matrices(self):
        from core.agent import AgentProfile

        agent_a = AgentProfile(agent_id="a", display_name="Agent A")
        agent_b = AgentProfile(agent_id="b", display_name="Agent B")
        agent_c = AgentProfile(agent_id="c", display_name="Agent C")

        graph = RoleGraph(
            node_ids=["a", "b", "c"],
            A_com=torch.eye(3, dtype=torch.float32),
        )
        graph.agents = [agent_a, agent_b, agent_c]

        graph.remove_node("b")

        assert graph.A_com.shape == (2, 2)
        assert len(graph.node_ids) == 2

    def test_remove_node_with_discard_policy(self):
        from core.agent import AgentProfile

        g = rx.PyDiGraph()
        g.add_node({"id": "a", "state": {"data": "important"}})

        agent_a = AgentProfile(agent_id="a", display_name="Agent A")
        graph = RoleGraph(
            node_ids=["a"],
            graph=g,
        )
        graph.agents = [agent_a]

        graph.remove_node("a", policy=StateMigrationPolicy.DISCARD)

        assert "a" not in graph.node_ids

    def test_remove_node_with_archive_policy(self):
        from core.agent import AgentProfile

        g = rx.PyDiGraph()
        g.add_node({"id": "a", "state": {"data": "important"}})

        agent_a = AgentProfile(agent_id="a", display_name="Agent A")
        storage = InMemoryStateStorage()
        graph = RoleGraph(
            node_ids=["a"],
            graph=g,
            state_storage=storage,
        )
        graph.agents = [agent_a]

        graph.remove_node("a", policy=StateMigrationPolicy.ARCHIVE)

        assert "a" not in graph.node_ids
        archived = storage.load("a")
        assert archived is not None


class TestReplaceNode:
    def test_replace_node_basic(self):
        from core.agent import AgentProfile

        g = rx.PyDiGraph()
        g.add_node({"id": "old", "role": "agent"})

        old_agent = AgentProfile(agent_id="old", display_name="Old Agent")
        graph = RoleGraph(
            node_ids=["old"],
            graph=g,
        )
        graph.agents = [old_agent]

        new_agent = AgentProfile(agent_id="new", display_name="New Agent")
        graph.replace_node("old", new_agent, StateMigrationPolicy.COPY)

        assert "old" not in graph.node_ids
        assert "new" in graph.node_ids

    def test_replace_preserves_connections(self):
        from core.agent import AgentProfile

        g = rx.PyDiGraph()
        g.add_node({"id": "a"})
        g.add_node({"id": "b"})
        g.add_node({"id": "c"})
        g.add_edge(0, 1, {"weight": 0.5})
        g.add_edge(1, 2, {"weight": 0.8})

        agent_a = AgentProfile(agent_id="a", display_name="Agent A")
        agent_b = AgentProfile(agent_id="b", display_name="Agent B")
        agent_c = AgentProfile(agent_id="c", display_name="Agent C")

        graph = RoleGraph(
            node_ids=["a", "b", "c"],
            role_connections={"a": ["b"], "b": ["c"], "c": []},
            graph=g,
        )
        graph.agents = [agent_a, agent_b, agent_c]

        agent_b_new = AgentProfile(agent_id="b_new", display_name="Agent B New")
        graph.replace_node("b", agent_b_new, StateMigrationPolicy.COPY)

        assert "b_new" in graph.node_ids
        assert "b_new" in graph.role_connections

    def test_replace_with_copy_policy(self):
        from core.agent import AgentProfile

        g = rx.PyDiGraph()
        g.add_node({"id": "old", "state": {"key": "value"}})

        old_agent = AgentProfile(agent_id="old", display_name="Old Agent")
        graph = RoleGraph(
            node_ids=["old"],
            graph=g,
        )
        graph.agents = [old_agent]

        new_agent = AgentProfile(agent_id="new", display_name="New Agent")
        graph.replace_node(
            "old",
            new_agent,
            policy=StateMigrationPolicy.COPY,
        )

        assert "new" in graph.node_ids
        assert "old" not in graph.node_ids


class TestIntegrity:
    def test_verify_integrity_valid(self):
        from core.agent import AgentProfile

        g = rx.PyDiGraph()
        g.add_node({"id": "a"})
        g.add_node({"id": "b"})
        g.add_edge(0, 1, {})

        agent_a = AgentProfile(agent_id="a", display_name="Agent A")
        agent_b = AgentProfile(agent_id="b", display_name="Agent B")

        graph = RoleGraph(
            node_ids=["a", "b"],
            role_connections={"a": ["b"], "b": []},
            graph=g,
            A_com=torch.tensor([[0, 1], [0, 0]], dtype=torch.float32),
        )
        graph.agents = [agent_a, agent_b]

        graph.verify_integrity()

    def test_is_consistent_true(self):
        from core.agent import AgentProfile

        g = rx.PyDiGraph()
        g.add_node({"id": "a"})

        agent_a = AgentProfile(agent_id="a", display_name="Agent A")
        graph = RoleGraph(
            node_ids=["a"],
            graph=g,
            A_com=torch.zeros((1, 1), dtype=torch.float32),
        )
        graph.agents = [agent_a]

        assert graph.is_consistent()

    def test_verify_integrity_mismatched_counts(self):
        from core.agent import AgentProfile

        g = rx.PyDiGraph()
        g.add_node({"id": "a"})
        g.add_node({"id": "b"})

        agent_a = AgentProfile(agent_id="a", display_name="Agent A")
        graph = RoleGraph(
            node_ids=["a"],
            graph=g,
        )
        graph.agents = [agent_a]

        with pytest.raises(GraphIntegrityError):
            graph.verify_integrity()


class TestSerialization:
    def test_model_dump_basic(self):
        from core.agent import AgentProfile

        agent_a = AgentProfile(agent_id="a", display_name="Agent A")
        agent_b = AgentProfile(agent_id="b", display_name="Agent B")

        graph = RoleGraph(
            node_ids=["a", "b"],
            role_connections={"a": ["b"], "b": []},
            query="test query",
        )
        graph.agents = [agent_a, agent_b]

        data = graph.model_dump(exclude={"graph"})

        assert "node_ids" in data
        assert "role_connections" in data
        assert data["query"] == "test query"

    def test_model_dump_excludes_graph(self):
        g = rx.PyDiGraph()
        graph = RoleGraph(graph=g)

        data = graph.model_dump(exclude={"graph"})

        assert "graph" not in data

    def test_json_roundtrip(self):
        from core.agent import AgentProfile

        agent_a = AgentProfile(agent_id="a", display_name="Agent A")
        agent_b = AgentProfile(agent_id="b", display_name="Agent B")

        graph = RoleGraph(
            node_ids=["a", "b"],
            role_connections={"a": ["b"], "b": []},
            query="test",
            answer="response",
        )
        graph.agents = [agent_a, agent_b]

        json_str = graph.model_dump_json(exclude={"graph", "A_com", "S_tilde", "p_matrix"})
        data = json.loads(json_str)

        assert data["node_ids"] == ["a", "b"]
        assert data["query"] == "test"


class TestEdgeOperations:
    def test_add_edge(self):
        from core.agent import AgentProfile

        g = rx.PyDiGraph()
        g.add_node({"id": "a"})
        g.add_node({"id": "b"})

        agent_a = AgentProfile(agent_id="a", display_name="Agent A")
        agent_b = AgentProfile(agent_id="b", display_name="Agent B")

        graph = RoleGraph(
            node_ids=["a", "b"],
            role_connections={"a": [], "b": []},
            graph=g,
            A_com=torch.zeros((2, 2), dtype=torch.float32),
        )
        graph.agents = [agent_a, agent_b]

        graph.add_edge("a", "b", weight=0.7)

        assert graph.num_edges == 1
        # Role connections are updated automatically in add_edge
        # Check via A_com instead
        assert graph.A_com[0, 1] == 0.7

    def test_remove_edge(self):
        g = rx.PyDiGraph()
        g.add_node({"id": "a"})
        g.add_node({"id": "b"})
        g.add_edge(0, 1, {"weight": 0.5})

        graph = RoleGraph(
            node_ids=["a", "b"],
            role_connections={"a": ["b"], "b": []},
            graph=g,
        )

        graph.remove_edge("a", "b")

        assert graph.num_edges == 0

    def test_update_edge_weight(self):
        from core.agent import AgentProfile

        g = rx.PyDiGraph()
        g.add_node({"id": "a"})
        g.add_node({"id": "b"})
        g.add_edge(0, 1, {"weight": 0.5})

        agent_a = AgentProfile(agent_id="a", display_name="Agent A")
        agent_b = AgentProfile(agent_id="b", display_name="Agent B")

        graph = RoleGraph(
            node_ids=["a", "b"],
            graph=g,
            A_com=torch.tensor([[0, 0.5], [0, 0]], dtype=torch.float32),
        )
        graph.agents = [agent_a, agent_b]

        # Remove and re-add edge with new weight
        graph.remove_edge("a", "b")
        graph.add_edge("a", "b", weight=0.9)

        # Check via edges property
        edges = graph.edges
        ab_edge = [e for e in edges if e["source"] == "a" and e["target"] == "b"]
        assert len(ab_edge) == 1
        assert ab_edge[0]["weight"] == 0.9


class TestPyGExport:
    def test_edge_index_empty(self):
        graph = RoleGraph()

        ei = graph.edge_index

        assert ei.shape == (2, 0)

    def test_edge_index_with_edges(self):
        from core.agent import AgentProfile

        g = rx.PyDiGraph()
        g.add_node({"id": "a"})
        g.add_node({"id": "b"})
        g.add_edge(0, 1, {})

        agent_a = AgentProfile(agent_id="a", display_name="Agent A")
        agent_b = AgentProfile(agent_id="b", display_name="Agent B")

        graph = RoleGraph(
            node_ids=["a", "b"],
            graph=g,
        )
        graph.agents = [agent_a, agent_b]

        ei = graph.edge_index

        assert ei.shape[0] == 2
        assert ei.shape[1] == 1
        assert ei[0, 0] == 0
        assert ei[1, 0] == 1

    def test_to_pyg_data(self):
        pytest.importorskip("torch_geometric", reason="torch_geometric not installed")
        from core.agent import AgentProfile

        g = rx.PyDiGraph()
        g.add_node({"id": "a"})
        g.add_node({"id": "b"})
        g.add_edge(0, 1, {"weight": 0.5})

        agent_a = AgentProfile(agent_id="a", display_name="Agent A")
        agent_b = AgentProfile(agent_id="b", display_name="Agent B")

        graph = RoleGraph(
            node_ids=["a", "b"],
            graph=g,
        )
        graph.agents = [agent_a, agent_b]

        data = graph.to_pyg_data()
        assert data is not None
        assert hasattr(data, "edge_index")

    def test_to_pyg_data_with_custom_features(self):
        pytest.importorskip("torch_geometric", reason="torch_geometric not installed")
        import torch

        from core.agent import AgentProfile

        g = rx.PyDiGraph()
        g.add_node({"id": "a"})
        g.add_node({"id": "b"})
        g.add_edge(0, 1, {})

        agent_a = AgentProfile(agent_id="a", display_name="Agent A")
        agent_b = AgentProfile(agent_id="b", display_name="Agent B")

        graph = RoleGraph(
            node_ids=["a", "b"],
            graph=g,
        )
        graph.agents = [agent_a, agent_b]

        node_features = {"custom": torch.tensor([[1.0, 0.0], [0.0, 1.0]], dtype=torch.float32)}
        edge_features = {"custom": torch.tensor([[0.5, 0.5]], dtype=torch.float32)}

        data = graph.to_pyg_data(
            node_features=node_features,
            edge_features=edge_features,
        )
        assert data.x.shape[0] == 2
        assert data.edge_attr.shape[0] == 1


class TestStateStorage:
    def test_in_memory_storage(self):
        storage = InMemoryStateStorage()

        storage.save("node1", {"key": "value"})

        assert storage.load("node1") == {"key": "value"}
        assert storage.load("nonexistent") is None

        storage.delete("node1")
        assert storage.load("node1") is None

    def test_file_storage(self):
        with tempfile.TemporaryDirectory() as tmpdir:
            storage = FileStateStorage(tmpdir)

            storage.save("node1", {"key": "value"})

            assert storage.load("node1") == {"key": "value"}

            storage.delete("node1")
            assert storage.load("node1") is None

    def test_graph_with_storage(self):
        from core.agent import AgentProfile

        storage = InMemoryStateStorage()

        g = rx.PyDiGraph()
        g.add_node({"id": "a", "state": {"data": 123}})

        agent_a = AgentProfile(agent_id="a", display_name="Agent A")
        graph = RoleGraph(
            node_ids=["a"],
            graph=g,
            state_storage=storage,
        )
        graph.agents = [agent_a]

        graph.remove_node("a", policy=StateMigrationPolicy.ARCHIVE)

        archived = storage.load("a")
        assert archived is not None
        assert isinstance(archived.get("state", []), list)


class TestProperties:
    """Tests for various properties of RoleGraph."""

    def test_role_sequence_from_agents(self):
        from core.agent import AgentProfile

        agent_a = AgentProfile(agent_id="a", display_name="Agent A")
        agent_b = AgentProfile(agent_id="b", display_name="Agent B")
        graph = RoleGraph(node_ids=["a", "b"])
        graph.agents = [agent_a, agent_b]

        seq = graph.role_sequence
        assert seq == ["a", "b"]

    def test_role_sequence_from_dicts(self):
        graph = RoleGraph(node_ids=["x", "y"])
        graph.agents = [{"id": "x"}, {"id": "y"}]

        seq = graph.role_sequence
        assert "x" in seq
        assert "y" in seq

    def test_embeddings_empty_without_embeddings(self):
        from core.agent import AgentProfile

        agent_a = AgentProfile(agent_id="a", display_name="Agent A")
        graph = RoleGraph(node_ids=["a"])
        graph.agents = [agent_a]

        emb = graph.embeddings
        # No embeddings set → empty tensor
        assert emb.numel() == 0

    def test_embeddings_with_agents(self):
        from core.agent import AgentProfile

        agent_a = AgentProfile(
            agent_id="a",
            display_name="Agent A",
            embedding=torch.tensor([1.0, 2.0, 3.0]),
        )
        agent_b = AgentProfile(
            agent_id="b",
            display_name="Agent B",
            embedding=torch.tensor([4.0, 5.0, 6.0]),
        )
        graph = RoleGraph(node_ids=["a", "b"])
        graph.agents = [agent_a, agent_b]

        emb = graph.embeddings
        assert emb.shape == (2, 3)

    def test_edge_attr_empty(self):
        graph = RoleGraph()
        ea = graph.edge_attr
        assert ea.shape == (0, 4)

    def test_edge_attr_with_edges(self):
        g = rx.PyDiGraph()
        g.add_node({"id": "a"})
        g.add_node({"id": "b"})
        # Edge without "attr" key
        g.add_edge(0, 1, {"weight": 0.5})
        graph = RoleGraph(node_ids=["a", "b"], graph=g)
        ea = graph.edge_attr
        # Default attr [1,0,0,0]
        assert ea.shape == (1, 4)

    def test_has_conditional_edges_false(self):
        graph = RoleGraph()
        assert graph.has_conditional_edges is False

    def test_has_conditional_edges_true(self):
        from core.agent import AgentProfile

        g = rx.PyDiGraph()
        g.add_node({"id": "a"})
        g.add_node({"id": "b"})

        agent_a = AgentProfile(agent_id="a", display_name="A")
        agent_b = AgentProfile(agent_id="b", display_name="B")
        graph = RoleGraph(node_ids=["a", "b"], graph=g)
        graph.agents = [agent_a, agent_b]

        result = graph.set_edge_condition("a", "b", "some_condition")
        assert result is True
        assert graph.has_conditional_edges is True

    def test_conditional_edges_list(self):
        from core.agent import AgentProfile

        g = rx.PyDiGraph()
        g.add_node({"id": "a"})
        g.add_node({"id": "b"})
        g.add_node({"id": "c"})

        agent_a = AgentProfile(agent_id="a", display_name="A")
        agent_b = AgentProfile(agent_id="b", display_name="B")
        agent_c = AgentProfile(agent_id="c", display_name="C")
        graph = RoleGraph(node_ids=["a", "b", "c"], graph=g)
        graph.agents = [agent_a, agent_b, agent_c]

        graph.set_edge_condition("a", "b", lambda _: True)
        graph.set_edge_condition("b", "c", "is_done")

        cond_edges = graph.conditional_edges
        assert ("a", "b") in cond_edges
        assert ("b", "c") in cond_edges


class TestEdgeConditions:
    def test_set_get_remove_callable_condition(self):
        from core.agent import AgentProfile

        g = rx.PyDiGraph()
        g.add_node({"id": "a"})
        g.add_node({"id": "b"})

        agent_a = AgentProfile(agent_id="a", display_name="A")
        agent_b = AgentProfile(agent_id="b", display_name="B")
        graph = RoleGraph(node_ids=["a", "b"], graph=g)
        graph.agents = [agent_a, agent_b]

        def cond(ctx):
            return True

        graph.set_edge_condition("a", "b", cond)

        retrieved = graph.get_edge_condition("a", "b")
        assert retrieved is cond

        removed = graph.remove_edge_condition("a", "b")
        assert removed is True
        assert graph.get_edge_condition("a", "b") is None

    def test_set_get_string_condition(self):
        from core.agent import AgentProfile

        g = rx.PyDiGraph()
        g.add_node({"id": "x"})
        g.add_node({"id": "y"})

        agent_x = AgentProfile(agent_id="x", display_name="X")
        agent_y = AgentProfile(agent_id="y", display_name="Y")
        graph = RoleGraph(node_ids=["x", "y"], graph=g)
        graph.agents = [agent_x, agent_y]

        graph.set_edge_condition("x", "y", "high_confidence")
        assert graph.get_edge_condition("x", "y") == "high_confidence"

    def test_set_condition_nonexistent_nodes_returns_false(self):
        graph = RoleGraph()
        result = graph.set_edge_condition("ghost", "phantom", "cond")
        assert result is False

    def test_get_all_edge_conditions(self):
        from core.agent import AgentProfile

        g = rx.PyDiGraph()
        g.add_node({"id": "a"})
        g.add_node({"id": "b"})
        g.add_node({"id": "c"})

        for _agent_id in ["a", "b", "c"]:
            pass
        agent_a = AgentProfile(agent_id="a", display_name="A")
        agent_b = AgentProfile(agent_id="b", display_name="B")
        agent_c = AgentProfile(agent_id="c", display_name="C")
        graph = RoleGraph(node_ids=["a", "b", "c"], graph=g)
        graph.agents = [agent_a, agent_b, agent_c]

        graph.set_edge_condition("a", "b", "str_cond")
        graph.set_edge_condition("b", "c", lambda _: False)

        all_conds = graph.get_all_edge_conditions()
        assert ("a", "b") in all_conds
        assert ("b", "c") in all_conds

    def test_remove_condition_not_set_returns_false(self):
        graph = RoleGraph()
        result = graph.remove_edge_condition("a", "b")
        assert result is False


class TestGetAgentById:
    def test_get_existing_agent(self):
        from core.agent import AgentProfile

        agent_a = AgentProfile(agent_id="alpha", display_name="Alpha")
        graph = RoleGraph(node_ids=["alpha"])
        graph.agents = [agent_a]

        result = graph.get_agent_by_id("alpha")
        assert result is agent_a

    def test_get_nonexistent_agent_returns_none(self):
        graph = RoleGraph()
        assert graph.get_agent_by_id("not_here") is None

    def test_get_agent_from_dict(self):
        graph = RoleGraph(node_ids=["dict_agent"])
        graph.agents = [{"id": "dict_agent", "name": "Dict Agent"}]

        result = graph.get_agent_by_id("dict_agent")
        assert result is not None
        assert result["id"] == "dict_agent"


class TestGetNeighbors:
    def _make_graph(self):
        from core.agent import AgentProfile

        g = rx.PyDiGraph()
        g.add_node({"id": "a"})
        g.add_node({"id": "b"})
        g.add_node({"id": "c"})
        g.add_edge(0, 1, {"weight": 1.0})
        g.add_edge(2, 0, {"weight": 1.0})

        graph = RoleGraph(
            node_ids=["a", "b", "c"],
            graph=g,
            A_com=torch.zeros((3, 3)),
        )
        agents = [AgentProfile(agent_id=aid, display_name=aid.upper()) for aid in ["a", "b", "c"]]
        graph.agents = agents
        return graph

    def test_get_out_neighbors(self):
        graph = self._make_graph()
        out_neighbors = graph.get_neighbors("a", direction="out")
        assert "b" in out_neighbors

    def test_get_in_neighbors(self):
        graph = self._make_graph()
        in_neighbors = graph.get_neighbors("a", direction="in")
        assert "c" in in_neighbors

    def test_get_both_neighbors(self):
        graph = self._make_graph()
        both = graph.get_neighbors("a", direction="both")
        assert "b" in both
        assert "c" in both

    def test_get_neighbors_nonexistent_node(self):
        graph = self._make_graph()
        result = graph.get_neighbors("ghost")
        assert result == []


class TestUpdateCommunication:
    def test_update_communication_basic(self):
        from core.agent import AgentProfile

        g = rx.PyDiGraph()
        g.add_node({"id": "a"})
        g.add_node({"id": "b"})
        g.add_node({"id": "c"})

        agents = [AgentProfile(agent_id=aid, display_name=aid) for aid in ["a", "b", "c"]]
        graph = RoleGraph(
            node_ids=["a", "b", "c"],
            graph=g,
            A_com=torch.zeros((3, 3)),
        )
        graph.agents = agents

        new_a = torch.tensor(
            [
                [0.0, 0.9, 0.0],
                [0.0, 0.0, 0.8],
                [0.0, 0.0, 0.0],
            ],
            dtype=torch.float32,
        )
        graph.update_communication(new_a)

        assert graph.A_com[0, 1] == pytest.approx(0.9)
        assert graph.num_edges == 2

    def test_update_communication_with_s_tilde(self):
        from core.agent import AgentProfile

        g = rx.PyDiGraph()
        g.add_node({"id": "a"})
        g.add_node({"id": "b"})

        agents = [AgentProfile(agent_id=aid, display_name=aid) for aid in ["a", "b"]]
        graph = RoleGraph(node_ids=["a", "b"], graph=g, A_com=torch.zeros((2, 2)))
        graph.agents = agents

        new_a = torch.tensor([[0.0, 0.9], [0.0, 0.0]])
        s_tilde = torch.tensor([[0.1, 0.8], [0.0, 0.1]])
        graph.update_communication(new_a, s_tilde=s_tilde)

        assert graph.S_tilde is not None
        assert graph.S_tilde[0, 1] == pytest.approx(0.8)

    def test_update_communication_with_p_matrix(self):
        from core.agent import AgentProfile

        g = rx.PyDiGraph()
        g.add_node({"id": "a"})
        g.add_node({"id": "b"})

        agents = [AgentProfile(agent_id=aid, display_name=aid) for aid in ["a", "b"]]
        graph = RoleGraph(node_ids=["a", "b"], graph=g, A_com=torch.zeros((2, 2)))
        graph.agents = agents

        new_a = torch.tensor([[0.0, 0.9], [0.0, 0.0]])
        p_matrix = torch.tensor([[0.3, 0.7], [0.5, 0.5]])
        graph.update_communication(new_a, p_matrix=p_matrix)

        assert graph.p_matrix is not None


class TestShrinkExpandAdjacency:
    def test_expand_with_s_tilde(self):
        from core.agent import AgentProfile

        agent_a = AgentProfile(agent_id="a", display_name="A")
        graph = RoleGraph(
            node_ids=["a"],
            A_com=torch.ones((1, 1)),
            S_tilde=torch.ones((1, 1)),
        )
        graph.agents = [agent_a]

        agent_b = AgentProfile(agent_id="b", display_name="B")
        graph.add_node(agent_b)

        assert graph.S_tilde is not None
        assert graph.S_tilde.shape == (2, 2)

    def test_expand_with_p_matrix(self):
        from core.agent import AgentProfile

        agent_a = AgentProfile(agent_id="a", display_name="A")
        graph = RoleGraph(
            node_ids=["a"],
            A_com=torch.ones((1, 1)),
            p_matrix=torch.ones((1, 1)),
        )
        graph.agents = [agent_a]

        agent_b = AgentProfile(agent_id="b", display_name="B")
        graph.add_node(agent_b)

        assert graph.p_matrix is not None
        assert graph.p_matrix.shape == (2, 2)

    def test_shrink_with_s_tilde(self):
        from core.agent import AgentProfile

        g = rx.PyDiGraph()
        g.add_node({"id": "a"})
        g.add_node({"id": "b"})

        agents = [AgentProfile(agent_id=aid, display_name=aid) for aid in ["a", "b"]]
        graph = RoleGraph(
            node_ids=["a", "b"],
            graph=g,
            A_com=torch.zeros((2, 2)),
            S_tilde=torch.ones((2, 2)),
        )
        graph.agents = agents

        graph.remove_node("b")
        assert graph.S_tilde is not None
        assert graph.S_tilde.shape == (1, 1)

    def test_shrink_with_p_matrix(self):
        from core.agent import AgentProfile

        g = rx.PyDiGraph()
        g.add_node({"id": "a"})
        g.add_node({"id": "b"})

        agents = [AgentProfile(agent_id=aid, display_name=aid) for aid in ["a", "b"]]
        graph = RoleGraph(
            node_ids=["a", "b"],
            graph=g,
            A_com=torch.zeros((2, 2)),
            p_matrix=torch.ones((2, 2)),
        )
        graph.agents = agents

        graph.remove_node("b")
        assert graph.p_matrix is not None
        assert graph.p_matrix.shape == (1, 1)


class TestVerifyIntegrity:
    def test_returns_errors_without_raising(self):
        from core.agent import AgentProfile

        g = rx.PyDiGraph()
        g.add_node({"id": "a"})
        g.add_node({"id": "b"})

        agent_a = AgentProfile(agent_id="a", display_name="A")
        # Deliberate mismatch: 1 agent, 2 rx nodes
        graph = RoleGraph(node_ids=["a"], graph=g, A_com=torch.zeros((1, 1)))
        graph.agents = [agent_a]

        errors = graph.verify_integrity(raise_on_error=False)
        assert len(errors) > 0

    def test_task_node_not_in_graph(self):
        from core.agent import AgentProfile

        g = rx.PyDiGraph()
        g.add_node({"id": "a"})

        agent_a = AgentProfile(agent_id="a", display_name="A")
        graph = RoleGraph(
            node_ids=["a"],
            graph=g,
            A_com=torch.zeros((1, 1)),
            task_node="nonexistent_task",
        )
        graph.agents = [agent_a]

        errors = graph.verify_integrity(raise_on_error=False)
        assert any("task_node" in e for e in errors)


class TestToDict:
    def test_to_dict_basic(self):
        from core.agent import AgentProfile

        agent_a = AgentProfile(agent_id="a", display_name="Agent A")
        g = rx.PyDiGraph()
        g.add_node({"id": "a"})

        graph = RoleGraph(
            node_ids=["a"],
            role_connections={"a": []},
            graph=g,
            A_com=torch.zeros((1, 1)),
            query="q",
            answer="ans",
        )
        graph.agents = [agent_a]

        d = graph.to_dict()
        assert d["query"] == "q"
        assert d["answer"] == "ans"
        assert "a" in d["node_ids"]
        assert "adjacency" in d
        assert "edges" in d

    def test_to_dict_with_embeddings(self):
        from core.agent import AgentProfile

        agent_a = AgentProfile(
            agent_id="a",
            display_name="Agent A",
            embedding=torch.tensor([1.0, 2.0]),
        )
        g = rx.PyDiGraph()
        g.add_node({"id": "a"})

        graph = RoleGraph(
            node_ids=["a"],
            graph=g,
            A_com=torch.zeros((1, 1)),
        )
        graph.agents = [agent_a]

        d = graph.to_dict()
        assert len(d["embeddings"]) > 0


class TestFromDict:
    def test_from_dict_basic(self):
        data = {
            "agents": [
                {
                    "agent_id": "a",
                    "display_name": "Agent A",
                    "persona": "",
                    "description": "",
                    "llm_backbone": None,
                    "tools": [],
                    "state": [],
                    "embedding": None,
                }
            ],
            "node_ids": ["a"],
            "role_connections": {"a": []},
            "task_node": None,
            "query": "test",
            "answer": None,
            "edges": [],
            "adjacency": [[0.0]],
        }

        graph = RoleGraph.from_dict(data, verify=False)
        assert "a" in graph.node_ids
        assert graph.query == "test"

    def test_from_dict_with_edges(self):
        data = {
            "agents": [
                {"agent_id": "a", "display_name": "A", "persona": "", "description": "", "tools": [], "state": []},
                {"agent_id": "b", "display_name": "B", "persona": "", "description": "", "tools": [], "state": []},
            ],
            "node_ids": ["a", "b"],
            "role_connections": {"a": ["b"], "b": []},
            "task_node": None,
            "query": None,
            "answer": None,
            "edges": [{"source": "a", "target": "b", "weight": 0.8}],
            "adjacency": [[0.0, 0.8], [0.0, 0.0]],
        }

        graph = RoleGraph.from_dict(data, verify=False)
        assert graph.num_edges == 1


class TestFromGraph:
    def test_from_graph_basic(self):
        from core.agent import AgentProfile

        agents = [
            AgentProfile(agent_id="x", display_name="X"),
            AgentProfile(agent_id="y", display_name="Y"),
        ]
        g = rx.PyDiGraph()
        g.add_node({"id": "x"})
        g.add_node({"id": "y"})
        g.add_edge(0, 1, {"weight": 1.0})

        a_com = torch.tensor([[0.0, 1.0], [0.0, 0.0]])
        connections = {"x": ["y"], "y": []}

        graph = RoleGraph.from_graph(agents, g, a_com, connections, verify=False)
        assert "x" in graph.node_ids
        assert "y" in graph.node_ids
        assert graph.num_edges == 1


class TestSubgraph:
    def test_subgraph_basic(self):
        from core.agent import AgentProfile

        agents = [AgentProfile(agent_id=aid, display_name=aid) for aid in ["a", "b", "c"]]
        g = rx.PyDiGraph()
        for aid in ["a", "b", "c"]:
            g.add_node({"id": aid})
        g.add_edge(0, 1, {"weight": 1.0})
        g.add_edge(1, 2, {"weight": 1.0})

        graph = RoleGraph(
            node_ids=["a", "b", "c"],
            role_connections={"a": ["b"], "b": ["c"], "c": []},
            graph=g,
            A_com=torch.tensor([[0, 1, 0], [0, 0, 1], [0, 0, 0]], dtype=torch.float32),
        )
        graph.agents = agents

        sub = graph.subgraph(["a", "b"])
        assert "a" in sub.node_ids
        assert "b" in sub.node_ids
        assert "c" not in sub.node_ids

    def test_subgraph_preserves_edges(self):
        from core.agent import AgentProfile

        agents = [AgentProfile(agent_id=aid, display_name=aid) for aid in ["a", "b", "c"]]
        g = rx.PyDiGraph()
        for aid in ["a", "b", "c"]:
            g.add_node({"id": aid})
        g.add_edge(0, 1, {"weight": 0.9})
        g.add_edge(1, 2, {"weight": 0.7})

        graph = RoleGraph(
            node_ids=["a", "b", "c"],
            role_connections={"a": ["b"], "b": ["c"], "c": []},
            graph=g,
            A_com=torch.tensor([[0, 0.9, 0], [0, 0, 0.7], [0, 0, 0]], dtype=torch.float32),
        )
        graph.agents = agents

        sub = graph.subgraph(["a", "b"])
        assert sub.num_edges == 1


class TestStartEndNodes:
    def _make_graph(self):
        from core.agent import AgentProfile

        agents = [AgentProfile(agent_id=aid, display_name=aid) for aid in ["start", "mid", "end"]]
        g = rx.PyDiGraph()
        for aid in ["start", "mid", "end"]:
            g.add_node({"id": aid})
        graph = RoleGraph(
            node_ids=["start", "mid", "end"],
            graph=g,
        )
        graph.agents = agents
        return graph

    def test_set_start_node(self):
        graph = self._make_graph()
        assert graph.set_start_node("start") is True
        assert graph.start_node == "start"

    def test_set_start_node_nonexistent(self):
        graph = self._make_graph()
        assert graph.set_start_node("ghost") is False

    def test_set_end_node(self):
        graph = self._make_graph()
        assert graph.set_end_node("end") is True
        assert graph.end_node == "end"

    def test_set_end_node_nonexistent(self):
        graph = self._make_graph()
        assert graph.set_end_node("phantom") is False

    def test_set_execution_bounds(self):
        graph = self._make_graph()
        result = graph.set_execution_bounds("start", "end")
        assert result is True
        assert graph.start_node == "start"
        assert graph.end_node == "end"

    def test_set_execution_bounds_invalid_start(self):
        graph = self._make_graph()
        assert graph.set_execution_bounds("nonexistent", "end") is False

    def test_set_execution_bounds_invalid_end(self):
        graph = self._make_graph()
        assert graph.set_execution_bounds("start", "nonexistent") is False

    def test_set_execution_bounds_none_values(self):
        graph = self._make_graph()
        result = graph.set_execution_bounds(None, None)
        assert result is True
        assert graph.start_node is None
        assert graph.end_node is None


class TestDisableEnable:
    def _make_graph(self):
        from core.agent import AgentProfile

        agents = [AgentProfile(agent_id=aid, display_name=aid) for aid in ["a", "b", "c"]]
        g = rx.PyDiGraph()
        for aid in ["a", "b", "c"]:
            g.add_node({"id": aid})
        graph = RoleGraph(node_ids=["a", "b", "c"], graph=g)
        graph.agents = agents
        return graph

    def test_disable_single_node(self):
        graph = self._make_graph()
        count = graph.disable("a")
        assert count == 1
        assert "a" in graph.disabled_nodes

    def test_disable_multiple_nodes(self):
        graph = self._make_graph()
        count = graph.disable(["a", "b"])
        assert count == 2

    def test_disable_nonexistent_node(self):
        graph = self._make_graph()
        count = graph.disable("ghost")
        assert count == 0

    def test_enable_single_node(self):
        graph = self._make_graph()
        graph.disable("a")
        count = graph.enable("a")
        assert count == 1
        assert "a" not in graph.disabled_nodes

    def test_enable_all_nodes(self):
        graph = self._make_graph()
        graph.disable(["a", "b"])
        count = graph.enable()
        assert count == 2
        assert len(graph.disabled_nodes) == 0

    def test_is_enabled(self):
        graph = self._make_graph()
        assert graph.is_enabled("a") is True
        graph.disable("a")
        assert graph.is_enabled("a") is False

    def test_get_enabled(self):
        graph = self._make_graph()
        graph.disable("a")
        enabled = graph.get_enabled()
        assert "a" not in enabled
        assert "b" in enabled
        assert "c" in enabled

    def test_get_disabled(self):
        graph = self._make_graph()
        graph.disable(["a", "b"])
        disabled = graph.get_disabled()
        assert "a" in disabled
        assert "b" in disabled
        assert "c" not in disabled


class TestReachabilityMethods:
    def _make_linear_graph(self):
        """Create a -> b -> c -> d linear graph."""
        from core.agent import AgentProfile

        agents = [AgentProfile(agent_id=aid, display_name=aid) for aid in ["a", "b", "c", "d"]]
        g = rx.PyDiGraph()
        for aid in ["a", "b", "c", "d"]:
            g.add_node({"id": aid})
        g.add_edge(0, 1, {"weight": 1.0})
        g.add_edge(1, 2, {"weight": 1.0})
        g.add_edge(2, 3, {"weight": 1.0})

        adj_matrix = torch.tensor(
            [
                [0, 1, 0, 0],
                [0, 0, 1, 0],
                [0, 0, 0, 1],
                [0, 0, 0, 0],
            ],
            dtype=torch.float32,
        )

        graph = RoleGraph(
            node_ids=["a", "b", "c", "d"],
            role_connections={"a": ["b"], "b": ["c"], "c": ["d"], "d": []},
            graph=g,
            A_com=adj_matrix,
        )
        graph.agents = agents
        return graph

    def test_get_reachable_from(self):
        graph = self._make_linear_graph()
        reachable = graph.get_reachable_from("b")
        assert "b" in reachable
        assert "c" in reachable
        assert "d" in reachable
        assert "a" not in reachable

    def test_get_reachable_from_nonexistent(self):
        graph = self._make_linear_graph()
        result = graph.get_reachable_from("ghost")
        assert result == set()

    def test_get_nodes_reaching(self):
        graph = self._make_linear_graph()
        reaching = graph.get_nodes_reaching("c")
        assert "c" in reaching
        assert "b" in reaching
        assert "a" in reaching
        assert "d" not in reaching

    def test_get_nodes_reaching_nonexistent(self):
        graph = self._make_linear_graph()
        result = graph.get_nodes_reaching("ghost")
        assert result == set()

    def test_get_relevant_nodes(self):
        graph = self._make_linear_graph()
        relevant = graph.get_relevant_nodes("a", "d")
        assert "a" in relevant
        assert "b" in relevant
        assert "c" in relevant
        assert "d" in relevant

    def test_get_isolated_nodes(self):
        from core.agent import AgentProfile

        agents = [AgentProfile(agent_id=aid, display_name=aid) for aid in ["a", "b", "c", "iso"]]
        g = rx.PyDiGraph()
        for aid in ["a", "b", "c", "iso"]:
            g.add_node({"id": aid})
        g.add_edge(0, 1, {"weight": 1.0})
        g.add_edge(1, 2, {"weight": 1.0})
        # "iso" has no connections

        adj_matrix = torch.tensor(
            [
                [0, 1, 0, 0],
                [0, 0, 1, 0],
                [0, 0, 0, 0],
                [0, 0, 0, 0],
            ],
            dtype=torch.float32,
        )

        graph = RoleGraph(
            node_ids=["a", "b", "c", "iso"],
            role_connections={"a": ["b"], "b": ["c"], "c": [], "iso": []},
            graph=g,
            A_com=adj_matrix,
        )
        graph.agents = agents

        isolated = graph.get_isolated_nodes("a", "c")
        assert "iso" in isolated
        assert "a" not in isolated

    def test_get_optimized_execution_order(self):
        graph = self._make_linear_graph()
        order = graph.get_optimized_execution_order("a", "d")
        assert order[0] == "a"
        assert order[-1] == "d"


class TestSchemaFeatures:
    def test_get_edge_features_from_schema(self):
        g = rx.PyDiGraph()
        g.add_node({"id": "a"})
        g.add_node({"id": "b"})
        g.add_edge(0, 1, {"weight": 0.8, "probability": 0.9})

        graph = RoleGraph(node_ids=["a", "b"], graph=g)
        features = graph.get_edge_features_from_schema()

        assert "weight" in features
        assert "probability" in features
        assert "trust" in features
        assert features["weight"][0].item() == pytest.approx(0.8)

    def test_get_node_features_from_schema(self):
        g = rx.PyDiGraph()
        g.add_node({"id": "a", "schema": {"trust_score": 0.9}})
        g.add_node({"id": "b", "schema": {}})

        graph = RoleGraph(node_ids=["a", "b"], graph=g)
        features = graph.get_node_features_from_schema()

        assert "trust_score" in features
        assert "quality_score" in features
        assert features["trust_score"][0].item() == pytest.approx(0.9)

    def test_get_agent_schema_not_found(self):
        graph = RoleGraph()
        result = graph.get_agent_schema("nonexistent")
        assert result is None

    def test_validate_agent_input_no_schema(self):
        graph = RoleGraph()
        result = graph.validate_agent_input("ghost", {"data": "value"})
        assert result.valid is True

    def test_validate_agent_output_no_schema(self):
        graph = RoleGraph()
        result = graph.validate_agent_output("ghost", {"data": "value"})
        assert result.valid is True

    def test_has_input_schema_no_agent(self):
        graph = RoleGraph()
        assert graph.has_input_schema("ghost") is False

    def test_has_output_schema_no_agent(self):
        graph = RoleGraph()
        assert graph.has_output_schema("ghost") is False

    def test_get_input_schema_json_no_agent(self):
        graph = RoleGraph()
        assert graph.get_input_schema_json("ghost") is None

    def test_get_output_schema_json_no_agent(self):
        graph = RoleGraph()
        assert graph.get_output_schema_json("ghost") is None


class TestReplaceNodeWithTaskNode:
    def test_replace_task_node_updates_task_node_attr(self):
        from core.agent import AgentProfile

        g = rx.PyDiGraph()
        g.add_node({"id": "task1"})

        agent = AgentProfile(agent_id="task1", display_name="Task 1")
        graph = RoleGraph(
            node_ids=["task1"],
            graph=g,
            task_node="task1",
        )
        graph.agents = [agent]

        new_agent = AgentProfile(agent_id="task2", display_name="Task 2")
        graph.replace_node("task1", new_agent, StateMigrationPolicy.DISCARD)

        assert graph.task_node == "task2"
        assert "task2" in graph.node_ids

    def test_replace_nonexistent_node_returns_none(self):
        graph = RoleGraph()
        result = graph.replace_node("ghost", object())
        assert result is None


class TestRemoveNodeWithTaskNode:
    def test_remove_task_node_clears_task_node_attr(self):
        from core.agent import AgentProfile

        g = rx.PyDiGraph()
        g.add_node({"id": "task"})

        agent = AgentProfile(agent_id="task", display_name="Task")
        graph = RoleGraph(
            node_ids=["task"],
            graph=g,
            task_node="task",
        )
        graph.agents = [agent]

        graph.remove_node("task", policy=StateMigrationPolicy.DISCARD)

        assert graph.task_node is None


class TestToPyGDataWithPMatrix:
    def test_to_pyg_data_with_p_matrix(self):
        pytest.importorskip("torch_geometric", reason="torch_geometric not installed")
        from core.agent import AgentProfile

        g = rx.PyDiGraph()
        g.add_node({"id": "a"})
        g.add_node({"id": "b"})
        g.add_edge(0, 1, {"weight": 0.5})

        agents = [AgentProfile(agent_id=aid, display_name=aid) for aid in ["a", "b"]]
        p = torch.tensor([[0.3, 0.7], [0.4, 0.6]])
        graph = RoleGraph(
            node_ids=["a", "b"],
            graph=g,
            A_com=torch.zeros((2, 2)),
            p_matrix=p,
        )
        graph.agents = agents

        data = graph.to_pyg_data()
        assert hasattr(data, "p_matrix")
        assert data.p_matrix.shape == (2, 2)


class TestGetAgentIdFunction:
    """Tests for the module-level _get_agent_id function."""

    def test_object_with_agent_id(self):
        from core.agent import AgentProfile
        from core.graph import _get_agent_id

        agent = AgentProfile(agent_id="agent1", display_name="Agent 1")
        assert _get_agent_id(agent) == "agent1"

    def test_dict_with_id_key(self):
        from core.graph import _get_agent_id

        assert _get_agent_id({"id": "agent1"}) == "agent1"

    def test_dict_with_agent_id_key(self):
        from core.graph import _get_agent_id

        assert _get_agent_id({"agent_id": "agent1"}) == "agent1"

    def test_returns_none_for_non_matching_object(self):
        from core.graph import _get_agent_id

        assert _get_agent_id(42) is None
        assert _get_agent_id("just a string") is None


class TestRoleSequenceStr:
    """Test role_sequence when agent is not object or dict."""

    def test_role_sequence_with_string_agent(self):
        graph = RoleGraph()
        graph.agents = ["agent_str"]
        graph.node_ids = ["agent_str"]
        seq = graph.role_sequence
        assert "agent_str" in seq


class TestEdgesWithTensorValues:
    """Test edges property with tensor values in edge data."""

    def test_edges_with_tensor_value(self):
        g = rx.PyDiGraph()
        g.add_node({"id": "a"})
        g.add_node({"id": "b"})
        tensor_val = torch.tensor([1.0, 2.0, 3.0])
        g.add_edge(0, 1, {"weight": 1.0, "tensor_data": tensor_val})

        graph = RoleGraph(node_ids=["a", "b"], graph=g)
        edges = graph.edges
        assert len(edges) == 1
        assert "tensor_data" in edges[0]
        # tensor_data should be converted to a list
        assert isinstance(edges[0]["tensor_data"], list)


class TestEdgeAttrNonTensor:
    """Test edge_attr when attr is a list (not tensor)."""

    def test_edge_attr_with_list(self):
        g = rx.PyDiGraph()
        g.add_node({"id": "a"})
        g.add_node({"id": "b"})
        g.add_edge(0, 1, {"weight": 1.0, "attr": [0.5, 0.5, 0.5, 0.5]})

        graph = RoleGraph(node_ids=["a", "b"], graph=g)
        attr = graph.edge_attr
        assert attr.shape == (1, 4)
        assert attr[0, 0].item() == pytest.approx(0.5)


class TestRemoveEdgeConditionBoth:
    """Test removing both callable and string edge conditions."""

    def test_remove_both_conditions(self):
        graph = RoleGraph(
            node_ids=["a", "b"],
            role_connections={"a": ["b"], "b": []},
        )
        # Set a callable condition
        graph.edge_conditions[("a", "b")] = lambda _: True
        # Set a string condition
        graph.edge_condition_names[("a", "b")] = "some_condition"

        result = graph.remove_edge_condition("a", "b")
        assert result is True
        assert ("a", "b") not in graph.edge_conditions
        assert ("a", "b") not in graph.edge_condition_names


class TestAddNodeWithConnections:
    """Test add_node with connections_from and connections_to."""

    def test_add_node_with_connections_from(self):
        from core.agent import AgentProfile

        # Create a graph with an existing node
        g = rx.PyDiGraph()
        g.add_node({"id": "existing"})
        existing_agent = AgentProfile(agent_id="existing", display_name="Existing")
        graph = RoleGraph(
            node_ids=["existing"],
            role_connections={"existing": []},
            graph=g,
            A_com=torch.zeros((1, 1)),
        )
        graph.agents = [existing_agent]

        # Add new node with connections_from an existing node
        new_agent = AgentProfile(agent_id="new_node", display_name="New Node")
        result = graph.add_node(new_agent, connections_from=["existing"])
        assert result is True
        assert "new_node" in graph.node_ids
        assert graph.num_edges == 1

    def test_add_node_already_exists_returns_false(self):
        from core.agent import AgentProfile

        graph = RoleGraph()
        agent = AgentProfile(agent_id="agent1", display_name="Agent 1")
        graph.add_node(agent)
        # Adding same agent again should return False
        result = graph.add_node(agent)
        assert result is False


class TestRemoveNodeConnections:
    """Test that removing a node also removes it from other nodes' connections."""

    def test_remove_node_removes_from_connections(self):
        from core.agent import AgentProfile

        g = rx.PyDiGraph()
        g.add_node({"id": "a"})
        g.add_node({"id": "b"})
        g.add_edge(0, 1, {"weight": 1.0})

        agents = [
            AgentProfile(agent_id="a", display_name="A"),
            AgentProfile(agent_id="b", display_name="B"),
        ]
        graph = RoleGraph(
            node_ids=["a", "b"],
            role_connections={"a": ["b"], "b": []},
            graph=g,
            A_com=torch.tensor([[0.0, 1.0], [0.0, 0.0]]),
        )
        graph.agents = agents

        # Remove "b" - "a" still has "b" in connections
        graph.remove_node("b")
        assert "b" not in graph.node_ids
        assert "b" not in graph.role_connections.get("a", [])


class TestReplaceNodeWithArchive:
    """Test replace_node with StateMigrationPolicy.ARCHIVE."""

    def test_replace_node_archive_with_state_storage(self):
        from core.agent import AgentProfile
        from utils.state_storage import InMemoryStateStorage

        g = rx.PyDiGraph()
        g.add_node({"id": "agent1"})
        agent = AgentProfile(agent_id="agent1", display_name="Agent 1")
        storage = InMemoryStateStorage()
        graph = RoleGraph(
            node_ids=["agent1"],
            graph=g,
            A_com=torch.zeros((1, 1)),
            state_storage=storage,
        )
        graph.agents = [agent]

        new_agent = AgentProfile(agent_id="agent2", display_name="Agent 2")
        result = graph.replace_node("agent1", new_agent, StateMigrationPolicy.ARCHIVE)
        assert result is agent
        assert "agent2" in graph.node_ids

    def test_replace_node_no_id_uses_generated_id(self):
        """Test replace_node when new agent has no id."""
        from core.agent import AgentProfile

        class NoIdAgent:
            """An agent with no agent_id attribute."""

            def __init__(self):
                self.name = "no_id_agent"

        g = rx.PyDiGraph()
        g.add_node({"id": "agent1"})
        agent = AgentProfile(agent_id="agent1", display_name="Agent 1")
        graph = RoleGraph(
            node_ids=["agent1"],
            graph=g,
            A_com=torch.zeros((1, 1)),
        )
        graph.agents = [agent]

        no_id_agent = NoIdAgent()
        result = graph.replace_node("agent1", no_id_agent, StateMigrationPolicy.DISCARD)
        assert result is agent
        # A new ID was generated from id(no_id_agent)
        assert len(graph.node_ids) == 1


class TestCopyStateWithHiddenAndEmbedding:
    """Test _copy_state with hidden_state and embedding."""

    def test_copy_state_with_hidden_state(self):
        """Test that with_hidden_state is called when old agent has hidden_state."""
        from core.graph import RoleGraph

        graph = RoleGraph()

        # Use simple objects to avoid MagicMock chain replacement issue
        class OldAgent:
            hidden_state = torch.tensor([1.0, 2.0])
            embedding = None

        hidden_state_calls = []

        class NewAgent:
            def with_hidden_state(self, hs):
                hidden_state_calls.append(hs)
                return self

        old_agent = OldAgent()
        new_agent = NewAgent()
        graph._copy_state(old_agent, new_agent)
        assert len(hidden_state_calls) == 1

    def test_copy_state_with_embedding(self):
        """Test that with_embedding is called when old agent has embedding."""
        from core.graph import RoleGraph

        graph = RoleGraph()

        class OldAgent:
            hidden_state = None
            embedding = torch.tensor([1.0, 2.0, 3.0])

        embedding_calls = []

        class NewAgent:
            def with_embedding(self, emb):
                embedding_calls.append(emb)
                return self

        old_agent = OldAgent()
        new_agent = NewAgent()
        graph._copy_state(old_agent, new_agent)
        assert len(embedding_calls) == 1


class TestAddRemoveEdgeFalse:
    """Test add_edge and remove_edge returning False."""

    def test_add_edge_nonexistent_source_returns_false(self):
        graph = RoleGraph()
        result = graph.add_edge("nonexistent", "also_nonexistent")
        assert result is False

    def test_remove_edge_nonexistent_node_returns_false(self):
        graph = RoleGraph()
        result = graph.remove_edge("nonexistent", "also_nonexistent")
        assert result is False

    def test_remove_edge_no_matching_edge_returns_false(self):
        from core.agent import AgentProfile

        g = rx.PyDiGraph()
        g.add_node({"id": "a"})
        g.add_node({"id": "b"})
        # No edge between them

        agents = [
            AgentProfile(agent_id="a", display_name="A"),
            AgentProfile(agent_id="b", display_name="B"),
        ]
        graph = RoleGraph(
            node_ids=["a", "b"],
            role_connections={"a": [], "b": []},
            graph=g,
            A_com=torch.zeros((2, 2)),
        )
        graph.agents = agents

        result = graph.remove_edge("a", "b")
        assert result is False


class TestVerifyIntegrityErrors:
    """Test verify_integrity with various error conditions."""

    def test_agents_count_mismatch(self):
        from core.agent import AgentProfile

        g = rx.PyDiGraph()
        g.add_node({"id": "a"})
        g.add_node({"id": "b"})

        # Only one agent but two nodes
        graph = RoleGraph(
            node_ids=["a", "b"],
            graph=g,
            A_com=torch.zeros((2, 2)),
        )
        # Only one agent instead of two
        graph.agents = [AgentProfile(agent_id="a", display_name="A")]

        errors = graph.verify_integrity(raise_on_error=False)
        assert any("agents" in e for e in errors)

    def test_role_sequence_mismatch(self):
        from core.agent import AgentProfile

        g = rx.PyDiGraph()
        g.add_node({"id": "a"})
        g.add_node({"id": "b"})
        a_com = torch.zeros((2, 2))
        agents = [
            AgentProfile(agent_id="a", display_name="A"),
            AgentProfile(agent_id="c", display_name="C"),  # Mismatched ID
        ]
        graph = RoleGraph(
            node_ids=["a", "b"],
            role_connections={"a": [], "b": []},
            graph=g,
            A_com=a_com,
        )
        graph.agents = agents

        errors = graph.verify_integrity(raise_on_error=False)
        # Should detect role_sequence != node_ids
        assert len(errors) > 0

    def test_connection_source_not_in_nodes(self):
        from core.agent import AgentProfile

        g = rx.PyDiGraph()
        g.add_node({"id": "a"})
        a_com = torch.zeros((1, 1))
        agents = [AgentProfile(agent_id="a", display_name="A")]
        # role_connections has "ghost" which is not in node_ids
        graph = RoleGraph(
            node_ids=["a"],
            role_connections={"a": [], "ghost": []},
            graph=g,
            A_com=a_com,
        )
        graph.agents = agents

        errors = graph.verify_integrity(raise_on_error=False)
        assert any("ghost" in e for e in errors)


class TestGetRelevantNodesAutoDetect:
    """Test get_relevant_nodes when start/end are auto-detected."""

    def _make_linear_graph(self):
        from core.agent import AgentProfile

        agents = [AgentProfile(agent_id=aid, display_name=aid) for aid in ["a", "b", "c"]]
        g = rx.PyDiGraph()
        for aid in ["a", "b", "c"]:
            g.add_node({"id": aid})
        g.add_edge(0, 1, {"weight": 1.0})
        g.add_edge(1, 2, {"weight": 1.0})

        adj_matrix = torch.tensor(
            [
                [0, 1, 0],
                [0, 0, 1],
                [0, 0, 0],
            ],
            dtype=torch.float32,
        )

        graph = RoleGraph(
            node_ids=["a", "b", "c"],
            role_connections={"a": ["b"], "b": ["c"], "c": []},
            graph=g,
            A_com=adj_matrix,
        )
        graph.agents = agents
        return graph

    def test_get_relevant_nodes_auto_start_end(self):
        graph = self._make_linear_graph()
        # Without specifying start/end, should auto-detect
        relevant = graph.get_relevant_nodes()
        assert len(relevant) > 0

    def test_get_relevant_nodes_empty_graph_returns_empty(self):
        graph = RoleGraph()
        relevant = graph.get_relevant_nodes()
        assert relevant == set()

    def test_get_optimized_execution_order_with_cycle(self):
        """Test get_optimized_execution_order falls back for cyclic graph."""
        from core.agent import AgentProfile

        # Create a graph with a cycle: a -> b -> a
        agents = [AgentProfile(agent_id=aid, display_name=aid) for aid in ["a", "b"]]
        g = rx.PyDiGraph()
        g.add_node({"id": "a"})
        g.add_node({"id": "b"})
        g.add_edge(0, 1, {"weight": 1.0})
        g.add_edge(1, 0, {"weight": 1.0})  # cycle

        adj_matrix = torch.tensor([[0, 1], [1, 0]], dtype=torch.float32)
        graph = RoleGraph(
            node_ids=["a", "b"],
            role_connections={"a": ["b"], "b": ["a"]},
            graph=g,
            A_com=adj_matrix,
        )
        graph.agents = agents
        # Should not raise, just return some order
        order = graph.get_optimized_execution_order("a", "b")
        assert len(order) >= 2


class TestGetAgentSchemaWithData:
    """Test get_agent_schema when node data contains schema."""

    def test_get_agent_schema_with_valid_schema(self):
        from core.schema import AgentNodeSchema, NodeType

        schema = AgentNodeSchema(id="agent1")
        schema_dict = schema.model_dump()
        schema_dict["type"] = NodeType.AGENT.value

        g = rx.PyDiGraph()
        g.add_node({"id": "agent1", "schema": schema_dict})

        graph = RoleGraph(node_ids=["agent1"], graph=g)
        retrieved = graph.get_agent_schema("agent1")
        assert retrieved is not None
        assert retrieved.id == "agent1"

    def test_get_agent_schema_node_not_dict(self):
        g = rx.PyDiGraph()
        g.add_node("not_a_dict")  # non-dict node data

        graph = RoleGraph(node_ids=[], graph=g)
        result = graph.get_agent_schema("nonexistent")
        assert result is None

    def test_validate_agent_input_with_schema(self):
        from core.schema import AgentNodeSchema, NodeType

        schema = AgentNodeSchema(id="agent1", input_schema_json={"required": ["field1"]})
        schema_dict = schema.model_dump()
        schema_dict["type"] = NodeType.AGENT.value

        g = rx.PyDiGraph()
        g.add_node({"id": "agent1", "schema": schema_dict})

        graph = RoleGraph(node_ids=["agent1"], graph=g)
        result = graph.validate_agent_input("agent1", {"field1": "value"})
        assert result.valid is True

    def test_validate_agent_output_with_schema(self):
        from core.schema import AgentNodeSchema, NodeType

        schema = AgentNodeSchema(id="agent1", output_schema_json={"required": ["result"]})
        schema_dict = schema.model_dump()
        schema_dict["type"] = NodeType.AGENT.value

        g = rx.PyDiGraph()
        g.add_node({"id": "agent1", "schema": schema_dict})

        graph = RoleGraph(node_ids=["agent1"], graph=g)
        result = graph.validate_agent_output("agent1", {"result": "answer"})
        assert result.valid is True

    def test_get_input_schema_json_with_schema(self):
        from core.schema import AgentNodeSchema, NodeType

        schema = AgentNodeSchema(id="agent1", input_schema_json={"type": "object"})
        schema_dict = schema.model_dump()
        schema_dict["type"] = NodeType.AGENT.value

        g = rx.PyDiGraph()
        g.add_node({"id": "agent1", "schema": schema_dict})

        graph = RoleGraph(node_ids=["agent1"], graph=g)
        json_schema = graph.get_input_schema_json("agent1")
        assert json_schema is not None

    def test_get_output_schema_json_with_schema(self):
        from core.schema import AgentNodeSchema, NodeType

        schema = AgentNodeSchema(id="agent1", output_schema_json={"type": "object"})
        schema_dict = schema.model_dump()
        schema_dict["type"] = NodeType.AGENT.value

        g = rx.PyDiGraph()
        g.add_node({"id": "agent1", "schema": schema_dict})

        graph = RoleGraph(node_ids=["agent1"], graph=g)
        json_schema = graph.get_output_schema_json("agent1")
        assert json_schema is not None


class TestGetNodeFeaturesNonDict:
    """Test get_node_features_from_schema when node data is not a dict."""

    def test_non_dict_node_data(self):
        g = rx.PyDiGraph()
        g.add_node("not_a_dict")  # non-dict node data
        g.add_node({"id": "b"})

        graph = RoleGraph(node_ids=["non_dict_id", "b"], graph=g)
        # get_node_features_from_schema iterates over node_ids and gets idx
        # When idx is not None but data is not dict, uses default values
        features = graph.get_node_features_from_schema()
        assert "trust_score" in features
        assert "quality_score" in features


class TestSubgraphEdgeCases:
    """Test subgraph with edge cases."""

    def test_subgraph_agent_without_id_skipped(self):
        """Agent in self.agents that has no agent_id should be skipped."""

        class NoIdAgent:
            def __init__(self):
                self.name = "no_id"

        from core.agent import AgentProfile

        g = rx.PyDiGraph()
        g.add_node({"id": "a"})
        g.add_node({"id": "b"})
        g.add_edge(0, 1, {"weight": 1.0})
        adj_matrix = torch.tensor([[0.0, 1.0], [0.0, 0.0]])

        graph = RoleGraph(
            node_ids=["a", "b"],
            role_connections={"a": ["b"], "b": []},
            graph=g,
            A_com=adj_matrix,
        )
        # Inject an agent with no agent_id
        no_id = NoIdAgent()
        graph.agents = [no_id, AgentProfile(agent_id="b", display_name="B")]

        # Creating subgraph with "b" should work despite no_id agent
        sub = graph.subgraph(["b"])
        assert "b" in sub.node_ids

    def test_subgraph_empty_a_com(self):
        """Test subgraph when A_com is empty."""
        from core.agent import AgentProfile

        g = rx.PyDiGraph()
        g.add_node({"id": "a"})
        agents = [AgentProfile(agent_id="a", display_name="A")]
        graph = RoleGraph(
            node_ids=["a"],
            role_connections={"a": []},
            graph=g,
            A_com=torch.zeros((0, 0)),
        )
        graph.agents = agents

        sub = graph.subgraph(["a"])
        assert "a" in sub.node_ids


class TestGetEdgeFeaturesNonDict:
    """Test get_edge_features_from_schema when edge data is not a dict."""

    def test_non_dict_edge_data(self):
        g = rx.PyDiGraph()
        g.add_node({"id": "a"})
        g.add_node({"id": "b"})
        g.add_edge(0, 1, "not_a_dict")  # non-dict edge data

        graph = RoleGraph(node_ids=["a", "b"], graph=g)
        features = graph.get_edge_features_from_schema()
        assert "weight" in features
        assert features["weight"][0].item() == pytest.approx(1.0)  # default


if __name__ == "__main__":
    pytest.main([__file__, "-v"])