hypergraph-rs 0.3.0

Hypergraphs for Rust: a port of XGI built on rustworkx-core, with a value on every membership
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
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
//! Conformance replay: committed XGI ground-truth vectors
//! (`conformance/xgi_ground_truth.json`, generated from the installed XGI
//! runtime — never its docstrings — by `conformance/generate_fixtures.py`)
//! replayed against the Rust core.
//!
//! Every vector is either CONFORMANT (Rust asserts XGI's recorded outcome)
//! or a REGISTERED divergence (Dn — see the design spec's Divergence
//! Register), where the test asserts Rust's deliberate behavior AND pins
//! XGI's recorded truth, so drift on either side fails loudly. Regenerate
//! the fixture with `mise run rust:fixtures`; a fixture diff is news —
//! investigate before committing.

use hypergraph_rs::{
    DiHypergraph, DiRole, EdgeError, Hypergraph, MembershipError, NodeError, SimplicialComplex,
};
use serde_json::Value;

fn ground_truth() -> Value {
    let path = concat!(
        env!("CARGO_MANIFEST_DIR"),
        "/conformance/xgi_ground_truth.json"
    );
    let text = std::fs::read_to_string(path)
        .expect("conformance fixture missing — regenerate: mise run rust:fixtures");
    serde_json::from_str(&text).expect("conformance fixture is not valid JSON")
}

fn vector<'a>(gt: &'a Value, id: &str) -> &'a Value {
    &gt["vectors"][id]
}

/// XGI ids are typed (int auto-ids; arbitrary hashables for explicit ids);
/// the Rust core is stringly-typed at the ID boundary. Divergence D7.
fn id_str(v: &Value) -> String {
    match v {
        Value::Number(n) => n.to_string(),
        Value::String(s) => s.clone(),
        other => panic!("unexpected id type in fixture: {other}"),
    }
}

fn ids(v: &Value) -> Vec<String> {
    v.as_array().unwrap().iter().map(id_str).collect()
}

#[test]
fn fixture_is_pinned_to_xgi_1_1() {
    let gt = ground_truth();
    assert_eq!(gt["xgi_version"], "1.1");
    assert_eq!(gt["generated_by"], "conformance/generate_fixtures.py");
}

#[test]
fn conform_add_edge_empty_creates_edge() {
    // D1 RESOLVED: XGI's docstring claims XGIError on empty members; the
    // runtime creates an empty edge (and XGI's own test suite asserts it).
    // Rust matches the runtime.
    let gt = ground_truth();
    let v = vector(&gt, "add_edge_empty_creates_edge");
    assert_eq!(v["num_edges"], 1);
    assert_eq!(v["num_nodes"], 0);

    let mut h: Hypergraph = Hypergraph::new();
    let id = h.add_edge(vec![], None, Value::Null).unwrap();
    assert_eq!(id, id_str(&v["edge_ids"][0]));
    assert_eq!(h.num_edges(), 1);
    assert_eq!(h.num_nodes(), 0);
    assert!(h.members(&id).unwrap().is_empty());
}

#[test]
fn conform_add_edge_three_empty_auto_ids() {
    let gt = ground_truth();
    let v = vector(&gt, "add_edge_three_empty_auto_ids");
    let mut h: Hypergraph = Hypergraph::new();
    for expected in ids(&v["edge_ids"]) {
        assert_eq!(h.add_edge(vec![], None, Value::Null).unwrap(), expected);
    }
    assert_eq!(h.num_edges(), 3);
}

#[test]
fn conform_add_edge_auto_ids_sequence() {
    let gt = ground_truth();
    let v = vector(&gt, "add_edge_auto_ids_sequence");
    let mut h: Hypergraph = Hypergraph::new();
    let a = h.add_edge(vec!["a".into()], None, Value::Null).unwrap();
    let b = h.add_edge(vec!["b".into()], None, Value::Null).unwrap();
    assert_eq!(vec![a, b], ids(&v["edge_ids"]));
}

#[test]
fn conform_add_edge_int_idx_bumps_counter() {
    // XGI with int idx 5 bumps the counter to 6. Rust is stringly-typed but
    // bumps for strings that parse as u64 — outcome-conformant.
    let gt = ground_truth();
    let v = vector(&gt, "add_edge_int_idx_bumps_counter");
    let mut h: Hypergraph = Hypergraph::new();
    h.add_edge(vec!["a".into()], Some("5".into()), Value::Null)
        .unwrap();
    let auto = h.add_edge(vec!["b".into()], None, Value::Null).unwrap();
    assert_eq!(vec!["5".to_string(), auto], ids(&v["edge_ids"]));
}

#[test]
fn conform_add_edge_dedups_members() {
    let gt = ground_truth();
    let v = vector(&gt, "add_edge_dedups_members");
    let mut h: Hypergraph = Hypergraph::new();
    h.add_edge(
        vec!["a".into(), "a".into(), "b".into()],
        Some("e1".into()),
        Value::Null,
    )
    .unwrap();
    assert_eq!(h.num_nodes(), v["num_nodes"].as_u64().unwrap() as usize);
    assert_eq!(h.members("e1").unwrap(), vec!["a", "b"]);
}

#[test]
fn diverge_d2_dup_idx_errors_instead_of_warn_noop() {
    // D2: XGI warns + no-ops (returns None); the Rust core returns
    // Err(AlreadyExists). The PyO3 binding MUST translate back to
    // UserWarning + None for conformance. XGI's warning is pinned here.
    let gt = ground_truth();
    let v = vector(&gt, "add_edge_dup_idx_warns_noop");
    assert_eq!(v["warned"], true);
    assert!(v["warning_prefix"]
        .as_str()
        .unwrap()
        .starts_with("uid e1 already exists"));

    let mut h: Hypergraph = Hypergraph::new();
    h.add_edge(vec!["a".into()], Some("e1".into()), Value::Null)
        .unwrap();
    let err = h.add_edge(vec!["b".into()], Some("e1".into()), Value::Null);
    assert!(matches!(err, Err(EdgeError::AlreadyExists { .. })));
    assert_eq!(h.num_edges(), 1);
    assert_eq!(h.members("e1").unwrap(), vec!["a"]);
}

#[test]
fn diverge_d3_str_numeric_idx_bumps_counter() {
    // D3: XGI does NOT bump its uid counter for a string idx ("5" → next
    // auto 0). Rust bumps iff `idx.parse::<u64>()` succeeds ("5" → "6").
    // Rationale: the ID boundary is stringly-typed (D7); XGI's int-idx
    // behavior is the common case worth preserving.
    let gt = ground_truth();
    let v = vector(&gt, "add_edge_str_idx_no_bump");
    assert_eq!(ids(&v["edge_ids"]), vec!["5", "0"]); // XGI truth, pinned

    let mut h: Hypergraph = Hypergraph::new();
    h.add_edge(vec!["a".into()], Some("5".into()), Value::Null)
        .unwrap();
    let auto = h.add_edge(vec!["b".into()], None, Value::Null).unwrap();
    assert_eq!(auto, "6"); // Rust divergence, deliberate
}

#[test]
fn diverge_d4_float_idx_does_not_bump() {
    // D4: XGI bumps for float idx 5.0 (float.is_integer()); Rust's
    // parse::<u64> rejects "5.0", so no bump — the D3 rule is exact.
    let gt = ground_truth();
    let v = vector(&gt, "add_edge_float_idx_bumps");
    assert_eq!(ids(&v["edge_ids"]), vec!["5.0", "6"]); // XGI truth, pinned

    let mut h: Hypergraph = Hypergraph::new();
    h.add_edge(vec!["a".into()], Some("5.0".into()), Value::Null)
        .unwrap();
    let auto = h.add_edge(vec!["b".into()], None, Value::Null).unwrap();
    assert_eq!(auto, "0"); // Rust divergence, deliberate
}

#[test]
fn diverge_d6_add_node_replaces_instead_of_merging() {
    // D6: XGI merges attrs when re-adding an existing node ({x:1} then
    // {y:2} → {x:1, y:2}); the Rust core REPLACES (a generic N cannot
    // merge). The PyO3 binding merges dicts before calling to recover XGI
    // semantics.
    let gt = ground_truth();
    let v = vector(&gt, "add_node_existing_updates_attrs");
    assert_eq!(v["attrs"], serde_json::json!({"x": 1, "y": 2})); // XGI truth

    let mut h: Hypergraph = Hypergraph::new();
    h.add_node("a", serde_json::json!({"x": 1}));
    h.add_node("a", serde_json::json!({"y": 2}));
    assert_eq!(h.node_attrs("a").unwrap(), &serde_json::json!({"y": 2}));
    assert_eq!(h.num_nodes(), 1);
}

#[test]
fn conform_node_attr_set_read() {
    // XGI-facing mutation: H.nodes["a"]["color"] = "red" mutates the node's
    // attr dict in place. The Rust core exposes the same write path via
    // node_attrs_mut; reading it back matches XGI's recorded dict.
    let gt = ground_truth();
    let v = vector(&gt, "node_attr_set_read");
    assert_eq!(v["attrs"], serde_json::json!({"color": "red"})); // XGI truth

    let mut h: Hypergraph = Hypergraph::new();
    h.add_node("a", serde_json::json!({}));
    h.node_attrs_mut("a").unwrap()["color"] = serde_json::json!("red");
    assert_eq!(h.node_attrs("a").unwrap(), &v["attrs"]);
}

#[test]
fn conform_d10_clear_preserves_uid_counter() {
    // XGI's clear() (remove_net_attr=True default) empties all nodes, edges,
    // node/edge attrs, and net attrs — the Rust core conforms on all of
    // that. D10 (DISSOLVED, owner ruling 2026-07-22): XGI does NOT reset
    // its auto-id counter (the next auto id continues at 1); main's
    // clear() (hypergraph.rs:354-360) deliberately preserves the counter
    // too, matching XGI — the fixture pins "1", not "0".
    let gt = ground_truth();
    let v = vector(&gt, "clear_all");
    assert_eq!(v["num_nodes"], 0); // XGI truth, pinned
    assert_eq!(v["num_edges"], 0);
    assert_eq!(v["node_ids"], serde_json::json!([]));
    assert_eq!(v["edge_ids"], serde_json::json!([]));
    assert_eq!(v["net_attrs"], serde_json::json!({}));
    assert_eq!(ids(&v["auto_ids_after_clear"]), vec!["1"]); // XGI truth, pinned

    let mut h: Hypergraph = Hypergraph::new();
    h.add_edge(vec!["a".into(), "b".into()], None, Value::Null)
        .unwrap();
    h.add_edge(
        vec!["c".into(), "d".into()],
        Some("e1".into()),
        serde_json::json!({"heat": 0.5}),
    )
    .unwrap();
    h.add_node("lonely", serde_json::json!({"x": 1}));
    h.set_graph_attr("name", serde_json::json!("test"));
    h.clear();

    assert_eq!(h.num_nodes(), 0);
    assert_eq!(h.num_edges(), 0);
    assert!(h.node_ids().is_empty());
    assert!(h.edge_ids().is_empty());
    assert!(h.graph_attr("name").is_none());
    assert!(h.node_attrs("lonely").is_none());
    assert!(h.edge_attrs("e1").is_none());

    // D10 (DISSOLVED): main preserves the counter — the post-clear auto id
    // continues at "1", matching XGI.
    let auto = h.add_edge(vec!["z".into()], None, Value::Null).unwrap();
    assert_eq!(auto, "1"); // XGI-conformant
}

#[test]
fn conform_remove_edge_basic() {
    let gt = ground_truth();
    let v = vector(&gt, "remove_edge_basic");

    let mut h: Hypergraph = Hypergraph::new();
    h.add_edge(vec!["a".into(), "b".into()], Some("e1".into()), Value::Null)
        .unwrap();
    h.add_edge(vec!["a".into(), "c".into()], Some("e2".into()), Value::Null)
        .unwrap();
    h.remove_edge("e1").unwrap();

    assert_eq!(h.edge_ids(), ids(&v["edge_ids"]));
    assert_eq!(h.num_edges(), v["num_edges"].as_u64().unwrap() as usize);
    assert_eq!(h.num_nodes(), v["num_nodes"].as_u64().unwrap() as usize);
    // Nodes survive edge removal (XGI parity).
    let mut rust_nodes = h.node_ids();
    rust_nodes.sort();
    assert_eq!(rust_nodes, ids(&v["node_ids"]));
    // Surviving edge keeps its members.
    let mut rust_members = h.members("e2").unwrap();
    rust_members.sort();
    assert_eq!(rust_members, ids(&v["members"]["e2"]));
    // Every surviving node's memberships reflect the removal.
    for (nid, expected) in v["memberships"].as_object().unwrap() {
        let mut got = h.memberships(nid).unwrap();
        got.sort();
        assert_eq!(got, ids(expected));
    }
}

#[test]
fn diverge_d2_remove_edge_missing_errors() {
    // Same error-channel class as D2: XGI signals a missing edge by raising
    // IDNotFound; the Rust core returns Err(EdgeError::NotFound) and the
    // PyO3 binding translates Err → raise. No new divergence number.
    let gt = ground_truth();
    let v = vector(&gt, "remove_edge_missing_raises");
    assert_eq!(v["exception"], "IDNotFound"); // XGI truth, pinned
    assert_eq!(v["message"], "'ID nonexistent not found'");

    let mut h: Hypergraph = Hypergraph::new();
    let err = h.remove_edge("nonexistent");
    assert!(matches!(err, Err(EdgeError::NotFound { .. })));
}

#[test]
fn conform_remove_node_weak() {
    // Weak removal (XGI defaults strong=False, remove_empty=True): the node
    // is dropped from every containing edge; an edge it leaves EMPTY is
    // removed (e3 was the singleton ["b"]). Other nodes and edges survive.
    let gt = ground_truth();
    let v = vector(&gt, "remove_node_weak");

    let mut h: Hypergraph = Hypergraph::new();
    h.add_edge(
        vec!["a".into(), "b".into(), "c".into()],
        Some("e1".into()),
        Value::Null,
    )
    .unwrap();
    h.add_edge(vec!["b".into(), "d".into()], Some("e2".into()), Value::Null)
        .unwrap();
    h.add_edge(vec!["b".into()], Some("e3".into()), Value::Null)
        .unwrap();
    h.remove_node("b", false, true).unwrap();

    assert_eq!(h.edge_ids(), ids(&v["edge_ids"])); // e3 emptied -> removed
    assert_eq!(h.num_edges(), v["num_edges"].as_u64().unwrap() as usize);
    assert_eq!(h.num_nodes(), v["num_nodes"].as_u64().unwrap() as usize);
    let mut rust_nodes = h.node_ids();
    rust_nodes.sort();
    assert_eq!(rust_nodes, ids(&v["node_ids"]));
    for (eid, expected) in v["members"].as_object().unwrap() {
        let mut got = h.members(eid).unwrap();
        got.sort();
        assert_eq!(got, ids(expected));
    }
    for (nid, expected) in v["memberships"].as_object().unwrap() {
        let mut got = h.memberships(nid).unwrap();
        got.sort();
        assert_eq!(got, ids(expected));
    }
}

#[test]
fn conform_remove_node_strong() {
    // Strong removal: EVERY edge containing the node is removed (e1, e2);
    // edges not containing it survive (e4), as do the other nodes.
    let gt = ground_truth();
    let v = vector(&gt, "remove_node_strong");

    let mut h: Hypergraph = Hypergraph::new();
    h.add_edge(vec!["a".into(), "b".into()], Some("e1".into()), Value::Null)
        .unwrap();
    h.add_edge(
        vec!["a".into(), "c".into(), "d".into()],
        Some("e2".into()),
        Value::Null,
    )
    .unwrap();
    h.add_edge(vec!["c".into(), "d".into()], Some("e4".into()), Value::Null)
        .unwrap();
    h.remove_node("a", true, true).unwrap();

    assert_eq!(h.edge_ids(), ids(&v["edge_ids"]));
    assert_eq!(h.num_edges(), v["num_edges"].as_u64().unwrap() as usize);
    assert_eq!(h.num_nodes(), v["num_nodes"].as_u64().unwrap() as usize);
    let mut rust_nodes = h.node_ids();
    rust_nodes.sort();
    assert_eq!(rust_nodes, ids(&v["node_ids"]));
    for (eid, expected) in v["members"].as_object().unwrap() {
        let mut got = h.members(eid).unwrap();
        got.sort();
        assert_eq!(got, ids(expected));
    }
    for (nid, expected) in v["memberships"].as_object().unwrap() {
        let mut got = h.memberships(nid).unwrap();
        got.sort();
        assert_eq!(got, ids(expected));
    }
}

#[test]
fn diverge_d2_remove_node_missing_errors() {
    // Same error-channel class as D2: XGI signals a missing node by raising
    // IDNotFound; the Rust core returns Err(NodeError::NotFound) and the
    // PyO3 binding translates Err → raise. No new divergence number.
    let gt = ground_truth();
    let v = vector(&gt, "remove_node_missing_raises");
    assert_eq!(v["exception"], "IDNotFound"); // XGI truth, pinned
    assert_eq!(v["message"], "'ID nonexistent not found'");

    let mut h: Hypergraph = Hypergraph::new();
    let err = h.remove_node("nonexistent", false, true);
    assert!(matches!(err, Err(NodeError::NotFound { .. })));
}

#[test]
fn conform_remove_node_remove_empty() {
    // XGI's remove_node(n, strong, remove_empty) is three-mode (register
    // D9, implemented in Phase 2 Task 2): weak + remove_empty=False leaves
    // the emptied edge in place (queryable: members(e) == []); weak +
    // remove_empty=True (the XGI default) drops it; strong removes every
    // incident edge REGARDLESS of the flag. The Rust core conforms on all
    // three modes.
    let gt = ground_truth();
    let v = vector(&gt, "remove_node_remove_empty");
    assert_eq!(v["weak_keep"]["return"], Value::Null); // XGI truth, pinned
    assert_eq!(v["weak_keep"]["has_node_b"], false); // XGI truth, pinned
    assert_eq!(v["weak_keep"]["members"]["e2"], serde_json::json!([])); // pinned

    // Weak + remove_empty=False: the emptied edge SURVIVES.
    let mut h: Hypergraph = Hypergraph::new();
    h.add_edge(vec!["a".into(), "b".into()], Some("e1".into()), Value::Null)
        .unwrap();
    h.add_edge(vec!["b".into()], Some("e2".into()), Value::Null)
        .unwrap();
    h.remove_node("b", false, false).unwrap();
    assert_eq!(h.edge_ids(), ids(&v["weak_keep"]["edge_ids"]));
    assert_eq!(
        h.num_edges(),
        v["weak_keep"]["num_edges"].as_u64().unwrap() as usize
    );
    assert!(!h.has_node("b"));
    assert_eq!(h.node_ids(), ids(&v["weak_keep"]["node_ids"]));
    assert_eq!(h.members("e1").unwrap(), vec!["a"]);
    assert_eq!(h.members("e2").unwrap(), Vec::<String>::new()); // emptied, alive

    // Weak + remove_empty=True: the emptied edge is dropped.
    let mut h: Hypergraph = Hypergraph::new();
    h.add_edge(vec!["a".into(), "b".into()], Some("e1".into()), Value::Null)
        .unwrap();
    h.add_edge(vec!["b".into()], Some("e2".into()), Value::Null)
        .unwrap();
    h.remove_node("b", false, true).unwrap();
    assert_eq!(h.edge_ids(), ids(&v["weak_drop"]["edge_ids"]));
    assert_eq!(
        h.num_edges(),
        v["weak_drop"]["num_edges"].as_u64().unwrap() as usize
    );

    // Strong + remove_empty=False: incident edges are removed ANYWAY.
    let mut h: Hypergraph = Hypergraph::new();
    h.add_edge(vec!["a".into(), "b".into()], Some("e1".into()), Value::Null)
        .unwrap();
    h.add_edge(
        vec!["a".into(), "c".into(), "d".into()],
        Some("e2".into()),
        Value::Null,
    )
    .unwrap();
    h.add_edge(vec!["c".into(), "d".into()], Some("e4".into()), Value::Null)
        .unwrap();
    h.remove_node("a", true, false).unwrap();
    assert_eq!(h.edge_ids(), ids(&v["strong_ignores_flag"]["edge_ids"]));
    assert_eq!(h.node_ids(), ids(&v["strong_ignores_flag"]["node_ids"]));
    assert_eq!(h.members("e4").unwrap(), vec!["c", "d"]);
}

#[test]
fn diverge_d2_remove_nodes_from_missing_warns_per_item() {
    // XGI's remove_nodes_from WARNS on a missing id ("Node ghost not in
    // hypergraph" — note: no "the", unlike remove_node's IDNotFound
    // message), SKIPS it, and CONTINUES with the rest; returns None.
    // D2-class channel translation: the Rust core records a per-item
    // Err(NodeError::NotFound) in the returned Vec and continues; the
    // binding warns per Err item to reproduce XGI's behavior.
    let gt = ground_truth();
    let v = vector(&gt, "remove_nodes_from_missing");
    assert_eq!(v["return"], Value::Null); // XGI truth, pinned
    assert_eq!(v["warned"], true); // XGI truth, pinned
    assert_eq!(v["warning_message"], "Node ghost not in hypergraph"); // pinned

    let mut h: Hypergraph = Hypergraph::new();
    h.add_edge(vec!["a".into(), "b".into()], Some("e1".into()), Value::Null)
        .unwrap();
    h.add_edge(vec!["b".into(), "c".into()], Some("e2".into()), Value::Null)
        .unwrap();
    let results = h.remove_nodes_from(
        &["b".to_string(), "ghost".to_string(), "c".to_string()],
        false,
        true,
    );
    assert_eq!(results.len(), 3);
    assert!(results[0].is_ok());
    assert_eq!(
        results[1],
        Err(NodeError::NotFound {
            node_id: "ghost".to_string()
        })
    );
    assert!(results[2].is_ok(), "continues past the missing id");

    assert_eq!(h.node_ids(), ids(&v["node_ids"]));
    assert_eq!(h.edge_ids(), ids(&v["edge_ids"]));
    assert_eq!(h.members("e1").unwrap(), vec!["a"]);
}

#[test]
fn diverge_d2_remove_edges_from_missing_stops_after_err() {
    // XGI's remove_edges_from RAISES IDNotFound("ID ghost not found") on
    // the first missing id — ids BEFORE it are already removed (partial
    // effects); ids AFTER it are never attempted (["e1", "ghost", "e3"]
    // leaves e2 AND e3 in place). D2-class channel translation: the Rust
    // core records per-item results and STOPS after the first Err (the
    // returned Vec has one entry per ATTEMPTED id, length <= input), so
    // the binding can reproduce the raise exactly — the state already
    // matches XGI's post-raise state.
    let gt = ground_truth();
    let v = vector(&gt, "remove_edges_from_missing");
    assert_eq!(v["exception"], "IDNotFound"); // XGI truth, pinned
    assert_eq!(v["message"], "'ID ghost not found'"); // XGI truth, pinned
    assert_eq!(v["all_valid_return"], Value::Null); // XGI truth, pinned

    let mut h: Hypergraph = Hypergraph::new();
    h.add_edge(vec!["a".into(), "b".into()], Some("e1".into()), Value::Null)
        .unwrap();
    h.add_edge(vec!["b".into(), "c".into()], Some("e2".into()), Value::Null)
        .unwrap();
    h.add_edge(vec!["c".into(), "d".into()], Some("e3".into()), Value::Null)
        .unwrap();
    let results = h.remove_edges_from(&["e1".to_string(), "ghost".to_string(), "e3".to_string()]);
    assert_eq!(results.len(), 2, "e3 was never attempted");
    assert!(results[0].is_ok());
    assert_eq!(
        results[1],
        Err(EdgeError::NotFound {
            edge_id: "ghost".to_string()
        })
    );
    assert_eq!(h.edge_ids(), ids(&v["edge_ids_after"])); // e2 AND e3 survive
    assert_eq!(h.num_nodes(), v["num_nodes"].as_u64().unwrap() as usize);

    // All-valid bunch: every listed edge removed, nodes survive.
    let mut h2: Hypergraph = Hypergraph::new();
    h2.add_edge(vec!["a".into(), "b".into()], Some("e1".into()), Value::Null)
        .unwrap();
    h2.add_edge(vec!["b".into(), "c".into()], Some("e2".into()), Value::Null)
        .unwrap();
    let results = h2.remove_edges_from(&["e1".to_string(), "e2".to_string()]);
    assert_eq!(results.len(), 2);
    assert!(results.iter().all(|r| r.is_ok()));
    assert!(h2.edge_ids().is_empty());
    assert_eq!(h2.node_ids(), ids(&v["all_valid_nodes"]));
}

#[test]
fn conform_remove_edge_then_readd() {
    // Reviewer insurance: removing an edge must not leave residue. A re-added
    // idx gets FRESH members (a/b do not resurrect into "e1"), and XGI's uid
    // counter does not reuse the removed id — string idx "e1" never bumped
    // the counter, so the next auto id is 0 (recorded as int in the fixture).
    let gt = ground_truth();
    let v = vector(&gt, "remove_edge_then_readd");
    assert_eq!(v["return"], Value::Null); // XGI add_edge returns None, pinned

    let mut h: Hypergraph = Hypergraph::new();
    h.add_edge(vec!["a".into(), "b".into()], Some("e1".into()), Value::Null)
        .unwrap();
    h.remove_edge("e1").unwrap();
    h.add_edge(vec!["c".into()], Some("e1".into()), Value::Null)
        .unwrap();
    let auto = h.add_edge(vec!["d".into()], None, Value::Null).unwrap();

    // Fresh members for the re-added idx — no resurrection of a/b.
    assert_eq!(h.members("e1").unwrap(), vec!["c"]);
    assert_eq!(auto, "0");
    assert_eq!(h.edge_ids(), ids(&v["edge_ids"]));
    assert_eq!(h.num_edges(), v["num_edges"].as_u64().unwrap() as usize);
    assert_eq!(h.num_nodes(), v["num_nodes"].as_u64().unwrap() as usize);
    let mut rust_nodes = h.node_ids();
    rust_nodes.sort();
    assert_eq!(rust_nodes, ids(&v["node_ids"]));
    for (eid, expected) in v["members"].as_object().unwrap() {
        let mut got = h.members(eid).unwrap();
        got.sort();
        assert_eq!(got, ids(expected));
    }
}

#[test]
fn conform_copy_independence() {
    // XGI's H.copy() is a DEEP, independent clone: mutating the original in
    // any channel (node attrs, edge attrs, net attrs, membership) leaves
    // the copy untouched. The Rust core conforms — clone() is deep on every
    // channel (serde_json::Value attrs clone by value).
    let gt = ground_truth();
    let v = vector(&gt, "copy_independence");

    let mut h: Hypergraph = Hypergraph::new();
    h.add_node("a", serde_json::json!({"color": "red"}));
    h.add_edge(
        vec!["a".into(), "b".into()],
        Some("e1".into()),
        serde_json::json!({"heat": 0.5}),
    )
    .unwrap();
    h.set_graph_attr("name", serde_json::json!("test"));

    let c = h.copy();

    // Mutate the original in every channel.
    h.node_attrs_mut("a").unwrap()["color"] = serde_json::json!("blue");
    h.edge_attrs_mut("e1").unwrap()["heat"] = serde_json::json!(0.9);
    h.set_graph_attr("name", serde_json::json!("modified"));
    h.add_node("c", Value::Null);

    // The copy is untouched — XGI's recorded truth.
    assert_eq!(c.node_attrs("a").unwrap(), &v["node_attrs"]);
    assert_eq!(c.edge_attrs("e1").unwrap(), &v["edge_attrs"]);
    assert_eq!(c.graph_attr("name"), Some(&v["net_name"]));
    assert_eq!(c.num_nodes(), v["num_nodes"].as_u64().unwrap() as usize);
    assert_eq!(c.num_edges(), v["num_edges"].as_u64().unwrap() as usize);
    assert_eq!(c.has_node("c"), v["has_c"].as_bool().unwrap());
}

#[test]
fn conform_eq_structural() {
    // XGI's Hypergraph.__eq__ delegates to xgi.algorithms.equal with the
    // defaults (compare_edge_ids=True, compare_attrs=True): edge-id ->
    // members mapping, node attrs, edge attrs, and net attrs are all
    // significant; insertion/member order is not. The Rust core's PartialEq
    // matches every recorded verdict.
    let gt = ground_truth();
    let v = vector(&gt, "eq_structural");
    // XGI truth, pinned.
    assert_eq!(v["same"], true);
    assert_eq!(v["diff_edge_attr"], false);
    assert_eq!(v["diff_members"], false);
    assert_eq!(v["diff_edge_id"], false);
    assert_eq!(v["diff_net_attr"], false);
    assert_eq!(v["member_order_insignificant"], true);
    assert_eq!(v["lonely_same"], true);
    assert_eq!(v["diff_node_attr"], false);

    let build = |members: &[&str],
                 idx: &str,
                 edge_attr: Value,
                 solo: Option<(&str, Value)>,
                 net: Option<(&str, Value)>| {
        let mut h: Hypergraph = Hypergraph::new();
        h.add_edge(
            members.iter().map(|m| m.to_string()).collect(),
            Some(idx.into()),
            edge_attr,
        )
        .unwrap();
        if let Some((n, attrs)) = solo {
            h.add_node(n, attrs);
        }
        if let Some((k, val)) = net {
            h.set_graph_attr(k, val);
        }
        h
    };
    let a = build(&["a", "b"], "e1", serde_json::json!({"w": 1}), None, None);
    assert_eq!(
        a,
        build(&["a", "b"], "e1", serde_json::json!({"w": 1}), None, None)
    );
    assert_ne!(
        a,
        build(&["a", "b"], "e1", serde_json::json!({"w": 2}), None, None)
    );
    assert_ne!(a, build(&["a", "c"], "e1", Value::Null, None, None));
    assert_ne!(a, build(&["a", "b"], "e2", Value::Null, None, None));
    assert_ne!(
        a,
        build(
            &["a", "b"],
            "e1",
            serde_json::json!({"w": 1}),
            None,
            Some(("name", serde_json::json!("x")))
        )
    );
    assert_eq!(
        a,
        build(&["b", "a"], "e1", serde_json::json!({"w": 1}), None, None)
    );
    let l1 = build(
        &[],
        "e1",
        Value::Null,
        Some(("solo", serde_json::json!({"color": "red"}))),
        None,
    );
    let l2 = build(
        &[],
        "e1",
        Value::Null,
        Some(("solo", serde_json::json!({"color": "red"}))),
        None,
    );
    let l3 = build(
        &[],
        "e1",
        Value::Null,
        Some(("solo", serde_json::json!({"color": "blue"}))),
        None,
    );
    assert_eq!(l1, l2);
    assert_ne!(l1, l3);
}

#[test]
fn conform_copy_counter_preserved() {
    // Reviewer insurance (S3-1): XGI's copy() carries the auto-id counter
    // (`cp._edge_uid = copy(self._edge_uid)`) — an auto edge added to the
    // copy gets the NEXT counter value, it does not restart at 0. The Rust
    // core conforms: copy() clones edge_uid_counter.
    let gt = ground_truth();
    let v = vector(&gt, "copy_counter_preserved");
    assert_eq!(ids(&v["h_edge_ids"]), vec!["0"]); // XGI truth, pinned
    assert_eq!(ids(&v["cp_edge_ids"]), vec!["0", "1"]); // XGI truth, pinned

    let mut h: Hypergraph = Hypergraph::new();
    assert_eq!(
        h.add_edge(vec!["a".into()], None, Value::Null).unwrap(),
        "0"
    );
    let mut cp = h.copy();
    let auto = cp.add_edge(vec!["b".into()], None, Value::Null).unwrap();
    assert_eq!(auto, "1");
    assert_eq!(h.edge_ids(), ids(&v["h_edge_ids"]));
    assert_eq!(cp.edge_ids(), ids(&v["cp_edge_ids"]));
    assert_eq!(h.num_edges(), v["h_num_edges"].as_u64().unwrap() as usize);
    assert_eq!(cp.num_edges(), v["cp_num_edges"].as_u64().unwrap() as usize);
}

#[test]
fn conform_add_node_to_edge_autocreate() {
    // XGI's add_node_to_edge auto-creates a missing edge AND a missing node
    // (runtime-verified), returns None, is idempotent on re-add (set
    // semantics), and preserves existing edge attrs. The Rust core conforms
    // on every channel.
    let gt = ground_truth();
    let v = vector(&gt, "add_node_to_edge_autocreate");
    assert_eq!(v["return_create"], Value::Null); // XGI truth, pinned
    assert_eq!(v["return_readd"], Value::Null); // XGI truth, pinned

    let mut h: Hypergraph = Hypergraph::new();
    h.add_node_to_edge("new_edge", "new_node").unwrap(); // both missing
    h.add_edge(
        vec!["a".into(), "b".into()],
        Some("e1".into()),
        serde_json::json!({"heat": 0.5}),
    )
    .unwrap();
    h.add_node_to_edge("e1", "c").unwrap(); // existing edge, new node
    h.add_node_to_edge("e1", "c").unwrap(); // idempotent re-add
    h.add_node_to_edge("e1", "a").unwrap(); // existing node into existing edge

    assert_eq!(h.edge_ids(), ids(&v["edge_ids"]));
    assert_eq!(h.num_edges(), v["num_edges"].as_u64().unwrap() as usize);
    assert_eq!(h.num_nodes(), v["num_nodes"].as_u64().unwrap() as usize);
    let mut rust_nodes = h.node_ids();
    rust_nodes.sort();
    assert_eq!(rust_nodes, ids(&v["node_ids"]));
    for (eid, expected) in v["members"].as_object().unwrap() {
        let mut got = h.members(eid).unwrap();
        got.sort();
        assert_eq!(got, ids(expected));
    }
    for (nid, expected) in v["memberships"].as_object().unwrap() {
        let mut got = h.memberships(nid).unwrap();
        got.sort();
        assert_eq!(got, ids(expected));
    }
    assert_eq!(h.edge_attrs("e1").unwrap(), &v["edge_attrs_e1"]);
}

#[test]
fn conform_add_node_to_edge_numeric_advances_counter() {
    // D11 is closed by XGI 1.1: add_node_to_edge now calls update_uid_counter,
    // so auto-creating numeric edge 5 makes the next auto id 6, as the Rust
    // core always did (it bumps iff `edge_id.parse::<u64>()` succeeds — the D3
    // rule extended to this method). Under XGI 0.10.2 the next id was 0 and
    // silently overwrote edge 0's members.
    let gt = ground_truth();
    let v = vector(&gt, "add_node_to_edge_numeric_id_no_bump");
    assert_eq!(ids(&v["edge_ids"]), vec!["5", "6"]); // XGI truth, pinned

    let mut h: Hypergraph = Hypergraph::new();
    h.add_node_to_edge("5", "x").unwrap();
    let auto = h.add_edge(vec!["y".into()], None, Value::Null).unwrap();
    assert_eq!(auto, "6");
    assert_eq!(h.edge_ids(), ids(&v["edge_ids"]));
    assert_eq!(h.members("5").unwrap(), vec!["x"]);
    assert_eq!(h.members("6").unwrap(), vec!["y"]);
}

#[test]
fn conform_remove_node_from_edge_keep_empty() {
    // remove_empty=False: the emptied edge SURVIVES (empty member set);
    // the node survives too. The Rust core conforms.
    let gt = ground_truth();
    let v = vector(&gt, "remove_node_from_edge_keep_empty");
    assert_eq!(ids(&v["edge_ids"]), vec!["e1"]); // XGI truth, pinned

    let mut h: Hypergraph = Hypergraph::new();
    h.add_edge(vec!["a".into()], Some("e1".into()), Value::Null)
        .unwrap();
    h.remove_node_from_edge("e1", "a", false).unwrap();

    assert_eq!(h.edge_ids(), ids(&v["edge_ids"]));
    assert_eq!(h.num_edges(), v["num_edges"].as_u64().unwrap() as usize);
    assert_eq!(h.num_nodes(), v["num_nodes"].as_u64().unwrap() as usize);
    assert!(h.has_node("a"));
    for (eid, expected) in v["members"].as_object().unwrap() {
        let mut got = h.members(eid).unwrap();
        got.sort();
        assert_eq!(got, ids(expected));
    }
    for (nid, expected) in v["memberships"].as_object().unwrap() {
        let mut got = h.memberships(nid).unwrap();
        got.sort();
        assert_eq!(got, ids(expected));
    }
}

#[test]
fn conform_remove_node_from_edge_drop_empty() {
    // remove_empty=True (the XGI default): an edge left empty is removed;
    // the node survives (still a member of e1). The Rust core conforms.
    let gt = ground_truth();
    let v = vector(&gt, "remove_node_from_edge_drop_empty");
    assert_eq!(ids(&v["edge_ids"]), vec!["e1"]); // XGI truth, pinned

    let mut h: Hypergraph = Hypergraph::new();
    h.add_edge(vec!["a".into(), "b".into()], Some("e1".into()), Value::Null)
        .unwrap();
    h.add_edge(vec!["b".into()], Some("e2".into()), Value::Null)
        .unwrap();
    h.remove_node_from_edge("e2", "b", true).unwrap();

    assert_eq!(h.edge_ids(), ids(&v["edge_ids"]));
    assert_eq!(h.num_edges(), v["num_edges"].as_u64().unwrap() as usize);
    assert_eq!(h.num_nodes(), v["num_nodes"].as_u64().unwrap() as usize);
    let mut rust_nodes = h.node_ids();
    rust_nodes.sort();
    assert_eq!(rust_nodes, ids(&v["node_ids"]));
    for (eid, expected) in v["members"].as_object().unwrap() {
        let mut got = h.members(eid).unwrap();
        got.sort();
        assert_eq!(got, ids(expected));
    }
    for (nid, expected) in v["memberships"].as_object().unwrap() {
        let mut got = h.memberships(nid).unwrap();
        got.sort();
        assert_eq!(got, ids(expected));
    }
}

#[test]
fn conform_membership_errors() {
    // XGI raises XGIError on all three remove_node_from_edge failure
    // branches, each with a DISTINCT message (pinned below). The Rust core
    // maps each branch to a dedicated MembershipError variant
    // (EdgeNotFound / NodeNotFound / NotAMember) so callers can
    // discriminate without string-matching; the PyO3 binding translates
    // Err -> raise, reproducing XGI's exact messages (D2 error-channel
    // class — no new divergence number).
    let gt = ground_truth();
    let v = vector(&gt, "membership_errors");
    assert_eq!(v["missing_edge"]["exception"], "XGIError"); // XGI truth, pinned
    assert_eq!(
        v["missing_edge"]["message"],
        "Edge noedge not in the hypergraph"
    );
    assert_eq!(v["missing_node"]["exception"], "XGIError"); // XGI truth, pinned
    assert_eq!(
        v["missing_node"]["message"],
        "Node ghost not in the hypergraph"
    );
    assert_eq!(v["not_in_edge"]["exception"], "XGIError"); // XGI truth, pinned
    assert_eq!(
        v["not_in_edge"]["message"],
        "Edge e1 does not contain node b"
    );

    let mut h: Hypergraph = Hypergraph::new();
    let err = h.remove_node_from_edge("noedge", "a", true);
    assert_eq!(
        err,
        Err(MembershipError::EdgeNotFound {
            edge_id: "noedge".to_string()
        })
    );

    let mut h2: Hypergraph = Hypergraph::new();
    h2.add_edge(vec!["a".into()], Some("e1".into()), Value::Null)
        .unwrap();
    let err = h2.remove_node_from_edge("e1", "ghost", true);
    assert_eq!(
        err,
        Err(MembershipError::NodeNotFound {
            node_id: "ghost".to_string()
        })
    );

    let mut h3: Hypergraph = Hypergraph::new();
    h3.add_edge(vec!["a".into()], Some("e1".into()), Value::Null)
        .unwrap();
    h3.add_node("b", Value::Null);
    let err = h3.remove_node_from_edge("e1", "b", true);
    assert_eq!(
        err,
        Err(MembershipError::NotAMember {
            node_id: "b".to_string(),
            edge_id: "e1".to_string()
        })
    );
}

#[test]
fn conform_set_node_attributes_bulk() {
    // XGI's set_node_attributes(values, name=None) takes a dict-of-dicts:
    // it MERGES into each existing node's attr dict, and a missing node is
    // warned about ("Node ghost does not exist!") + SKIPPED — never
    // auto-created, never raises. A list-of-pairs input raises XGIError at
    // the Python boundary (XGI is dict-of-dicts only; the Rust core takes
    // pairs and the binding converts — D7 class). The warn channel is a
    // binding concern (the core never warns — D2 channel class); the core
    // is outcome-conformant on every recorded channel.
    let gt = ground_truth();
    let v = vector(&gt, "set_node_attributes_bulk");
    assert_eq!(v["return"], Value::Null); // XGI truth, pinned
    assert_eq!(v["warned"], true); // XGI truth, pinned
    assert_eq!(v["warning_message"], "Node ghost does not exist!");
    assert_eq!(v["pairs_exception"], "XGIError"); // XGI truth, pinned
    assert_eq!(v["pairs_message"], "Must pass a dictionary of dictionaries");
    assert_eq!(v["attrs_a"], serde_json::json!({"x": 1, "color": "red"})); // merge

    let mut h: Hypergraph = Hypergraph::new();
    h.add_node("a", serde_json::json!({"x": 1}));
    h.add_node("b", serde_json::json!({}));
    let color = |c: &str| {
        let mut m = serde_json::Map::new();
        m.insert("color".to_string(), serde_json::json!(c));
        m
    };
    h.set_node_attributes(vec![
        ("a".to_string(), color("red")),
        ("b".to_string(), color("blue")),
        ("ghost".to_string(), color("green")),
    ]);

    // Existing nodes MERGED; ghost silently skipped, never auto-created.
    assert_eq!(h.node_attrs("a").unwrap(), &v["attrs_a"]);
    assert_eq!(h.node_attrs("b").unwrap(), &v["attrs_b"]);
    assert!(!h.has_node("ghost"));
    assert_eq!(h.num_nodes(), v["num_nodes"].as_u64().unwrap() as usize);
}

#[test]
fn conform_set_edge_attributes_bulk() {
    // Edge twin of the above: merge into existing edge attr dicts; a
    // missing edge id warns ("Edge ghost does not exist!") + skips; edge
    // count and membership untouched. The Rust core conforms on outcome.
    let gt = ground_truth();
    let v = vector(&gt, "set_edge_attributes_bulk");
    assert_eq!(v["return"], Value::Null); // XGI truth, pinned
    assert_eq!(v["warned"], true); // XGI truth, pinned
    assert_eq!(v["warning_message"], "Edge ghost does not exist!");
    assert_eq!(v["attrs_e1"], serde_json::json!({"w": 1, "heat": 0.5})); // merge

    let mut h: Hypergraph = Hypergraph::new();
    h.add_edge(
        vec!["a".into()],
        Some("e1".into()),
        serde_json::json!({"w": 1}),
    )
    .unwrap();
    h.add_edge(vec!["b".into()], Some("e2".into()), serde_json::json!({}))
        .unwrap();
    let mut heat = serde_json::Map::new();
    heat.insert("heat".to_string(), serde_json::json!(0.5));
    let mut x = serde_json::Map::new();
    x.insert("x".to_string(), serde_json::json!(1));
    h.set_edge_attributes(vec![("e1".to_string(), heat), ("ghost".to_string(), x)]);

    assert_eq!(h.edge_attrs("e1").unwrap(), &v["attrs_e1"]);
    assert_eq!(h.edge_attrs("e2").unwrap(), &v["attrs_e2"]);
    assert!(!h.has_edge("ghost"));
    assert_eq!(h.num_edges(), v["num_edges"].as_u64().unwrap() as usize);
}

#[test]
fn conform_clear_edges_keeps_nodes_counter() {
    // XGI's clear_edges(): "Remove all edges from the graph without
    // altering any nodes." Nodes, node attrs, and net attrs survive;
    // memberships empty; returns None. Like clear() (D10) it does NOT
    // reset the uid counter — but unlike D10 there is no "cleared ≡
    // fresh" reading (the node state is preserved), so counter continuity
    // matches state continuity and the Rust core CONFORMS: no reset.
    let gt = ground_truth();
    let v = vector(&gt, "clear_edges_keeps_nodes_counter");
    assert_eq!(v["return"], Value::Null); // XGI truth, pinned
    assert_eq!(ids(&v["auto_ids_after_clear_edges"]), vec!["1"]); // XGI truth

    let mut h: Hypergraph = Hypergraph::new();
    h.add_edge(vec!["a".into(), "b".into()], None, Value::Null)
        .unwrap();
    h.add_edge(
        vec!["c".into(), "d".into()],
        Some("e1".into()),
        serde_json::json!({"heat": 0.5}),
    )
    .unwrap();
    h.add_node("lonely", serde_json::json!({"x": 1}));
    h.set_graph_attr("name", serde_json::json!("test"));
    h.clear_edges();

    assert_eq!(h.num_nodes(), v["num_nodes"].as_u64().unwrap() as usize);
    assert_eq!(h.num_edges(), 0);
    let mut rust_nodes = h.node_ids();
    rust_nodes.sort();
    assert_eq!(rust_nodes, ids(&v["node_ids"]));
    assert_eq!(h.node_attrs("lonely").unwrap(), &v["lonely_attrs"]);
    assert_eq!(
        h.graph_attr("name"),
        Some(&v["net_attrs"]["name"]),
        "net attrs survive clear_edges"
    );
    assert!(h.memberships("a").unwrap().is_empty());
    assert!(h.edge_ids().is_empty());

    // CONFORM (no D-number): the counter continues — next auto id "1".
    let auto = h.add_edge(vec!["z".into()], None, Value::Null).unwrap();
    assert_eq!(auto, "1");
    assert_eq!(vec![auto], ids(&v["auto_ids_after_clear_edges"]));
}

#[test]
fn conform_freeze_blocks_mutation() {
    // XGI's freeze() guards add_node(s)_from, remove_node(s)_from,
    // add_edge(s)_from, remove_edge(s)_from, add_node_to_edge,
    // remove_node_from_edge, and clear by monkey-patching each with a
    // raiser (`XGIError: Frozen higher-order network can't be modified`);
    // is_frozen reads the `frozen` attribute. The Rust core panics on the
    // same structural mutators (panic ≡ raise at the core; the binding
    // converts — D2 error-channel class). XGI leaves the attr-dict
    // channel OPEN on frozen networks (set_node_attributes /
    // set_edge_attributes / net-attr set / private-dict writes all
    // unguarded) — the Rust core matches: no guard on the attr setters
    // (and node_attrs_mut/edge_attrs_mut cannot be guarded — they return
    // &mut; same hole shape as XGI's private-dict access).
    let gt = ground_truth();
    let v = vector(&gt, "freeze_blocks_mutation");
    assert_eq!(v["is_frozen_before"], false); // XGI truth, pinned
    assert_eq!(v["is_frozen_after"], true); // XGI truth, pinned
    for method in [
        "add_node",
        "add_edge",
        "remove_node",
        "remove_edge",
        "add_node_to_edge",
        "remove_node_from_edge",
        "clear",
    ] {
        assert_eq!(v["guarded"][method]["exception"], "XGIError"); // pinned
        assert_eq!(
            v["guarded"][method]["message"],
            "Frozen higher-order network can't be modified"
        );
    }
    // The attr-dict channel is NOT guarded in XGI — pinned as truth.
    assert_eq!(v["guarded"]["set_node_attributes"], Value::Null);
    assert_eq!(v["guarded"]["set_edge_attributes"], Value::Null);

    let mut h: Hypergraph = Hypergraph::new();
    h.add_edge(
        vec!["a".into(), "b".into()],
        Some("e1".into()),
        serde_json::json!({"w": 1}),
    )
    .unwrap();
    assert!(!h.is_frozen());
    h.freeze();
    assert!(h.is_frozen());

    // Every XGI-guarded structural mutator panics in the Rust core. The
    // guards fire before any mutation, so one frozen graph serves every
    // probe.
    let mut panics = |f: &mut dyn FnMut(&mut Hypergraph)| {
        std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| f(&mut h))).is_err()
    };
    assert!(panics(&mut |h| {
        h.add_node("z", Value::Null);
    }));
    assert!(panics(&mut |h| {
        h.add_edge(vec!["a".into()], None, Value::Null).unwrap();
    }));
    assert!(panics(&mut |h| h.remove_node("a", false, true).unwrap()));
    assert!(panics(&mut |h| h.remove_edge("e1").unwrap()));
    assert!(panics(&mut |h| h.add_node_to_edge("e1", "c").unwrap()));
    assert!(panics(&mut |h| h
        .remove_node_from_edge("e1", "a", true)
        .unwrap()));
    assert!(panics(&mut |h| h.clear()));

    // XGI parity: the attr-dict channel stays OPEN on a frozen graph.
    let mut attrs = serde_json::Map::new();
    attrs.insert("k".to_string(), serde_json::json!(1));
    h.set_node_attributes(vec![("a".to_string(), attrs.clone())]);
    h.set_edge_attributes(vec![("e1".to_string(), attrs)]);
    assert_eq!(h.node_attrs("a").unwrap()["k"], 1);
    assert_eq!(h.edge_attrs("e1").unwrap()["k"], 1);
}

#[test]
fn diverge_d12_freeze_guards_clear_edges() {
    // D12: XGI's freeze monkey-patch list omits clear_edges — a FROZEN
    // XGI network can still have every edge deleted (probed live:
    // guarded["clear_edges"] is None = no raise). XGI's omission is an
    // artifact of freeze-by-method-swizzling, not a designed semantic; a
    // freeze that permits wholesale edge deletion is not a freeze. The
    // Rust core's frozen flag guards ALL structural mutators uniformly,
    // clear_edges included.
    let gt = ground_truth();
    let v = vector(&gt, "freeze_blocks_mutation");
    assert_eq!(v["guarded"]["clear_edges"], Value::Null); // XGI truth, pinned

    let mut h: Hypergraph = Hypergraph::new();
    h.add_edge(vec!["a".into(), "b".into()], Some("e1".into()), Value::Null)
        .unwrap();
    h.freeze();
    let result = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| h.clear_edges()));
    assert!(
        result.is_err(),
        "Rust divergence: clear_edges panics when frozen"
    );
    // The panic fired BEFORE any mutation: the original is untouched.
    assert_eq!(h.num_edges(), 1);
}

#[test]
fn diverge_d13_copy_carries_frozen() {
    // D13: XGI's freeze is per-instance method-swizzling — copy() builds a
    // fresh instance that never gets the patch, so a copy of a frozen XGI
    // network is NOT frozen (an implementation artifact, not semantics).
    // The Rust core's frozen flag is data; copy() is a deep clone of data
    // and carries it — a clone that silently drops immutability is a
    // footgun the core declines to reproduce.
    let gt = ground_truth();
    let v = vector(&gt, "freeze_blocks_mutation");
    assert_eq!(v["copy_of_frozen_is_frozen"], false); // XGI truth, pinned

    let mut h: Hypergraph = Hypergraph::new();
    h.add_edge(vec!["a".into()], Some("e1".into()), Value::Null)
        .unwrap();
    h.freeze();
    let cp = h.copy();
    assert!(cp.is_frozen(), "Rust divergence: copy of frozen is frozen");
}

#[test]
fn diverge_d2_add_edges_from_dup_errors_continues() {
    // XGI's add_edges_from warns + skips a duplicate idx and CONTINUES with
    // the rest (["b"]/"e1" dropped — its member "b" is never added; ["c"]/
    // "e2" kept). Same D2 error-channel class: the Rust core surfaces the
    // dup as Err(AlreadyExists) in the per-edge Vec<Result> and still
    // continues — no new divergence number. The PyO3 binding translates
    // Err → UserWarning + skip for conformance.
    let gt = ground_truth();
    let v = vector(&gt, "add_edges_from_dup_warns_continues");
    assert_eq!(v["return"], Value::Null); // XGI truth, pinned
    assert_eq!(v["warned"], true); // XGI truth, pinned
    assert!(v["warning_prefix"]
        .as_str()
        .unwrap()
        .starts_with("uid e1 already exists"));

    let mut h: Hypergraph = Hypergraph::new();
    let results = h.add_edges_from(vec![
        (vec!["a".into()], Some("e1".into()), Value::Null),
        (vec!["b".into()], Some("e1".into()), Value::Null),
        (vec!["c".into()], Some("e2".into()), Value::Null),
    ]);
    assert_eq!(results.len(), 3);
    assert!(results[0].is_ok());
    assert!(matches!(results[1], Err(EdgeError::AlreadyExists { .. })));
    assert!(results[2].is_ok());

    // Dup skipped, the rest kept — XGI's recorded final state.
    assert_eq!(h.edge_ids(), ids(&v["edge_ids"]));
    assert_eq!(h.num_edges(), v["num_edges"].as_u64().unwrap() as usize);
    assert_eq!(h.num_nodes(), v["num_nodes"].as_u64().unwrap() as usize);
    for (eid, expected) in v["members"].as_object().unwrap() {
        let mut got = h.members(eid).unwrap();
        got.sort();
        assert_eq!(got, ids(expected));
    }
}

#[test]
fn conform_repr_format() {
    // XGI 1.1's __repr__ is f"{cls}({self.edges.members()})" — the class name
    // wrapping the edge-members DICT ({id: members}); XGI 0.10.2 wrapped a list. The Rust core's Debug still
    // prints a LIST (Hypergraph([{...}, ...])), so the shapes differ; the check compares literals. Members in INSERTION
    // order — cited divergence D5 (XGI's member sets are unordered; their
    // repr order is hash-randomized across runs, so the fixture records
    // members SORTED and the stable projections only). Rust is strictly
    // more defined: deterministic where XGI is set-ordered. No new
    // D-number — the D5 row's "strictly more defined" rationale covers
    // the repr surface, including rendering an empty edge as "{}" where
    // Python must say "set()".
    let gt = ground_truth();
    let v = vector(&gt, "repr_format");
    assert_eq!(v["repr_prefix"], "Hypergraph("); // XGI truth, pinned
    assert_eq!(v["repr_empty"], "Hypergraph({})"); // XGI 1.1 truth, pinned (a dict)
    assert_eq!(v["repr_lone_empty_edge"], "Hypergraph({0: set()})"); // pinned
    assert_eq!(
        v["members_sorted"],
        serde_json::json!([["a", "b", "c"], ["b", "c"]])
    ); // XGI truth (sorted), pinned

    // Same graph in Rust: members format insertion-ordered (D5), lonely
    // nodes absent (XGI parity — only edges' members appear).
    let mut h: Hypergraph = Hypergraph::new();
    h.add_edge(vec!["a".into(), "b".into(), "c".into()], None, Value::Null)
        .unwrap();
    h.add_edge(vec!["b".into(), "c".into()], Some("e1".into()), Value::Null)
        .unwrap();
    h.add_node("lonely", Value::Null);
    let repr = format!("{h:?}");
    assert!(repr.starts_with(v["repr_prefix"].as_str().unwrap()));
    assert_eq!(repr, "Hypergraph([{a, b, c}, {b, c}])");
    // Every fixture-recorded (sorted) member set matches the Rust set.
    for (i, eid) in ["0", "e1"].iter().enumerate() {
        let mut got = h.members(eid).unwrap();
        got.sort();
        assert_eq!(got, ids(&v["members_sorted"][i]));
    }

    // XGI 1.1 renders the edges as a dict ({id: members}); the Rust Debug keeps its list shape, so
    // only the empty network's "()" frame is compared with the fixture's string.
    let empty: Hypergraph = Hypergraph::new();
    assert_eq!(format!("{empty:?}"), "Hypergraph([])");

    // Empty edge: XGI's Python-set artifact "set()" is pinned as truth;
    // Rust formats braces uniformly — "{}" (same D5 class).
    let mut lone_empty: Hypergraph = Hypergraph::new();
    lone_empty.add_edge(vec![], None, Value::Null).unwrap();
    assert_eq!(format!("{lone_empty:?}"), "Hypergraph([{}])");
}

// ---------------------------------------------------------------------------
// DiHypergraph (Phase 2 Task 3+)
// ---------------------------------------------------------------------------

/// Assert a directed edge's (tail, head) against the fixture's sorted lists.
/// Rust returns insertion-ordered vecs (D5); the fixture records sorted, so
/// both sides are sorted before comparison.
fn assert_dimembers(h: &DiHypergraph, edge_id: &str, recorded: &Value) {
    let (mut tail, mut head) = h.dimembers(edge_id).unwrap();
    tail.sort();
    head.sort();
    assert_eq!(tail, ids(&recorded["tail"]));
    assert_eq!(head, ids(&recorded["head"]));
}

#[test]
fn conform_di_add_edge_dimembers() {
    // XGI: add_edge((tail, head)) — tail FIRST, head SECOND; returns None
    // (D8 class: the Rust core returns Ok(id)). dimembers(e) = (tail,
    // head); members(e) = tail ∪ head. dimemberships(n) = (in, out) —
    // "in" = edges where n is in the HEAD, "out" = edges where n is in the
    // TAIL — IN FIRST (probed: tail-only node 1 -> (set(), {0}); head-only
    // node 4 -> ({0}, set())).
    let gt = ground_truth();
    let v = vector(&gt, "di_add_edge_dimembers");
    assert_eq!(v["return"], Value::Null); // XGI truth, pinned
    assert_eq!(v["dimemberships"]["1"], serde_json::json!([[], ["0"]])); // pinned
    assert_eq!(v["dimemberships"]["4"], serde_json::json!([["0"], []])); // pinned

    let mut h: DiHypergraph = DiHypergraph::new();
    let eid = h
        .add_edge(
            vec!["1".into(), "2".into(), "3".into()],
            vec!["2".into(), "3".into(), "4".into()],
            None,
            Value::Null,
        )
        .unwrap();
    assert_eq!(eid, id_str(&v["edge_ids"][0]));
    assert_eq!(h.num_nodes(), v["num_nodes"].as_u64().unwrap() as usize);
    assert_dimembers(&h, &eid, &v["dimembers"]["0"]);
    assert_eq!(h.tail(&eid).unwrap(), vec!["1", "2", "3"]);
    assert_eq!(h.head(&eid).unwrap(), vec!["2", "3", "4"]);
    assert_eq!(h.members(&eid).unwrap(), vec!["1", "2", "3", "4"]);

    // dimemberships: (head-edges, tail-edges), IN first — XGI's order.
    assert_eq!(
        h.dimemberships("1").unwrap(),
        (Vec::<String>::new(), vec!["0".to_string()])
    );
    assert_eq!(
        h.dimemberships("4").unwrap(),
        (vec!["0".to_string()], Vec::<String>::new())
    );
    for (nid, expected) in v["dimemberships"].as_object().unwrap() {
        let (mut head_edges, mut tail_edges) = h.dimemberships(nid).unwrap();
        head_edges.sort();
        tail_edges.sort();
        assert_eq!(vec![head_edges, tail_edges], ids_nested(expected));
    }
    for (nid, expected) in v["memberships"].as_object().unwrap() {
        let mut got = h.memberships(nid).unwrap();
        got.sort();
        assert_eq!(got, ids(expected));
    }
}

fn ids_nested(v: &Value) -> Vec<Vec<String>> {
    v.as_array().unwrap().iter().map(ids).collect()
}

#[test]
fn conform_di_uid_counter() {
    // DiHypergraph shares update_uid_counter with Hypergraph (probed):
    // auto ids 0, 1; int idx 5 bumps to 6; str "5" no bump; float 5.0
    // bumps; "x" no bump. The Rust core bumps iff idx.parse::<u64>()
    // succeeds — conforming on int-idx, diverging as registered on
    // str-idx (D3) and float-idx (D4).
    let gt = ground_truth();
    let v = vector(&gt, "di_uid_counter");
    assert_eq!(ids(&v["int_idx_bumps"]), vec!["0", "1", "5", "6"]); // XGI truth
    assert_eq!(ids(&v["str_idx_no_bump"]), vec!["5", "0"]); // XGI truth
    assert_eq!(ids(&v["float_idx_bumps"]), vec!["5.0", "6"]); // XGI truth
    assert_eq!(ids(&v["nonnumeric_idx_no_bump"]), vec!["x", "0"]); // XGI truth

    let mut h: DiHypergraph = DiHypergraph::new();
    assert_eq!(
        h.add_edge(vec!["1".into()], vec!["2".into()], None, Value::Null)
            .unwrap(),
        "0"
    );
    assert_eq!(
        h.add_edge(vec!["3".into()], vec!["4".into()], None, Value::Null)
            .unwrap(),
        "1"
    );
    h.add_edge(
        vec!["5".into()],
        vec!["6".into()],
        Some("5".into()),
        Value::Null,
    )
    .unwrap();
    // D3: Rust bumps for str-numeric "5" — next auto is "6", not "0".
    let auto = h
        .add_edge(vec!["7".into()], vec!["8".into()], None, Value::Null)
        .unwrap();
    assert_eq!(auto, "6");

    // D4: "5.0" fails parse::<u64>() — no bump.
    let mut h2: DiHypergraph = DiHypergraph::new();
    h2.add_edge(
        vec!["1".into()],
        vec!["2".into()],
        Some("5.0".into()),
        Value::Null,
    )
    .unwrap();
    let auto2 = h2
        .add_edge(vec!["3".into()], vec!["4".into()], None, Value::Null)
        .unwrap();
    assert_eq!(auto2, "0");
}

#[test]
fn diverge_d2_di_dup_idx_errors_instead_of_warn_noop() {
    // Same D2 error-channel class as the undirected dup-idx: XGI warns +
    // no-ops (returns None); the Rust core returns Err(AlreadyExists) and
    // the binding translates back to UserWarning + None.
    let gt = ground_truth();
    let v = vector(&gt, "di_dup_idx");
    assert_eq!(v["return"], Value::Null); // XGI truth, pinned
    assert_eq!(v["warned"], true); // XGI truth, pinned
    assert!(v["warning_prefix"]
        .as_str()
        .unwrap()
        .starts_with("uid e1 already exists"));

    let mut h: DiHypergraph = DiHypergraph::new();
    h.add_edge(
        vec!["1".into()],
        vec!["2".into()],
        Some("e1".into()),
        Value::Null,
    )
    .unwrap();
    let err = h.add_edge(
        vec!["3".into()],
        vec!["4".into()],
        Some("e1".into()),
        Value::Null,
    );
    assert!(matches!(err, Err(EdgeError::AlreadyExists { .. })));
    assert_eq!(h.num_edges(), 1);
    assert_eq!(h.num_nodes(), v["num_nodes"].as_u64().unwrap() as usize);
    assert_eq!(h.tail("e1").unwrap(), vec!["1"]);
    assert_eq!(h.head("e1").unwrap(), vec!["2"]);
}

#[test]
fn conform_di_empty_edge() {
    // D1-class parity: add_edge(([], [])) creates an empty directed edge;
    // empty-tail-only and empty-head-only are likewise allowed (probed).
    let gt = ground_truth();
    let v = vector(&gt, "di_empty_edge");
    assert_eq!(v["both_empty"]["return"], Value::Null); // XGI truth, pinned

    let mut h: DiHypergraph = DiHypergraph::new();
    let eid = h.add_edge(vec![], vec![], None, Value::Null).unwrap();
    assert_eq!(eid, id_str(&v["both_empty"]["edge_ids"][0]));
    assert_eq!(h.num_edges(), 1);
    assert_eq!(h.num_nodes(), 0);
    assert_eq!(
        h.dimembers(&eid).unwrap(),
        (Vec::<String>::new(), Vec::<String>::new())
    );
    assert!(h.members(&eid).unwrap().is_empty());

    let mut h2: DiHypergraph = DiHypergraph::new();
    let e2 = h2
        .add_edge(vec![], vec!["1".into()], None, Value::Null)
        .unwrap();
    assert_eq!(h2.tail(&e2).unwrap(), Vec::<String>::new());
    assert_eq!(h2.head(&e2).unwrap(), vec!["1"]);

    let mut h3: DiHypergraph = DiHypergraph::new();
    let e3 = h3
        .add_edge(vec!["1".into()], vec![], None, Value::Null)
        .unwrap();
    assert_eq!(h3.tail(&e3).unwrap(), vec!["1"]);
    assert_eq!(h3.head(&e3).unwrap(), Vec::<String>::new());
}

#[test]
fn conform_di_both_directions() {
    // A node listed in BOTH tail and head of the same edge is stored in
    // both sets and survives round-trip; duplicates within one direction
    // are deduped (set semantics per direction, probed).
    let gt = ground_truth();
    let v = vector(&gt, "di_both_directions");
    assert_eq!(v["dimemberships"]["2"], serde_json::json!([["e1"], ["e1"]])); // pinned

    let mut h: DiHypergraph = DiHypergraph::new();
    h.add_edge(
        vec!["1".into(), "1".into(), "2".into()],
        vec!["2".into(), "2".into(), "3".into()],
        Some("e1".into()),
        Value::Null,
    )
    .unwrap();
    assert_eq!(h.tail("e1").unwrap(), vec!["1", "2"]);
    assert_eq!(h.head("e1").unwrap(), vec!["2", "3"]);
    assert_eq!(h.members("e1").unwrap(), vec!["1", "2", "3"]);
    assert_eq!(h.num_nodes(), v["num_nodes"].as_u64().unwrap() as usize);
    assert_eq!(
        h.dimemberships("2").unwrap(),
        (vec!["e1".to_string()], vec!["e1".to_string()])
    );
}

#[test]
fn diverge_d14_members_must_be_pair() {
    // D14: XGI 1.1 raises TypeError "Directed edge must be a list or tuple!"
    // on non-list/tuple members (and a raw TypeError on a list of ints),
    // and ValueError "Invalid direction!" on a bad direction string (XGI
    // 0.10.2 raised XGIError for both). The
    // Rust core makes BOTH compile-time-impossible: add_edge takes
    // (Vec<String>, Vec<String>) and direction is the Direction enum —
    // type-level prevention. The Phase 7 binding exposes shims raising
    // XGIError for conformance. XGI's runtime errors are pinned here.
    let gt = ground_truth();
    let v = vector(&gt, "di_members_must_be_pair");
    assert_eq!(v["set_members"]["exception"], "TypeError"); // XGI 1.1 truth, pinned
    assert_eq!(
        v["set_members"]["message"],
        "Directed edge must be a list or tuple!"
    );
    assert_eq!(v["str_members"]["exception"], "TypeError"); // pinned
    assert_eq!(
        v["str_members"]["message"],
        "Directed edge must be a list or tuple!"
    );
    assert_eq!(v["int_list_members"]["exception"], "TypeError"); // pinned
    assert_eq!(v["invalid_direction"]["exception"], "ValueError"); // pinned
    assert_eq!(v["invalid_direction"]["message"], "Invalid direction!");

    // Rust: the pair shape and the direction vocabulary are types, not
    // runtime checks — this test's existence (it compiles) is the proof.
    let mut h: DiHypergraph = DiHypergraph::new();
    h.add_edge(
        vec!["1".into()],
        vec!["2".into()],
        Some("e1".into()),
        Value::Null,
    )
    .unwrap();
    assert_eq!(h.tail("e1").unwrap(), vec!["1"]);
    assert_eq!(h.head("e1").unwrap(), vec!["2"]);
}

#[test]
fn conform_di_add_node_to_edge() {
    // XGI: direction "in" puts the node in the TAIL, "out" in the HEAD;
    // auto-creates a missing edge AND node; returns None; set semantics —
    // re-adding the same (node, direction) is a no-op; adding the same
    // node in the OTHER direction puts it in BOTH sets.
    let gt = ground_truth();
    let v = vector(&gt, "di_add_node_to_edge");
    assert_eq!(v["return_in"], Value::Null); // XGI truth, pinned
    assert_eq!(v["return_out"], Value::Null); // XGI truth, pinned

    let mut h: DiHypergraph = DiHypergraph::new();
    h.add_node_to_edge("newedge", "newnode", DiRole::Tail)
        .unwrap(); // both missing
    h.add_node_to_edge("e2", "n2", DiRole::Head).unwrap(); // both missing
    h.add_edge(
        vec!["1".into()],
        vec!["2".into()],
        Some("e1".into()),
        Value::Null,
    )
    .unwrap();
    h.add_node_to_edge("e1", "1", DiRole::Tail).unwrap(); // re-add same direction: no-op
    h.add_node_to_edge("e1", "1", DiRole::Head).unwrap(); // other direction: BOTH

    assert_eq!(h.edge_ids(), ids(&v["edge_ids"]));
    assert_eq!(h.num_nodes(), v["num_nodes"].as_u64().unwrap() as usize);
    for (eid, recorded) in v["dimembers"].as_object().unwrap() {
        assert_dimembers(&h, eid, recorded);
    }
    // Node 1 is in BOTH directions of e1.
    assert_eq!(
        h.dimemberships("1").unwrap(),
        (vec!["e1".to_string()], vec!["e1".to_string()])
    );
    for (nid, expected) in v["dimemberships"].as_object().unwrap() {
        let (mut head_edges, mut tail_edges) = h.dimemberships(nid).unwrap();
        head_edges.sort();
        tail_edges.sort();
        assert_eq!(vec![head_edges, tail_edges], ids_nested(expected));
    }
}

#[test]
fn conform_di_add_node_to_edge_numeric_advances_counter() {
    // D11-extension closed by XGI 1.1: DiHypergraph.add_node_to_edge now calls
    // update_uid_counter too, so auto-creating numeric edge 5 makes the next
    // auto id 6, as the Rust core always did.
    let gt = ground_truth();
    let v = vector(&gt, "di_add_node_to_edge");
    assert_eq!(ids(&v["numeric_id_no_bump"]["edge_ids"]), vec!["5", "6"]); // XGI truth

    let mut h: DiHypergraph = DiHypergraph::new();
    h.add_node_to_edge("5", "x", DiRole::Tail).unwrap();
    let auto = h
        .add_edge(vec!["1".into()], vec!["2".into()], None, Value::Null)
        .unwrap();
    assert_eq!(auto, "6");
    assert_eq!(h.tail("5").unwrap(), vec!["x"]);
    assert_eq!(h.tail("6").unwrap(), vec!["1"]);
    assert_eq!(h.head("6").unwrap(), vec!["2"]);
}

#[test]
fn conform_di_remove_node_from_edge() {
    // XGI: removes ONLY the direction's side; directed "emptied" = BOTH
    // tail AND head empty (an edge with one side still populated survives
    // even with remove_empty=True); remove_empty=False keeps a both-empty
    // edge. Errors are per-direction (a head-only member fails "in").
    let gt = ground_truth();
    let v = vector(&gt, "di_remove_node_from_edge");
    // XGI truth, pinned.
    assert_eq!(
        v["errors"]["missing_edge"]["message"],
        "Edge noedge not in the hypergraph"
    );
    assert_eq!(
        v["errors"]["missing_node"]["message"],
        "Node ghost not in the hypergraph"
    );
    assert_eq!(
        v["errors"]["not_in_tail"]["message"],
        "in-edge e1 does not contain node b"
    );
    assert_eq!(
        v["errors"]["not_in_head"]["message"],
        "out-edge e1 does not contain node b"
    );
    assert_eq!(
        v["errors"]["wrong_direction_member"]["message"],
        "in-edge e1 does not contain node 2"
    );

    // Removes ONLY the direction's side: node 2 leaves the tail but stays
    // in the head.
    let mut h: DiHypergraph = DiHypergraph::new();
    h.add_edge(
        vec!["1".into(), "2".into()],
        vec!["2".into(), "3".into()],
        Some("e1".into()),
        Value::Null,
    )
    .unwrap();
    h.remove_node_from_edge("e1", "2", DiRole::Tail, false)
        .unwrap();
    assert_dimembers(&h, "e1", &v["direction_only"]["dimembers"]["e1"]);
    assert_eq!(
        h.dimemberships("2").unwrap(),
        (vec!["e1".to_string()], Vec::<String>::new())
    );

    // Emptied = BOTH sides: removing the last tail member with the head
    // populated leaves the edge ALIVE even with remove_empty=True.
    let mut h2: DiHypergraph = DiHypergraph::new();
    h2.add_edge(
        vec!["1".into()],
        vec!["2".into()],
        Some("e2".into()),
        Value::Null,
    )
    .unwrap();
    h2.remove_node_from_edge("e2", "1", DiRole::Tail, true)
        .unwrap();
    assert_eq!(h2.edge_ids(), ids(&v["empty_means_both_sides"]["edge_ids"]));
    assert_dimembers(&h2, "e2", &v["empty_means_both_sides"]["dimembers"]["e2"]);
    // Removing the last head member empties BOTH sides -> dropped.
    h2.remove_node_from_edge("e2", "2", DiRole::Head, true)
        .unwrap();
    assert!(h2.edge_ids().is_empty());
    assert_eq!(h2.num_nodes(), 2); // nodes survive

    // remove_empty=False keeps a both-empty edge.
    let mut h3: DiHypergraph = DiHypergraph::new();
    h3.add_edge(vec!["1".into()], vec![], Some("e3".into()), Value::Null)
        .unwrap();
    h3.remove_node_from_edge("e3", "1", DiRole::Tail, false)
        .unwrap();
    assert_eq!(h3.edge_ids(), ids(&v["keep_empty"]["edge_ids"]));
    assert_eq!(
        h3.dimembers("e3").unwrap(),
        (Vec::<String>::new(), Vec::<String>::new())
    );

    // Errors map to MembershipError variants (D2 channel class).
    let mut he: DiHypergraph = DiHypergraph::new();
    assert_eq!(
        he.remove_node_from_edge("noedge", "a", DiRole::Tail, true),
        Err(MembershipError::EdgeNotFound {
            edge_id: "noedge".to_string()
        })
    );
    let mut hn: DiHypergraph = DiHypergraph::new();
    hn.add_edge(
        vec!["1".into()],
        vec!["2".into()],
        Some("e1".into()),
        Value::Null,
    )
    .unwrap();
    assert_eq!(
        hn.remove_node_from_edge("e1", "ghost", DiRole::Tail, true),
        Err(MembershipError::NodeNotFound {
            node_id: "ghost".to_string()
        })
    );
    hn.add_node("b", Value::Null);
    assert_eq!(
        hn.remove_node_from_edge("e1", "b", DiRole::Tail, true),
        Err(MembershipError::NotAMember {
            node_id: "b".to_string(),
            edge_id: "e1".to_string()
        })
    );
    assert_eq!(
        hn.remove_node_from_edge("e1", "b", DiRole::Head, true),
        Err(MembershipError::NotAMember {
            node_id: "b".to_string(),
            edge_id: "e1".to_string()
        })
    );
    // Head-only member fails direction In (per-direction membership check).
    assert_eq!(
        hn.remove_node_from_edge("e1", "2", DiRole::Tail, true),
        Err(MembershipError::NotAMember {
            node_id: "2".to_string(),
            edge_id: "e1".to_string()
        })
    );
}

#[test]
fn conform_di_remove_node_modes() {
    // XGI's DiHypergraph.remove_node(n, strong, remove_empty) is
    // three-mode like the undirected (register D9 class): weak drops the
    // node from BOTH directions of every containing edge and removes an
    // edge iff BOTH tail and head are empty AND remove_empty; strong
    // removes every incident edge ENTIRELY, ignoring the flag.
    let gt = ground_truth();
    let v = vector(&gt, "di_remove_node_modes");
    assert_eq!(v["weak_keep"]["return"], Value::Null); // XGI truth, pinned
    assert_eq!(v["weak_keep"]["has_node_2"], false); // XGI truth, pinned
    assert_eq!(v["missing_node"]["exception"], "IDNotFound"); // pinned
    assert_eq!(
        v["nodes_from_missing"]["warning_message"],
        "Node ghost not in dihypergraph"
    ); // pinned
    assert_eq!(v["edges_from_missing"]["exception"], "IDNotFound"); // pinned

    // Weak + remove_empty=False: node removed from both directions; an
    // edge emptied on BOTH sides would survive; one-sided edges keep
    // their other side.
    let mut h: DiHypergraph = DiHypergraph::new();
    h.add_edge(
        vec!["1".into(), "2".into()],
        vec!["2".into(), "3".into()],
        Some("e1".into()),
        Value::Null,
    )
    .unwrap();
    h.add_edge(
        vec!["2".into()],
        vec!["4".into()],
        Some("e2".into()),
        Value::Null,
    )
    .unwrap();
    h.add_edge(
        vec!["5".into()],
        vec!["2".into()],
        Some("e3".into()),
        Value::Null,
    )
    .unwrap();
    h.remove_node("2", false, false).unwrap();
    assert_eq!(h.edge_ids(), ids(&v["weak_keep"]["edge_ids"]));
    assert!(!h.has_node("2"));
    for (eid, recorded) in v["weak_keep"]["dimembers"].as_object().unwrap() {
        assert_dimembers(&h, eid, recorded);
    }

    // Weak + remove_empty=True (XGI default): only BOTH-empty edges drop
    // — e2 keeps its head, e5 (tail-only singleton) drops.
    let mut h2: DiHypergraph = DiHypergraph::new();
    h2.add_edge(
        vec!["2".into()],
        vec!["4".into()],
        Some("e2".into()),
        Value::Null,
    )
    .unwrap();
    h2.add_edge(vec!["2".into()], vec![], Some("e5".into()), Value::Null)
        .unwrap();
    h2.remove_node("2", false, true).unwrap();
    assert_eq!(h2.edge_ids(), ids(&v["weak_drop"]["edge_ids"]));
    assert_dimembers(&h2, "e2", &v["weak_drop"]["dimembers"]["e2"]);

    // Strong + remove_empty=False: incident edges removed ENTIRELY anyway.
    let mut h3: DiHypergraph = DiHypergraph::new();
    h3.add_edge(
        vec!["1".into(), "2".into()],
        vec!["3".into()],
        Some("e1".into()),
        Value::Null,
    )
    .unwrap();
    h3.add_edge(
        vec!["4".into()],
        vec!["2".into(), "5".into()],
        Some("e2".into()),
        Value::Null,
    )
    .unwrap();
    h3.add_edge(
        vec!["6".into()],
        vec!["7".into()],
        Some("e4".into()),
        Value::Null,
    )
    .unwrap();
    h3.remove_node("2", true, false).unwrap();
    assert_eq!(h3.edge_ids(), ids(&v["strong_ignores_flag"]["edge_ids"]));
    assert_dimembers(&h3, "e4", &v["strong_ignores_flag"]["dimembers"]["e4"]);
    let mut rust_nodes = h3.node_ids();
    rust_nodes.sort();
    assert_eq!(rust_nodes, ids(&v["strong_ignores_flag"]["node_ids"]));

    // Missing node: NodeError::NotFound (D2 channel class).
    let mut h4: DiHypergraph = DiHypergraph::new();
    assert!(matches!(
        h4.remove_node("ghost", false, true),
        Err(NodeError::NotFound { .. })
    ));
}

// SKIPPED (Task 11, D16/Di-bulk deferred to Phase 7 ruling): main's
// DiHypergraph does not yet implement the bulk/attrs API this vector
// exercises (add_edges_from/remove_edges_from/remove_nodes_from/
// clear_edges/attrs accessors) — body preserved verbatim for Phase 7
// Di-parity revival; disabled via cfg(any()) rather than deleted.
#[cfg(any())]
#[test]
fn diverge_d2_di_remove_nodes_from_missing_warns_per_item() {
    // XGI's DiHypergraph.remove_nodes_from WARNS "Node ghost not in
    // dihypergraph" (note: "dihypergraph" — the undirected message says
    // "hypergraph"), SKIPS, CONTINUES; returns None. D2-class channel
    // translation: per-item Err(NodeError::NotFound) in the Vec; the
    // binding warns per Err item.
    let gt = ground_truth();
    let v = vector(&gt, "di_remove_node_modes")["nodes_from_missing"].clone();
    assert_eq!(v["return"], Value::Null); // XGI truth, pinned
    assert_eq!(v["warned"], true); // XGI truth, pinned

    let mut h: DiHypergraph = DiHypergraph::new();
    h.add_edge(
        vec!["1".into(), "2".into()],
        vec!["3".into()],
        Some("e1".into()),
        Value::Null,
    )
    .unwrap();
    let results = h.remove_nodes_from(
        vec!["1".to_string(), "ghost".to_string(), "2".to_string()],
        false,
        true,
    );
    assert_eq!(results.len(), 3);
    assert!(results[0].is_ok());
    assert_eq!(
        results[1],
        Err(NodeError::NotFound {
            node_id: "ghost".to_string()
        })
    );
    assert!(results[2].is_ok(), "continues past the missing id");
    assert_eq!(h.node_ids(), ids(&v["node_ids"]));
    assert_eq!(h.edge_ids(), ids(&v["edge_ids"]));
    // e1's tail emptied (1 and 2 removed) but head {3} survives — e1 lives.
    assert_dimembers(&h, "e1", &v["dimembers"]["e1"]);
}

// SKIPPED (Task 11, D16/Di-bulk deferred to Phase 7 ruling): main's
// DiHypergraph does not yet implement the bulk/attrs API this vector
// exercises (add_edges_from/remove_edges_from/remove_nodes_from/
// clear_edges/attrs accessors) — body preserved verbatim for Phase 7
// Di-parity revival; disabled via cfg(any()) rather than deleted.
#[cfg(any())]
#[test]
fn diverge_d2_di_remove_edges_from_missing_stops_after_err() {
    // XGI's DiHypergraph.remove_edges_from RAISES IDNotFound mid-iteration
    // — ids before the miss are already removed, ids after never attempted
    // (["e1", "ghost", "e3"] leaves e2 AND e3). D2-class channel
    // translation: per-item results, STOP after the first Err.
    let gt = ground_truth();
    let v = vector(&gt, "di_remove_node_modes")["edges_from_missing"].clone();
    assert_eq!(v["message"], "'ID ghost not found'"); // XGI truth, pinned

    let mut h: DiHypergraph = DiHypergraph::new();
    h.add_edge(
        vec!["1".into()],
        vec!["2".into()],
        Some("e1".into()),
        Value::Null,
    )
    .unwrap();
    h.add_edge(
        vec!["2".into()],
        vec!["3".into()],
        Some("e2".into()),
        Value::Null,
    )
    .unwrap();
    h.add_edge(
        vec!["3".into()],
        vec!["4".into()],
        Some("e3".into()),
        Value::Null,
    )
    .unwrap();
    let results = h.remove_edges_from(vec![
        "e1".to_string(),
        "ghost".to_string(),
        "e3".to_string(),
    ]);
    assert_eq!(results.len(), 2, "e3 was never attempted");
    assert!(results[0].is_ok());
    assert_eq!(
        results[1],
        Err(EdgeError::NotFound {
            edge_id: "ghost".to_string()
        })
    );
    assert_eq!(h.edge_ids(), ids(&v["edge_ids_after"])); // e2 AND e3 survive
}

#[test]
fn diverge_d2_di_remove_edge_missing_errors() {
    // Same D2 error-channel class: XGI raises IDNotFound on a missing edge;
    // the Rust core returns Err(EdgeError::NotFound) and the binding
    // translates Err → raise.
    let gt = ground_truth();
    let v = vector(&gt, "di_remove_node_modes")["remove_edge_missing"].clone();
    assert_eq!(v["exception"], "IDNotFound"); // XGI truth, pinned
    assert_eq!(v["message"], "'ID ghost not found'"); // XGI truth, pinned

    let mut h: DiHypergraph = DiHypergraph::new();
    assert!(matches!(
        h.remove_edge("ghost"),
        Err(EdgeError::NotFound { .. })
    ));
}

// ---------------------------------------------------------------------------
// DiHypergraph bulk/attrs/copy/clear/freeze/Debug/eq (Phase 2 Task 5)
// ---------------------------------------------------------------------------

#[test]
fn conform_di_repr_format() {
    // XGI 1.1's DiHypergraph.__repr__ is f"{cls}({self.edges.dimembers()})" —
    // the class name wrapping a dict {id: (tail, head)} of set-tuples, edges
    // in insertion order (XGI 0.10.2 wrapped a list). The Rust core's Debug still prints a
    // LIST (DiHypergraph([({tail}, {head}), ...])), so the shapes differ; the check compares literals. Members in INSERTION
    // order and uniform braces — cited divergence D5 (XGI's member sets
    // are hash-ordered; the fixture records sorted projections only).
    // XGI renders an empty side as "set()"; Rust formats "{}" — same D5
    // class. Lonely nodes never appear (XGI parity).
    let gt = ground_truth();
    let v = vector(&gt, "di_repr");
    assert_eq!(v["repr_prefix"], "DiHypergraph("); // XGI truth, pinned
    assert_eq!(v["repr_empty"], "DiHypergraph({})"); // XGI 1.1 truth, pinned (a dict)
    assert_eq!(
        v["repr_both_empty_edge"],
        "DiHypergraph({0: (set(), set())})"
    ); // pinned
    assert_eq!(
        v["dimembers_sorted"],
        serde_json::json!([[["a", "b", "c"], ["b", "d"]], [["a"], []]])
    ); // XGI truth (sorted), pinned

    let mut h: DiHypergraph = DiHypergraph::new();
    h.add_edge(
        vec!["a".into(), "b".into(), "c".into()],
        vec!["b".into(), "d".into()],
        None,
        Value::Null,
    )
    .unwrap();
    h.add_edge(vec!["a".into()], vec![], Some("e1".into()), Value::Null)
        .unwrap();
    h.add_node("lonely", Value::Null);
    let repr = format!("{h:?}");
    assert!(repr.starts_with(v["repr_prefix"].as_str().unwrap()));
    assert_eq!(repr, "DiHypergraph([({a, b, c}, {b, d}), ({a}, {})])");
    // Every fixture-recorded (sorted) side matches the Rust side.
    for (i, eid) in ["0", "e1"].iter().enumerate() {
        let (mut tail, mut head) = h.dimembers(eid).unwrap();
        tail.sort();
        head.sort();
        assert_eq!(vec![tail, head], ids_nested(&v["dimembers_sorted"][i]));
    }

    // XGI 1.1 renders a dict; the Rust Debug keeps its list shape (see conform_repr_format).
    let empty: DiHypergraph = DiHypergraph::new();
    assert_eq!(format!("{empty:?}"), "DiHypergraph([])");

    // Both-empty edge: XGI's "(set(), set())" artifact is pinned as
    // truth; Rust formats braces uniformly — "({}, {})" (same D5 class).
    let mut both_empty: DiHypergraph = DiHypergraph::new();
    both_empty
        .add_edge(vec![], vec![], None, Value::Null)
        .unwrap();
    assert_eq!(format!("{both_empty:?}"), "DiHypergraph([({}, {})])");
}

// SKIPPED (Task 11, D16/Di-bulk deferred to Phase 7 ruling): main's
// DiHypergraph does not yet implement the net-attrs public API this vector
// exercises (set_graph_attr/graph_attr) even though the underlying
// graph_attrs field is already load-bearing for PartialEq/clear/copy —
// body preserved verbatim for Phase 7 Di-parity revival; disabled via
// cfg(any()) rather than deleted.
#[cfg(any())]
#[test]
fn conform_di_eq_structural() {
    // XGI's DiHypergraph.__eq__ delegates to xgi.algorithms.equal with
    // the defaults: the edge-id -> {"in": tail, "out": head} mapping,
    // node attrs, edge attrs, and net attrs are all significant;
    // member order is not. DIRECTION IS SIGNIFICANT (probed: tail/head
    // swapped -> NOT equal; both-directions vs tail-only -> NOT equal).
    // The Rust core's PartialEq matches every recorded verdict.
    let gt = ground_truth();
    let v = vector(&gt, "di_eq");
    // XGI truth, pinned.
    assert_eq!(v["same"], true);
    assert_eq!(v["direction_flipped"], false);
    assert_eq!(v["member_order_insignificant"], true);
    assert_eq!(v["diff_edge_id"], false);
    assert_eq!(v["diff_edge_attr"], false);
    assert_eq!(v["lonely_same"], true);
    assert_eq!(v["diff_node_attr"], false);
    assert_eq!(v["lonely_missing"], false);
    assert_eq!(v["diff_net_attr"], false);
    assert_eq!(v["both_vs_tail_only"], false);
    assert_eq!(v["empty_attr_lonely_vs_absent"], false);

    let build = |tail: &[&str],
                 head: &[&str],
                 idx: &str,
                 edge_attr: Value,
                 solo: Option<(&str, Value)>,
                 net: Option<(&str, Value)>| {
        let mut h: DiHypergraph = DiHypergraph::new();
        h.add_edge(
            tail.iter().map(|m| m.to_string()).collect(),
            head.iter().map(|m| m.to_string()).collect(),
            Some(idx.into()),
            edge_attr,
        )
        .unwrap();
        if let Some((n, attrs)) = solo {
            h.add_node(n, attrs);
        }
        if let Some((k, val)) = net {
            h.set_graph_attr(k, val);
        }
        h
    };
    let a = build(&["a", "b"], &["c"], "e1", Value::Null, None, None);
    assert_eq!(a, build(&["a", "b"], &["c"], "e1", Value::Null, None, None));
    // Direction flipped -> NOT equal.
    assert_ne!(a, build(&["c"], &["a", "b"], "e1", Value::Null, None, None));
    // Member order insignificant.
    assert_eq!(a, build(&["b", "a"], &["c"], "e1", Value::Null, None, None));
    // Edge id significant.
    assert_ne!(a, build(&["a", "b"], &["c"], "e2", Value::Null, None, None));
    // Edge attrs significant.
    assert_ne!(
        build(
            &["a", "b"],
            &["c"],
            "e1",
            serde_json::json!({"w": 1}),
            None,
            None
        ),
        build(
            &["a", "b"],
            &["c"],
            "e1",
            serde_json::json!({"w": 2}),
            None,
            None
        )
    );
    // Net attrs significant.
    assert_ne!(
        a,
        build(
            &["a", "b"],
            &["c"],
            "e1",
            Value::Null,
            None,
            Some(("name", serde_json::json!("x")))
        )
    );
    // Both-directions vs tail-only -> NOT equal.
    assert_ne!(
        build(&["a", "b"], &["b"], "e1", Value::Null, None, None),
        build(&["a", "b"], &[], "e1", Value::Null, None, None)
    );
    // Lonely node attrs significant; presence significant (even with
    // EMPTY attrs — XGI compares _node_attr, where every node carries a
    // dict).
    let l1 = build(
        &["a", "b"],
        &["c"],
        "e1",
        Value::Null,
        Some(("solo", serde_json::json!({"color": "red"}))),
        None,
    );
    let l2 = build(
        &["a", "b"],
        &["c"],
        "e1",
        Value::Null,
        Some(("solo", serde_json::json!({"color": "red"}))),
        None,
    );
    let l3 = build(
        &["a", "b"],
        &["c"],
        "e1",
        Value::Null,
        Some(("solo", serde_json::json!({"color": "blue"}))),
        None,
    );
    assert_eq!(l1, l2);
    assert_ne!(l1, l3);
    assert_ne!(l1, a);
    let e1 = build(
        &["a", "b"],
        &["c"],
        "e1",
        Value::Null,
        Some(("solo", serde_json::json!({}))),
        None,
    );
    assert_ne!(e1, a);
}

// SKIPPED (Task 11, D16/Di-bulk deferred to Phase 7 ruling): main's
// DiHypergraph does not yet implement the bulk/attrs API this vector
// exercises (add_edges_from/remove_edges_from/remove_nodes_from/
// clear_edges/attrs accessors) — body preserved verbatim for Phase 7
// Di-parity revival; disabled via cfg(any()) rather than deleted.
#[cfg(any())]
#[test]
fn conform_di_add_edges_from() {
    // XGI's add_edges_from accepts members-only (auto ids), (members,
    // idx), (members, attrdict), (members, idx, attrdict), and dict
    // bunches, plus **attr broadcast (per-edge attrs take precedence);
    // returns None. The Rust core takes uniform (tail, head, idx,
    // attrs) quadruples — format detection and broadcast merging are
    // binding concerns (D7 class); the outcomes conform. The Notes
    // claim empty edges are skipped — the runtime CREATES one for
    // ([], []) (D1-class docstring lie); the core conforms.
    let gt = ground_truth();
    let v = vector(&gt, "di_add_edges_from");
    assert_eq!(v["members_only"]["return"], Value::Null); // XGI truth, pinned
    assert_eq!(v["dup_warns_continues"]["return"], Value::Null); // pinned
    assert_eq!(v["dup_warns_continues"]["warned"], true); // pinned
    assert!(v["dup_warns_continues"]["warning_prefix"]
        .as_str()
        .unwrap()
        .starts_with("uid e1 already exists"));
    // Broadcast: per-edge color wins, size merges in — XGI truth, pinned.
    assert_eq!(
        v["broadcast"],
        serde_json::json!({"0": {"color": "red", "size": 10}})
    );

    // Members-only: auto ids in order.
    let mut h: DiHypergraph = DiHypergraph::new();
    let results = h.add_edges_from(vec![
        (
            vec!["a".into(), "b".into()],
            vec!["c".into()],
            None,
            Value::Null,
        ),
        (
            vec!["d".into()],
            vec!["e".into(), "f".into()],
            None,
            Value::Null,
        ),
    ]);
    assert!(results.iter().all(|r| r.is_ok()));
    assert_eq!(h.edge_ids(), ids(&v["members_only"]["edge_ids"]));
    for (eid, recorded) in v["members_only"]["dimembers"].as_object().unwrap() {
        assert_dimembers(&h, eid, recorded);
    }

    // (members, idx, attrs): ids and per-edge attrs land.
    let mut h2: DiHypergraph = DiHypergraph::new();
    h2.add_edges_from(vec![
        (
            vec!["a".into()],
            vec!["b".into()],
            Some("one".into()),
            serde_json::json!({"color": "red"}),
        ),
        (
            vec!["c".into()],
            vec![],
            Some("two".into()),
            serde_json::json!({"color": "blue", "age": 40}),
        ),
    ]);
    assert_eq!(h2.edge_ids(), ids(&v["with_idx_attrs"]["edge_ids"]));
    for (eid, attrs) in v["with_idx_attrs"]["attrs"].as_object().unwrap() {
        assert_eq!(h2.edge_attrs(eid).unwrap(), attrs);
    }
    for (eid, recorded) in v["with_idx_attrs"]["dimembers"].as_object().unwrap() {
        assert_dimembers(&h2, eid, recorded);
    }

    // Broadcast equivalence: the binding merges **attr into each edge's
    // dict (per-edge wins) before calling; the core receives the merged
    // attrs — the outcome matches XGI's recorded broadcast result.
    let mut h3: DiHypergraph = DiHypergraph::new();
    h3.add_edges_from(vec![(
        vec!["a".into()],
        vec!["b".into()],
        None,
        serde_json::json!({"color": "red", "size": 10}),
    )]);
    assert_eq!(h3.edge_attrs("0").unwrap(), &v["broadcast"]["0"]);

    // Empty edge is CREATED, not skipped (D1-class).
    let mut h4: DiHypergraph = DiHypergraph::new();
    h4.add_edges_from(vec![
        (vec![], vec![], None, Value::Null),
        (vec!["a".into()], vec!["b".into()], None, Value::Null),
    ]);
    assert_eq!(h4.edge_ids(), ids(&v["empty_created"]["edge_ids"]));
    for (eid, recorded) in v["empty_created"]["dimembers"].as_object().unwrap() {
        assert_dimembers(&h4, eid, recorded);
    }
}

// SKIPPED (Task 11, D16/Di-bulk deferred to Phase 7 ruling): main's
// DiHypergraph does not yet implement the bulk/attrs API this vector
// exercises (add_edges_from/remove_edges_from/remove_nodes_from/
// clear_edges/attrs accessors) — body preserved verbatim for Phase 7
// Di-parity revival; disabled via cfg(any()) rather than deleted.
#[cfg(any())]
#[test]
fn diverge_d2_di_add_edges_from_dup_errors_continues() {
    // Same D2 error-channel class as the undirected bulk add: XGI warns
    // + skips a duplicate idx and CONTINUES with the rest (the dup's
    // members are never added). The Rust core surfaces the dup as
    // Err(AlreadyExists) in the per-edge Vec<Result> and continues; the
    // binding translates Err -> UserWarning + skip.
    let gt = ground_truth();
    let v = vector(&gt, "di_add_edges_from")["dup_warns_continues"].clone();

    let mut h: DiHypergraph = DiHypergraph::new();
    let results = h.add_edges_from(vec![
        (
            vec!["a".into()],
            vec!["b".into()],
            Some("e1".into()),
            Value::Null,
        ),
        (
            vec!["c".into()],
            vec!["d".into()],
            Some("e1".into()),
            Value::Null,
        ),
        (
            vec!["e".into()],
            vec!["f".into()],
            Some("e2".into()),
            Value::Null,
        ),
    ]);
    assert_eq!(results.len(), 3);
    assert!(results[0].is_ok());
    assert!(matches!(results[1], Err(EdgeError::AlreadyExists { .. })));
    assert!(results[2].is_ok(), "continues past the dup");

    // Dup skipped, the rest kept — XGI's recorded final state.
    assert_eq!(h.edge_ids(), ids(&v["edge_ids"]));
    assert_eq!(h.num_nodes(), v["num_nodes"].as_u64().unwrap() as usize);
    for (eid, recorded) in v["dimembers"].as_object().unwrap() {
        assert_dimembers(&h, eid, recorded);
    }
}

// SKIPPED (Task 11, D16/Di-bulk deferred to Phase 7 ruling): main's
// DiHypergraph does not yet implement the bulk/attrs API this vector
// exercises (add_edges_from/remove_edges_from/remove_nodes_from/
// clear_edges/attrs accessors) — body preserved verbatim for Phase 7
// Di-parity revival; disabled via cfg(any()) rather than deleted.
#[cfg(any())]
#[test]
fn conform_di_set_attrs() {
    // set_node_attributes / set_edge_attributes mirror the undirected
    // class: dict-of-dicts MERGES into existing attr dicts; a missing id
    // warns + SKIPS, never auto-creates (the warn channel is a binding
    // concern — D2 class); a list of pairs raises XGIError at XGI's
    // Python boundary (the core takes pairs — D7 class); the scalar and
    // dict-of-scalars name= forms are binding sugar (their outcomes are
    // pinned as XGI truth; the core's per-node merge produces them).
    let gt = ground_truth();
    let v = vector(&gt, "di_set_attrs");
    // XGI truth, pinned.
    assert_eq!(v["node_dict_of_dicts"]["return"], Value::Null);
    assert_eq!(v["node_dict_of_dicts"]["warned"], true);
    assert_eq!(
        v["node_dict_of_dicts"]["warning_message"],
        "Node ghost does not exist!"
    );
    assert_eq!(v["node_pairs_exception"], "XGIError");
    assert_eq!(
        v["node_pairs_message"],
        "Must pass a dictionary of dictionaries"
    );
    assert_eq!(
        v["node_dict_of_dicts"]["attrs_a"],
        serde_json::json!({"x": 1, "color": "red"})
    );
    assert_eq!(v["edge_dict_of_dicts"]["return"], Value::Null);
    assert_eq!(v["edge_dict_of_dicts"]["warned"], true);
    assert_eq!(
        v["edge_dict_of_dicts"]["warning_message"],
        "Edge ghost does not exist!"
    );
    assert_eq!(
        v["edge_dict_of_dicts"]["attrs_e1"],
        serde_json::json!({"w": 1, "heat": 0.5})
    );
    // Scalar broadcast + dict-of-scalars name= forms: XGI truth, pinned.
    assert_eq!(
        v["node_scalar_broadcast"]["attrs_a"],
        serde_json::json!({"color": "red"})
    );
    assert_eq!(
        v["node_scalar_broadcast"]["attrs_c"],
        serde_json::json!({"color": "red"})
    );
    assert_eq!(
        v["node_dict_of_scalars"]["attrs_a"],
        serde_json::json!({"color": "red"})
    );
    assert_eq!(v["node_dict_of_scalars"]["attrs_b"], serde_json::json!({}));

    // Node dict-of-dicts: merge; ghost skipped, never auto-created.
    let mut h: DiHypergraph = DiHypergraph::new();
    h.add_edge(
        vec!["a".into(), "b".into()],
        vec!["c".into()],
        Some("e1".into()),
        Value::Null,
    )
    .unwrap();
    *h.node_attrs_mut("a").unwrap() = serde_json::json!({"x": 1});
    let color = |c: &str| {
        let mut m = serde_json::Map::new();
        m.insert("color".to_string(), serde_json::json!(c));
        m
    };
    h.set_node_attributes(vec![
        ("a".to_string(), color("red")),
        ("b".to_string(), color("blue")),
        ("ghost".to_string(), color("green")),
    ]);
    assert_eq!(
        h.node_attrs("a").unwrap(),
        &v["node_dict_of_dicts"]["attrs_a"]
    );
    assert_eq!(
        h.node_attrs("b").unwrap(),
        &v["node_dict_of_dicts"]["attrs_b"]
    );
    assert!(!h.has_node("ghost"));
    assert_eq!(
        h.num_nodes(),
        v["node_dict_of_dicts"]["num_nodes"].as_u64().unwrap() as usize
    );

    // Edge dict-of-dicts: merge; ghost skipped.
    let mut h2: DiHypergraph = DiHypergraph::new();
    h2.add_edge(
        vec!["a".into()],
        vec!["b".into()],
        Some("e1".into()),
        serde_json::json!({"w": 1}),
    )
    .unwrap();
    h2.add_edge(
        vec!["c".into()],
        vec!["d".into()],
        Some("e2".into()),
        serde_json::json!({}),
    )
    .unwrap();
    let mut heat = serde_json::Map::new();
    heat.insert("heat".to_string(), serde_json::json!(0.5));
    let mut x = serde_json::Map::new();
    x.insert("x".to_string(), serde_json::json!(1));
    h2.set_edge_attributes(vec![("e1".to_string(), heat), ("ghost".to_string(), x)]);
    assert_eq!(
        h2.edge_attrs("e1").unwrap(),
        &v["edge_dict_of_dicts"]["attrs_e1"]
    );
    assert_eq!(
        h2.edge_attrs("e2").unwrap(),
        &v["edge_dict_of_dicts"]["attrs_e2"]
    );
    assert!(!h2.has_edge("ghost"));
    assert_eq!(
        h2.num_edges(),
        v["edge_dict_of_dicts"]["num_edges"].as_u64().unwrap() as usize
    );
}

// SKIPPED (Task 11, D16/Di-bulk deferred to Phase 7 ruling): main's
// DiHypergraph does not yet implement the bulk/attrs API this vector
// exercises (add_edges_from/remove_edges_from/remove_nodes_from/
// clear_edges/attrs accessors) — body preserved verbatim for Phase 7
// Di-parity revival; disabled via cfg(any()) rather than deleted.
#[cfg(any())]
#[test]
fn diverge_d10_di_clear_resets_uid_counter() {
    // DiHypergraph.clear() empties nodes, edges, all attr channels, and
    // net attrs — the Rust core conforms on all of that. D10 (extended
    // to DiHypergraph): XGI does NOT reset its auto-id counter (the next
    // auto id continues at 1); the Rust core resets edge_uid_counter —
    // clear() ≡ new() (III.7 replay-from-empty determinism).
    let gt = ground_truth();
    let v = vector(&gt, "di_clear_freeze")["clear"].clone();
    assert_eq!(v["num_nodes"], 0); // XGI truth, pinned
    assert_eq!(v["num_edges"], 0);
    assert_eq!(v["node_ids"], serde_json::json!([]));
    assert_eq!(v["edge_ids"], serde_json::json!([]));
    assert_eq!(v["net_attrs"], serde_json::json!({}));
    assert_eq!(ids(&v["auto_ids_after_clear"]), vec!["1"]); // XGI truth, pinned

    let mut h: DiHypergraph = DiHypergraph::new();
    h.add_edge(
        vec!["a".into(), "b".into()],
        vec!["c".into()],
        None,
        Value::Null,
    )
    .unwrap();
    h.add_edge(
        vec!["d".into()],
        vec!["e".into()],
        Some("e1".into()),
        serde_json::json!({"heat": 0.5}),
    )
    .unwrap();
    h.add_node("lonely", serde_json::json!({"x": 1}));
    h.set_graph_attr("name", serde_json::json!("test"));
    h.clear();

    assert_eq!(h.num_nodes(), 0);
    assert_eq!(h.num_edges(), 0);
    assert!(h.node_ids().is_empty());
    assert!(h.edge_ids().is_empty());
    assert!(h.graph_attr("name").is_none());
    assert!(h.node_attrs("lonely").is_none());
    assert!(h.edge_attrs("e1").is_none());

    // D10: Rust resets the counter — the post-clear auto id is "0".
    let auto = h
        .add_edge(vec!["z".into()], vec![], None, Value::Null)
        .unwrap();
    assert_eq!(auto, "0"); // Rust divergence, deliberate
}

// SKIPPED (Task 11, D16/Di-bulk deferred to Phase 7 ruling): main's
// DiHypergraph does not yet implement the bulk/attrs API this vector
// exercises (add_edges_from/remove_edges_from/remove_nodes_from/
// clear_edges/attrs accessors) — body preserved verbatim for Phase 7
// Di-parity revival; disabled via cfg(any()) rather than deleted.
#[cfg(any())]
#[test]
fn diverge_d16_di_clear_edges_is_core_extension() {
    // D16: XGI's DiHypergraph HAS NO clear_edges — the attribute lookup
    // falls through XGI's __getattr__ stat fallback and raises
    // AttributeError (pinned below). The Rust core provides clear_edges
    // for API uniformity with Hypergraph: it removes every edge, keeps
    // all nodes/attrs/net attrs, and (like the undirected core) does NOT
    // reset the uid counter. Freeze-guarded per the D12 uniform-guard
    // rationale.
    let gt = ground_truth();
    let v = vector(&gt, "di_clear_freeze")["freeze"]["guarded"]["clear_edges"].clone();
    assert_eq!(v["exception"], "AttributeError"); // XGI truth, pinned
    assert!(v["message"]
        .as_str()
        .unwrap()
        .starts_with("clear_edges is not a method of DiHypergraph"));

    let mut h: DiHypergraph = DiHypergraph::new();
    h.add_edge(
        vec!["a".into(), "b".into()],
        vec!["c".into()],
        None,
        Value::Null,
    )
    .unwrap();
    h.add_edge(
        vec!["d".into()],
        vec!["e".into()],
        Some("e1".into()),
        serde_json::json!({"heat": 0.5}),
    )
    .unwrap();
    h.add_node("lonely", serde_json::json!({"x": 1}));
    h.set_graph_attr("name", serde_json::json!("test"));
    h.clear_edges();

    assert_eq!(h.num_edges(), 0);
    assert_eq!(h.num_nodes(), 6, "nodes survive");
    assert_eq!(
        h.node_attrs("lonely").unwrap(),
        &serde_json::json!({"x": 1})
    );
    assert_eq!(
        h.graph_attr("name"),
        Some(&serde_json::json!("test")),
        "net attrs survive"
    );
    assert!(h.memberships("a").unwrap().is_empty());

    // Counter NOT reset (uniformity with Hypergraph.clear_edges — the
    // node state survives, so counter continuity matches state
    // continuity): the next auto id is "1".
    let auto = h
        .add_edge(vec!["z".into()], vec![], None, Value::Null)
        .unwrap();
    assert_eq!(auto, "1");
}

// SKIPPED (Task 11, D16/Di-bulk deferred to Phase 7 ruling): main's
// DiHypergraph does not yet implement the bulk/attrs API this vector
// exercises (add_edges_from/remove_edges_from/remove_nodes_from/
// clear_edges/attrs accessors) — body preserved verbatim for Phase 7
// Di-parity revival; disabled via cfg(any()) rather than deleted.
#[cfg(any())]
#[test]
fn conform_di_freeze_blocks_mutation() {
    // XGI's DiHypergraph.freeze() guards add_node(s)_from,
    // add_edge(s)_from, remove_node(s)_from, remove_edge(s)_from, and
    // clear (XGIError "Frozen higher-order network can't be modified").
    // The Rust core panics on the same mutators (panic ≡ raise; the
    // binding converts — D2 error-channel class). The attr-dict channel
    // (set_node_attributes / set_edge_attributes) is unguarded in XGI —
    // the Rust core matches.
    let gt = ground_truth();
    let v = vector(&gt, "di_clear_freeze")["freeze"].clone();
    assert_eq!(v["is_frozen_before"], false); // XGI truth, pinned
    assert_eq!(v["is_frozen_after"], true); // XGI truth, pinned
    for method in [
        "add_node",
        "add_nodes_from",
        "add_edge",
        "add_edges_from",
        "remove_node",
        "remove_nodes_from",
        "remove_edge",
        "remove_edges_from",
        "clear",
    ] {
        assert_eq!(v["guarded"][method]["exception"], "XGIError"); // pinned
        assert_eq!(
            v["guarded"][method]["message"],
            "Frozen higher-order network can't be modified"
        );
    }
    // The attr-dict channel is NOT guarded in XGI — pinned as truth.
    assert_eq!(v["guarded"]["set_node_attributes"], Value::Null);
    assert_eq!(v["guarded"]["set_edge_attributes"], Value::Null);

    let mut h: DiHypergraph = DiHypergraph::new();
    h.add_edge(
        vec!["a".into(), "b".into()],
        vec!["c".into()],
        Some("e1".into()),
        serde_json::json!({"w": 1}),
    )
    .unwrap();
    assert!(!h.is_frozen());
    h.freeze();
    assert!(h.is_frozen());

    let mut panics = |f: &mut dyn FnMut(&mut DiHypergraph)| {
        std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| f(&mut h))).is_err()
    };
    assert!(panics(&mut |h| {
        h.add_node("z", Value::Null);
    }));
    assert!(panics(&mut |h| {
        h.add_nodes_from(vec![("z".to_string(), Value::Null)]);
    }));
    assert!(panics(&mut |h| {
        h.add_edge(vec!["a".into()], vec!["b".into()], None, Value::Null)
            .unwrap();
    }));
    assert!(panics(&mut |h| {
        h.add_edges_from(vec![(
            vec!["a".into()],
            vec!["b".into()],
            None,
            Value::Null,
        )]);
    }));
    assert!(panics(&mut |h| h.remove_node("a", false, true).unwrap()));
    assert!(panics(&mut |h| {
        h.remove_nodes_from(vec!["a".to_string()], false, true);
    }));
    assert!(panics(&mut |h| h.remove_edge("e1").unwrap()));
    assert!(panics(&mut |h| {
        h.remove_edges_from(vec!["e1".to_string()]);
    }));
    assert!(panics(&mut |h| h.clear()));

    // XGI parity: the attr-dict channel stays OPEN on a frozen graph.
    let mut attrs = serde_json::Map::new();
    attrs.insert("k".to_string(), serde_json::json!(1));
    h.set_node_attributes(vec![("a".to_string(), attrs.clone())]);
    h.set_edge_attributes(vec![("e1".to_string(), attrs)]);
    assert_eq!(h.node_attrs("a").unwrap()["k"], 1);
    assert_eq!(h.edge_attrs("e1").unwrap()["k"], 1);
}

// SKIPPED (Task 11, D16/Di-bulk deferred to Phase 7 ruling): main's
// DiHypergraph does not yet implement the bulk/attrs API this vector
// exercises (add_edges_from/remove_edges_from/remove_nodes_from/
// clear_edges/attrs accessors) — body preserved verbatim for Phase 7
// Di-parity revival; disabled via cfg(any()) rather than deleted.
#[cfg(any())]
#[test]
fn diverge_d12_di_freeze_guards_membership_ops_and_clear_edges() {
    // D12 (extended to DiHypergraph): XGI's DiHypergraph freeze list
    // omits add_node_to_edge AND remove_node_from_edge (unlike the
    // undirected class, which guards both) — probed: both mutate a
    // FROZEN DiHypergraph unimpeded. clear_edges does not exist at all
    // (D16). The Rust core's frozen flag guards ALL structural mutators
    // uniformly — a freeze that permits membership surgery or wholesale
    // edge deletion is not a freeze.
    let gt = ground_truth();
    let v = vector(&gt, "di_clear_freeze")["freeze"].clone();
    assert_eq!(v["guarded"]["add_node_to_edge"], Value::Null); // XGI truth, pinned
    assert_eq!(v["guarded"]["remove_node_from_edge"], Value::Null); // pinned

    let mut h: DiHypergraph = DiHypergraph::new();
    h.add_edge(
        vec!["a".into(), "b".into()],
        vec!["c".into()],
        Some("e1".into()),
        Value::Null,
    )
    .unwrap();
    h.freeze();
    let r1 = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| {
        h.add_node_to_edge("e1", "n", DiRole::Tail);
    }));
    assert!(
        r1.is_err(),
        "Rust divergence: add_node_to_edge panics when frozen"
    );
    let r2 = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| {
        h.remove_node_from_edge("e1", "a", DiRole::Tail, true)
            .unwrap();
    }));
    assert!(
        r2.is_err(),
        "Rust divergence: remove_node_from_edge panics when frozen"
    );
    let r3 = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| h.clear_edges()));
    assert!(
        r3.is_err(),
        "Rust divergence: clear_edges panics when frozen"
    );
    // The panics fired BEFORE any mutation: the original is untouched.
    assert_eq!(h.tail("e1").unwrap(), vec!["a", "b"]);
    assert!(!h.has_node("n"));
    assert_eq!(h.num_edges(), 1);
}

#[test]
fn diverge_d13_di_copy_carries_frozen() {
    // D13 (DiHypergraph parity): XGI's freeze is per-instance
    // method-swizzling — copy() of a frozen DiHypergraph is NOT frozen
    // (pinned). The Rust core's frozen flag is data; copy() carries it.
    let gt = ground_truth();
    let v = vector(&gt, "di_clear_freeze")["freeze"].clone();
    assert_eq!(v["copy_of_frozen_is_frozen"], false); // XGI truth, pinned

    let mut h: DiHypergraph = DiHypergraph::new();
    h.add_edge(
        vec!["a".into()],
        vec!["b".into()],
        Some("e1".into()),
        Value::Null,
    )
    .unwrap();
    h.freeze();
    let cp = h.copy();
    assert!(cp.is_frozen(), "Rust divergence: copy of frozen is frozen");
}

// ---------------------------------------------------------------------------
// SimplicialComplex (Phase 2 Task 6+)
// ---------------------------------------------------------------------------

/// The SET of member-sets (sorted for comparison) across all edges —
/// the face-id -> member-set MAPPING differs between XGI (hash-ordered
/// `set(faces)` iteration) and the Rust core (canonical combination
/// order, D5 class), so closure vectors compare the multiset, not the
/// mapping; XGI's exact mapping is pinned separately as truth.
fn member_set_multiset(members: &Value) -> Vec<Vec<String>> {
    let mut sets: Vec<Vec<String>> = members.as_object().unwrap().values().map(ids).collect();
    sets.sort();
    sets
}

fn sc_member_multiset(s: &SimplicialComplex) -> Vec<Vec<String>> {
    let mut sets: Vec<Vec<String>> = s
        .edge_ids()
        .iter()
        .map(|eid| {
            let mut m = s.members(eid).unwrap();
            m.sort();
            m
        })
        .collect();
    sets.sort();
    sets
}

#[test]
fn conform_sc_add_simplex_closure() {
    // XGI's add_simplex creates the top simplex FIRST (auto id 0), then
    // the subfaces — EXACTLY the proper non-empty subsets of sizes
    // 2..n-1 (NO singletons) — consuming auto ids in set(faces)
    // iteration order (deterministic for int members, hash-dependent
    // for str). The Rust core enumerates combinations canonically
    // (sizes n-1 down to 2, lexicographic by member position): the face
    // SET is identical, the face-id -> member-set mapping differs —
    // D5-class "strictly more defined". XGI's mapping is pinned as
    // truth; the multiset and every structural fact are asserted.
    let gt = ground_truth();
    let v = vector(&gt, "sc_add_simplex_closure");
    assert_eq!(v["three"]["return"], Value::Null); // XGI truth, pinned
                                                   // XGI's exact id -> members mapping for the 3-simplex, pinned.
    assert_eq!(
        v["three"]["members"],
        serde_json::json!({"0": ["1", "2", "3"], "1": ["2", "3"], "2": ["1", "2"], "3": ["1", "3"]})
    );
    assert_eq!(
        v["str_idx_no_bump"]["edge_ids"],
        serde_json::json!(["top", 0, 1, 2])
    ); // pinned
    assert_eq!(
        v["int_idx_bumps"]["edge_ids"],
        serde_json::json!([10, 11, 12, 13])
    ); // pinned

    // 3-simplex: top at "0", faces [1,2]/[1,3]/[2,3] at 1/2/3
    // (canonical order), no singletons.
    let mut s: SimplicialComplex = SimplicialComplex::new();
    s.add_simplex(vec!["1".into(), "2".into(), "3".into()], None, Value::Null)
        .unwrap();
    assert!(
        s.has_edge("0"),
        "auto id lands at \"0\" (D8: state, not return)"
    );
    assert_eq!(s.num_edges(), 4);
    assert_eq!(
        sc_member_multiset(&s),
        member_set_multiset(&v["three"]["members"])
    );
    assert_eq!(s.members("0").unwrap(), vec!["1", "2", "3"]);
    for eid in s.edge_ids() {
        assert_ne!(s.members(&eid).unwrap().len(), 1, "no singleton faces");
    }

    // 4-simplex: 11 edges — top + 4 size-3 + 6 size-2.
    let mut s4: SimplicialComplex = SimplicialComplex::new();
    s4.add_simplex(
        vec!["1".into(), "2".into(), "3".into(), "4".into()],
        None,
        Value::Null,
    )
    .unwrap();
    assert_eq!(s4.num_edges(), 11);
    assert_eq!(
        sc_member_multiset(&s4),
        member_set_multiset(&v["four"]["members"])
    );

    // 2-simplex: no subfaces.
    let mut s2: SimplicialComplex = SimplicialComplex::new();
    s2.add_simplex(vec!["1".into(), "2".into()], None, Value::Null)
        .unwrap();
    assert_eq!(s2.num_edges(), 1);
    assert_eq!(
        sc_member_multiset(&s2),
        member_set_multiset(&v["two"]["members"])
    );

    // str idx: no bump — faces take auto ids 0, 1, 2 (XGI parity).
    let mut s3: SimplicialComplex = SimplicialComplex::new();
    s3.add_simplex(
        vec!["1".into(), "2".into(), "3".into()],
        Some("top".into()),
        Value::Null,
    )
    .unwrap();
    assert_eq!(s3.edge_ids(), ids(&v["str_idx_no_bump"]["edge_ids"]));
    assert_eq!(
        sc_member_multiset(&s3),
        member_set_multiset(&v["str_idx_no_bump"]["members"])
    );

    // Numeric idx "10": the D3 rule bumps — faces take 11, 12, 13.
    // XGI's int-idx outcome is identical (conform).
    let mut s5: SimplicialComplex = SimplicialComplex::new();
    s5.add_simplex(
        vec!["1".into(), "2".into(), "3".into()],
        Some("10".into()),
        Value::Null,
    )
    .unwrap();
    assert_eq!(s5.edge_ids(), ids(&v["int_idx_bumps"]["edge_ids"]));
    assert_eq!(
        sc_member_multiset(&s5),
        member_set_multiset(&v["int_idx_bumps"]["members"])
    );
}

#[test]
fn conform_sc_redundant_simplex() {
    // Re-adding the same member SET is a SILENT no-op in XGI (no
    // warning, returns None, num_edges unchanged) — even with a NEW
    // explicit idx (the member-set check precedes the idx check; the
    // idx is NOT consumed), and for an existing subface. The Rust core
    // conforms on state and returns Ok(id of the EXISTING edge) — the
    // D8 return-channel class (XGI's None cannot report the id).
    let gt = ground_truth();
    let v = vector(&gt, "sc_redundant_simplex");
    assert_eq!(v["reorder"]["return"], Value::Null); // XGI truth, pinned
    assert_eq!(v["reorder"]["warned"], false); // pinned: SILENT, no warning
    assert_eq!(v["reorder_new_idx"]["warned"], false); // pinned
    assert_eq!(v["existing_face"]["warned"], false); // pinned
    assert_eq!(v["num_edges_before"], 4); // pinned

    let mut s: SimplicialComplex = SimplicialComplex::new();
    s.add_simplex(vec!["1".into(), "2".into(), "3".into()], None, Value::Null)
        .unwrap();
    s.add_simplex(vec!["3".into(), "2".into(), "1".into()], None, Value::Null)
        .unwrap();
    assert!(
        s.has_edge("0"),
        "reorder is a no-op on the existing edge's id (D8: state, not return)"
    );
    assert_eq!(
        s.num_edges(),
        v["reorder"]["num_edges"].as_u64().unwrap() as usize
    );
    assert_eq!(s.edge_ids(), ids(&v["reorder"]["edge_ids"]));

    s.add_simplex(
        vec!["3".into(), "2".into(), "1".into()],
        Some("newid".into()),
        Value::Null,
    )
    .unwrap();
    assert!(
        s.has_edge("0"),
        "new idx is NOT consumed (D8: state, not return)"
    );
    assert_eq!(s.edge_ids(), ids(&v["reorder_new_idx"]["edge_ids"])); // no "newid"

    s.add_simplex(vec!["1".into(), "2".into()], None, Value::Null)
        .unwrap();
    assert!(
        s.has_edge("1"),
        "existing face's id (D8: state, not return)"
    );
    assert_eq!(
        s.num_edges(),
        v["existing_face"]["num_edges"].as_u64().unwrap() as usize
    );
}

#[test]
fn conform_sc_dup_idx_silent_noop() {
    // ADAPTED (Task 11): unlike H/Di add_edge (D2 error-channel class:
    // Err(AlreadyExists) where XGI warns+no-ops), SimplicialComplex's
    // add_simplex has NO duplicate-idx error path — a dup idx with
    // DIFFERENT members is a silent Ok(()) no-op, matching XGI's
    // warn+no-op STATE outcome directly (the warn channel itself stays
    // binding-owned, D2 class; the core conforms on state).
    let gt = ground_truth();
    let v = vector(&gt, "sc_dup_idx");
    assert_eq!(v["return"], Value::Null); // XGI truth, pinned
    assert_eq!(v["warned"], true); // XGI truth, pinned
    assert!(v["warning_prefix"]
        .as_str()
        .unwrap()
        .starts_with("uid s1 already exists"));

    let mut s: SimplicialComplex = SimplicialComplex::new();
    s.add_simplex(
        vec!["1".into(), "2".into(), "3".into()],
        Some("s1".into()),
        Value::Null,
    )
    .unwrap();
    s.add_simplex(vec!["4".into(), "5".into()], Some("s1".into()), Value::Null)
        .unwrap();
    assert_eq!(s.num_edges(), v["num_edges"].as_u64().unwrap() as usize);
    assert_eq!(s.num_nodes(), v["num_nodes"].as_u64().unwrap() as usize);
    assert_eq!(s.edge_ids(), ids(&v["edge_ids"]));
    assert_eq!(sc_member_multiset(&s), member_set_multiset(&v["members"]));
}

#[test]
fn conform_sc_empty_simplex() {
    // D1-class docstring lie: XGI's Notes claim "currently cannot add
    // empty simplices"; the runtime CREATES an empty simplex (auto id
    // 0, no members). A second add_simplex([]) is a silent no-op
    // (has_simplex([]) becomes True). The Rust core conforms.
    let gt = ground_truth();
    let v = vector(&gt, "sc_empty_simplex");
    assert_eq!(v["return"], Value::Null); // XGI truth, pinned
    assert_eq!(v["num_nodes"], 0); // pinned
    assert_eq!(v["num_edges"], 1); // pinned
    assert_eq!(v["has_empty"], true); // pinned
    assert_eq!(v["again"]["num_edges"], 1); // pinned

    let mut s: SimplicialComplex = SimplicialComplex::new();
    s.add_simplex(vec![], None, Value::Null).unwrap();
    let id = id_str(&v["edge_ids"][0]);
    assert!(s.has_edge(&id)); // D8: state, not return
    assert_eq!(s.num_edges(), 1);
    assert_eq!(s.num_nodes(), 0);
    assert!(s.members(&id).unwrap().is_empty());
    assert!(s.has_simplex(&[]));
    s.add_simplex(vec![], None, Value::Null).unwrap();
    assert!(s.has_edge("0"));
    assert_eq!(s.num_edges(), 1);
}

#[test]
fn conform_sc_attrs_no_propagate() {
    // Simplex attrs land ONLY on the top simplex; every subface gets
    // XGI's empty attr dict {} — the core's Null placeholder ≈ {} (the
    // D7-class convention shared with auto-created nodes).
    let gt = ground_truth();
    let v = vector(&gt, "sc_attrs_no_propagate");
    assert_eq!(v["attrs"]["0"], serde_json::json!({"color": "red"})); // pinned
    assert_eq!(v["attrs"]["1"], serde_json::json!({})); // XGI truth, pinned
    assert_eq!(v["attrs"]["2"], serde_json::json!({})); // pinned
    assert_eq!(v["attrs"]["3"], serde_json::json!({})); // pinned

    let mut s: SimplicialComplex = SimplicialComplex::new();
    s.add_simplex(
        vec!["1".into(), "2".into(), "3".into()],
        None,
        serde_json::json!({"color": "red"}),
    )
    .unwrap();
    assert_eq!(s.edge_attrs("0").unwrap(), &v["attrs"]["0"]);
    for eid in ["1", "2", "3"] {
        assert_eq!(
            s.edge_attrs(eid).unwrap(),
            &Value::Null,
            "faces get the default"
        );
    }
}

#[test]
fn conform_sc_has_simplex() {
    // Member-SET comparison: a reordered query matches; a closure-added
    // face matches; a non-member set and singletons do not.
    let gt = ground_truth();
    let v = vector(&gt, "sc_has_simplex");
    assert_eq!(v["reordered"], true); // XGI truth, pinned
    assert_eq!(v["missing_set"], false); // pinned
    assert_eq!(v["top"], true); // pinned
    assert_eq!(v["closure_face"], true); // pinned
    assert_eq!(v["no_singletons"], false); // pinned

    let mut s: SimplicialComplex = SimplicialComplex::new();
    s.add_simplex(vec!["1".into(), "2".into()], None, Value::Null)
        .unwrap();
    s.add_simplex(vec!["2".into(), "3".into(), "4".into()], None, Value::Null)
        .unwrap();
    assert!(s.has_simplex(&["2".to_string(), "1".to_string()]));
    assert!(!s.has_simplex(&["1".to_string(), "3".to_string()]));
    assert!(s.has_simplex(&["2".to_string(), "3".into(), "4".into()]));
    assert!(s.has_simplex(&["2".to_string(), "3".to_string()]));
    assert!(!s.has_simplex(&["2".to_string()]));
}

#[test]
fn conform_sc_explicit_falsy_idx_is_honoured() {
    // D17 is closed by XGI 1.1: add_simplex honours an explicit falsy idx
    // (0 and ""), as the Rust core always did (Option<String> is exact:
    // Some("0") is an explicit id, None is auto). XGI 0.10.2 replaced both
    // by an auto id.
    let gt = ground_truth();
    let v = vector(&gt, "sc_falsy_idx_is_auto");
    assert_eq!(v["after_int_idx"], serde_json::json!([5, 6, 7, 8])); // pinned
    assert_eq!(v["zero_idx_edges"], serde_json::json!([5, 6, 7, 8, 0])); // XGI 1.1 truth, pinned
    assert_eq!(v["empty_str_idx_edges"], serde_json::json!([""])); // pinned

    let mut s: SimplicialComplex = SimplicialComplex::new();
    s.add_simplex(
        vec!["1".into(), "2".into(), "3".into()],
        Some("5".into()),
        Value::Null,
    )
    .unwrap();
    s.add_simplex(vec!["4".into(), "5".into()], Some("0".into()), Value::Null)
        .unwrap();
    assert!(s.has_edge("0"));
    assert_eq!(s.edge_ids(), vec!["5", "6", "7", "8", "0"]);

    let mut t: SimplicialComplex = SimplicialComplex::new();
    t.add_simplex(
        vec!["1".into(), "2".into()],
        Some(String::new()),
        Value::Null,
    )
    .unwrap();
    assert_eq!(t.edge_ids(), vec![""]);
}