peat-protocol 0.9.0-rc.1

Peat Coordination Protocol — hierarchical capability composition over CRDTs for heterogeneous mesh networks
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
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135
3136
3137
3138
3139
3140
3141
3142
3143
3144
3145
3146
3147
3148
3149
3150
3151
3152
3153
3154
3155
3156
3157
3158
3159
3160
3161
3162
3163
3164
3165
3166
3167
3168
3169
3170
3171
3172
3173
3174
3175
3176
3177
3178
3179
3180
3181
3182
3183
3184
3185
3186
3187
3188
3189
3190
3191
3192
3193
3194
3195
3196
3197
3198
3199
3200
3201
3202
3203
3204
3205
3206
3207
3208
3209
3210
3211
3212
3213
3214
3215
3216
3217
3218
3219
3220
3221
3222
3223
3224
3225
3226
3227
3228
3229
3230
3231
3232
3233
3234
3235
3236
3237
3238
3239
3240
3241
3242
3243
3244
3245
3246
3247
3248
3249
3250
3251
3252
3253
3254
3255
3256
3257
3258
3259
3260
3261
3262
3263
3264
3265
3266
3267
3268
3269
3270
3271
3272
3273
3274
3275
3276
3277
3278
3279
3280
3281
3282
3283
3284
3285
3286
3287
3288
3289
3290
3291
3292
3293
3294
3295
3296
3297
3298
3299
3300
3301
3302
3303
3304
3305
3306
3307
3308
3309
3310
3311
3312
3313
3314
3315
3316
3317
3318
3319
3320
3321
3322
3323
3324
3325
3326
3327
3328
3329
3330
3331
3332
3333
3334
3335
3336
3337
3338
3339
3340
3341
3342
3343
3344
3345
3346
3347
3348
3349
3350
3351
3352
3353
3354
3355
3356
3357
3358
3359
3360
3361
3362
3363
3364
3365
3366
3367
3368
3369
3370
3371
3372
3373
3374
3375
3376
3377
3378
3379
3380
3381
3382
3383
3384
3385
3386
3387
3388
3389
3390
3391
3392
3393
3394
3395
3396
3397
3398
3399
3400
3401
3402
3403
3404
3405
3406
3407
3408
3409
3410
3411
3412
3413
3414
3415
3416
3417
3418
3419
3420
3421
3422
3423
3424
3425
3426
3427
3428
3429
3430
3431
3432
3433
3434
3435
3436
3437
3438
3439
3440
3441
3442
3443
3444
3445
3446
3447
3448
3449
3450
3451
3452
3453
3454
3455
3456
3457
3458
3459
3460
3461
3462
3463
3464
3465
3466
3467
3468
3469
3470
3471
3472
3473
3474
3475
3476
3477
3478
3479
3480
3481
3482
3483
3484
3485
3486
3487
3488
3489
3490
3491
3492
3493
3494
3495
3496
3497
3498
3499
3500
3501
3502
3503
3504
3505
3506
3507
3508
3509
3510
3511
3512
3513
3514
3515
3516
3517
3518
3519
3520
3521
3522
3523
3524
3525
3526
3527
3528
3529
3530
3531
3532
3533
3534
3535
3536
3537
3538
3539
3540
3541
3542
3543
3544
3545
3546
3547
3548
3549
3550
3551
3552
3553
3554
3555
3556
3557
3558
3559
3560
3561
3562
3563
3564
3565
3566
3567
3568
3569
3570
3571
3572
3573
3574
3575
3576
3577
3578
3579
3580
3581
3582
3583
3584
3585
3586
3587
3588
3589
3590
3591
3592
3593
3594
3595
3596
3597
3598
3599
3600
3601
3602
3603
3604
3605
3606
3607
3608
3609
3610
3611
3612
3613
3614
3615
3616
3617
3618
3619
3620
3621
3622
3623
3624
3625
3626
3627
3628
3629
3630
3631
3632
3633
3634
3635
3636
3637
3638
3639
3640
3641
3642
3643
3644
3645
3646
3647
3648
3649
3650
3651
3652
3653
3654
3655
3656
3657
3658
3659
3660
3661
3662
3663
3664
3665
3666
3667
3668
3669
3670
3671
3672
3673
3674
3675
3676
3677
3678
3679
3680
3681
3682
3683
3684
3685
3686
3687
3688
3689
3690
3691
3692
3693
3694
3695
3696
3697
3698
3699
3700
3701
3702
3703
3704
3705
3706
3707
3708
3709
3710
3711
3712
3713
3714
3715
3716
3717
3718
3719
3720
3721
3722
3723
3724
3725
3726
3727
3728
3729
3730
3731
3732
3733
3734
3735
3736
3737
3738
3739
3740
3741
3742
3743
3744
3745
3746
3747
3748
3749
3750
3751
3752
3753
3754
3755
3756
3757
3758
3759
3760
3761
3762
3763
3764
3765
3766
3767
3768
3769
3770
3771
3772
3773
3774
3775
3776
3777
3778
3779
3780
3781
3782
3783
3784
3785
3786
3787
3788
3789
3790
3791
3792
3793
3794
3795
3796
3797
3798
3799
3800
3801
3802
3803
3804
3805
3806
3807
3808
3809
3810
3811
3812
3813
3814
3815
3816
3817
3818
3819
3820
3821
3822
3823
3824
3825
3826
3827
3828
3829
3830
3831
3832
3833
3834
3835
3836
3837
3838
3839
3840
3841
3842
3843
3844
3845
3846
3847
3848
3849
3850
3851
3852
3853
3854
3855
3856
3857
3858
3859
3860
3861
3862
3863
3864
3865
3866
3867
3868
3869
3870
3871
3872
3873
3874
3875
3876
3877
3878
3879
3880
3881
3882
3883
3884
3885
3886
3887
3888
3889
3890
3891
3892
3893
3894
3895
3896
3897
3898
3899
3900
3901
3902
3903
3904
3905
3906
3907
3908
3909
3910
3911
3912
3913
3914
3915
3916
3917
3918
3919
3920
3921
3922
3923
3924
3925
3926
3927
3928
3929
3930
3931
3932
3933
3934
3935
3936
3937
3938
3939
3940
3941
3942
3943
3944
3945
3946
3947
3948
3949
3950
3951
3952
3953
3954
3955
3956
3957
3958
3959
3960
3961
3962
3963
3964
3965
3966
3967
3968
3969
3970
3971
3972
3973
3974
3975
3976
3977
3978
3979
3980
3981
3982
3983
3984
3985
3986
3987
3988
3989
3990
3991
3992
3993
3994
3995
3996
3997
3998
3999
4000
4001
4002
4003
4004
4005
4006
4007
4008
4009
4010
4011
4012
4013
4014
4015
4016
4017
4018
4019
4020
4021
4022
4023
4024
4025
4026
4027
4028
4029
4030
4031
4032
4033
4034
4035
4036
4037
4038
4039
4040
4041
4042
4043
4044
4045
4046
4047
4048
4049
4050
4051
4052
4053
4054
4055
4056
4057
4058
4059
4060
4061
4062
4063
4064
4065
4066
4067
4068
4069
4070
4071
4072
4073
4074
4075
4076
4077
4078
4079
4080
4081
4082
4083
4084
4085
4086
4087
4088
4089
4090
4091
4092
4093
4094
4095
4096
4097
4098
4099
4100
4101
4102
4103
4104
4105
4106
4107
4108
4109
4110
4111
4112
4113
4114
4115
4116
4117
4118
4119
4120
4121
4122
4123
4124
4125
4126
4127
4128
4129
4130
4131
4132
4133
4134
4135
4136
4137
4138
4139
4140
4141
4142
4143
4144
4145
4146
4147
4148
4149
4150
4151
4152
4153
4154
4155
4156
4157
4158
4159
4160
4161
4162
4163
4164
4165
4166
4167
4168
4169
4170
4171
4172
4173
4174
4175
4176
4177
4178
4179
4180
4181
4182
4183
4184
4185
4186
4187
4188
4189
4190
4191
4192
4193
4194
4195
4196
4197
4198
4199
4200
4201
4202
4203
4204
4205
4206
4207
4208
4209
4210
4211
4212
4213
4214
4215
4216
4217
4218
4219
4220
4221
4222
4223
4224
4225
4226
4227
4228
4229
4230
4231
4232
4233
4234
4235
4236
4237
4238
4239
4240
4241
4242
4243
4244
4245
4246
4247
4248
4249
4250
4251
4252
4253
4254
4255
4256
4257
4258
4259
4260
4261
4262
4263
4264
4265
4266
4267
4268
4269
4270
4271
4272
4273
4274
4275
4276
4277
4278
4279
4280
4281
4282
4283
4284
4285
4286
4287
4288
4289
4290
4291
4292
4293
4294
4295
4296
4297
4298
4299
4300
4301
4302
4303
4304
4305
4306
4307
4308
4309
4310
4311
4312
4313
4314
4315
4316
4317
4318
4319
4320
4321
4322
4323
4324
4325
4326
4327
4328
4329
4330
4331
4332
4333
4334
4335
4336
4337
4338
4339
4340
4341
4342
4343
4344
4345
4346
4347
4348
4349
4350
4351
4352
4353
4354
4355
4356
4357
4358
4359
4360
4361
4362
4363
4364
4365
4366
4367
4368
4369
4370
4371
4372
4373
4374
4375
4376
4377
4378
4379
4380
4381
4382
4383
4384
4385
4386
4387
4388
4389
4390
4391
4392
4393
4394
4395
4396
4397
4398
4399
4400
4401
4402
4403
4404
4405
4406
4407
4408
4409
4410
4411
4412
4413
4414
4415
4416
4417
4418
4419
4420
4421
4422
4423
4424
4425
4426
4427
4428
4429
4430
4431
4432
4433
4434
4435
4436
4437
4438
4439
4440
4441
4442
4443
4444
4445
4446
4447
4448
4449
4450
4451
4452
4453
4454
4455
4456
4457
4458
4459
4460
4461
4462
4463
4464
4465
4466
4467
4468
4469
4470
4471
4472
4473
4474
4475
4476
4477
4478
4479
4480
4481
4482
4483
4484
4485
4486
4487
4488
4489
4490
4491
4492
4493
4494
4495
4496
4497
4498
4499
4500
4501
4502
4503
4504
4505
4506
4507
4508
4509
4510
4511
4512
4513
4514
4515
4516
4517
4518
4519
4520
4521
4522
4523
4524
4525
4526
4527
4528
4529
4530
4531
4532
4533
4534
4535
4536
4537
4538
4539
4540
4541
4542
4543
4544
4545
4546
4547
4548
4549
4550
4551
4552
4553
4554
4555
4556
4557
4558
4559
4560
4561
4562
4563
4564
4565
4566
4567
4568
4569
4570
4571
4572
4573
4574
4575
4576
4577
4578
4579
4580
4581
4582
4583
4584
4585
4586
4587
4588
4589
4590
4591
4592
4593
4594
4595
4596
4597
4598
4599
4600
4601
4602
4603
4604
4605
4606
4607
4608
4609
4610
4611
4612
4613
4614
4615
4616
4617
4618
4619
4620
4621
4622
4623
4624
4625
4626
4627
4628
4629
4630
4631
4632
4633
4634
4635
4636
4637
4638
4639
4640
4641
4642
4643
4644
4645
4646
4647
4648
4649
4650
4651
4652
4653
4654
4655
4656
4657
4658
4659
4660
4661
4662
4663
4664
4665
4666
4667
4668
4669
4670
4671
4672
4673
4674
4675
4676
4677
4678
4679
4680
4681
4682
4683
4684
4685
4686
4687
4688
4689
4690
4691
4692
4693
4694
4695
4696
4697
4698
4699
4700
4701
4702
4703
4704
4705
4706
4707
4708
4709
4710
4711
4712
4713
4714
4715
4716
4717
4718
4719
4720
4721
4722
4723
4724
4725
4726
4727
4728
4729
4730
4731
4732
4733
4734
4735
4736
4737
4738
4739
4740
4741
4742
4743
4744
4745
4746
4747
4748
4749
4750
4751
4752
4753
4754
4755
4756
4757
4758
4759
4760
4761
4762
4763
4764
4765
4766
4767
4768
4769
4770
4771
4772
4773
4774
4775
4776
4777
4778
4779
4780
4781
4782
4783
4784
4785
4786
4787
4788
4789
4790
4791
4792
4793
4794
4795
4796
4797
4798
4799
4800
4801
4802
4803
4804
4805
4806
4807
4808
4809
4810
4811
4812
4813
4814
4815
4816
4817
4818
4819
4820
4821
4822
4823
4824
4825
4826
4827
4828
4829
4830
4831
4832
4833
4834
4835
4836
4837
4838
4839
4840
4841
4842
4843
4844
4845
4846
4847
4848
4849
4850
4851
4852
4853
4854
4855
4856
4857
4858
4859
4860
4861
4862
4863
4864
4865
4866
4867
4868
4869
4870
4871
4872
4873
4874
4875
4876
4877
4878
4879
4880
4881
4882
4883
4884
4885
4886
4887
4888
4889
4890
4891
4892
4893
4894
4895
4896
4897
4898
4899
4900
4901
4902
4903
4904
4905
4906
4907
4908
4909
4910
4911
4912
4913
4914
4915
4916
4917
4918
4919
4920
4921
4922
4923
4924
4925
4926
4927
4928
4929
4930
4931
4932
4933
4934
4935
4936
4937
4938
4939
4940
4941
4942
4943
4944
4945
4946
4947
4948
4949
4950
4951
4952
4953
4954
4955
4956
4957
4958
4959
4960
4961
4962
4963
4964
4965
4966
4967
4968
4969
4970
4971
4972
4973
4974
4975
4976
4977
4978
4979
4980
4981
4982
4983
4984
4985
4986
4987
4988
4989
4990
4991
4992
4993
4994
4995
4996
4997
4998
4999
5000
5001
5002
5003
5004
5005
5006
5007
5008
5009
5010
5011
5012
5013
5014
5015
5016
5017
5018
5019
5020
5021
5022
5023
5024
5025
5026
5027
5028
5029
5030
5031
5032
5033
5034
5035
5036
5037
5038
5039
5040
5041
5042
5043
5044
5045
5046
5047
5048
5049
5050
5051
5052
5053
5054
5055
5056
5057
5058
5059
5060
5061
5062
5063
5064
5065
5066
5067
5068
5069
5070
5071
5072
5073
5074
5075
5076
5077
5078
5079
5080
5081
5082
5083
5084
5085
5086
5087
5088
5089
5090
5091
5092
5093
5094
5095
5096
5097
5098
5099
5100
5101
5102
5103
5104
5105
5106
5107
5108
5109
5110
5111
5112
5113
5114
5115
5116
5117
5118
5119
5120
5121
5122
5123
5124
5125
5126
5127
5128
5129
5130
5131
5132
5133
5134
5135
5136
5137
5138
5139
5140
5141
5142
5143
5144
5145
5146
5147
5148
5149
5150
5151
5152
5153
5154
5155
5156
5157
5158
5159
5160
5161
5162
5163
5164
5165
5166
5167
5168
5169
5170
5171
5172
5173
5174
5175
5176
5177
5178
5179
5180
5181
5182
5183
5184
5185
5186
5187
5188
5189
5190
5191
5192
5193
5194
5195
5196
5197
5198
5199
5200
5201
5202
5203
5204
5205
5206
5207
5208
5209
5210
5211
5212
5213
5214
5215
5216
5217
5218
5219
5220
5221
5222
5223
5224
5225
5226
5227
5228
5229
5230
5231
5232
5233
5234
5235
5236
5237
5238
5239
5240
5241
5242
5243
5244
5245
5246
5247
5248
5249
5250
5251
5252
5253
5254
5255
5256
5257
5258
5259
5260
5261
5262
5263
5264
5265
5266
5267
5268
5269
5270
5271
5272
5273
5274
5275
5276
5277
5278
5279
5280
5281
5282
5283
5284
5285
5286
5287
5288
5289
5290
5291
5292
5293
5294
5295
5296
5297
5298
5299
5300
5301
5302
5303
5304
5305
5306
5307
5308
5309
5310
5311
5312
5313
5314
5315
5316
5317
5318
5319
5320
5321
5322
5323
5324
5325
5326
5327
5328
5329
5330
5331
5332
5333
5334
5335
5336
5337
5338
5339
5340
5341
5342
5343
5344
5345
5346
5347
5348
5349
5350
5351
5352
5353
5354
5355
5356
5357
5358
5359
5360
5361
5362
5363
5364
5365
5366
5367
5368
5369
5370
5371
5372
5373
5374
5375
5376
5377
5378
5379
5380
5381
5382
5383
5384
5385
5386
5387
5388
5389
5390
5391
5392
5393
5394
5395
5396
5397
5398
5399
5400
5401
5402
5403
5404
5405
5406
5407
5408
5409
5410
5411
5412
5413
5414
5415
5416
5417
5418
5419
5420
5421
5422
5423
5424
5425
5426
5427
5428
5429
5430
5431
5432
5433
5434
5435
5436
5437
5438
5439
5440
5441
5442
5443
5444
5445
5446
5447
5448
5449
5450
5451
5452
5453
5454
5455
5456
5457
5458
5459
5460
5461
5462
5463
5464
5465
5466
5467
5468
5469
5470
5471
5472
5473
5474
5475
5476
5477
5478
5479
5480
5481
5482
5483
5484
5485
5486
5487
5488
5489
5490
5491
5492
//! Automerge-based implementation of DataSyncBackend
//!
//! This module provides a CRDT backend using the Automerge library (v0.7.1),
//! enabling eventual consistency without requiring Ditto SDK.
//!
//! # Architecture
//!
//! - **Documents**: Stored as Automerge CRDTs indexed by collection:id
//! - **Sync Protocol**: Uses Automerge's built-in sync state machine
//! - **Query Engine**: In-memory filtering on exported JSON
//!
//! # Example
//!
//! ```text
//! use peat_protocol::sync::automerge::AutomergeBackend;
//! use peat_protocol::sync::traits::*;
//! use peat_protocol::sync::types::*;
//!
//! # async fn example() -> Result<(), Box<dyn std::error::Error>> {
//! let backend = AutomergeBackend::new();
//! backend.initialize(BackendConfig::default()).await?;
//!
//! let doc_store = backend.document_store();
//! // Use DocumentStore API...
//! # Ok(())
//! # }
//! ```

use async_trait::async_trait;
use automerge::{sync, sync::SyncDoc, transaction::Transactable, Automerge};
use std::collections::HashMap;
use std::sync::atomic::{AtomicU64, Ordering};
use std::sync::{Arc, Mutex};
use std::time::Duration;
use tokio::sync::mpsc;

use crate::error::{Error, Result};
use crate::qos::{DeletionPolicy, DeletionPolicyRegistry, Tombstone, TombstoneSyncMessage};
#[cfg(feature = "automerge-backend")]
use crate::storage::automerge_conversion::automerge_to_message;
use crate::sync::traits::*;
use crate::sync::types::*;

/// Automerge-based backend for CRDT synchronization
///
/// This backend implements all DataSyncBackend traits using Automerge as the
/// underlying CRDT library, providing an alternative to Ditto.
#[derive(Clone)]
pub struct AutomergeBackend {
    /// Automerge documents indexed by collection:id key
    documents: Arc<Mutex<HashMap<String, Automerge>>>,

    /// Sync states for each peer:document pair
    sync_states: Arc<Mutex<HashMap<String, sync::State>>>,

    /// Configuration
    config: Arc<Mutex<Option<BackendConfig>>>,

    /// Initialized flag
    initialized: Arc<Mutex<bool>>,

    /// Change notification channels for observers
    observers: Arc<Mutex<Vec<mpsc::UnboundedSender<ChangeEvent>>>>,

    /// Tombstone storage indexed by collection:doc_id (ADR-034)
    tombstones: Arc<Mutex<HashMap<String, Tombstone>>>,

    /// Deletion policy registry (ADR-034)
    deletion_policy_registry: Arc<DeletionPolicyRegistry>,

    /// Monotonic Lamport counter for tombstone ordering (ADR-034, Issue #668)
    lamport_counter: Arc<AtomicU64>,

    /// Pending tombstones awaiting propagation to peers (ADR-034, Issue #668)
    pending_tombstones: Arc<Mutex<Vec<TombstoneSyncMessage>>>,

    /// GC task handle for periodic tombstone/TTL cleanup (ADR-034, Issue #668)
    gc_handle: Arc<Mutex<Option<tokio::task::JoinHandle<()>>>>,
}

impl AutomergeBackend {
    /// Create new AutomergeBackend
    ///
    /// # Example
    ///
    /// ```
    /// use peat_protocol::sync::automerge::AutomergeBackend;
    ///
    /// let backend = AutomergeBackend::new();
    /// ```
    pub fn new() -> Self {
        Self {
            documents: Arc::new(Mutex::new(HashMap::new())),
            sync_states: Arc::new(Mutex::new(HashMap::new())),
            config: Arc::new(Mutex::new(None)),
            initialized: Arc::new(Mutex::new(false)),
            observers: Arc::new(Mutex::new(Vec::new())),
            tombstones: Arc::new(Mutex::new(HashMap::new())),
            deletion_policy_registry: Arc::new(DeletionPolicyRegistry::new()),
            lamport_counter: Arc::new(AtomicU64::new(0)),
            pending_tombstones: Arc::new(Mutex::new(Vec::new())),
            gc_handle: Arc::new(Mutex::new(None)),
        }
    }

    /// Helper: Generate document key from collection and ID
    fn doc_key(collection: &str, doc_id: &DocumentId) -> String {
        format!("{}:{}", collection, doc_id)
    }

    /// Get the node ID for tombstone attribution (ADR-034, Issue #668)
    ///
    /// Uses the app_id from BackendConfig if initialized, falls back to "local".
    fn node_id(&self) -> String {
        self.config
            .lock()
            .ok()
            .and_then(|c| c.as_ref().map(|cfg| cfg.app_id.clone()))
            .unwrap_or_else(|| "local".to_string())
    }

    /// Get the next Lamport timestamp for tombstone ordering (ADR-034, Issue #668)
    fn next_lamport(&self) -> u64 {
        self.lamport_counter.fetch_add(1, Ordering::SeqCst)
    }

    /// Drain pending tombstones for propagation to peers (ADR-034, Issue #668)
    ///
    /// Called by the sync coordinator to retrieve tombstones created since
    /// the last drain. Returns and clears the pending queue.
    pub fn drain_pending_tombstones(&self) -> Vec<TombstoneSyncMessage> {
        self.pending_tombstones
            .lock()
            .map(|mut q| std::mem::take(&mut *q))
            .unwrap_or_default()
    }

    /// Helper: Convert Automerge document to our Document type
    ///
    /// Issue #518: Now supports nested objects and proper Counter extraction.
    fn automerge_to_document(doc: &Automerge, doc_id: DocumentId) -> Result<Document> {
        use automerge::ReadDoc;

        let mut fields = HashMap::new();

        // Try to read from the root/root path
        if let Ok(Some((automerge::Value::Object(automerge::ObjType::Map), obj_id))) =
            doc.get(automerge::ROOT, "root")
        {
            // Iterate over the map entries
            for item in doc.map_range(&obj_id, ..) {
                let key_str = item.key.to_string();
                if let Ok(Some((value, nested_id))) = doc.get(&obj_id, &item.key as &str) {
                    // Convert the Automerge value to serde_json::Value
                    // Pass the nested_id for recursive object traversal
                    if let Some(json_val) = Self::automerge_value_to_json(doc, &value, &nested_id) {
                        fields.insert(key_str, json_val);
                    }
                }
            }
        }

        Ok(Document {
            id: Some(doc_id),
            fields,
            updated_at: std::time::SystemTime::now(),
        })
    }

    /// Helper: Convert Automerge value to serde_json::Value with nested object support.
    ///
    /// Issue #518: This function properly handles:
    /// - Counter values (extracts actual i64 value)
    /// - Nested objects (recursively traverses Maps and Lists)
    /// - All scalar types
    ///
    /// # Arguments
    /// * `doc` - The Automerge document for nested object traversal
    /// * `value` - The Automerge value to convert
    /// * `obj_id` - The object ID (used when value is an Object type)
    fn automerge_value_to_json(
        doc: &Automerge,
        value: &automerge::Value,
        obj_id: &automerge::ObjId,
    ) -> Option<Value> {
        use automerge::ReadDoc;

        match value {
            automerge::Value::Scalar(scalar) => Self::automerge_scalar_to_json(scalar.as_ref()),
            automerge::Value::Object(obj_type) => {
                // Issue #518: Recursively convert nested objects
                match obj_type {
                    automerge::ObjType::Map | automerge::ObjType::Table => {
                        // Convert map to JSON object
                        let mut map = serde_json::Map::new();
                        for item in doc.map_range(obj_id, ..) {
                            let key = item.key.to_string();
                            if let Ok(Some((nested_value, nested_obj_id))) =
                                doc.get(obj_id, &item.key as &str)
                            {
                                if let Some(json_val) = Self::automerge_value_to_json(
                                    doc,
                                    &nested_value,
                                    &nested_obj_id,
                                ) {
                                    map.insert(key, json_val);
                                }
                            }
                        }
                        Some(Value::Object(map))
                    }
                    automerge::ObjType::List => {
                        // Convert list to JSON array
                        let length = doc.length(obj_id);
                        let mut arr = Vec::with_capacity(length);
                        for idx in 0..length {
                            if let Ok(Some((nested_value, nested_obj_id))) = doc.get(obj_id, idx) {
                                if let Some(json_val) = Self::automerge_value_to_json(
                                    doc,
                                    &nested_value,
                                    &nested_obj_id,
                                ) {
                                    arr.push(json_val);
                                }
                            }
                        }
                        Some(Value::Array(arr))
                    }
                    automerge::ObjType::Text => {
                        // Convert text to string
                        let text = doc.text(obj_id).ok()?;
                        Some(Value::String(text))
                    }
                }
            }
        }
    }

    /// Helper: Convert Automerge scalar value to serde_json::Value
    ///
    /// Issue #518: Counter values now properly extract the i64 value.
    fn automerge_scalar_to_json(scalar: &automerge::ScalarValue) -> Option<Value> {
        let json_val = match scalar {
            automerge::ScalarValue::Str(s) => Value::String(s.to_string()),
            automerge::ScalarValue::Int(i) => Value::Number(serde_json::Number::from(*i)),
            automerge::ScalarValue::Uint(u) => Value::Number(serde_json::Number::from(*u)),
            automerge::ScalarValue::F64(f) => serde_json::Number::from_f64(*f)
                .map(Value::Number)
                .unwrap_or(Value::Null),
            automerge::ScalarValue::Boolean(b) => Value::Bool(*b),
            automerge::ScalarValue::Null => Value::Null,
            automerge::ScalarValue::Bytes(bytes) => {
                // Encode bytes as array of numbers
                let byte_array: Vec<serde_json::Value> = bytes
                    .iter()
                    .map(|b| Value::Number(serde_json::Number::from(*b)))
                    .collect();
                Value::Array(byte_array)
            }
            automerge::ScalarValue::Counter(c) => {
                // Issue #518: Extract actual counter value using From<&Counter> for i64
                // The Counter type implements From trait to convert to i64
                let counter_value: i64 = i64::from(c);
                Value::Number(serde_json::Number::from(counter_value))
            }
            automerge::ScalarValue::Timestamp(ts) => Value::Number(serde_json::Number::from(*ts)),
            automerge::ScalarValue::Unknown { .. } => Value::Null,
        };
        Some(json_val)
    }

    /// Helper: Apply Document fields to Automerge doc
    fn apply_document_to_automerge(doc: &mut Automerge, document: &Document) -> Result<()> {
        doc.transact::<_, _, automerge::AutomergeError>(|tx| {
            // Create or get root map
            let root = tx.put_object(automerge::ROOT, "root", automerge::ObjType::Map)?;

            for (key, value) in &document.fields {
                // Convert serde_json::Value to Automerge scalar
                Self::put_json_value(tx, &root, key, value)?;
            }

            Ok(())
        })
        .map_err(|e| Error::Internal(format!("Transaction failed: {:?}", e)))?;

        Ok(())
    }

    /// Helper: Put JSON value into Automerge
    fn put_json_value(
        tx: &mut automerge::transaction::Transaction,
        obj: &automerge::ObjId,
        key: &str,
        value: &serde_json::Value,
    ) -> std::result::Result<(), automerge::AutomergeError> {
        use serde_json::Value;

        match value {
            Value::String(s) => {
                tx.put(obj, key, s.clone())?;
            }
            Value::Number(n) => {
                if let Some(i) = n.as_i64() {
                    tx.put(obj, key, i)?;
                } else if let Some(f) = n.as_f64() {
                    tx.put(obj, key, f)?;
                }
            }
            Value::Bool(b) => {
                tx.put(obj, key, *b)?;
            }
            Value::Null => {
                // Skip null values
            }
            Value::Array(arr) => {
                // Create list
                let list = tx.put_object(obj, key, automerge::ObjType::List)?;
                for (idx, item) in arr.iter().enumerate() {
                    Self::insert_json_value(tx, &list, idx, item)?;
                }
            }
            Value::Object(map) => {
                // Create nested map
                let nested = tx.put_object(obj, key, automerge::ObjType::Map)?;
                for (k, v) in map {
                    Self::put_json_value(tx, &nested, k, v)?;
                }
            }
        }

        Ok(())
    }

    /// Helper: Insert JSON value into Automerge list
    fn insert_json_value(
        tx: &mut automerge::transaction::Transaction,
        list: &automerge::ObjId,
        index: usize,
        value: &serde_json::Value,
    ) -> std::result::Result<(), automerge::AutomergeError> {
        use serde_json::Value;

        match value {
            Value::String(s) => {
                tx.insert(list, index, s.clone())?;
            }
            Value::Number(n) => {
                if let Some(i) = n.as_i64() {
                    tx.insert(list, index, i)?;
                } else if let Some(f) = n.as_f64() {
                    tx.insert(list, index, f)?;
                }
            }
            Value::Bool(b) => {
                tx.insert(list, index, *b)?;
            }
            Value::Null => {
                // Skip null values
            }
            Value::Array(_) | Value::Object(_) => {
                // For complex nested types, serialize as JSON string
                let json_str =
                    serde_json::to_string(value).map_err(|_| automerge::AutomergeError::Fail)?;
                tx.insert(list, index, json_str)?;
            }
        }

        Ok(())
    }

    /// Helper: Check if document matches query
    fn matches_query(&self, document: &Document, query: &Query) -> Result<bool> {
        match query {
            Query::All => Ok(true),

            Query::Eq { field, value } => {
                if let Some(doc_value) = document.fields.get(field) {
                    Ok(doc_value == value)
                } else {
                    Ok(false)
                }
            }

            Query::Lt { field, value } => {
                if let Some(doc_value) = document.fields.get(field) {
                    Ok(self.compare_values(doc_value, value)? < 0)
                } else {
                    Ok(false)
                }
            }

            Query::Gt { field, value } => {
                if let Some(doc_value) = document.fields.get(field) {
                    Ok(self.compare_values(doc_value, value)? > 0)
                } else {
                    Ok(false)
                }
            }

            Query::And(queries) => {
                for q in queries {
                    if !self.matches_query(document, q)? {
                        return Ok(false);
                    }
                }
                Ok(true)
            }

            Query::Or(queries) => {
                for q in queries {
                    if self.matches_query(document, q)? {
                        return Ok(true);
                    }
                }
                Ok(false)
            }

            // === Negation query (Issue #357) ===
            Query::Not(inner) => Ok(!self.matches_query(document, inner)?),

            // === Custom query support (Issue #517) ===
            // Evaluate DQL-like custom queries using pattern-based parser
            Query::Custom(query_str) => Ok(evaluate_custom_query(document, query_str)),

            // === Spatial queries (Issue #356) ===
            Query::WithinRadius {
                center,
                radius_meters,
                lat_field,
                lon_field,
            } => {
                let lat_key = lat_field.as_deref().unwrap_or("lat");
                let lon_key = lon_field.as_deref().unwrap_or("lon");

                if let (Some(lat_val), Some(lon_val)) = (
                    document.fields.get(lat_key).and_then(|v| v.as_f64()),
                    document.fields.get(lon_key).and_then(|v| v.as_f64()),
                ) {
                    let doc_point = GeoPoint::new(lat_val, lon_val);
                    Ok(doc_point.within_radius(center, *radius_meters))
                } else {
                    Ok(false)
                }
            }

            Query::WithinBounds {
                min,
                max,
                lat_field,
                lon_field,
            } => {
                let lat_key = lat_field.as_deref().unwrap_or("lat");
                let lon_key = lon_field.as_deref().unwrap_or("lon");

                if let (Some(lat_val), Some(lon_val)) = (
                    document.fields.get(lat_key).and_then(|v| v.as_f64()),
                    document.fields.get(lon_key).and_then(|v| v.as_f64()),
                ) {
                    let doc_point = GeoPoint::new(lat_val, lon_val);
                    Ok(doc_point.within_bounds(min, max))
                } else {
                    Ok(false)
                }
            }

            // === Deletion-aware queries (ADR-034, Issue #369) ===
            Query::IncludeDeleted(inner) => {
                // IncludeDeleted wraps another query - run the inner query
                // The soft-delete filter bypass is handled at the query() method level
                self.matches_query(document, inner)
            }

            Query::DeletedOnly => {
                // Only match documents with _deleted=true
                let is_deleted = document
                    .fields
                    .get("_deleted")
                    .and_then(|v| v.as_bool())
                    .unwrap_or(false);
                Ok(is_deleted)
            }
        }
    }

    /// Helper: Compare two JSON values
    fn compare_values(&self, a: &serde_json::Value, b: &serde_json::Value) -> Result<i8> {
        use serde_json::Value;

        match (a, b) {
            (Value::Number(a_num), Value::Number(b_num)) => {
                if let (Some(a_f), Some(b_f)) = (a_num.as_f64(), b_num.as_f64()) {
                    if a_f < b_f {
                        Ok(-1)
                    } else if a_f > b_f {
                        Ok(1)
                    } else {
                        Ok(0)
                    }
                } else {
                    Err(Error::Internal("Number comparison failed".into()))
                }
            }
            (Value::String(a_str), Value::String(b_str)) => {
                if a_str < b_str {
                    Ok(-1)
                } else if a_str > b_str {
                    Ok(1)
                } else {
                    Ok(0)
                }
            }
            _ => Err(Error::Internal("Unsupported value comparison".into())),
        }
    }

    /// Generate sync message for a document
    ///
    /// This uses Automerge's sync protocol to generate a message containing
    /// the changes needed to sync with a peer.
    pub fn generate_sync_message(
        &self,
        collection: &str,
        doc_id: &DocumentId,
        peer_id: &str,
    ) -> Result<Vec<u8>> {
        let key = Self::doc_key(collection, doc_id);
        let docs = self
            .documents
            .lock()
            .map_err(|_| Error::Internal("documents lock poisoned".into()))?;

        let automerge_doc = docs.get(&key).ok_or_else(|| Error::NotFound {
            resource_type: "Document".to_string(),
            id: doc_id.clone(),
        })?;

        // Get or create sync state for this peer
        let mut sync_states = self
            .sync_states
            .lock()
            .map_err(|_| Error::Internal("sync_states lock poisoned".into()))?;
        let sync_state = sync_states
            .entry(format!("{}:{}", peer_id, key))
            .or_default();

        // Generate sync message
        let message = automerge_doc.generate_sync_message(sync_state);

        // Encode message (handle Option)
        match message {
            Some(msg) => Ok(msg.encode()),
            None => Ok(Vec::new()), // No changes to sync
        }
    }

    /// Receive and apply sync message
    ///
    /// This applies changes from a peer's sync message to our local document.
    pub fn receive_sync_message(
        &self,
        collection: &str,
        doc_id: &DocumentId,
        peer_id: &str,
        message: &[u8],
    ) -> Result<()> {
        let key = Self::doc_key(collection, doc_id);
        let mut docs = self
            .documents
            .lock()
            .map_err(|_| Error::Internal("documents lock poisoned".into()))?;

        let automerge_doc = docs.get_mut(&key).ok_or_else(|| Error::NotFound {
            resource_type: "Document".to_string(),
            id: doc_id.clone(),
        })?;

        // Decode message
        let sync_message = sync::Message::decode(message)
            .map_err(|e| Error::Internal(format!("Message decode failed: {:?}", e)))?;

        // Get sync state
        let mut sync_states = self
            .sync_states
            .lock()
            .map_err(|_| Error::Internal("sync_states lock poisoned".into()))?;
        let sync_state = sync_states
            .entry(format!("{}:{}", peer_id, key))
            .or_default();

        // Apply sync message
        automerge_doc
            .receive_sync_message(sync_state, sync_message)
            .map_err(|e| Error::Internal(format!("Sync message apply failed: {:?}", e)))?;

        Ok(())
    }
}

impl Default for AutomergeBackend {
    fn default() -> Self {
        Self::new()
    }
}

// ============================================================================
// DocumentStore Trait Implementation
// ============================================================================

#[async_trait]
impl DocumentStore for AutomergeBackend {
    async fn upsert(&self, collection: &str, mut document: Document) -> anyhow::Result<DocumentId> {
        // Generate ID if not present
        let doc_id = document
            .id
            .clone()
            .unwrap_or_else(|| uuid::Uuid::new_v4().to_string());

        let key = Self::doc_key(collection, &doc_id);
        let mut docs = self
            .documents
            .lock()
            .map_err(|_| Error::Internal("documents lock poisoned".into()))?;

        if let Some(existing_doc) = docs.get_mut(&key) {
            // Update existing document
            Self::apply_document_to_automerge(existing_doc, &document)?;
        } else {
            // Create new document
            let mut automerge_doc = Automerge::new();
            Self::apply_document_to_automerge(&mut automerge_doc, &document)?;
            docs.insert(key, automerge_doc);
        }

        document.id = Some(doc_id.clone());

        // Notify observers
        drop(docs); // Release lock before notifying
        let observers = self
            .observers
            .lock()
            .map_err(|_| Error::Internal("observers lock poisoned".into()))?;
        for observer in observers.iter() {
            let _ = observer.send(ChangeEvent::Updated {
                collection: collection.to_string(),
                document: document.clone(),
            });
        }
        drop(observers);

        Ok(doc_id)
    }

    async fn query(&self, collection: &str, query: &Query) -> anyhow::Result<Vec<Document>> {
        let docs = self
            .documents
            .lock()
            .map_err(|_| Error::Internal("documents lock poisoned".into()))?;
        let mut results = Vec::new();

        // Iterate all documents in collection
        for (key, automerge_doc) in docs.iter() {
            if !key.starts_with(&format!("{}:", collection)) {
                continue;
            }

            // Extract document ID from key
            let doc_id = key.split(':').nth(1).unwrap_or("").to_string();

            // Convert to our Document type
            let document = Self::automerge_to_document(automerge_doc, doc_id)?;

            // Apply soft-delete filter (ADR-034, Issue #369)
            // By default, queries exclude documents with _deleted=true
            // IncludeDeleted and DeletedOnly queries override this behavior
            if !query.matches_deletion_state(&document) {
                continue;
            }

            // Apply query filter
            if self.matches_query(&document, query)? {
                results.push(document);
            }
        }

        Ok(results)
    }

    async fn remove(&self, collection: &str, doc_id: &DocumentId) -> anyhow::Result<()> {
        let key = Self::doc_key(collection, doc_id);
        let mut docs = self
            .documents
            .lock()
            .map_err(|_| Error::Internal("documents lock poisoned".into()))?;

        docs.remove(&key).ok_or_else(|| Error::NotFound {
            resource_type: "Document".to_string(),
            id: doc_id.clone(),
        })?;

        // Notify observers
        drop(docs); // Release lock before notifying
        let observers = self
            .observers
            .lock()
            .map_err(|_| Error::Internal("observers lock poisoned".into()))?;
        for observer in observers.iter() {
            let _ = observer.send(ChangeEvent::Removed {
                collection: collection.to_string(),
                doc_id: doc_id.clone(),
            });
        }
        drop(observers);

        Ok(())
    }

    async fn get(&self, collection: &str, doc_id: &DocumentId) -> anyhow::Result<Option<Document>> {
        let key = Self::doc_key(collection, doc_id);
        let docs = self
            .documents
            .lock()
            .map_err(|_| Error::Internal("documents lock poisoned".into()))?;

        if let Some(automerge_doc) = docs.get(&key) {
            let document = Self::automerge_to_document(automerge_doc, doc_id.clone())?;
            Ok(Some(document))
        } else {
            Ok(None)
        }
    }

    async fn count(&self, collection: &str, query: &Query) -> anyhow::Result<usize> {
        let results = self.query(collection, query).await?;
        Ok(results.len())
    }

    fn observe(&self, collection: &str, query: &Query) -> anyhow::Result<ChangeStream> {
        let (tx, rx) = tokio::sync::mpsc::unbounded_channel();

        // Send initial snapshot of matching documents
        let docs = self
            .documents
            .lock()
            .map_err(|_| Error::Internal("documents lock poisoned".into()))?;
        let mut initial_docs = Vec::new();

        for (key, automerge_doc) in docs.iter() {
            if !key.starts_with(&format!("{}:", collection)) {
                continue;
            }

            let doc_id = key.split(':').nth(1).unwrap_or("").to_string();
            if let Ok(document) = Self::automerge_to_document(automerge_doc, doc_id) {
                if self.matches_query(&document, query).unwrap_or(false) {
                    initial_docs.push(document);
                }
            }
        }

        drop(docs); // Release lock

        // Send initial snapshot
        let _ = tx.send(ChangeEvent::Initial {
            documents: initial_docs,
        });

        // Register this observer for future updates
        self.observers
            .lock()
            .map_err(|_| Error::Internal("observers lock poisoned".into()))?
            .push(tx.clone());

        Ok(ChangeStream { receiver: rx })
    }

    // === Deletion methods (ADR-034) ===

    async fn delete(
        &self,
        collection: &str,
        doc_id: &DocumentId,
        reason: Option<&str>,
    ) -> anyhow::Result<crate::qos::DeleteResult> {
        let policy = self.deletion_policy(collection);

        match policy {
            DeletionPolicy::Immutable => {
                // Cannot delete immutable documents
                Ok(crate::qos::DeleteResult::immutable())
            }
            DeletionPolicy::ImplicitTTL { .. } => {
                // Implicit TTL: no-op, documents expire automatically
                Ok(crate::qos::DeleteResult {
                    deleted: false,
                    tombstone_id: None,
                    expires_at: None,
                    policy: policy.clone(),
                })
            }
            DeletionPolicy::Tombstone {
                tombstone_ttl,
                delete_wins: _,
            } => {
                // Create tombstone with real node ID and Lamport (Issue #668)
                let node_id = self.node_id();
                let lamport = self.next_lamport();
                let tombstone = if let Some(reason_str) = reason {
                    Tombstone::with_reason(
                        doc_id.clone(),
                        collection.to_string(),
                        node_id,
                        lamport,
                        reason_str,
                    )
                } else {
                    Tombstone::new(doc_id.clone(), collection.to_string(), node_id, lamport)
                };
                let tombstone_id = format!("{}:{}", collection, doc_id);

                // Store tombstone
                self.tombstones
                    .lock()
                    .map_err(|_| Error::Internal("tombstones lock poisoned".into()))?
                    .insert(tombstone_id.clone(), tombstone.clone());

                // Enqueue for propagation to peers (Issue #668)
                if let Ok(mut pending) = self.pending_tombstones.lock() {
                    pending.push(TombstoneSyncMessage::from_tombstone(tombstone));
                }

                // Remove the actual document
                self.remove(collection, doc_id).await.ok(); // Ignore if not found

                Ok(crate::qos::DeleteResult {
                    deleted: true,
                    tombstone_id: Some(tombstone_id),
                    expires_at: Some(std::time::SystemTime::now() + tombstone_ttl),
                    policy: policy.clone(),
                })
            }
            DeletionPolicy::SoftDelete {
                include_deleted_default: _,
            } => {
                // Soft delete: mark document with _deleted=true
                if let Some(mut doc) = self.get(collection, doc_id).await? {
                    doc.fields.insert("_deleted".to_string(), Value::Bool(true));
                    doc.fields.insert(
                        "_deleted_at".to_string(),
                        Value::String(chrono::Utc::now().format("%Y-%m-%dT%H:%M:%SZ").to_string()),
                    );
                    if let Some(reason) = reason {
                        doc.fields.insert(
                            "_deleted_reason".to_string(),
                            Value::String(reason.to_string()),
                        );
                    }
                    self.upsert(collection, doc).await?;

                    Ok(crate::qos::DeleteResult::soft_deleted(policy.clone()))
                } else {
                    // Document not found - still report as deleted
                    Ok(crate::qos::DeleteResult {
                        deleted: false,
                        tombstone_id: None,
                        expires_at: None,
                        policy: policy.clone(),
                    })
                }
            }
        }
    }

    async fn is_deleted(&self, collection: &str, doc_id: &DocumentId) -> anyhow::Result<bool> {
        let key = format!("{}:{}", collection, doc_id);

        // Check if there's a tombstone
        if self
            .tombstones
            .lock()
            .map_err(|_| Error::Internal("tombstones lock poisoned".into()))?
            .contains_key(&key)
        {
            return Ok(true);
        }

        // Check for soft-delete (_deleted field)
        if let Some(doc) = self.get(collection, doc_id).await? {
            if let Some(deleted) = doc.fields.get("_deleted") {
                return Ok(deleted.as_bool().unwrap_or(false));
            }
        }

        Ok(false)
    }

    fn deletion_policy(&self, collection: &str) -> crate::qos::DeletionPolicy {
        self.deletion_policy_registry.get(collection)
    }

    async fn get_tombstones(&self, collection: &str) -> anyhow::Result<Vec<crate::qos::Tombstone>> {
        let tombstones = self
            .tombstones
            .lock()
            .map_err(|_| Error::Internal("tombstones lock poisoned".into()))?;
        let prefix = format!("{}:", collection);

        Ok(tombstones
            .iter()
            .filter(|(key, _)| key.starts_with(&prefix))
            .map(|(_, tombstone)| tombstone.clone())
            .collect())
    }

    async fn apply_tombstone(&self, tombstone: &crate::qos::Tombstone) -> anyhow::Result<()> {
        let key = format!("{}:{}", tombstone.collection, tombstone.document_id);

        // Store the tombstone
        self.tombstones
            .lock()
            .map_err(|_| Error::Internal("tombstones lock poisoned".into()))?
            .insert(key, tombstone.clone());

        // Remove the document if it exists
        self.remove(&tombstone.collection, &tombstone.document_id)
            .await
            .ok();

        Ok(())
    }
}

// ============================================================================
// GcStore Trait Implementation (ADR-034, Issue #668)
// ============================================================================

impl crate::qos::GcStore for AutomergeBackend {
    fn get_all_tombstones(&self) -> anyhow::Result<Vec<Tombstone>> {
        Ok(self
            .tombstones
            .lock()
            .map_err(|_| Error::Internal("tombstones lock poisoned".into()))?
            .values()
            .cloned()
            .collect())
    }

    fn remove_tombstone(&self, collection: &str, document_id: &str) -> anyhow::Result<bool> {
        let key = format!("{}:{}", collection, document_id);
        Ok(self
            .tombstones
            .lock()
            .map_err(|_| Error::Internal("tombstones lock poisoned".into()))?
            .remove(&key)
            .is_some())
    }

    fn has_tombstone(&self, collection: &str, document_id: &str) -> anyhow::Result<bool> {
        let key = format!("{}:{}", collection, document_id);
        Ok(self
            .tombstones
            .lock()
            .map_err(|_| Error::Internal("tombstones lock poisoned".into()))?
            .contains_key(&key))
    }

    fn get_expired_documents(
        &self,
        _collection: &str,
        _cutoff: std::time::SystemTime,
    ) -> anyhow::Result<Vec<String>> {
        // In-memory backend doesn't track document timestamps for TTL expiry
        Ok(Vec::new())
    }

    fn hard_delete(&self, collection: &str, document_id: &str) -> anyhow::Result<()> {
        let key = format!("{}:{}", collection, document_id);
        self.documents
            .lock()
            .map_err(|_| Error::Internal("documents lock poisoned".into()))?
            .remove(&key);
        Ok(())
    }

    fn list_collections(&self) -> anyhow::Result<Vec<String>> {
        let docs = self
            .documents
            .lock()
            .map_err(|_| Error::Internal("documents lock poisoned".into()))?;
        let mut collections: Vec<String> = docs
            .keys()
            .filter_map(|k| k.split(':').next().map(|s| s.to_string()))
            .collect::<std::collections::HashSet<_>>()
            .into_iter()
            .collect();
        collections.sort();
        Ok(collections)
    }
}

// ============================================================================
// PeerDiscovery Trait Implementation
// ============================================================================

#[async_trait]
impl PeerDiscovery for AutomergeBackend {
    async fn start(&self) -> anyhow::Result<()> {
        // Manual peer discovery only for initial implementation
        // Full implementation would support mDNS, etc.
        Ok(())
    }

    async fn stop(&self) -> anyhow::Result<()> {
        Ok(())
    }

    async fn discovered_peers(&self) -> anyhow::Result<Vec<PeerInfo>> {
        // Return empty - manual configuration required
        Ok(Vec::new())
    }

    async fn add_peer(&self, _address: &str, _transport: TransportType) -> anyhow::Result<()> {
        // Manual peer addition not implemented in initial version
        Ok(())
    }

    async fn wait_for_peer(&self, _peer_id: &PeerId, _timeout: Duration) -> anyhow::Result<()> {
        // Peer waiting not implemented in initial version
        Err(Error::Internal("wait_for_peer not implemented".into()).into())
    }

    fn on_peer_event(&self, _callback: Box<dyn Fn(PeerEvent) + Send + Sync>) {
        // Callback registration not implemented in initial version
        // Would store in a Vec for future notifications
    }

    async fn get_peer_info(&self, _peer_id: &PeerId) -> anyhow::Result<Option<PeerInfo>> {
        // Peer info lookup not implemented in initial version
        Ok(None)
    }
}

// ============================================================================
// SyncEngine Trait Implementation
// ============================================================================

#[async_trait]
impl SyncEngine for AutomergeBackend {
    async fn start_sync(&self) -> anyhow::Result<()> {
        // For Automerge, sync is pull-based via generate/receive_sync_message
        // This method indicates we're ready to sync
        Ok(())
    }

    async fn stop_sync(&self) -> anyhow::Result<()> {
        // Clean up sync states
        self.sync_states
            .lock()
            .map_err(|_| Error::Internal("sync_states lock poisoned".into()))?
            .clear();
        Ok(())
    }

    async fn subscribe(
        &self,
        collection: &str,
        _query: &Query,
    ) -> anyhow::Result<SyncSubscription> {
        // Create subscription handle
        // For Automerge, subscriptions are logical - we track interest
        Ok(SyncSubscription::new(
            collection.to_string(),
            Box::new(AutomergeSubscriptionHandle {
                collection: collection.to_string(),
            }),
        ))
    }

    async fn is_syncing(&self) -> anyhow::Result<bool> {
        // Always ready to sync with Automerge
        Ok(self.is_ready().await)
    }
}

/// Subscription handle for Automerge
struct AutomergeSubscriptionHandle {
    #[allow(dead_code)]
    collection: String,
}

// ============================================================================
// DataSyncBackend Trait Implementation
// ============================================================================

#[async_trait]
impl DataSyncBackend for AutomergeBackend {
    async fn initialize(&self, config: BackendConfig) -> anyhow::Result<()> {
        let mut initialized = self
            .initialized
            .lock()
            .map_err(|_| Error::Internal("initialized lock poisoned".into()))?;
        if *initialized {
            return Err(Error::Internal("Already initialized".into()).into());
        }

        *self
            .config
            .lock()
            .map_err(|_| Error::Internal("config lock poisoned".into()))? = Some(config);
        *initialized = true;

        // Start periodic garbage collection for tombstones and TTL (Issue #668)
        let gc = Arc::new(crate::qos::GarbageCollector::with_policy_registry(
            Arc::new(self.clone()),
            Arc::clone(&self.deletion_policy_registry),
            crate::qos::GcConfig::default(),
        ));
        let handle = crate::qos::start_periodic_gc(gc);
        *self
            .gc_handle
            .lock()
            .map_err(|_| Error::Internal("gc_handle lock poisoned".into()))? = Some(handle);

        Ok(())
    }

    async fn shutdown(&self) -> anyhow::Result<()> {
        // Stop GC task (Issue #668)
        if let Ok(mut handle) = self.gc_handle.lock() {
            if let Some(h) = handle.take() {
                h.abort();
            }
        }

        self.stop_sync().await?;
        self.documents
            .lock()
            .map_err(|_| Error::Internal("documents lock poisoned".into()))?
            .clear();
        self.sync_states
            .lock()
            .map_err(|_| Error::Internal("sync_states lock poisoned".into()))?
            .clear();
        *self
            .initialized
            .lock()
            .map_err(|_| Error::Internal("initialized lock poisoned".into()))? = false;

        Ok(())
    }

    fn document_store(&self) -> Arc<dyn DocumentStore> {
        Arc::new(self.clone())
    }

    fn peer_discovery(&self) -> Arc<dyn PeerDiscovery> {
        Arc::new(self.clone())
    }

    fn sync_engine(&self) -> Arc<dyn SyncEngine> {
        Arc::new(self.clone())
    }

    fn as_any(&self) -> &dyn std::any::Any {
        self
    }

    async fn is_ready(&self) -> bool {
        self.initialized.lock().map(|guard| *guard).unwrap_or(false)
    }

    fn backend_info(&self) -> BackendInfo {
        BackendInfo {
            name: "Automerge".to_string(),
            version: "0.7.1".to_string(),
        }
    }
}

// ============================================================================
// AutomergeIroh Backend Adapter (Phase 7: Lab Integration)
// ============================================================================

/// Type alias for peer event callback list
type PeerCallbacks = Arc<Mutex<Vec<Box<dyn Fn(PeerEvent) + Send + Sync>>>>;

/// Topology-driven connection events
///
/// These events allow external topology managers (e.g., peat-mesh TopologyManager)
/// to control which peers the backend connects to, avoiding N² mesh formation.
/// When a topology event receiver is configured, the backend delegates connection
/// decisions to the topology manager instead of connecting to all discovered peers.
#[derive(Debug, Clone)]
pub enum TopologyConnectionEvent {
    /// Connect to a peer selected by topology manager
    ConnectPeer {
        /// Peer identifier (node_id)
        peer_id: String,
        /// Network addresses for the peer
        addresses: Vec<String>,
        /// Optional relay URL
        relay_url: Option<String>,
    },
    /// Disconnect from a peer (topology decision)
    DisconnectPeer {
        /// Peer identifier to disconnect
        peer_id: String,
    },
}

/// Default maximum connections when topology manager is not configured
pub const DEFAULT_MAX_CONNECTIONS: usize = 7;

/// DataSyncBackend adapter for storage::AutomergeBackend
///
/// This adapter wraps the storage::AutomergeBackend (RocksDB + Iroh + Automerge)
/// to provide DataSyncBackend trait compatibility for cap_sim_node.rs
#[derive(Clone)]
pub struct AutomergeIrohBackend {
    /// The underlying Automerge+Iroh backend
    backend: Arc<crate::storage::AutomergeBackend>,

    /// Reference to the transport for peer discovery
    transport: Arc<crate::network::IrohTransport>,

    /// Peer event callbacks
    peer_callbacks: PeerCallbacks,

    /// Initialization state
    initialized: Arc<Mutex<bool>>,

    /// Formation key for peer authentication (ADR-030)
    /// Peers must share the same app_id and secret_key to connect
    formation_key: Arc<std::sync::RwLock<Option<crate::security::FormationKey>>>,

    /// Peer discovery manager (ADR-011 Phase 3)
    #[cfg(feature = "automerge-backend")]
    discovery_manager: Arc<tokio::sync::RwLock<crate::discovery::peer::DiscoveryManager>>,

    /// Optional blob store for file/model transfer (Issue #379, ADR-025)
    ///
    /// When enabled, provides content-addressed blob storage with P2P transfer
    /// capability via iroh-blobs. Peers connected for document sync are automatically
    /// registered for blob transfer as well.
    #[cfg(feature = "automerge-backend")]
    blob_store: Option<Arc<crate::storage::NetworkedIrohBlobStore>>,

    /// Optional topology event receiver for topology-driven connections
    ///
    /// When provided, the backend delegates connection decisions to the topology
    /// manager instead of connecting to all discovered peers. This prevents N²
    /// mesh formation and enables multi-hop routing.
    #[cfg(feature = "automerge-backend")]
    topology_event_rx:
        Arc<tokio::sync::Mutex<Option<mpsc::UnboundedReceiver<TopologyConnectionEvent>>>>,

    /// Maximum peer connections when topology manager is not configured
    ///
    /// Defaults to DEFAULT_MAX_CONNECTIONS (7). When topology events are
    /// provided, this limit is ignored (topology manager controls connections).
    #[cfg(feature = "automerge-backend")]
    max_connections: usize,

    /// Deletion policy registry for tombstone/soft-delete dispatch (Issue #668)
    deletion_policy_registry: Arc<DeletionPolicyRegistry>,

    /// Monotonic Lamport counter for tombstone ordering (Issue #668)
    lamport_counter: Arc<AtomicU64>,
}

impl AutomergeIrohBackend {
    /// Create a new adapter
    pub fn new(
        backend: Arc<crate::storage::AutomergeBackend>,
        transport: Arc<crate::network::IrohTransport>,
    ) -> Self {
        Self {
            backend,
            transport,
            peer_callbacks: Arc::new(Mutex::new(Vec::new())),
            initialized: Arc::new(Mutex::new(false)),
            formation_key: Arc::new(std::sync::RwLock::new(None)),
            #[cfg(feature = "automerge-backend")]
            discovery_manager: Arc::new(tokio::sync::RwLock::new(
                crate::discovery::peer::DiscoveryManager::default(),
            )),
            #[cfg(feature = "automerge-backend")]
            blob_store: None,
            #[cfg(feature = "automerge-backend")]
            topology_event_rx: Arc::new(tokio::sync::Mutex::new(None)),
            #[cfg(feature = "automerge-backend")]
            max_connections: DEFAULT_MAX_CONNECTIONS,
            deletion_policy_registry: Arc::new(DeletionPolicyRegistry::new()),
            lamport_counter: Arc::new(AtomicU64::new(0)),
        }
    }

    /// Configure topology-driven connection management
    ///
    /// When topology events are provided, the backend delegates all connection
    /// decisions to the external topology manager (e.g., peat-mesh TopologyManager).
    /// This prevents N² mesh formation and enables multi-hop routing.
    ///
    /// # Example
    ///
    /// ```ignore
    /// let (tx, rx) = mpsc::unbounded_channel();
    /// let backend = AutomergeIrohBackend::new(storage, transport)
    ///     .with_topology_events(rx);
    ///
    /// // TopologyManager sends events via tx
    /// tx.send(TopologyConnectionEvent::ConnectPeer { ... });
    /// ```
    #[cfg(feature = "automerge-backend")]
    pub fn with_topology_events(
        mut self,
        rx: mpsc::UnboundedReceiver<TopologyConnectionEvent>,
    ) -> Self {
        self.topology_event_rx = Arc::new(tokio::sync::Mutex::new(Some(rx)));
        self
    }

    /// Set maximum peer connections for fallback mode
    ///
    /// When topology events are not configured, the backend limits connections
    /// to this many peers discovered via mDNS/static config. Defaults to 7.
    #[cfg(feature = "automerge-backend")]
    pub fn with_max_connections(mut self, max: usize) -> Self {
        self.max_connections = max;
        self
    }

    /// Check if topology-driven connection management is enabled
    #[cfg(feature = "automerge-backend")]
    pub fn has_topology_events(&self) -> bool {
        // Check if the receiver exists (non-blocking)
        self.topology_event_rx
            .try_lock()
            .is_ok_and(|guard| guard.is_some())
    }

    /// Get the formation key (if initialized with credentials)
    pub fn formation_key(&self) -> Option<crate::security::FormationKey> {
        self.formation_key
            .read()
            .ok()
            .and_then(|guard| guard.clone())
    }

    /// Get the formation ID (app_id used as formation identifier)
    pub fn formation_id(&self) -> Option<String> {
        self.formation_key
            .read()
            .ok()
            .and_then(|guard| guard.as_ref().map(|k| k.formation_id().to_string()))
    }

    /// Create from store and transport (convenience method)
    pub fn from_parts(
        store: Arc<crate::storage::AutomergeStore>,
        transport: Arc<crate::network::IrohTransport>,
    ) -> Self {
        let backend = Arc::new(crate::storage::AutomergeBackend::with_transport(
            store,
            Arc::clone(&transport),
        ));
        Self::new(backend, transport)
    }

    /// Get the transport (for testing/advanced usage)
    pub fn transport(&self) -> Arc<crate::network::IrohTransport> {
        Arc::clone(&self.transport)
    }

    /// Get the storage backend (Issue #378: shared with sync coordinator)
    ///
    /// Returns the underlying `AutomergeBackend` used by this sync backend.
    /// This ensures callers use the same backend instance that the sync
    /// coordinator uses, preventing state from being split across instances.
    pub fn storage_backend(&self) -> Arc<crate::storage::AutomergeBackend> {
        Arc::clone(&self.backend)
    }

    /// Get the transport Arc pointer address (for debugging Issue #271)
    ///
    /// This returns the raw pointer address of the transport Arc, which can be used
    /// to verify that cloned backends share the same transport instance.
    /// If two backends show different addresses, they have different transports.
    pub fn transport_arc_ptr(&self) -> *const crate::network::IrohTransport {
        Arc::as_ptr(&self.transport)
    }

    /// Debug method to verify transport sharing (Issue #271)
    ///
    /// Logs the transport Arc pointer address. Call this on original and cloned
    /// backends to verify they share the same transport instance.
    pub fn debug_log_transport_ptr(&self, context: &str) {
        tracing::debug!(
            transport_ptr = ?Arc::as_ptr(&self.transport),
            endpoint_id = %self.transport.endpoint_id(),
            peer_count = self.transport.peer_count(),
            context = context,
            "AutomergeIrohBackend transport instance"
        );
    }

    /// Get this node's endpoint ID
    pub fn endpoint_id(&self) -> iroh::EndpointId {
        self.transport.endpoint_id()
    }

    // =========================================================================
    // Blob Store Methods (Issue #379, ADR-025)
    // =========================================================================

    /// Enable blob storage with P2P transfer capability
    ///
    /// Creates a `NetworkedIrohBlobStore` for content-addressed file transfer.
    /// The blob store uses a separate iroh endpoint for the iroh-blobs protocol,
    /// but peers are automatically synchronized when document sync connections
    /// are established.
    ///
    /// # Arguments
    ///
    /// * `blob_dir` - Directory for blob storage and metadata sidecars
    ///
    /// # Example
    ///
    /// ```ignore
    /// use peat_protocol::sync::automerge::AutomergeIrohBackend;
    /// use std::path::PathBuf;
    ///
    /// let backend = AutomergeIrohBackend::from_parts(store, transport);
    /// backend.enable_blob_store(PathBuf::from("/tmp/peat-blobs")).await?;
    ///
    /// // Now you can use the blob store
    /// let blob_store = backend.blob_store().unwrap();
    /// let token = blob_store.create_blob_from_bytes(data, metadata).await?;
    /// ```
    #[cfg(feature = "automerge-backend")]
    pub async fn enable_blob_store(
        &mut self,
        blob_dir: std::path::PathBuf,
    ) -> std::result::Result<(), anyhow::Error> {
        use crate::storage::NetworkedIrohBlobStore;

        let blob_store = NetworkedIrohBlobStore::new(blob_dir).await?;

        // Register currently connected peers with the blob store
        let connected_peers = self.transport.connected_peers();
        for peer_id in connected_peers {
            blob_store.add_peer(peer_id).await;
        }

        self.blob_store = Some(blob_store);

        tracing::info!(
            endpoint_id = %self.transport.endpoint_id(),
            "Blob store enabled for AutomergeIrohBackend"
        );

        Ok(())
    }

    /// Get reference to the blob store (if enabled)
    ///
    /// Returns `None` if `enable_blob_store()` has not been called.
    #[cfg(feature = "automerge-backend")]
    pub fn blob_store(&self) -> Option<Arc<crate::storage::NetworkedIrohBlobStore>> {
        self.blob_store.clone()
    }

    /// Check if blob storage is enabled
    #[cfg(feature = "automerge-backend")]
    pub fn has_blob_store(&self) -> bool {
        self.blob_store.is_some()
    }

    /// Register a peer with the blob store for file transfer
    ///
    /// This is called automatically when document sync connections are established,
    /// but can also be called manually if needed.
    #[cfg(feature = "automerge-backend")]
    pub async fn register_blob_peer(&self, peer_id: iroh::EndpointId) {
        if let Some(ref blob_store) = self.blob_store {
            blob_store.add_peer(peer_id).await;
            tracing::debug!(
                peer_id = %peer_id.fmt_short(),
                "Registered peer for blob transfer"
            );
        }
    }

    /// Unregister a peer from the blob store
    #[cfg(feature = "automerge-backend")]
    pub async fn unregister_blob_peer(&self, peer_id: &iroh::EndpointId) {
        if let Some(ref blob_store) = self.blob_store {
            blob_store.remove_peer(peer_id).await;
            tracing::debug!(
                peer_id = %peer_id.fmt_short(),
                "Unregistered peer from blob transfer"
            );
        }
    }

    /// Start automatic peer synchronization for blob transfers
    ///
    /// Spawns a background task that listens to transport peer events and
    /// automatically registers/unregisters peers with the blob store when
    /// document sync connections are established or closed.
    ///
    /// This should be called after `enable_blob_store()` and before starting
    /// peer connections.
    ///
    /// # Example
    ///
    /// ```ignore
    /// backend.enable_blob_store(blob_dir).await?;
    /// backend.start_blob_peer_sync();
    /// backend.initialize(config).await?; // Now peer connections auto-register
    /// ```
    #[cfg(feature = "automerge-backend")]
    pub fn start_blob_peer_sync(&self) {
        use crate::network::iroh_transport::TransportPeerEvent;

        let blob_store = match &self.blob_store {
            Some(store) => Arc::clone(store),
            None => {
                tracing::warn!("start_blob_peer_sync called but blob store not enabled");
                return;
            }
        };

        let mut events = self.transport.subscribe_peer_events();

        tokio::spawn(async move {
            tracing::debug!("Blob peer sync task started");

            while let Some(event) = events.recv().await {
                match event {
                    TransportPeerEvent::Connected { endpoint_id, .. } => {
                        blob_store.add_peer(endpoint_id).await;
                        tracing::debug!(
                            peer_id = %endpoint_id.fmt_short(),
                            "Auto-registered peer for blob transfer on connect"
                        );
                    }
                    TransportPeerEvent::Disconnected { endpoint_id, .. } => {
                        blob_store.remove_peer(&endpoint_id).await;
                        tracing::debug!(
                            peer_id = %endpoint_id.fmt_short(),
                            "Auto-unregistered peer from blob transfer on disconnect"
                        );
                    }
                }
            }

            tracing::debug!("Blob peer sync task stopped");
        });
    }

    /// Manually trigger sync for a specific document with all connected peers
    ///
    /// This is useful for testing or for explicit sync triggering when the
    /// automatic sync triggered by upsert may have been blocked by cooldown.
    ///
    /// # Arguments
    ///
    /// * `doc_key` - The full document key (e.g., "beacons:edge-sensor-001")
    pub async fn sync_document(&self, doc_key: &str) -> Result<()> {
        self.backend
            .sync_document(doc_key)
            .await
            .map_err(|e| Error::Network {
                message: format!("Failed to sync document {}: {}", doc_key, e),
                peer_id: None,
                source: None,
            })
    }

    /// Add a discovery strategy to the peer discovery manager
    ///
    /// This allows configuring static peers, mDNS discovery, etc.
    #[cfg(feature = "automerge-backend")]
    pub async fn add_discovery_strategy(
        &self,
        strategy: Box<dyn crate::discovery::peer::DiscoveryStrategy>,
    ) -> Result<()> {
        let mut manager = self.discovery_manager.write().await;
        manager.add_strategy(strategy);
        Ok(())
    }

    /// Immediately connect to all discovered peers
    ///
    /// This bypasses the background connection task's periodic interval, allowing
    /// tests to establish connections without waiting 1-7 seconds for the next cycle.
    ///
    /// Returns the number of new connections established.
    ///
    /// # Example
    ///
    /// ```ignore
    /// // Add discovery strategy with peer info
    /// backend_a.add_discovery_strategy(Box::new(StaticDiscovery::from_peers(vec![peer_b]))).await?;
    /// backend_b.add_discovery_strategy(Box::new(StaticDiscovery::from_peers(vec![peer_a]))).await?;
    ///
    /// // Connect immediately instead of waiting for background task
    /// backend_a.connect_to_discovered_peers_now().await?;
    /// backend_b.connect_to_discovered_peers_now().await?;
    /// ```
    #[cfg(feature = "automerge-backend")]
    pub async fn connect_to_discovered_peers_now(&self) -> Result<usize> {
        use crate::network::formation_handshake::perform_initiator_handshake;
        use crate::network::PeerInfo as NetworkPeerInfo;

        let formation_key = self
            .formation_key
            .read()
            .map_err(|_| Error::Internal("formation_key lock poisoned".into()))?
            .clone()
            .ok_or_else(|| Error::config_error("Backend not initialized", None))?;

        // Get discovered peers
        let manager = self.discovery_manager.read().await;
        let discovered_peers = manager.get_peers().await;
        drop(manager);

        let mut new_connections = 0;

        for peer in discovered_peers {
            let network_peer_info = NetworkPeerInfo {
                name: peer.name.clone(),
                node_id: peer.node_id.clone(),
                addresses: peer.addresses.clone(),
                relay_url: peer.relay_url.clone(),
            };

            if let Ok(endpoint_id) = peer.endpoint_id() {
                match self.transport.connect_peer(&network_peer_info).await {
                    Ok(Some(conn)) => {
                        // Issue #346: Give the accept loop a moment to process any
                        // incoming connection from this peer. In symmetric discovery
                        // (both peers have each other in config), both will connect
                        // simultaneously and the accept loop needs time to process
                        // the incoming connection and do conflict resolution.
                        tokio::task::yield_now().await;
                        tokio::time::sleep(tokio::time::Duration::from_millis(10)).await;

                        // Check if connection was closed by conflict resolution
                        if conn.close_reason().is_some() {
                            tracing::debug!(
                                "Immediate connect: peer {} superseded by accept path",
                                peer.name
                            );
                            continue;
                        }

                        // New connection - perform formation handshake
                        match perform_initiator_handshake(&conn, &formation_key).await {
                            Ok(()) => {
                                tracing::debug!(
                                    "Immediate connect: authenticated with peer {}",
                                    peer.name
                                );
                                // Issue #346: Emit Connected AFTER successful handshake
                                self.transport.emit_peer_connected(endpoint_id);
                                new_connections += 1;
                            }
                            Err(e) => {
                                tracing::warn!(
                                    "Immediate connect: peer {} failed auth: {}",
                                    peer.name,
                                    e
                                );
                                conn.close(1u32.into(), b"authentication failed");
                                // Issue #346: Don't call disconnect() here - the connection
                                // in the map might be a different one after conflict resolution.
                                // conn.close() is sufficient; close monitor handles cleanup.
                            }
                        }
                    }
                    Ok(None) => {
                        // Accept path is handling connection - no action needed
                        tracing::debug!(
                            "Immediate connect: peer {} handled by accept path",
                            peer.name
                        );
                    }
                    Err(e) => {
                        tracing::debug!(
                            "Immediate connect: failed to connect to {}: {}",
                            peer.name,
                            e
                        );
                    }
                }
            }
        }

        Ok(new_connections)
    }

    /// Get access to the peer discovery information
    ///
    /// Returns a handle for querying discovered peers.
    #[cfg(feature = "automerge-backend")]
    pub fn get_peer_discovery(&self) -> PeerDiscoveryHandle {
        PeerDiscoveryHandle {
            manager: Arc::clone(&self.discovery_manager),
        }
    }
}

/// Handle for accessing peer discovery information
#[cfg(feature = "automerge-backend")]
pub struct PeerDiscoveryHandle {
    manager: Arc<tokio::sync::RwLock<crate::discovery::peer::DiscoveryManager>>,
}

#[cfg(feature = "automerge-backend")]
impl PeerDiscoveryHandle {
    /// Get all discovered peers
    ///
    /// Queries all discovery strategies and returns their currently cached peers.
    /// Strategies update their caches asynchronously, so this is a fast read operation.
    pub async fn discovered_peers(&self) -> Result<Vec<crate::discovery::peer::PeerInfo>> {
        let manager = self.manager.read().await;
        manager
            .discovered_peers()
            .await
            .map_err(|e| Error::Discovery {
                message: e.to_string(),
                source: None,
            })
    }

    /// Get the number of discovered peers
    ///
    /// Queries all discovery strategies and counts their currently cached peers.
    pub async fn peer_count(&self) -> usize {
        let manager = self.manager.read().await;
        manager.peer_count().await
    }
}

// DocumentStore implementation for AutomergeIrohBackend
struct IrohDocumentStore {
    backend: Arc<crate::storage::AutomergeBackend>,
    /// Deletion policy registry for tombstone/soft-delete dispatch (Issue #668)
    deletion_policy_registry: Arc<DeletionPolicyRegistry>,
    /// Monotonic Lamport counter for tombstone ordering (Issue #668)
    lamport_counter: Arc<AtomicU64>,
    /// Node ID for tombstone attribution (Issue #668)
    node_id: String,
}

#[async_trait]
impl DocumentStore for IrohDocumentStore {
    async fn upsert(&self, collection: &str, document: Document) -> anyhow::Result<DocumentId> {
        use crate::storage::traits::StorageBackend;

        // Generate ID if not provided
        let doc_id = document.id.clone().unwrap_or_else(|| {
            use std::time::SystemTime;
            let timestamp = SystemTime::now()
                .duration_since(SystemTime::UNIX_EPOCH)
                .expect("system clock before UNIX epoch")
                .as_nanos();
            format!("doc-{}", timestamp)
        });

        // Serialize document to JSON bytes
        let json_bytes = serde_json::to_vec(&document)?;

        // Get collection and upsert
        let coll = self.backend.collection(collection);
        coll.upsert(&doc_id, json_bytes)
            .map_err(|e| Error::Storage {
                message: e.to_string(),
                operation: Some("upsert".to_string()),
                key: Some(doc_id.clone()),
                source: None,
            })?;

        // Trigger sync to push the document to connected peers
        // The doc_key format is "collection:doc_id"
        let doc_key = format!("{}:{}", collection, doc_id);
        match self.backend.sync_document(&doc_key).await {
            Ok(()) => {
                tracing::debug!("Sync triggered for document {} after upsert", doc_key);
            }
            Err(e) => {
                // Log but don't fail - sync is best-effort
                tracing::debug!("Failed to sync document {} after upsert: {}", doc_key, e);
            }
        }

        Ok(doc_id)
    }

    async fn query(&self, collection: &str, query: &Query) -> anyhow::Result<Vec<Document>> {
        use crate::storage::traits::StorageBackend;

        let coll = self.backend.collection(collection);
        let all_items = coll.scan().map_err(|e| Error::Storage {
            message: e.to_string(),
            operation: Some("scan".to_string()),
            key: None,
            source: None,
        })?;

        // Deserialize and filter
        let mut results = Vec::new();
        for (doc_id, bytes) in all_items {
            if let Ok(mut doc) = serde_json::from_slice::<Document>(&bytes) {
                // Set the ID from the key if not already set
                if doc.id.is_none() {
                    doc.id = Some(doc_id);
                }

                // Apply soft-delete filter (ADR-034, Issue #369)
                // By default, queries exclude documents with _deleted=true
                // IncludeDeleted and DeletedOnly queries override this behavior
                if !query.matches_deletion_state(&doc) {
                    continue;
                }

                if matches_query(&doc, query) {
                    results.push(doc);
                }
            }
        }

        Ok(results)
    }

    async fn remove(&self, collection: &str, doc_id: &DocumentId) -> anyhow::Result<()> {
        use crate::storage::traits::StorageBackend;

        let coll = self.backend.collection(collection);
        coll.delete(doc_id).map_err(|e| Error::Storage {
            message: e.to_string(),
            operation: Some("delete".to_string()),
            key: Some(doc_id.clone()),
            source: None,
        })?;
        Ok(())
    }

    async fn delete(
        &self,
        collection: &str,
        doc_id: &DocumentId,
        reason: Option<&str>,
    ) -> anyhow::Result<crate::qos::DeleteResult> {
        let policy = self.deletion_policy(collection);
        let store = self.backend.automerge_store();

        match policy {
            DeletionPolicy::Immutable => Ok(crate::qos::DeleteResult::immutable()),
            DeletionPolicy::ImplicitTTL { .. } => Ok(crate::qos::DeleteResult {
                deleted: false,
                tombstone_id: None,
                expires_at: None,
                policy: policy.clone(),
            }),
            DeletionPolicy::Tombstone {
                tombstone_ttl,
                delete_wins: _,
            } => {
                let lamport = self.lamport_counter.fetch_add(1, Ordering::SeqCst);
                let tombstone = if let Some(reason_str) = reason {
                    Tombstone::with_reason(
                        doc_id.clone(),
                        collection.to_string(),
                        self.node_id.clone(),
                        lamport,
                        reason_str,
                    )
                } else {
                    Tombstone::new(
                        doc_id.clone(),
                        collection.to_string(),
                        self.node_id.clone(),
                        lamport,
                    )
                };
                let tombstone_id = format!("{}:{}", collection, doc_id);

                // Store tombstone in AutomergeStore (persisted to RocksDB)
                store
                    .put_tombstone(&tombstone)
                    .map_err(|e| Error::Storage {
                        message: e.to_string(),
                        operation: Some("put_tombstone".to_string()),
                        key: Some(tombstone_id.clone()),
                        source: None,
                    })?;

                // Remove the document
                let doc_key = format!("{}:{}", collection, doc_id);
                store.delete(&doc_key).ok();

                // Propagate tombstone to all connected peers (Issue #668)
                // The tombstone is already stored in AutomergeStore, so
                // sync_tombstones_with_peer will include it in the batch.
                if let Some(coordinator) = self.backend.sync_coordinator() {
                    let coordinator = coordinator.clone();
                    let backend = Arc::clone(&self.backend);
                    tokio::spawn(async move {
                        // Get connected peers via the transport
                        if let Some(transport) = backend.iroh_transport() {
                            for peer_id in transport.connected_peers() {
                                if let Err(e) = coordinator.sync_tombstones_with_peer(peer_id).await
                                {
                                    tracing::debug!(
                                        "Tombstone propagation to peer {:?} failed: {}",
                                        peer_id,
                                        e
                                    );
                                }
                            }
                        }
                    });
                }

                Ok(crate::qos::DeleteResult {
                    deleted: true,
                    tombstone_id: Some(tombstone_id),
                    expires_at: Some(std::time::SystemTime::now() + tombstone_ttl),
                    policy: policy.clone(),
                })
            }
            DeletionPolicy::SoftDelete {
                include_deleted_default: _,
            } => {
                // Soft delete: get doc, mark _deleted=true, upsert back
                let doc_key = format!("{}:{}", collection, doc_id);
                if let Some(automerge_doc) = store.get(&doc_key).map_err(|e| Error::Storage {
                    message: e.to_string(),
                    operation: Some("get".to_string()),
                    key: Some(doc_key.clone()),
                    source: None,
                })? {
                    // Apply soft-delete fields via Automerge transaction
                    let mut doc = automerge_doc;
                    let mut tx = doc.transaction();
                    let root = automerge::ROOT;
                    tx.put(&root, "_deleted", true).ok();
                    tx.put(
                        &root,
                        "_deleted_at",
                        chrono::Utc::now().format("%Y-%m-%dT%H:%M:%SZ").to_string(),
                    )
                    .ok();
                    if let Some(r) = reason {
                        tx.put(&root, "_deleted_reason", r).ok();
                    }
                    tx.commit();
                    store.put(&doc_key, &doc).map_err(|e| Error::Storage {
                        message: e.to_string(),
                        operation: Some("put".to_string()),
                        key: Some(doc_key.clone()),
                        source: None,
                    })?;

                    // Trigger sync so soft-delete propagates via normal document sync
                    if let Ok(()) = self.backend.sync_document(&doc_key).await {
                        tracing::debug!("Sync triggered for soft-deleted document {}", doc_key);
                    }

                    Ok(crate::qos::DeleteResult::soft_deleted(policy.clone()))
                } else {
                    Ok(crate::qos::DeleteResult {
                        deleted: false,
                        tombstone_id: None,
                        expires_at: None,
                        policy: policy.clone(),
                    })
                }
            }
        }
    }

    async fn is_deleted(&self, collection: &str, doc_id: &DocumentId) -> anyhow::Result<bool> {
        let store = self.backend.automerge_store();

        // Check tombstone first
        if store.has_tombstone(collection, doc_id).unwrap_or(false) {
            return Ok(true);
        }

        // Check soft-delete field
        let doc_key = format!("{}:{}", collection, doc_id);
        if let Ok(Some(automerge_doc)) = store.get(&doc_key) {
            use automerge::ReadDoc;
            if let Ok(Some((automerge::Value::Scalar(s), _))) =
                automerge_doc.get(automerge::ROOT, "_deleted")
            {
                if let automerge::ScalarValue::Boolean(true) = s.as_ref() {
                    return Ok(true);
                }
            }
        }

        Ok(false)
    }

    fn deletion_policy(&self, collection: &str) -> crate::qos::DeletionPolicy {
        self.deletion_policy_registry.get(collection)
    }

    async fn get_tombstones(&self, collection: &str) -> anyhow::Result<Vec<Tombstone>> {
        self.backend
            .automerge_store()
            .get_tombstones_for_collection(collection)
            .map_err(|e| {
                Error::Storage {
                    message: e.to_string(),
                    operation: Some("get_tombstones".to_string()),
                    key: None,
                    source: None,
                }
                .into()
            })
    }

    async fn apply_tombstone(&self, tombstone: &Tombstone) -> anyhow::Result<()> {
        let store = self.backend.automerge_store();
        store.put_tombstone(tombstone).map_err(|e| Error::Storage {
            message: e.to_string(),
            operation: Some("put_tombstone".to_string()),
            key: Some(format!(
                "{}:{}",
                tombstone.collection, tombstone.document_id
            )),
            source: None,
        })?;

        // Remove the document if it exists
        let doc_key = format!("{}:{}", tombstone.collection, tombstone.document_id);
        store.delete(&doc_key).ok();
        Ok(())
    }

    fn observe(&self, collection: &str, query: &Query) -> anyhow::Result<ChangeStream> {
        let (tx, rx) = tokio::sync::mpsc::unbounded_channel();

        // Get initial snapshot
        // Issue #457: Use direct store scan to handle both Collection::upsert
        // and message_to_automerge storage formats
        let collection_prefix = format!("{}:", collection);
        let all_docs = self
            .backend
            .automerge_store()
            .scan_prefix(&collection_prefix)
            .map_err(|e| Error::Storage {
                message: e.to_string(),
                operation: Some("scan_prefix".to_string()),
                key: None,
                source: None,
            })?;

        let mut initial_docs = Vec::new();
        for (doc_key, automerge_doc) in all_docs {
            // Extract doc_id from key
            let doc_id = match doc_key.strip_prefix(&collection_prefix) {
                Some(id) => id.to_string(),
                None => continue,
            };

            // Convert Automerge doc to Document
            if let Ok(json_value) = automerge_to_message::<serde_json::Value>(&automerge_doc) {
                let fields = if let serde_json::Value::Object(map) = json_value {
                    map.into_iter().collect()
                } else {
                    serde_json::Map::new().into_iter().collect()
                };
                let doc = Document {
                    id: Some(doc_id),
                    fields,
                    updated_at: std::time::SystemTime::now(),
                };

                if matches_query(&doc, query) {
                    initial_docs.push(doc);
                }
            }
        }

        // Send initial snapshot
        let _ = tx.send(ChangeEvent::Initial {
            documents: initial_docs,
        });

        // Subscribe to observer notifications from the store (Issue #221, Issue #377)
        // This enables emitting ChangeEvent::Updated when documents sync from peers.
        // Using subscribe_to_observer_changes() instead of subscribe_to_changes() ensures
        // we get notifications for ALL document changes, including remotely synced docs.
        let mut change_rx = self
            .backend
            .automerge_store()
            .subscribe_to_observer_changes();
        let collection_name = collection.to_string();
        let collection_prefix = format!("{}:", collection);
        let query_clone = query.clone();
        let backend = Arc::clone(&self.backend);
        let tx_clone = tx.clone();

        // Spawn background task to listen for changes and emit Updated events
        tokio::spawn(async move {
            loop {
                match change_rx.recv().await {
                    Ok(doc_key) => {
                        // Check if this change is for our collection
                        if !doc_key.starts_with(&collection_prefix) {
                            continue;
                        }

                        // Extract doc_id from key (format: "collection:doc_id")
                        let doc_id = match doc_key.strip_prefix(&collection_prefix) {
                            Some(id) => id.to_string(),
                            None => continue,
                        };

                        // Fetch the updated document directly from store
                        // Issue #457: AutomergeSummaryStorage uses message_to_automerge which stores
                        // fields at ROOT, but Collection::get expects a "data" field wrapper.
                        // Use direct store access for consistent handling of all document formats.
                        let maybe_doc: Option<Document> = if let Ok(Some(automerge_doc)) =
                            backend.automerge_store().get(&doc_key)
                        {
                            // Convert Automerge doc to JSON Value, then to Document
                            if let Ok(json_value) =
                                automerge_to_message::<serde_json::Value>(&automerge_doc)
                            {
                                // Convert JSON Value to Document
                                let fields = if let serde_json::Value::Object(map) = json_value {
                                    map.into_iter().collect()
                                } else {
                                    serde_json::Map::new().into_iter().collect()
                                };
                                Some(Document {
                                    id: Some(doc_id.clone()),
                                    fields,
                                    updated_at: std::time::SystemTime::now(),
                                })
                            } else {
                                None
                            }
                        } else {
                            None
                        };

                        if let Some(mut doc) = maybe_doc {
                            if doc.id.is_none() {
                                doc.id = Some(doc_id);
                            }

                            // Check if document matches query
                            if matches_query(&doc, &query_clone) {
                                // Emit Updated event
                                if tx_clone
                                    .send(ChangeEvent::Updated {
                                        collection: collection_name.clone(),
                                        document: doc,
                                    })
                                    .is_err()
                                {
                                    // Receiver dropped, stop listening
                                    break;
                                }
                            }
                        }
                    }
                    Err(tokio::sync::broadcast::error::RecvError::Lagged(n)) => {
                        // Issue #346: When lagged, re-emit all documents in the collection
                        // to ensure observers don't miss updates. This is critical for
                        // metrics tracking and hierarchical aggregation callbacks.
                        tracing::warn!(
                            "Observer change notification lagged, skipped {} messages - re-emitting all documents",
                            n
                        );

                        // Re-scan collection and emit Updated for all matching documents
                        // Issue #457: Use direct store scan to handle both Collection::upsert
                        // and message_to_automerge storage formats
                        let prefix = &collection_prefix;
                        if let Ok(all_docs) = backend.automerge_store().scan_prefix(prefix) {
                            for (doc_key, automerge_doc) in all_docs {
                                // Extract doc_id from key
                                let doc_id = match doc_key.strip_prefix(prefix) {
                                    Some(id) => id.to_string(),
                                    None => continue,
                                };

                                // Try to convert Automerge doc to Document
                                let maybe_doc: Option<Document> = if let Ok(json_value) =
                                    automerge_to_message::<serde_json::Value>(&automerge_doc)
                                {
                                    let fields = if let serde_json::Value::Object(map) = json_value
                                    {
                                        map.into_iter().collect()
                                    } else {
                                        serde_json::Map::new().into_iter().collect()
                                    };
                                    Some(Document {
                                        id: Some(doc_id),
                                        fields,
                                        updated_at: std::time::SystemTime::now(),
                                    })
                                } else {
                                    None
                                };

                                if let Some(doc) = maybe_doc {
                                    // Send event if document matches query
                                    #[allow(clippy::collapsible_if)]
                                    if matches_query(&doc, &query_clone) {
                                        if tx_clone
                                            .send(ChangeEvent::Updated {
                                                collection: collection_name.clone(),
                                                document: doc,
                                            })
                                            .is_err()
                                        {
                                            // Receiver dropped, stop listening
                                            break;
                                        }
                                    }
                                }
                            }
                        }
                    }
                    Err(tokio::sync::broadcast::error::RecvError::Closed) => {
                        // Channel closed, stop listening
                        break;
                    }
                }
            }
        });

        Ok(ChangeStream { receiver: rx })
    }
}

// PeerDiscovery implementation for AutomergeIrohBackend
struct IrohPeerDiscovery {
    transport: Arc<crate::network::IrohTransport>,
    peer_callbacks: PeerCallbacks,
    #[cfg(feature = "automerge-backend")]
    discovery_manager: Arc<tokio::sync::RwLock<crate::discovery::peer::DiscoveryManager>>,
    /// Formation key for peer authentication (required for secure connections)
    #[cfg(feature = "automerge-backend")]
    formation_key: Arc<std::sync::RwLock<Option<crate::security::FormationKey>>>,
    /// Whether the event forwarder task is running (Issue #275)
    event_forwarder_running: Arc<std::sync::atomic::AtomicBool>,
    /// Optional topology event receiver for topology-driven connections
    #[cfg(feature = "automerge-backend")]
    topology_event_rx:
        Arc<tokio::sync::Mutex<Option<mpsc::UnboundedReceiver<TopologyConnectionEvent>>>>,
    /// Maximum peer connections when topology manager is not configured
    #[cfg(feature = "automerge-backend")]
    max_connections: usize,
}

#[async_trait]
impl PeerDiscovery for IrohPeerDiscovery {
    async fn start(&self) -> anyhow::Result<()> {
        // Get formation key for authentication (required)
        let formation_key = self
            .formation_key
            .read()
            .map_err(|_| Error::Internal("formation_key lock poisoned".into()))?
            .clone()
            .ok_or_else(|| Error::Internal("Formation key not initialized".to_string()))?;

        // Start authenticated accept loop (replaces simple start_accept_loop)
        // This spawns a background task that accepts connections and performs handshake
        //
        // IMPORTANT (Issue #229): We MUST mark the accept loop as managed BEFORE spawning
        // our custom loop. This prevents AutomergeBackend::start_sync() from starting a
        // duplicate accept loop via transport.start_accept_loop(), which would cause
        // competing loops where one might accept connections without doing the handshake.
        #[cfg(feature = "automerge-backend")]
        {
            // Mark accept loop as externally managed to prevent duplicate loops
            self.transport.mark_accept_loop_managed().map_err(|e| {
                Error::Internal(format!("Failed to mark accept loop as managed: {}", e))
            })?;

            let transport = Arc::clone(&self.transport);
            let formation_key_accept = formation_key.clone();

            tokio::spawn(async move {
                use crate::network::formation_handshake::perform_responder_handshake;

                // Issue #346: Track consecutive errors to detect permanent failures
                let mut consecutive_errors = 0u32;
                const MAX_CONSECUTIVE_ERRORS: u32 = 10;

                loop {
                    // Accept incoming connection
                    // Note (Issue #229): accept() returns Option<Connection>
                    // - Some(conn) = new connection that needs authentication
                    // - None = duplicate/transient (already handled or failed QUIC handshake)
                    match transport.accept().await {
                        Ok(Some(conn)) => {
                            consecutive_errors = 0; // Reset on success
                            let peer_id = conn.remote_id();

                            // Perform formation handshake to authenticate peer
                            match perform_responder_handshake(&conn, &formation_key_accept).await {
                                Ok(()) => {
                                    // Issue #346: Emit Connected AFTER successful handshake
                                    transport.emit_peer_connected(peer_id);
                                }
                                Err(e) => {
                                    tracing::warn!(
                                        ?peer_id,
                                        error = %e,
                                        "Formation handshake failed"
                                    );
                                    // Close the unauthenticated connection - connection monitor
                                    // will handle cleanup (Issue #346 stable_id check)
                                    conn.close(1u32.into(), b"authentication failed");
                                }
                            }
                        }
                        Ok(None) => {
                            // Issue #346: This now includes transient errors (failed QUIC handshake)
                            // as well as duplicate connections. Either way, continue accepting.
                            consecutive_errors = 0; // Reset - we're still accepting
                        }
                        Err(e) => {
                            // Issue #346: Only fatal errors (endpoint closed) should stop the loop
                            // But add a circuit breaker for repeated failures
                            consecutive_errors += 1;
                            let error_msg = format!("{}", e);

                            if error_msg.contains("Endpoint closed")
                                || error_msg.contains("no more")
                            {
                                tracing::info!("Accept loop stopped: endpoint closed");
                                break;
                            }

                            if consecutive_errors >= MAX_CONSECUTIVE_ERRORS {
                                tracing::error!(
                                    consecutive_errors,
                                    error = %e,
                                    "Accept loop stopping after {} consecutive errors",
                                    MAX_CONSECUTIVE_ERRORS
                                );
                                break;
                            }

                            tracing::warn!(
                                error = %e,
                                consecutive_errors,
                                "Accept error (will retry, {} more before stopping)",
                                MAX_CONSECUTIVE_ERRORS - consecutive_errors
                            );
                            // Small delay before retrying to avoid tight error loop
                            tokio::time::sleep(std::time::Duration::from_millis(100)).await;
                        }
                    }
                }
                tracing::info!("Authenticated accept loop stopped");
            });
        }

        // Start discovery manager
        #[cfg(feature = "automerge-backend")]
        {
            let mut manager = self.discovery_manager.write().await;
            manager.start().await.map_err(|e| {
                Error::Internal(format!("Failed to start discovery manager: {}", e))
            })?;
        }

        // Spawn mDNS discovery event handler (Issue #233)
        // This subscribes to Iroh's MdnsDiscovery stream and connects to newly discovered peers.
        // Without this, mDNS only populates the address book but doesn't trigger connections.
        #[cfg(feature = "automerge-backend")]
        if let Some(mdns) = self.transport.mdns_discovery() {
            use futures_lite::StreamExt;
            use iroh::address_lookup::mdns::DiscoveryEvent;

            let mdns = mdns.clone();
            let transport = Arc::clone(&self.transport);
            let formation_key_mdns = formation_key.clone();

            tokio::spawn(async move {
                use crate::network::formation_handshake::perform_initiator_handshake;

                tracing::info!("Starting mDNS discovery event handler");
                let mut stream = mdns.subscribe().await;

                while let Some(event) = stream.next().await {
                    match event {
                        DiscoveryEvent::Discovered { endpoint_info, .. } => {
                            let peer_id = endpoint_info.endpoint_id;
                            tracing::info!(
                                peer_id = %peer_id,
                                "mDNS discovered peer, attempting connection"
                            );

                            // Check if already connected
                            if transport.get_connection(&peer_id).is_some() {
                                tracing::debug!(
                                    peer_id = %peer_id,
                                    "Already connected to mDNS-discovered peer"
                                );
                                continue;
                            }

                            // Connect using just the EndpointId (addresses from mDNS discovery)
                            match transport.connect_by_id(peer_id).await {
                                Ok(Some(conn)) => {
                                    // New connection - perform formation handshake
                                    match perform_initiator_handshake(&conn, &formation_key_mdns)
                                        .await
                                    {
                                        Ok(()) => {
                                            tracing::info!(
                                                peer_id = %peer_id,
                                                "mDNS peer connected and authenticated"
                                            );
                                            // Issue #346: Emit Connected AFTER successful handshake
                                            transport.emit_peer_connected(peer_id);
                                        }
                                        Err(e) => {
                                            tracing::warn!(
                                                peer_id = %peer_id,
                                                error = %e,
                                                "mDNS peer failed authentication"
                                            );
                                            conn.close(1u32.into(), b"authentication failed");
                                            transport.disconnect(&peer_id).ok();
                                        }
                                    }
                                }
                                Ok(None) => {
                                    // Accept path is handling connection
                                    tracing::debug!(
                                        peer_id = %peer_id,
                                        "mDNS peer connection handled by accept path"
                                    );
                                }
                                Err(e) => {
                                    tracing::debug!(
                                        peer_id = %peer_id,
                                        error = %e,
                                        "Failed to connect to mDNS-discovered peer"
                                    );
                                }
                            }
                        }
                        DiscoveryEvent::Expired { endpoint_id } => {
                            tracing::debug!(
                                peer_id = %endpoint_id,
                                "mDNS peer expired (no longer advertising)"
                            );
                            // Note: We don't disconnect immediately since the peer might still
                            // be reachable. The connection will fail naturally if unreachable.
                        }
                    }
                }
                tracing::debug!("mDNS discovery event handler stopped");
            });
        }

        // Check if topology-driven connection management is configured
        #[cfg(feature = "automerge-backend")]
        let has_topology_events = {
            let guard = self.topology_event_rx.lock().await;
            guard.is_some()
        };

        // Spawn topology event handler if configured (prevents N² mesh)
        #[cfg(feature = "automerge-backend")]
        if has_topology_events {
            let topology_rx = self.topology_event_rx.clone();
            let transport = Arc::clone(&self.transport);
            let formation_key_topology = formation_key.clone();

            tokio::spawn(async move {
                use crate::network::formation_handshake::perform_initiator_handshake;
                use crate::network::PeerInfo as NetworkPeerInfo;

                // Take the receiver from the mutex
                let mut rx = {
                    let mut guard = topology_rx.lock().await;
                    guard.take()
                };

                if let Some(ref mut receiver) = rx {
                    tracing::info!("Topology-driven connection management enabled");

                    while let Some(event) = receiver.recv().await {
                        match event {
                            TopologyConnectionEvent::ConnectPeer {
                                peer_id,
                                addresses,
                                relay_url,
                            } => {
                                tracing::debug!(
                                    peer_id = %peer_id,
                                    "Topology event: connecting to peer"
                                );

                                let network_peer_info = NetworkPeerInfo {
                                    name: peer_id.clone(),
                                    node_id: peer_id.clone(),
                                    addresses,
                                    relay_url,
                                };

                                match transport.connect_peer(&network_peer_info).await {
                                    Ok(Some(conn)) => {
                                        // Give accept loop time for conflict resolution
                                        tokio::task::yield_now().await;
                                        tokio::time::sleep(tokio::time::Duration::from_millis(10))
                                            .await;

                                        if conn.close_reason().is_some() {
                                            tracing::debug!(
                                                "Topology peer {} superseded by accept path",
                                                peer_id
                                            );
                                            continue;
                                        }

                                        // Perform formation handshake
                                        match perform_initiator_handshake(
                                            &conn,
                                            &formation_key_topology,
                                        )
                                        .await
                                        {
                                            Ok(()) => {
                                                // Convert peer_id hex string to EndpointId
                                                if let Ok(bytes) = hex::decode(&peer_id) {
                                                    if bytes.len() == 32 {
                                                        let mut array = [0u8; 32];
                                                        array.copy_from_slice(&bytes);
                                                        if let Ok(endpoint_id) =
                                                            iroh::EndpointId::from_bytes(&array)
                                                        {
                                                            transport
                                                                .emit_peer_connected(endpoint_id);
                                                            tracing::info!(
                                                                "Topology: connected and authenticated with peer: {}",
                                                                peer_id
                                                            );
                                                        }
                                                    }
                                                }
                                            }
                                            Err(e) => {
                                                tracing::warn!(
                                                    "Topology peer {} failed authentication: {}",
                                                    peer_id,
                                                    e
                                                );
                                                conn.close(1u32.into(), b"authentication failed");
                                            }
                                        }
                                    }
                                    Ok(None) => {
                                        tracing::debug!(
                                            "Topology peer {} handled by accept path",
                                            peer_id
                                        );
                                    }
                                    Err(e) => {
                                        tracing::debug!(
                                            "Failed to connect to topology peer {}: {}",
                                            peer_id,
                                            e
                                        );
                                    }
                                }
                            }
                            TopologyConnectionEvent::DisconnectPeer { peer_id } => {
                                tracing::debug!(
                                    peer_id = %peer_id,
                                    "Topology event: disconnecting from peer"
                                );
                                // Convert peer_id hex string to EndpointId
                                if let Ok(bytes) = hex::decode(&peer_id) {
                                    if bytes.len() == 32 {
                                        let mut array = [0u8; 32];
                                        array.copy_from_slice(&bytes);
                                        if let Ok(endpoint_id) =
                                            iroh::EndpointId::from_bytes(&array)
                                        {
                                            let _ = transport.disconnect(&endpoint_id);
                                        }
                                    }
                                }
                            }
                        }
                    }
                }
                tracing::debug!("Topology event handler stopped");
            });
        }

        // Spawn background task to connect to discovered peers (with authentication)
        // Only runs if topology events are NOT configured (fallback to limited discovery)
        #[cfg(feature = "automerge-backend")]
        if !has_topology_events {
            let discovery_manager = Arc::clone(&self.discovery_manager);
            let transport = Arc::clone(&self.transport);
            let formation_key_connect = formation_key;
            let max_connections = self.max_connections;

            tokio::spawn(async move {
                use crate::network::formation_handshake::perform_initiator_handshake;
                use crate::network::iroh_transport::TransportPeerEvent;
                use crate::network::PeerInfo as NetworkPeerInfo;

                tracing::info!(
                    "Discovery-based connection management enabled (max {} connections)",
                    max_connections
                );

                // Subscribe to peer events for immediate reconnection on disconnect (Issue #504)
                let mut peer_events = transport.subscribe_peer_events();

                // Adaptive interval: start fast (1s), slow down once mesh is stable (up to 5s)
                let mut interval_secs = 1u64;
                let mut consecutive_no_new_connections = 0u32;

                loop {
                    // Issue #504: Use select! to react immediately to disconnect events
                    // instead of waiting up to 5 seconds for the next polling cycle
                    let sleep_future =
                        tokio::time::sleep(std::time::Duration::from_secs(interval_secs));
                    tokio::pin!(sleep_future);

                    tokio::select! {
                        _ = &mut sleep_future => {
                            // Normal timeout - continue with connection cycle
                        }
                        event = peer_events.recv() => {
                            match event {
                                Some(TransportPeerEvent::Disconnected { endpoint_id, reason }) => {
                                    tracing::debug!(
                                        peer = %endpoint_id.fmt_short(),
                                        reason = %reason,
                                        "Peer disconnected - triggering immediate reconnection attempt"
                                    );
                                    // Reset to fast polling for quick recovery
                                    interval_secs = 1;
                                    consecutive_no_new_connections = 0;
                                }
                                Some(TransportPeerEvent::Connected { .. }) => {
                                    // New connection - continue normally
                                }
                                None => {
                                    // Channel closed, exit the loop
                                    tracing::debug!("Peer event channel closed, stopping connection manager");
                                    break;
                                }
                            }
                        }
                    }

                    // Check current connection count
                    let current_connections = transport.connected_peers().len();
                    if current_connections >= max_connections {
                        tracing::debug!(
                            "At max connections ({}/{}), skipping discovery connect cycle",
                            current_connections,
                            max_connections
                        );
                        consecutive_no_new_connections += 1;
                        if consecutive_no_new_connections >= 3 && interval_secs < 5 {
                            interval_secs = (interval_secs * 2).min(5);
                        }
                        continue;
                    }

                    // Get discovered peers
                    let manager = discovery_manager.read().await;
                    let discovered_peers = manager.get_peers().await;
                    drop(manager);

                    // Try to connect to discovered peers (up to max_connections limit)
                    let mut made_new_connection = false;
                    let slots_available = max_connections.saturating_sub(current_connections);

                    for peer in discovered_peers.into_iter().take(slots_available) {
                        // Convert discovery::peer::PeerInfo to network::PeerInfo
                        let network_peer_info = NetworkPeerInfo {
                            name: peer.name.clone(),
                            node_id: peer.node_id.clone(),
                            addresses: peer.addresses.clone(),
                            relay_url: peer.relay_url.clone(),
                        };

                        // Try to connect to the peer
                        // connect_peer() returns Option<Connection> (Issue #229):
                        // - Some(conn): New connection, we need to do initiator handshake
                        // - None: Already connected via accept path, no action needed
                        if let Ok(endpoint_id) = peer.endpoint_id() {
                            match transport.connect_peer(&network_peer_info).await {
                                Ok(Some(conn)) => {
                                    // Issue #346: Give the accept loop a moment to process any
                                    // incoming connection from this peer. In symmetric discovery
                                    // (both peers have each other in config), both will connect
                                    // simultaneously and the accept loop needs time to process
                                    // the incoming connection and do conflict resolution.
                                    tokio::task::yield_now().await;
                                    tokio::time::sleep(tokio::time::Duration::from_millis(10))
                                        .await;

                                    // Check if connection was closed by conflict resolution
                                    // (accept path superseded this connection).
                                    if conn.close_reason().is_some() {
                                        tracing::debug!(
                                            "Peer {} connection superseded by accept path",
                                            peer.name
                                        );
                                        continue;
                                    }

                                    // New connection - perform formation handshake
                                    match perform_initiator_handshake(&conn, &formation_key_connect)
                                        .await
                                    {
                                        Ok(()) => {
                                            tracing::info!(
                                                "Connected and authenticated with peer: {} ({}/{})",
                                                peer.name,
                                                transport.connected_peers().len(),
                                                max_connections
                                            );
                                            // Issue #346: Emit Connected AFTER successful handshake
                                            transport.emit_peer_connected(endpoint_id);
                                            made_new_connection = true;
                                        }
                                        Err(e) => {
                                            tracing::warn!(
                                                "Peer {} failed authentication: {}. Disconnecting.",
                                                peer.name,
                                                e
                                            );
                                            // Issue #346: Don't call disconnect() here - the connection
                                            // in the map might be a different one after conflict resolution.
                                            // conn.close() is sufficient; close monitor handles cleanup.
                                            conn.close(1u32.into(), b"authentication failed");
                                        }
                                    }
                                }
                                Ok(None) => {
                                    // Accept path is handling connection
                                    tracing::debug!(
                                        "Peer {} connection handled by accept path",
                                        peer.name
                                    );
                                }
                                Err(e) => {
                                    tracing::debug!(
                                        "Failed to connect to discovered peer {}: {}",
                                        peer.name,
                                        e
                                    );
                                }
                            }
                        }
                    }

                    // Adaptive backoff: stay fast while forming mesh, slow down once stable
                    if made_new_connection {
                        // Reset to fast polling when we're actively connecting
                        interval_secs = 1;
                        consecutive_no_new_connections = 0;
                    } else {
                        consecutive_no_new_connections += 1;
                        // After 3 cycles with no new connections, increase interval (max 5s)
                        if consecutive_no_new_connections >= 3 && interval_secs < 5 {
                            interval_secs = (interval_secs * 2).min(5);
                            tracing::debug!(
                                "Mesh stable, increasing connect interval to {}s",
                                interval_secs
                            );
                        }
                    }
                }
            });
        }

        Ok(())
    }

    async fn stop(&self) -> anyhow::Result<()> {
        Ok(())
    }

    async fn discovered_peers(&self) -> anyhow::Result<Vec<PeerInfo>> {
        let mut peers = Vec::new();

        // Get connected peers from transport
        let peer_ids = self.transport.connected_peers();
        for peer_id in peer_ids {
            if self.transport.get_connection(&peer_id).is_some() {
                peers.push(PeerInfo {
                    peer_id: hex::encode(peer_id.as_bytes()),
                    address: None,
                    transport: TransportType::Custom,
                    connected: true,
                    last_seen: std::time::SystemTime::now(),
                    metadata: HashMap::new(),
                });
            }
        }

        // Add discovered but not yet connected peers from discovery manager
        #[cfg(feature = "automerge-backend")]
        {
            let manager = self.discovery_manager.read().await;
            for discovered_peer in manager.get_peers().await {
                // Check if already connected
                if !peers.iter().any(|p| p.peer_id == discovered_peer.node_id) {
                    peers.push(PeerInfo {
                        peer_id: discovered_peer.node_id.clone(),
                        address: discovered_peer.addresses.first().cloned(),
                        transport: TransportType::Custom,
                        connected: false,
                        last_seen: std::time::SystemTime::now(),
                        metadata: HashMap::new(),
                    });
                }
            }
        }

        Ok(peers)
    }

    async fn add_peer(&self, address: &str, _transport: TransportType) -> anyhow::Result<()> {
        use crate::network::iroh_transport::IrohTransport;
        use crate::network::PeerInfo as NetworkPeerInfo;

        // Get formation key for authentication
        let formation_key = self
            .formation_key
            .read()
            .map_err(|_| Error::Internal("formation_key lock poisoned".into()))?
            .clone()
            .ok_or_else(|| Error::Internal("Formation key not initialized".to_string()))?;

        // Parse address format (Issue #226):
        // Format 1: "seed|hostname:port" - Derives EndpointId from seed (for containerlab)
        // Format 2: "hex_node_id" - Raw hex EndpointId (legacy static config)
        //
        // Example: "alpha-formation/node-1|192.168.1.100:9000"
        let (node_id, socket_addr) = if address.contains('|') {
            // Seed-based format: "seed|address"
            let parts: Vec<&str> = address.splitn(2, '|').collect();
            if parts.len() != 2 {
                return Err(Error::Internal(format!(
                    "Invalid address format: {}. Expected 'seed|host:port'",
                    address
                ))
                .into());
            }
            let seed = parts[0];
            let addr = parts[1];

            // Derive EndpointId from seed using deterministic key generation
            let endpoint_id = IrohTransport::endpoint_id_from_seed(seed);
            let node_id_hex = hex::encode(endpoint_id.as_bytes());

            tracing::debug!(
                seed = seed,
                node_id = %node_id_hex,
                address = addr,
                "Derived EndpointId from seed for add_peer"
            );

            (node_id_hex, addr.to_string())
        } else {
            // Legacy format: assume address is a hex-encoded EndpointId
            // (for backwards compatibility with existing static configs)
            (address.to_string(), address.to_string())
        };

        let peer_info = NetworkPeerInfo {
            name: "manual-peer".to_string(),
            node_id,
            addresses: vec![socket_addr],
            relay_url: None,
        };

        // Connect to peer (conflict resolution handled by transport layer)
        let conn_opt =
            self.transport
                .connect_peer(&peer_info)
                .await
                .map_err(|e| Error::Network {
                    message: format!("Failed to connect to peer: {}", e),
                    peer_id: None,
                    source: None,
                })?;

        // Perform formation handshake to authenticate (only if we got a new connection)
        #[cfg(feature = "automerge-backend")]
        if let Some(conn) = conn_opt {
            use crate::network::formation_handshake::perform_initiator_handshake;

            let endpoint_id = conn.remote_id();
            if let Err(e) = perform_initiator_handshake(&conn, &formation_key).await {
                // Authentication failed - close the connection
                // Issue #346: Don't call disconnect() here - the connection
                // in the map might be a different one after conflict resolution.
                // conn.close() is sufficient; close monitor handles cleanup.
                conn.close(1u32.into(), b"authentication failed");

                return Err(Error::Network {
                    message: format!("Peer authentication failed: {}", e),
                    peer_id: Some(address.to_string()),
                    source: None,
                }
                .into());
            }
            // Issue #346: Emit Connected AFTER successful handshake
            self.transport.emit_peer_connected(endpoint_id);
        }
        // If conn_opt is None, accept path is handling the connection

        Ok(())
    }

    async fn wait_for_peer(&self, peer_id: &PeerId, timeout: Duration) -> anyhow::Result<()> {
        let start = std::time::Instant::now();

        loop {
            let peers = self.discovered_peers().await?;
            if peers.iter().any(|p| &p.peer_id == peer_id) {
                return Ok(());
            }

            if start.elapsed() > timeout {
                return Err(Error::Network {
                    message: format!("Timeout waiting for peer: {}", peer_id),
                    peer_id: Some(peer_id.clone()),
                    source: None,
                }
                .into());
            }

            tokio::time::sleep(Duration::from_millis(100)).await;
        }
    }

    fn on_peer_event(&self, callback: Box<dyn Fn(PeerEvent) + Send + Sync>) {
        if let Ok(mut callbacks) = self.peer_callbacks.lock() {
            callbacks.push(callback);
        }

        // Start event forwarder on first callback registration (Issue #275)
        // Use compare_exchange to ensure we only start once
        if self
            .event_forwarder_running
            .compare_exchange(
                false,
                true,
                std::sync::atomic::Ordering::SeqCst,
                std::sync::atomic::Ordering::SeqCst,
            )
            .is_ok()
        {
            // Subscribe to transport events and forward to callbacks
            let mut rx = self.transport.subscribe_peer_events();
            let callbacks = Arc::clone(&self.peer_callbacks);
            let running = Arc::clone(&self.event_forwarder_running);

            // Spawn the forwarder task using std::thread with a tokio runtime
            // (since on_peer_event is not async)
            std::thread::spawn(move || {
                let rt = tokio::runtime::Builder::new_current_thread()
                    .enable_all()
                    .build()
                    .expect("Failed to create event forwarder runtime");

                rt.block_on(async move {
                    use crate::network::TransportPeerEvent;

                    while running.load(std::sync::atomic::Ordering::SeqCst) {
                        match tokio::time::timeout(std::time::Duration::from_millis(100), rx.recv())
                            .await
                        {
                            Ok(Some(transport_event)) => {
                                // Convert TransportPeerEvent to PeerEvent
                                let peer_event = match transport_event {
                                    TransportPeerEvent::Connected { endpoint_id, .. } => {
                                        PeerEvent::Connected(PeerInfo {
                                            peer_id: format!("{:?}", endpoint_id),
                                            address: None,
                                            transport: TransportType::Tcp, // QUIC maps to TCP for now
                                            connected: true,
                                            last_seen: std::time::SystemTime::now(),
                                            metadata: std::collections::HashMap::new(),
                                        })
                                    }
                                    TransportPeerEvent::Disconnected {
                                        endpoint_id,
                                        reason,
                                    } => PeerEvent::Disconnected {
                                        peer_id: format!("{:?}", endpoint_id),
                                        reason: Some(reason),
                                    },
                                };

                                // Invoke all callbacks
                                if let Ok(cbs) = callbacks.lock() {
                                    for cb in cbs.iter() {
                                        cb(peer_event.clone());
                                    }
                                }
                            }
                            Ok(None) => {
                                // Channel closed, stop forwarder
                                break;
                            }
                            Err(_) => {
                                // Timeout - continue to check running flag
                            }
                        }
                    }
                });
            });
        }
    }

    async fn get_peer_info(&self, peer_id: &PeerId) -> anyhow::Result<Option<PeerInfo>> {
        let peers = self.discovered_peers().await?;
        Ok(peers.into_iter().find(|p| &p.peer_id == peer_id))
    }
}

// SyncEngine implementation for AutomergeIrohBackend
struct IrohSyncEngine {
    backend: Arc<crate::storage::AutomergeBackend>,
    transport: Arc<crate::network::IrohTransport>,
    formation_key: Option<crate::security::FormationKey>,
}

#[async_trait]
impl SyncEngine for IrohSyncEngine {
    async fn start_sync(&self) -> anyhow::Result<()> {
        use crate::storage::capabilities::SyncCapable;
        self.backend.start_sync().map_err(|e| Error::Storage {
            message: format!("Failed to start sync: {}", e),
            operation: Some("start_sync".to_string()),
            key: None,
            source: None,
        })?;
        Ok(())
    }

    async fn stop_sync(&self) -> anyhow::Result<()> {
        use crate::storage::capabilities::SyncCapable;
        self.backend.stop_sync().map_err(|e| Error::Storage {
            message: format!("Failed to stop sync: {}", e),
            operation: Some("stop_sync".to_string()),
            key: None,
            source: None,
        })?;
        Ok(())
    }

    async fn subscribe(
        &self,
        collection: &str,
        _query: &Query,
    ) -> anyhow::Result<SyncSubscription> {
        Ok(SyncSubscription::new(collection, ()))
    }

    async fn is_syncing(&self) -> anyhow::Result<bool> {
        use crate::storage::capabilities::SyncCapable;
        let stats = self.backend.sync_stats().map_err(|e| Error::Storage {
            message: format!("Failed to get sync stats: {}", e),
            operation: Some("sync_stats".to_string()),
            key: None,
            source: None,
        })?;
        Ok(stats.peer_count > 0)
    }

    /// Connect to a peer using their EndpointId and addresses (Issue #235)
    ///
    /// This enables static peer configuration in containerlab and similar environments
    /// where mDNS discovery may not work across network namespaces.
    async fn connect_to_peer(
        &self,
        endpoint_id_hex: &str,
        addresses: &[String],
    ) -> anyhow::Result<bool> {
        use crate::network::PeerInfo as NetworkPeerInfo;

        // Parse the endpoint ID from hex
        let endpoint_id_bytes = hex::decode(endpoint_id_hex)
            .map_err(|e| Error::Internal(format!("Invalid endpoint_id_hex: {}", e)))?;

        if endpoint_id_bytes.len() != 32 {
            return Err(Error::Internal(format!(
                "Invalid endpoint_id_hex length: expected 32 bytes, got {}",
                endpoint_id_bytes.len()
            ))
            .into());
        }

        // Issue #346: Removed tie-breaking from sync layer
        //
        // Tie-breaking is handled by the transport layer (IrohTransport::connect).
        // For static configurations (TCP_CONNECT), we should always attempt to connect
        // when explicitly configured. The transport will return Ok(None) if we should
        // wait for the peer to connect to us, which we handle below.
        //
        // Having tie-breaking at BOTH layers caused connections to fail when:
        // - Child node (soldier) has higher EndpointId than parent (squad leader)
        // - Child's TCP_CONNECT says "connect to parent"
        // - Sync layer tie-breaking blocked the connection
        // - Parent doesn't have child in config, so never connects
        // - Result: no connection!
        let our_endpoint_id = self.transport.endpoint_id();
        let our_endpoint_hex = hex::encode(our_endpoint_id.as_bytes());

        tracing::debug!(
            our_endpoint = %our_endpoint_hex,
            peer_endpoint = %endpoint_id_hex,
            addresses = ?addresses,
            "Connecting to peer via static configuration"
        );

        // Create PeerInfo for the transport
        let peer_info = NetworkPeerInfo {
            name: format!("peer-{}", &endpoint_id_hex[..8]),
            node_id: endpoint_id_hex.to_string(),
            addresses: addresses.to_vec(),
            relay_url: None,
        };

        // Issue #346: connect_peer returns Option<Connection>
        // - Some(conn): New connection, we need to do initiator handshake
        // - None: Accept path is handling, no action needed
        match self.transport.connect_peer(&peer_info).await {
            Ok(Some(conn)) => {
                // Issue #346: Check if connection was closed by conflict resolution
                if conn.close_reason().is_some() {
                    tracing::debug!(
                        peer_endpoint = %endpoint_id_hex,
                        "Connection superseded by accept path"
                    );
                    return Ok(false);
                }

                // New connection - perform formation handshake
                if let Some(ref formation_key) = self.formation_key {
                    use crate::network::formation_handshake::perform_initiator_handshake;
                    match perform_initiator_handshake(&conn, formation_key).await {
                        Ok(()) => {
                            tracing::info!(
                                peer_endpoint = %endpoint_id_hex,
                                "Successfully connected to peer and authenticated"
                            );
                            // Issue #378: Emit peer connected event to notify sync handlers
                            if let Ok(peer_id) = peer_info.endpoint_id() {
                                self.transport.emit_peer_connected(peer_id);
                            }
                            Ok(true)
                        }
                        Err(e) => {
                            tracing::warn!(
                                peer_endpoint = %endpoint_id_hex,
                                error = %e,
                                "Peer authentication failed"
                            );
                            // Close the connection on auth failure
                            if let Ok(peer_id) = peer_info.endpoint_id() {
                                conn.close(1u32.into(), b"authentication failed");
                                self.transport.disconnect(&peer_id).ok();
                            }
                            Err(Error::Network {
                                message: format!("Peer authentication failed: {}", e),
                                peer_id: Some(endpoint_id_hex.to_string()),
                                source: None,
                            }
                            .into())
                        }
                    }
                } else {
                    // No formation key - just report connected
                    tracing::info!(
                        peer_endpoint = %endpoint_id_hex,
                        "Successfully connected to peer (no authentication)"
                    );
                    // Issue #378: Emit peer connected event to notify sync handlers
                    if let Ok(peer_id) = peer_info.endpoint_id() {
                        self.transport.emit_peer_connected(peer_id);
                    }
                    Ok(true)
                }
            }
            Ok(None) => {
                // Accept path is handling connection
                tracing::debug!(
                    peer_endpoint = %endpoint_id_hex,
                    "Connection handled by accept path"
                );
                // Return true since a connection will be established via accept path
                Ok(true)
            }
            Err(e) => {
                tracing::warn!(
                    peer_endpoint = %endpoint_id_hex,
                    error = %e,
                    "Failed to connect to peer"
                );
                Err(Error::Network {
                    message: format!("Failed to connect to peer: {}", e),
                    peer_id: Some(endpoint_id_hex.to_string()),
                    source: None,
                }
                .into())
            }
        }
    }
}

// DataSyncBackend implementation
#[async_trait]
impl DataSyncBackend for AutomergeIrohBackend {
    async fn initialize(&self, config: BackendConfig) -> anyhow::Result<()> {
        // Require shared_key for peer authentication
        let shared_key = config.shared_key.as_ref().ok_or_else(|| {
            Error::config_error(
                "AutomergeIroh backend requires PEAT_SECRET_KEY for peer authentication",
                Some("shared_key".to_string()),
            )
        })?;

        // Create FormationKey from app_id (formation_id) and shared_key
        // This ensures only peers with matching credentials can sync
        let formation_key = crate::security::FormationKey::from_base64(&config.app_id, shared_key)
            .map_err(|e| {
                Error::config_error(
                    format!(
                        "Invalid shared_key format: {}. Expected base64-encoded 32-byte key.",
                        e
                    ),
                    Some("shared_key".to_string()),
                )
            })?;

        // Store the formation key for peer authentication
        *self
            .formation_key
            .write()
            .map_err(|_| Error::Internal("formation_key lock poisoned".into()))? =
            Some(formation_key);

        *self
            .initialized
            .lock()
            .map_err(|_| Error::Internal("initialized lock poisoned".into()))? = true;
        self.peer_discovery().start().await?;
        Ok(())
    }

    async fn shutdown(&self) -> anyhow::Result<()> {
        if self.is_ready().await {
            let _ = self.sync_engine().stop_sync().await;
            let _ = self.peer_discovery().stop().await;
        }
        *self
            .initialized
            .lock()
            .map_err(|_| Error::Internal("initialized lock poisoned".into()))? = false;
        Ok(())
    }

    fn document_store(&self) -> Arc<dyn DocumentStore> {
        // Derive node ID from transport endpoint (unique per node)
        let node_id = self.transport.endpoint_id().to_string();
        Arc::new(IrohDocumentStore {
            backend: Arc::clone(&self.backend),
            deletion_policy_registry: Arc::clone(&self.deletion_policy_registry),
            lamport_counter: Arc::clone(&self.lamport_counter),
            node_id,
        })
    }

    fn peer_discovery(&self) -> Arc<dyn PeerDiscovery> {
        Arc::new(IrohPeerDiscovery {
            transport: Arc::clone(&self.transport),
            peer_callbacks: Arc::clone(&self.peer_callbacks),
            #[cfg(feature = "automerge-backend")]
            discovery_manager: Arc::clone(&self.discovery_manager),
            #[cfg(feature = "automerge-backend")]
            formation_key: Arc::clone(&self.formation_key),
            event_forwarder_running: Arc::new(std::sync::atomic::AtomicBool::new(false)),
            #[cfg(feature = "automerge-backend")]
            topology_event_rx: Arc::clone(&self.topology_event_rx),
            #[cfg(feature = "automerge-backend")]
            max_connections: self.max_connections,
        })
    }

    fn sync_engine(&self) -> Arc<dyn SyncEngine> {
        Arc::new(IrohSyncEngine {
            backend: Arc::clone(&self.backend),
            transport: Arc::clone(&self.transport),
            formation_key: self.formation_key(),
        })
    }

    async fn is_ready(&self) -> bool {
        self.initialized.lock().map(|guard| *guard).unwrap_or(false)
    }

    fn backend_info(&self) -> BackendInfo {
        BackendInfo {
            name: "AutomergeIroh".to_string(),
            version: env!("CARGO_PKG_VERSION").to_string(),
        }
    }

    fn as_any(&self) -> &dyn std::any::Any {
        self
    }
}

// Implement HierarchicalStorageCapable for AutomergeIrohBackend
// This enables peat-sim hierarchical mode with Automerge backend
#[cfg(feature = "automerge-backend")]
impl crate::storage::HierarchicalStorageCapable for AutomergeIrohBackend {
    fn summary_storage(&self) -> Arc<dyn crate::hierarchy::SummaryStorage> {
        // Delegate to the underlying storage::AutomergeBackend
        crate::storage::HierarchicalStorageCapable::summary_storage(self.backend.as_ref())
    }

    fn command_storage(&self) -> Arc<dyn crate::command::CommandStorage> {
        // Delegate to the underlying storage::AutomergeBackend
        crate::storage::HierarchicalStorageCapable::command_storage(self.backend.as_ref())
    }
}

// ============================================================================
// Custom Query Parser (Issue #517, #520)
// ============================================================================
//
// This module provides a simple pattern-based query evaluator for DQL-like
// custom queries. Instead of implementing a full SQL parser, we handle the
// specific patterns used in Peat Protocol.
//
// Supported patterns (Issue #517 - original):
// - `field == 'value'` / `field == true/false`
// - `field STARTS WITH 'prefix'`
// - `field ENDS WITH 'suffix'`
// - `CONTAINS(field, 'value')`
// - `A AND B` / `A OR B` (compound expressions)
//
// Extended patterns (Issue #520 - full syntactic parity):
// - `field != 'value'` / `field != true/false` (inequality)
// - `field LIKE '%pattern%'` (wildcard matching)
// - `field IN ['a', 'b', 'c']` (set membership)
// - `field.nested.path` (nested field access)
// - `NOT (expr)` (negation wrapper)
// - `field IS NULL` / `field IS NOT NULL` (null checks)
//
// For unrecognized patterns, we return `true` (match all) as a conservative
// fallback - this ensures we never hide documents that should match.
// ============================================================================

/// Evaluate a custom DQL-like query string against a document.
///
/// This is a pattern-based evaluator that handles the specific query patterns
/// used in Peat Protocol. For unrecognized patterns, returns `true` (conservative).
///
/// # Arguments
/// * `doc` - The document to match against
/// * `query_str` - The DQL-like query string (e.g., "collection_name == 'squad_summaries'")
///
/// # Returns
/// * `true` if the document matches the query (or query is unrecognized)
/// * `false` if the document definitely doesn't match
fn evaluate_custom_query(doc: &Document, query_str: &str) -> bool {
    let trimmed = query_str.trim();

    // Handle compound OR expressions (lowest precedence)
    // Split on " OR " but be careful not to split inside quotes
    if let Some((left, right)) = split_compound(trimmed, " OR ") {
        return evaluate_custom_query(doc, left) || evaluate_custom_query(doc, right);
    }

    // Handle compound AND expressions
    if let Some((left, right)) = split_compound(trimmed, " AND ") {
        return evaluate_custom_query(doc, left) && evaluate_custom_query(doc, right);
    }

    // Strip outer parentheses if present
    let expr = if trimmed.starts_with('(') && trimmed.ends_with(')') {
        &trimmed[1..trimmed.len() - 1]
    } else {
        trimmed
    };

    // Pattern: NOT (expr) - negation wrapper (Issue #520)
    if let Some(inner) = parse_not_expression(expr) {
        return !evaluate_custom_query(doc, inner);
    }

    // Pattern: CONTAINS(field, 'value')
    if expr.starts_with("CONTAINS(") && expr.ends_with(')') {
        return evaluate_contains(doc, expr);
    }

    // Pattern: field IS NULL / field IS NOT NULL (Issue #520)
    if let Some((field, is_null)) = parse_is_null(expr) {
        return evaluate_is_null(doc, field, is_null);
    }

    // Pattern: field != 'value' or field != true/false (Issue #520)
    // Must check before equality since != contains =
    if let Some((field, value)) = parse_inequality(expr) {
        return !evaluate_equality(doc, field, value);
    }

    // Pattern: field == 'value' or field == true/false
    if let Some((field, value)) = parse_equality(expr) {
        return evaluate_equality(doc, field, value);
    }

    // Pattern: field LIKE '%pattern%' (Issue #520)
    if let Some((field, pattern)) = parse_like(expr) {
        return evaluate_like(doc, field, pattern);
    }

    // Pattern: field IN ['a', 'b', 'c'] (Issue #520)
    if let Some((field, values)) = parse_in(expr) {
        return evaluate_in(doc, field, &values);
    }

    // Pattern: field STARTS WITH 'prefix'
    if let Some((field, prefix)) = parse_starts_with(expr) {
        return evaluate_starts_with(doc, field, prefix);
    }

    // Pattern: field ENDS WITH 'suffix'
    if let Some((field, suffix)) = parse_ends_with(expr) {
        return evaluate_ends_with(doc, field, suffix);
    }

    // Unrecognized pattern: return true (conservative fallback)
    // This ensures we never hide documents that should match
    true
}

/// Split a compound expression on a delimiter, respecting parentheses and quotes.
fn split_compound<'a>(expr: &'a str, delimiter: &str) -> Option<(&'a str, &'a str)> {
    let mut depth = 0;
    let mut in_quote = false;
    let bytes = expr.as_bytes();

    for i in 0..expr.len() {
        match bytes[i] {
            b'\'' => in_quote = !in_quote,
            b'(' if !in_quote => depth += 1,
            b')' if !in_quote => depth -= 1,
            _ if !in_quote && depth == 0 && expr[i..].starts_with(delimiter) => {
                return Some((&expr[..i], &expr[i + delimiter.len()..]));
            }
            _ => {}
        }
    }
    None
}

/// Parse equality expression: `field == 'value'` or `field == true/false`
fn parse_equality(expr: &str) -> Option<(&str, &str)> {
    let parts: Vec<&str> = expr.splitn(2, "==").collect();
    if parts.len() == 2 {
        let field = parts[0].trim();
        let value = parts[1].trim();
        Some((field, value))
    } else {
        None
    }
}

/// Parse STARTS WITH expression: `field STARTS WITH 'prefix'`
fn parse_starts_with(expr: &str) -> Option<(&str, &str)> {
    let upper = expr.to_uppercase();
    if let Some(idx) = upper.find(" STARTS WITH ") {
        let field = expr[..idx].trim();
        let value = expr[idx + 13..].trim(); // " STARTS WITH " is 13 chars
        Some((field, value))
    } else {
        None
    }
}

/// Parse ENDS WITH expression: `field ENDS WITH 'suffix'`
fn parse_ends_with(expr: &str) -> Option<(&str, &str)> {
    let upper = expr.to_uppercase();
    if let Some(idx) = upper.find(" ENDS WITH ") {
        let field = expr[..idx].trim();
        let value = expr[idx + 11..].trim(); // " ENDS WITH " is 11 chars
        Some((field, value))
    } else {
        None
    }
}

/// Extract string literal from quoted value: 'value' -> value
fn extract_string_literal(value: &str) -> Option<&str> {
    let trimmed = value.trim();
    if trimmed.starts_with('\'') && trimmed.ends_with('\'') && trimmed.len() >= 2 {
        Some(&trimmed[1..trimmed.len() - 1])
    } else {
        None
    }
}

/// Evaluate CONTAINS(field, 'value') pattern
fn evaluate_contains(doc: &Document, expr: &str) -> bool {
    // Parse CONTAINS(field, 'value')
    let inner = &expr[9..expr.len() - 1]; // Strip "CONTAINS(" and ")"
    let parts: Vec<&str> = inner.splitn(2, ',').collect();

    if parts.len() != 2 {
        return true; // Conservative fallback
    }

    let field = parts[0].trim();
    let value = parts[1].trim();

    let search_value = match extract_string_literal(value) {
        Some(v) => v,
        None => return true, // Conservative fallback
    };

    // Check if field value contains the search value
    match doc.get(field) {
        Some(serde_json::Value::Array(arr)) => arr.iter().any(|item| {
            if let Some(s) = item.as_str() {
                s == search_value
            } else {
                false
            }
        }),
        Some(serde_json::Value::String(s)) => s.contains(search_value),
        _ => false,
    }
}

/// Evaluate field == value pattern
/// Supports nested field access via get_nested_field (Issue #520)
fn evaluate_equality(doc: &Document, field: &str, value: &str) -> bool {
    // Handle boolean values
    if value == "true" {
        return get_nested_field(doc, field)
            .and_then(|v| v.as_bool())
            .unwrap_or(false);
    }
    if value == "false" {
        return !get_nested_field(doc, field)
            .and_then(|v| v.as_bool())
            .unwrap_or(true);
    }

    // Handle string literals
    if let Some(string_value) = extract_string_literal(value) {
        return match get_nested_field(doc, field) {
            Some(serde_json::Value::String(s)) => s == string_value,
            _ => false,
        };
    }

    // Handle numeric values (try to parse as number)
    if let Ok(num) = value.parse::<i64>() {
        return match get_nested_field(doc, field) {
            Some(serde_json::Value::Number(n)) => n.as_i64() == Some(num),
            _ => false,
        };
    }
    if let Ok(num) = value.parse::<f64>() {
        return match get_nested_field(doc, field) {
            Some(serde_json::Value::Number(n)) => n
                .as_f64()
                .map(|f| (f - num).abs() < f64::EPSILON)
                .unwrap_or(false),
            _ => false,
        };
    }

    // Unknown value format, conservative fallback
    true
}

/// Evaluate field STARTS WITH 'prefix' pattern
fn evaluate_starts_with(doc: &Document, field: &str, value: &str) -> bool {
    let prefix = match extract_string_literal(value) {
        Some(v) => v,
        None => return true, // Conservative fallback
    };

    match doc.get(field) {
        Some(serde_json::Value::String(s)) => s.starts_with(prefix),
        _ => false,
    }
}

/// Evaluate field ENDS WITH 'suffix' pattern
fn evaluate_ends_with(doc: &Document, field: &str, value: &str) -> bool {
    let suffix = match extract_string_literal(value) {
        Some(v) => v,
        None => return true, // Conservative fallback
    };

    match doc.get(field) {
        Some(serde_json::Value::String(s)) => s.ends_with(suffix),
        _ => false,
    }
}

// ============================================================================
// Issue #520: Extended DQL patterns for full syntactic parity
// ============================================================================

/// Parse inequality expression: `field != 'value'` or `field != true/false`
fn parse_inequality(expr: &str) -> Option<(&str, &str)> {
    // Look for != operator
    if let Some(idx) = expr.find("!=") {
        let field = expr[..idx].trim();
        let value = expr[idx + 2..].trim();
        // Make sure this isn't part of == (shouldn't happen, but be safe)
        if !field.is_empty() && !value.is_empty() {
            return Some((field, value));
        }
    }
    None
}

/// Parse NOT expression: `NOT (expr)` or `NOT expr`
fn parse_not_expression(expr: &str) -> Option<&str> {
    let upper = expr.to_uppercase();
    if upper.starts_with("NOT ") {
        let rest = expr[4..].trim();
        // If wrapped in parens, strip them
        if rest.starts_with('(') && rest.ends_with(')') {
            Some(&rest[1..rest.len() - 1])
        } else {
            Some(rest)
        }
    } else {
        None
    }
}

/// Parse IS NULL / IS NOT NULL expression
fn parse_is_null(expr: &str) -> Option<(&str, bool)> {
    let upper = expr.to_uppercase();
    if let Some(idx) = upper.find(" IS NOT NULL") {
        let field = expr[..idx].trim();
        return Some((field, false)); // is_null = false means IS NOT NULL
    }
    if let Some(idx) = upper.find(" IS NULL") {
        let field = expr[..idx].trim();
        return Some((field, true)); // is_null = true means IS NULL
    }
    None
}

/// Evaluate IS NULL / IS NOT NULL pattern
fn evaluate_is_null(doc: &Document, field: &str, is_null: bool) -> bool {
    let field_value = get_nested_field(doc, field);
    let value_is_null = field_value.is_none() || field_value == Some(&serde_json::Value::Null);
    if is_null {
        value_is_null
    } else {
        !value_is_null
    }
}

/// Parse LIKE expression: `field LIKE '%pattern%'`
fn parse_like(expr: &str) -> Option<(&str, &str)> {
    let upper = expr.to_uppercase();
    if let Some(idx) = upper.find(" LIKE ") {
        let field = expr[..idx].trim();
        let pattern = expr[idx + 6..].trim(); // " LIKE " is 6 chars
        Some((field, pattern))
    } else {
        None
    }
}

/// Evaluate LIKE pattern with % wildcards
fn evaluate_like(doc: &Document, field: &str, pattern: &str) -> bool {
    let pattern_str = match extract_string_literal(pattern) {
        Some(v) => v,
        None => return true, // Conservative fallback
    };

    let field_value = match get_nested_field(doc, field) {
        Some(serde_json::Value::String(s)) => s.as_str(),
        _ => return false,
    };

    // Convert SQL LIKE pattern to simple matching
    // % matches any sequence of characters
    // _ matches any single character (not implemented for simplicity)
    match_like_pattern(field_value, pattern_str)
}

/// Match a value against a SQL LIKE pattern with % wildcards
fn match_like_pattern(value: &str, pattern: &str) -> bool {
    // Split pattern by % and match segments
    let segments: Vec<&str> = pattern.split('%').collect();

    if segments.is_empty() {
        return true;
    }

    // Handle patterns like '%', '%%', etc.
    if segments.iter().all(|s| s.is_empty()) {
        return true;
    }

    let mut pos = 0;
    let starts_with_wildcard = pattern.starts_with('%');
    let ends_with_wildcard = pattern.ends_with('%');

    for (i, segment) in segments.iter().enumerate() {
        if segment.is_empty() {
            continue;
        }

        if i == 0 && !starts_with_wildcard {
            // First segment must match at start
            if !value.starts_with(segment) {
                return false;
            }
            pos = segment.len();
        } else if i == segments.len() - 1 && !ends_with_wildcard {
            // Last segment must match at end
            if !value.ends_with(segment) {
                return false;
            }
        } else {
            // Middle segment - find it anywhere after current position
            if let Some(found_pos) = value[pos..].find(segment) {
                pos += found_pos + segment.len();
            } else {
                return false;
            }
        }
    }

    true
}

/// Parse IN expression: `field IN ['a', 'b', 'c']`
fn parse_in(expr: &str) -> Option<(&str, Vec<String>)> {
    let upper = expr.to_uppercase();
    if let Some(idx) = upper.find(" IN ") {
        let field = expr[..idx].trim();
        let values_str = expr[idx + 4..].trim(); // " IN " is 4 chars

        // Parse the array: ['a', 'b', 'c'] or [1, 2, 3]
        if values_str.starts_with('[') && values_str.ends_with(']') {
            let inner = &values_str[1..values_str.len() - 1];
            let values: Vec<String> = inner
                .split(',')
                .map(|v| {
                    let trimmed = v.trim();
                    // Extract string literal or use as-is for numbers
                    if let Some(s) = extract_string_literal(trimmed) {
                        s.to_string()
                    } else {
                        trimmed.to_string()
                    }
                })
                .collect();
            return Some((field, values));
        }
    }
    None
}

/// Evaluate IN pattern for set membership
fn evaluate_in(doc: &Document, field: &str, values: &[String]) -> bool {
    let field_value = match get_nested_field(doc, field) {
        Some(v) => v,
        None => return false,
    };

    match field_value {
        serde_json::Value::String(s) => values.iter().any(|v| v == s),
        serde_json::Value::Number(n) => {
            if let Some(i) = n.as_i64() {
                values.iter().any(|v| v.parse::<i64>().ok() == Some(i))
            } else if let Some(f) = n.as_f64() {
                values.iter().any(|v| {
                    v.parse::<f64>()
                        .ok()
                        .map(|vf| (vf - f).abs() < f64::EPSILON)
                        == Some(true)
                })
            } else {
                false
            }
        }
        serde_json::Value::Bool(b) => {
            let bool_str = if *b { "true" } else { "false" };
            values.iter().any(|v| v == bool_str)
        }
        _ => false,
    }
}

/// Get a potentially nested field value from a document
/// Supports both simple fields ("name") and nested paths ("address.city")
fn get_nested_field<'a>(doc: &'a Document, field: &str) -> Option<&'a serde_json::Value> {
    if !field.contains('.') {
        // Simple field access
        return doc.get(field);
    }

    // Nested field access: field.subfield.subsubfield
    let parts: Vec<&str> = field.split('.').collect();
    let mut current = doc.get(parts[0])?;

    for part in &parts[1..] {
        match current {
            serde_json::Value::Object(obj) => {
                current = obj.get(*part)?;
            }
            _ => return None,
        }
    }

    Some(current)
}

// Helper function for query matching
fn matches_query(doc: &Document, query: &Query) -> bool {
    match query {
        Query::All => true,
        Query::Eq { field, value } => {
            // Special case for "id" field - check doc.id instead of doc.fields
            if field == "id" {
                if let Some(ref doc_id) = doc.id {
                    if let Some(value_str) = value.as_str() {
                        return doc_id == value_str;
                    }
                }
                return false;
            }
            doc.get(field) == Some(value)
        }
        Query::Lt { field, value } => {
            if let Some(doc_val) = doc.get(field) {
                compare_values(doc_val, value) < 0
            } else {
                false
            }
        }
        Query::Gt { field, value } => {
            if let Some(doc_val) = doc.get(field) {
                compare_values(doc_val, value) > 0
            } else {
                false
            }
        }
        Query::And(queries) => queries.iter().all(|q| matches_query(doc, q)),
        Query::Or(queries) => queries.iter().any(|q| matches_query(doc, q)),

        // === Custom query support (Issue #517) ===
        // Evaluate DQL-like custom queries using pattern-based parser
        Query::Custom(query_str) => evaluate_custom_query(doc, query_str),

        // === Spatial queries (Issue #356) ===
        Query::WithinRadius {
            center,
            radius_meters,
            lat_field,
            lon_field,
        } => {
            let lat_key = lat_field.as_deref().unwrap_or("lat");
            let lon_key = lon_field.as_deref().unwrap_or("lon");

            if let (Some(lat_val), Some(lon_val)) = (
                doc.get(lat_key).and_then(|v| v.as_f64()),
                doc.get(lon_key).and_then(|v| v.as_f64()),
            ) {
                let doc_point = GeoPoint::new(lat_val, lon_val);
                doc_point.within_radius(center, *radius_meters)
            } else {
                false
            }
        }

        Query::WithinBounds {
            min,
            max,
            lat_field,
            lon_field,
        } => {
            let lat_key = lat_field.as_deref().unwrap_or("lat");
            let lon_key = lon_field.as_deref().unwrap_or("lon");

            if let (Some(lat_val), Some(lon_val)) = (
                doc.get(lat_key).and_then(|v| v.as_f64()),
                doc.get(lon_key).and_then(|v| v.as_f64()),
            ) {
                let doc_point = GeoPoint::new(lat_val, lon_val);
                doc_point.within_bounds(min, max)
            } else {
                false
            }
        }

        // === Negation query (Issue #357) ===
        Query::Not(inner) => !matches_query(doc, inner),

        // === Deletion-aware queries (ADR-034, Issue #369) ===
        Query::IncludeDeleted(inner) => {
            // IncludeDeleted wraps another query - run the inner query
            // The soft-delete filter bypass is handled at the query() method level
            matches_query(doc, inner)
        }

        Query::DeletedOnly => {
            // Only match documents with _deleted=true
            doc.fields
                .get("_deleted")
                .and_then(|v| v.as_bool())
                .unwrap_or(false)
        }
    }
}

fn compare_values(a: &serde_json::Value, b: &serde_json::Value) -> i32 {
    use serde_json::Value as V;

    match (a, b) {
        (V::Number(n1), V::Number(n2)) => {
            if let (Some(f1), Some(f2)) = (n1.as_f64(), n2.as_f64()) {
                if f1 < f2 {
                    -1
                } else if f1 > f2 {
                    1
                } else {
                    0
                }
            } else {
                0
            }
        }
        (V::String(s1), V::String(s2)) => s1.cmp(s2) as i32,
        _ => 0,
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use std::collections::HashMap;
    use std::path::PathBuf;

    /// Helper: Create test BackendConfig with valid credentials
    fn test_config() -> BackendConfig {
        // Generate a valid test secret key (base64-encoded 32 bytes)
        let test_secret = crate::security::FormationKey::generate_secret();
        BackendConfig {
            app_id: "test_app".to_string(),
            persistence_dir: PathBuf::from("/tmp/automerge_test"),
            shared_key: Some(test_secret),
            transport: TransportConfig::default(),
            extra: HashMap::new(),
        }
    }

    #[tokio::test]
    async fn test_automerge_backend_creation() {
        let backend = AutomergeBackend::new();
        assert!(!backend.is_ready().await);
    }

    #[tokio::test]
    async fn test_document_upsert() {
        let backend = AutomergeBackend::new();
        backend.initialize(test_config()).await.unwrap();

        let mut fields = HashMap::new();
        fields.insert("name".to_string(), serde_json::json!("test"));
        fields.insert("value".to_string(), serde_json::json!(42));

        let doc = Document::new(fields);
        let doc_id = backend
            .document_store()
            .upsert("test_collection", doc)
            .await
            .unwrap();

        assert!(!doc_id.is_empty());
    }

    #[tokio::test]
    async fn test_document_query() {
        let backend = AutomergeBackend::new();
        backend.initialize(test_config()).await.unwrap();

        // Insert test document
        let mut fields = HashMap::new();
        fields.insert("status".to_string(), serde_json::json!("active"));
        let doc = Document::new(fields);
        backend
            .document_store()
            .upsert("test_collection", doc)
            .await
            .unwrap();

        // Query
        let query = Query::Eq {
            field: "status".to_string(),
            value: serde_json::json!("active"),
        };

        let results = backend
            .document_store()
            .query("test_collection", &query)
            .await
            .unwrap();

        assert_eq!(results.len(), 1);
    }

    #[tokio::test]
    async fn test_document_get() {
        let backend = AutomergeBackend::new();
        backend.initialize(test_config()).await.unwrap();

        // Insert document
        let mut fields = HashMap::new();
        fields.insert("data".to_string(), serde_json::json!("test_value"));
        let doc = Document::new(fields);
        let doc_id = backend
            .document_store()
            .upsert("test_coll", doc)
            .await
            .unwrap();

        // Get document
        let retrieved = backend
            .document_store()
            .get("test_coll", &doc_id)
            .await
            .unwrap();

        assert!(retrieved.is_some());
        let retrieved_doc = retrieved.unwrap();
        assert_eq!(
            retrieved_doc.fields.get("data").unwrap(),
            &serde_json::json!("test_value")
        );
    }

    #[tokio::test]
    async fn test_document_remove() {
        let backend = AutomergeBackend::new();
        backend.initialize(test_config()).await.unwrap();

        // Insert document
        let mut fields = HashMap::new();
        fields.insert("temp".to_string(), serde_json::json!(true));
        let doc = Document::new(fields);
        let doc_id = backend
            .document_store()
            .upsert("temp_coll", doc)
            .await
            .unwrap();

        // Remove document
        backend
            .document_store()
            .remove("temp_coll", &doc_id)
            .await
            .unwrap();

        // Verify removed
        let retrieved = backend
            .document_store()
            .get("temp_coll", &doc_id)
            .await
            .unwrap();

        assert!(retrieved.is_none());
    }
}

/// Tests for AutomergeIrohBackend credential requirements
#[cfg(all(test, feature = "automerge-backend"))]
mod iroh_credential_tests {
    use super::*;
    use std::collections::HashMap;
    use std::path::PathBuf;

    /// Test that AutomergeIrohBackend initialization fails without shared_key
    #[tokio::test]
    async fn test_automerge_iroh_requires_credentials() {
        // Create backend components
        let temp_dir = tempfile::tempdir().unwrap();
        let store = Arc::new(crate::storage::AutomergeStore::open(temp_dir.path()).unwrap());
        let transport = Arc::new(crate::network::IrohTransport::new().await.unwrap());

        let backend = AutomergeIrohBackend::from_parts(store, transport);

        // Config without shared_key should fail
        let config = BackendConfig {
            app_id: "test_app".to_string(),
            persistence_dir: PathBuf::from("/tmp/test"),
            shared_key: None, // Missing!
            transport: TransportConfig::default(),
            extra: HashMap::new(),
        };

        let result = backend.initialize(config).await;
        assert!(result.is_err());

        let error = result.unwrap_err();
        let error_msg = error.to_string();
        assert!(
            error_msg.contains("PEAT_SECRET_KEY") || error_msg.contains("shared_key"),
            "Error should mention missing credentials: {}",
            error_msg
        );
    }

    /// Test that AutomergeIrohBackend initializes successfully with valid credentials
    #[tokio::test]
    async fn test_automerge_iroh_with_valid_credentials() {
        // Create backend components
        let temp_dir = tempfile::tempdir().unwrap();
        let store = Arc::new(crate::storage::AutomergeStore::open(temp_dir.path()).unwrap());
        let transport = Arc::new(crate::network::IrohTransport::new().await.unwrap());

        let backend = AutomergeIrohBackend::from_parts(store, transport);

        // Generate valid test credentials
        let test_secret = crate::security::FormationKey::generate_secret();

        let config = BackendConfig {
            app_id: "test_formation".to_string(),
            persistence_dir: temp_dir.path().to_path_buf(),
            shared_key: Some(test_secret),
            transport: TransportConfig::default(),
            extra: HashMap::new(),
        };

        let result = backend.initialize(config).await;
        assert!(result.is_ok(), "Should initialize with valid credentials");

        // Verify formation key was stored
        let formation_key = backend.formation_key();
        assert!(
            formation_key.is_some(),
            "Formation key should be set after initialization"
        );
        assert_eq!(
            formation_key.unwrap().formation_id(),
            "test_formation",
            "Formation ID should match app_id"
        );
    }

    /// Test that invalid shared_key format is rejected
    #[tokio::test]
    async fn test_automerge_iroh_rejects_invalid_key_format() {
        // Create backend components
        let temp_dir = tempfile::tempdir().unwrap();
        let store = Arc::new(crate::storage::AutomergeStore::open(temp_dir.path()).unwrap());
        let transport = Arc::new(crate::network::IrohTransport::new().await.unwrap());

        let backend = AutomergeIrohBackend::from_parts(store, transport);

        // Invalid base64 key
        let config = BackendConfig {
            app_id: "test_app".to_string(),
            persistence_dir: PathBuf::from("/tmp/test"),
            shared_key: Some("not-valid-base64!!!".to_string()),
            transport: TransportConfig::default(),
            extra: HashMap::new(),
        };

        let result = backend.initialize(config).await;
        assert!(result.is_err(), "Should reject invalid base64 key");

        let error_msg = result.unwrap_err().to_string();
        assert!(
            error_msg.contains("Invalid shared_key format"),
            "Error should mention invalid format: {}",
            error_msg
        );
    }
}

/// Tests for Issue #271: Verify Clone correctly shares transport instance
#[cfg(all(test, feature = "automerge-backend"))]
mod issue_271_clone_tests {
    use super::*;

    /// Test that cloning AutomergeIrohBackend shares the same transport Arc
    ///
    /// Issue #271: When cloning AutomergeIrohBackend, the transport should be
    /// shared (same Arc pointer), not duplicated. This ensures connections
    /// accumulate correctly across all references to the backend.
    #[tokio::test]
    async fn test_clone_shares_transport_arc() {
        // Create backend components
        let temp_dir = tempfile::tempdir().unwrap();
        let store = Arc::new(crate::storage::AutomergeStore::open(temp_dir.path()).unwrap());
        let transport = Arc::new(crate::network::IrohTransport::new().await.unwrap());

        let original = AutomergeIrohBackend::from_parts(store, Arc::clone(&transport));
        let cloned = original.clone();

        // Verify transport Arc is shared (same pointer)
        let original_transport_ptr = Arc::as_ptr(&original.transport());
        let cloned_transport_ptr = Arc::as_ptr(&cloned.transport());

        assert_eq!(
            original_transport_ptr, cloned_transport_ptr,
            "Clone should share the same transport Arc, but got different pointers:\n  Original: {:?}\n  Clone: {:?}",
            original_transport_ptr, cloned_transport_ptr
        );

        // Verify both point to the same transport as the original Arc
        let source_transport_ptr = Arc::as_ptr(&transport);
        assert_eq!(
            original_transport_ptr, source_transport_ptr,
            "Original backend transport should be same as source transport Arc"
        );
    }

    /// Test that cloning AutomergeIrohBackend shares the same backend Arc
    #[tokio::test]
    async fn test_clone_shares_backend_arc() {
        let temp_dir = tempfile::tempdir().unwrap();
        let store = Arc::new(crate::storage::AutomergeStore::open(temp_dir.path()).unwrap());
        let transport = Arc::new(crate::network::IrohTransport::new().await.unwrap());

        let original = AutomergeIrohBackend::from_parts(store, transport);
        let cloned = original.clone();

        // Verify backend Arc is shared (same pointer)
        // We need to access the internal backend field - using a helper method
        // Since backend is private, we verify via behavior: both should see same endpoint_id
        assert_eq!(
            original.endpoint_id(),
            cloned.endpoint_id(),
            "Clone should have same endpoint_id as original"
        );
    }

    /// Test that transport peer_count is consistent across clone
    ///
    /// This verifies that if connections are managed via one reference,
    /// they are visible via the clone (because they share the same transport).
    #[tokio::test]
    async fn test_clone_shares_peer_count() {
        let temp_dir = tempfile::tempdir().unwrap();
        let store = Arc::new(crate::storage::AutomergeStore::open(temp_dir.path()).unwrap());
        let transport = Arc::new(crate::network::IrohTransport::new().await.unwrap());

        let original = AutomergeIrohBackend::from_parts(store, Arc::clone(&transport));
        let cloned = original.clone();

        // Both should report the same peer count (0 initially)
        let original_count = original.transport().peer_count();
        let cloned_count = cloned.transport().peer_count();

        assert_eq!(
            original_count, cloned_count,
            "Original and clone should report same peer_count"
        );
        assert_eq!(original_count, 0, "Initial peer count should be 0");

        // Verify via source transport as well
        assert_eq!(
            transport.peer_count(),
            original_count,
            "Source transport should have same count"
        );
    }

    /// Test that formation_key is shared across clone
    #[tokio::test]
    async fn test_clone_shares_formation_key() {
        let temp_dir = tempfile::tempdir().unwrap();
        let store = Arc::new(crate::storage::AutomergeStore::open(temp_dir.path()).unwrap());
        let transport = Arc::new(crate::network::IrohTransport::new().await.unwrap());

        let original = AutomergeIrohBackend::from_parts(store, transport);

        // Initialize with credentials
        let test_secret = crate::security::FormationKey::generate_secret();
        let config = BackendConfig {
            app_id: "test_formation".to_string(),
            persistence_dir: temp_dir.path().to_path_buf(),
            shared_key: Some(test_secret),
            transport: TransportConfig::default(),
            extra: std::collections::HashMap::new(),
        };
        original.initialize(config).await.unwrap();

        // Clone after initialization
        let cloned = original.clone();

        // Both should see the formation key
        let original_key = original.formation_key();
        let cloned_key = cloned.formation_key();

        assert!(original_key.is_some(), "Original should have formation key");
        assert!(cloned_key.is_some(), "Clone should have formation key");
        assert_eq!(
            original_key.as_ref().map(|k| k.formation_id()),
            cloned_key.as_ref().map(|k| k.formation_id()),
            "Clone should share same formation key"
        );
    }

    /// Test that initialized state is shared across clone
    #[tokio::test]
    async fn test_clone_shares_initialized_state() {
        let temp_dir = tempfile::tempdir().unwrap();
        let store = Arc::new(crate::storage::AutomergeStore::open(temp_dir.path()).unwrap());
        let transport = Arc::new(crate::network::IrohTransport::new().await.unwrap());

        let original = AutomergeIrohBackend::from_parts(store, transport);

        // Before initialization
        let cloned_before = original.clone();
        assert!(
            !original.is_ready().await,
            "Original should not be ready before init"
        );
        assert!(
            !cloned_before.is_ready().await,
            "Clone should not be ready before init"
        );

        // Initialize original
        let test_secret = crate::security::FormationKey::generate_secret();
        let config = BackendConfig {
            app_id: "test_formation".to_string(),
            persistence_dir: temp_dir.path().to_path_buf(),
            shared_key: Some(test_secret),
            transport: TransportConfig::default(),
            extra: std::collections::HashMap::new(),
        };
        original.initialize(config).await.unwrap();

        // Clone created before init should NOW see it as ready
        // (because initialized flag is in shared Arc<Mutex<bool>>)
        assert!(
            original.is_ready().await,
            "Original should be ready after init"
        );
        assert!(
            cloned_before.is_ready().await,
            "Clone (created before init) should also be ready, proving Arc is shared"
        );
    }

    // === Deletion Tests (ADR-034) ===

    fn deletion_test_config() -> BackendConfig {
        let test_secret = crate::security::FormationKey::generate_secret();
        BackendConfig {
            app_id: "deletion_test".to_string(),
            persistence_dir: std::path::PathBuf::from("/tmp/deletion_test"),
            shared_key: Some(test_secret),
            transport: TransportConfig::default(),
            extra: HashMap::new(),
        }
    }

    #[tokio::test]
    async fn test_soft_delete() {
        let backend = AutomergeBackend::new();
        backend.initialize(deletion_test_config()).await.unwrap();

        // Insert document
        let mut fields = HashMap::new();
        fields.insert("data".to_string(), serde_json::json!("test_value"));
        let doc = Document::new(fields);
        let doc_id = backend
            .document_store()
            .upsert("test_collection", doc)
            .await
            .unwrap();

        // Verify document exists
        let retrieved = backend
            .document_store()
            .get("test_collection", &doc_id)
            .await
            .unwrap();
        assert!(retrieved.is_some());
        assert!(!backend
            .document_store()
            .is_deleted("test_collection", &doc_id)
            .await
            .unwrap());

        // Delete (default policy is SoftDelete)
        let result = backend
            .document_store()
            .delete("test_collection", &doc_id, Some("test deletion"))
            .await
            .unwrap();
        assert!(result.deleted);

        // Document should now be marked as deleted
        assert!(backend
            .document_store()
            .is_deleted("test_collection", &doc_id)
            .await
            .unwrap());

        // Document should still exist (soft delete preserves it)
        let deleted_doc = backend
            .document_store()
            .get("test_collection", &doc_id)
            .await
            .unwrap();
        assert!(deleted_doc.is_some());
        let deleted_doc = deleted_doc.unwrap();
        assert_eq!(
            deleted_doc.fields.get("_deleted"),
            Some(&serde_json::json!(true))
        );
        assert!(deleted_doc.fields.contains_key("_deleted_at"));
        assert_eq!(
            deleted_doc.fields.get("_deleted_reason"),
            Some(&serde_json::json!("test deletion"))
        );
    }

    #[tokio::test]
    async fn test_tombstone_delete() {
        let backend = AutomergeBackend::new();
        backend.initialize(deletion_test_config()).await.unwrap();

        // Configure tombstone policy for this collection
        backend.deletion_policy_registry.set(
            "tombstone_collection",
            crate::qos::DeletionPolicy::Tombstone {
                tombstone_ttl: std::time::Duration::from_secs(3600),
                delete_wins: true,
            },
        );

        // Insert document
        let mut fields = HashMap::new();
        fields.insert("data".to_string(), serde_json::json!("tombstone_test"));
        let doc = Document::new(fields);
        let doc_id = backend
            .document_store()
            .upsert("tombstone_collection", doc)
            .await
            .unwrap();

        // Delete with tombstone policy
        let result = backend
            .document_store()
            .delete("tombstone_collection", &doc_id, Some("removed"))
            .await
            .unwrap();
        assert!(result.deleted);
        assert!(result.tombstone_id.is_some());
        assert!(result.expires_at.is_some());

        // Document should be deleted
        assert!(backend
            .document_store()
            .is_deleted("tombstone_collection", &doc_id)
            .await
            .unwrap());

        // Document should be removed (not just marked)
        let removed_doc = backend
            .document_store()
            .get("tombstone_collection", &doc_id)
            .await
            .unwrap();
        assert!(removed_doc.is_none());

        // Tombstone should exist with real node ID and lamport (Issue #668)
        let tombstones = backend
            .document_store()
            .get_tombstones("tombstone_collection")
            .await
            .unwrap();
        assert_eq!(tombstones.len(), 1);
        assert_eq!(tombstones[0].document_id, doc_id);
        assert_eq!(tombstones[0].reason, Some("removed".to_string()));
        // After initialize(), node_id should be app_id from config
        assert_eq!(tombstones[0].deleted_by, "deletion_test");
        // First delete should get lamport=0
        assert_eq!(tombstones[0].lamport, 0);
    }

    #[tokio::test]
    async fn test_deletion_policy() {
        let backend = AutomergeBackend::new();

        // Default policy is SoftDelete
        let policy = backend
            .document_store()
            .deletion_policy("unknown_collection");
        assert!(matches!(
            policy,
            crate::qos::DeletionPolicy::SoftDelete { .. }
        ));

        // Verify default policies for known collections
        assert!(matches!(
            backend.document_store().deletion_policy("beacons"),
            crate::qos::DeletionPolicy::ImplicitTTL { .. }
        ));
        assert!(matches!(
            backend.document_store().deletion_policy("nodes"),
            crate::qos::DeletionPolicy::Tombstone { .. }
        ));
        assert!(matches!(
            backend.document_store().deletion_policy("contact_reports"),
            crate::qos::DeletionPolicy::SoftDelete { .. }
        ));
    }

    #[tokio::test]
    async fn test_apply_tombstone() {
        let backend = AutomergeBackend::new();
        backend.initialize(deletion_test_config()).await.unwrap();

        // Insert document
        let mut fields = HashMap::new();
        fields.insert("data".to_string(), serde_json::json!("to_be_deleted"));
        let doc = Document::new(fields);
        let doc_id = backend
            .document_store()
            .upsert("sync_test", doc)
            .await
            .unwrap();

        // Create a tombstone (simulating receiving from sync)
        let tombstone = crate::qos::Tombstone::with_reason(
            doc_id.clone(),
            "sync_test".to_string(),
            "remote_node".to_string(),
            1, // Lamport timestamp
            "synced deletion",
        );

        // Apply tombstone
        backend
            .document_store()
            .apply_tombstone(&tombstone)
            .await
            .unwrap();

        // Document should be deleted
        assert!(backend
            .document_store()
            .is_deleted("sync_test", &doc_id)
            .await
            .unwrap());

        // Document should be removed
        let removed_doc = backend
            .document_store()
            .get("sync_test", &doc_id)
            .await
            .unwrap();
        assert!(removed_doc.is_none());
    }

    // === Issue #668: Lamport, Node ID, Pending Tombstones, GC Tests ===

    #[tokio::test]
    async fn test_delete_increments_lamport() {
        let backend = AutomergeBackend::new();
        backend.initialize(deletion_test_config()).await.unwrap();
        backend.deletion_policy_registry.set(
            "nodes",
            crate::qos::DeletionPolicy::Tombstone {
                tombstone_ttl: std::time::Duration::from_secs(3600),
                delete_wins: true,
            },
        );

        // Insert two documents
        let doc1 = Document::new(HashMap::from([("x".to_string(), serde_json::json!(1))]));
        let doc2 = Document::new(HashMap::from([("x".to_string(), serde_json::json!(2))]));
        let id1 = backend
            .document_store()
            .upsert("nodes", doc1)
            .await
            .unwrap();
        let id2 = backend
            .document_store()
            .upsert("nodes", doc2)
            .await
            .unwrap();

        // Delete both
        backend
            .document_store()
            .delete("nodes", &id1, None)
            .await
            .unwrap();
        backend
            .document_store()
            .delete("nodes", &id2, None)
            .await
            .unwrap();

        // Verify monotonic lamport
        let tombstones = backend
            .document_store()
            .get_tombstones("nodes")
            .await
            .unwrap();
        assert_eq!(tombstones.len(), 2);
        let lamports: Vec<u64> = tombstones.iter().map(|t| t.lamport).collect();
        assert!(
            lamports.contains(&0) && lamports.contains(&1),
            "Expected lamport 0 and 1, got {:?}",
            lamports
        );
    }

    #[tokio::test]
    async fn test_delete_uses_config_node_id() {
        let backend = AutomergeBackend::new();

        // Before initialization, node_id falls back to "local"
        backend.deletion_policy_registry.set(
            "test_coll",
            crate::qos::DeletionPolicy::Tombstone {
                tombstone_ttl: std::time::Duration::from_secs(3600),
                delete_wins: true,
            },
        );
        let doc = Document::new(HashMap::from([("x".to_string(), serde_json::json!(1))]));
        let id = backend
            .document_store()
            .upsert("test_coll", doc)
            .await
            .unwrap();
        backend
            .document_store()
            .delete("test_coll", &id, None)
            .await
            .unwrap();
        let tombstones = backend
            .document_store()
            .get_tombstones("test_coll")
            .await
            .unwrap();
        assert_eq!(tombstones[0].deleted_by, "local");

        // After initialization, node_id should be app_id
        let backend2 = AutomergeBackend::new();
        backend2.initialize(deletion_test_config()).await.unwrap();
        backend2.deletion_policy_registry.set(
            "test_coll",
            crate::qos::DeletionPolicy::Tombstone {
                tombstone_ttl: std::time::Duration::from_secs(3600),
                delete_wins: true,
            },
        );
        let doc = Document::new(HashMap::from([("x".to_string(), serde_json::json!(2))]));
        let id2 = backend2
            .document_store()
            .upsert("test_coll", doc)
            .await
            .unwrap();
        backend2
            .document_store()
            .delete("test_coll", &id2, None)
            .await
            .unwrap();
        let tombstones2 = backend2
            .document_store()
            .get_tombstones("test_coll")
            .await
            .unwrap();
        assert_eq!(tombstones2[0].deleted_by, "deletion_test");
    }

    #[tokio::test]
    async fn test_drain_pending_tombstones() {
        let backend = AutomergeBackend::new();
        backend.initialize(deletion_test_config()).await.unwrap();
        backend.deletion_policy_registry.set(
            "nodes",
            crate::qos::DeletionPolicy::Tombstone {
                tombstone_ttl: std::time::Duration::from_secs(3600),
                delete_wins: true,
            },
        );

        // Initially empty
        assert!(backend.drain_pending_tombstones().is_empty());

        // Insert and delete
        let doc = Document::new(HashMap::from([("x".to_string(), serde_json::json!(1))]));
        let id = backend.document_store().upsert("nodes", doc).await.unwrap();
        backend
            .document_store()
            .delete("nodes", &id, Some("test"))
            .await
            .unwrap();

        // Should have one pending tombstone
        let pending = backend.drain_pending_tombstones();
        assert_eq!(pending.len(), 1);
        assert_eq!(pending[0].tombstone.document_id, id);
        assert_eq!(pending[0].tombstone.collection, "nodes");

        // After drain, should be empty again
        assert!(backend.drain_pending_tombstones().is_empty());
    }

    #[tokio::test]
    async fn test_gc_starts_on_init() {
        let backend = AutomergeBackend::new();
        // Before init, no GC handle
        assert!(backend.gc_handle.lock().unwrap().is_none());

        backend.initialize(deletion_test_config()).await.unwrap();
        // After init, GC handle should exist
        assert!(backend.gc_handle.lock().unwrap().is_some());

        // Shutdown should clear it
        backend.shutdown().await.unwrap();
        assert!(backend.gc_handle.lock().unwrap().is_none());
    }

    #[tokio::test]
    async fn test_gc_store_impl() {
        use crate::qos::GcStore;

        let backend = AutomergeBackend::new();
        backend.initialize(deletion_test_config()).await.unwrap();
        backend.deletion_policy_registry.set(
            "nodes",
            crate::qos::DeletionPolicy::Tombstone {
                tombstone_ttl: std::time::Duration::from_secs(3600),
                delete_wins: true,
            },
        );

        // Insert, delete, create tombstone
        let doc = Document::new(HashMap::from([("x".to_string(), serde_json::json!(1))]));
        let id = backend.document_store().upsert("nodes", doc).await.unwrap();
        backend
            .document_store()
            .delete("nodes", &id, None)
            .await
            .unwrap();

        // GcStore methods should work
        assert!(backend.has_tombstone("nodes", &id).unwrap());
        assert_eq!(backend.get_all_tombstones().unwrap().len(), 1);

        // Remove tombstone
        assert!(backend.remove_tombstone("nodes", &id).unwrap());
        assert!(!backend.has_tombstone("nodes", &id).unwrap());
        assert_eq!(backend.get_all_tombstones().unwrap().len(), 0);

        // list_collections
        let collections = backend.list_collections().unwrap();
        // May be empty since we deleted the only doc; that's OK
        assert!(collections.is_empty() || collections.contains(&"nodes".to_string()));
    }

    // ============================================================================
    // Issue #517: Query::Custom Parser Tests
    // ============================================================================

    /// Helper: Create a test document with given fields
    fn create_test_doc(fields: Vec<(&str, serde_json::Value)>) -> Document {
        let mut field_map = HashMap::new();
        for (key, value) in fields {
            field_map.insert(key.to_string(), value);
        }
        Document::new(field_map)
    }

    #[test]
    fn test_custom_query_equality_string() {
        // Test: collection_name == 'squad_summaries'
        let doc = create_test_doc(vec![(
            "collection_name",
            serde_json::json!("squad_summaries"),
        )]);

        assert!(evaluate_custom_query(
            &doc,
            "collection_name == 'squad_summaries'"
        ));
        assert!(!evaluate_custom_query(&doc, "collection_name == 'other'"));
    }

    #[test]
    fn test_custom_query_equality_boolean() {
        // Test: public == true / public == false
        let doc_public = create_test_doc(vec![("public", serde_json::json!(true))]);
        let doc_private = create_test_doc(vec![("public", serde_json::json!(false))]);

        assert!(evaluate_custom_query(&doc_public, "public == true"));
        assert!(!evaluate_custom_query(&doc_public, "public == false"));
        assert!(evaluate_custom_query(&doc_private, "public == false"));
        assert!(!evaluate_custom_query(&doc_private, "public == true"));
    }

    #[test]
    fn test_custom_query_starts_with() {
        // Test: collection_name STARTS WITH 'squad-'
        let doc = create_test_doc(vec![("collection_name", serde_json::json!("squad-alpha"))]);

        assert!(evaluate_custom_query(
            &doc,
            "collection_name STARTS WITH 'squad-'"
        ));
        assert!(evaluate_custom_query(
            &doc,
            "collection_name starts with 'squad-'"
        )); // Case insensitive
        assert!(!evaluate_custom_query(
            &doc,
            "collection_name STARTS WITH 'platoon-'"
        ));
    }

    #[test]
    fn test_custom_query_ends_with() {
        // Test: collection_name ENDS WITH '.summaries'
        let doc = create_test_doc(vec![(
            "collection_name",
            serde_json::json!("squad.summaries"),
        )]);

        assert!(evaluate_custom_query(
            &doc,
            "collection_name ENDS WITH '.summaries'"
        ));
        assert!(evaluate_custom_query(
            &doc,
            "collection_name ends with '.summaries'"
        )); // Case insensitive
        assert!(!evaluate_custom_query(
            &doc,
            "collection_name ENDS WITH '.reports'"
        ));
    }

    #[test]
    fn test_custom_query_contains_array() {
        // Test: CONTAINS(authorized_roles, 'soldier')
        let doc = create_test_doc(vec![(
            "authorized_roles",
            serde_json::json!(["soldier", "squad_leader"]),
        )]);

        assert!(evaluate_custom_query(
            &doc,
            "CONTAINS(authorized_roles, 'soldier')"
        ));
        assert!(evaluate_custom_query(
            &doc,
            "CONTAINS(authorized_roles, 'squad_leader')"
        ));
        assert!(!evaluate_custom_query(
            &doc,
            "CONTAINS(authorized_roles, 'general')"
        ));
    }

    #[test]
    fn test_custom_query_contains_string() {
        // Test: CONTAINS on string field (substring search)
        let doc = create_test_doc(vec![(
            "description",
            serde_json::json!("This is a squad summary document"),
        )]);

        assert!(evaluate_custom_query(
            &doc,
            "CONTAINS(description, 'squad')"
        ));
        assert!(evaluate_custom_query(
            &doc,
            "CONTAINS(description, 'summary')"
        ));
        assert!(!evaluate_custom_query(
            &doc,
            "CONTAINS(description, 'platoon')"
        ));
    }

    #[test]
    fn test_custom_query_or_compound() {
        // Test: type == 'node_state' OR type == 'squad_summary'
        let doc_node = create_test_doc(vec![("type", serde_json::json!("node_state"))]);
        let doc_squad = create_test_doc(vec![("type", serde_json::json!("squad_summary"))]);
        let doc_other = create_test_doc(vec![("type", serde_json::json!("other"))]);

        let query = "type == 'node_state' OR type == 'squad_summary'";
        assert!(evaluate_custom_query(&doc_node, query));
        assert!(evaluate_custom_query(&doc_squad, query));
        assert!(!evaluate_custom_query(&doc_other, query));
    }

    #[test]
    fn test_custom_query_and_compound() {
        // Test: public == true AND type == 'node_state'
        let doc_match = create_test_doc(vec![
            ("public", serde_json::json!(true)),
            ("type", serde_json::json!("node_state")),
        ]);
        let doc_partial = create_test_doc(vec![
            ("public", serde_json::json!(true)),
            ("type", serde_json::json!("other")),
        ]);

        let query = "public == true AND type == 'node_state'";
        assert!(evaluate_custom_query(&doc_match, query));
        assert!(!evaluate_custom_query(&doc_partial, query));
    }

    #[test]
    fn test_custom_query_complex_compound() {
        // Test: (public == true OR CONTAINS(authorized_roles, 'soldier'))
        let doc_public = create_test_doc(vec![
            ("public", serde_json::json!(true)),
            ("authorized_roles", serde_json::json!([])),
        ]);
        let doc_soldier = create_test_doc(vec![
            ("public", serde_json::json!(false)),
            ("authorized_roles", serde_json::json!(["soldier"])),
        ]);
        let doc_neither = create_test_doc(vec![
            ("public", serde_json::json!(false)),
            ("authorized_roles", serde_json::json!(["general"])),
        ]);

        let query = "public == true OR CONTAINS(authorized_roles, 'soldier')";
        assert!(evaluate_custom_query(&doc_public, query));
        assert!(evaluate_custom_query(&doc_soldier, query));
        assert!(!evaluate_custom_query(&doc_neither, query));
    }

    #[test]
    fn test_custom_query_with_parentheses() {
        // Test: queries with parentheses are handled
        let doc = create_test_doc(vec![(
            "collection_name",
            serde_json::json!("squad_summaries"),
        )]);

        assert!(evaluate_custom_query(
            &doc,
            "(collection_name == 'squad_summaries')"
        ));
    }

    #[test]
    fn test_custom_query_unknown_pattern_returns_true() {
        // Test: Unknown patterns return true (conservative fallback)
        let doc = create_test_doc(vec![("field", serde_json::json!("value"))]);

        // These are patterns we don't recognize - should return true
        assert!(evaluate_custom_query(&doc, "SOME_UNKNOWN_FUNCTION(x, y)"));
        assert!(evaluate_custom_query(&doc, "field BETWEEN 1 AND 10")); // BETWEEN not implemented
        assert!(evaluate_custom_query(&doc, "field REGEXP '^test'")); // REGEXP not implemented
    }

    #[test]
    fn test_custom_query_matches_query_integration() {
        // Test that Query::Custom works through matches_query
        let doc = create_test_doc(vec![(
            "collection_name",
            serde_json::json!("squad_summaries"),
        )]);

        let query = Query::Custom("collection_name == 'squad_summaries'".to_string());
        assert!(matches_query(&doc, &query));

        let query_no_match = Query::Custom("collection_name == 'other'".to_string());
        assert!(!matches_query(&doc, &query_no_match));
    }

    #[test]
    fn test_custom_query_real_world_patterns() {
        // Test actual patterns from the Peat codebase

        // Pattern 1: collection_name == 'squad_summaries' (from peat-sim)
        let doc_summaries = create_test_doc(vec![(
            "collection_name",
            serde_json::json!("squad_summaries"),
        )]);
        assert!(evaluate_custom_query(
            &doc_summaries,
            "collection_name == 'squad_summaries'"
        ));

        // Pattern 2: collection_name STARTS WITH 'squad-1' OR type == 'node_state'
        let doc_squad = create_test_doc(vec![
            ("collection_name", serde_json::json!("squad-1-alpha")),
            ("type", serde_json::json!("other")),
        ]);
        let doc_node = create_test_doc(vec![
            ("collection_name", serde_json::json!("other")),
            ("type", serde_json::json!("node_state")),
        ]);
        let query = "collection_name STARTS WITH 'squad-1' OR type == 'node_state'";
        assert!(evaluate_custom_query(&doc_squad, query));
        assert!(evaluate_custom_query(&doc_node, query));

        // Pattern 3: collection_name ENDS WITH '.summaries' OR type == 'squad_summary'
        let doc_suffix = create_test_doc(vec![
            ("collection_name", serde_json::json!("platoon.summaries")),
            ("type", serde_json::json!("other")),
        ]);
        let query2 = "collection_name ENDS WITH '.summaries' OR type == 'squad_summary'";
        assert!(evaluate_custom_query(&doc_suffix, query2));

        // Pattern 4: public == true OR CONTAINS(authorized_roles, 'soldier')
        let doc_with_role = create_test_doc(vec![
            ("public", serde_json::json!(false)),
            ("authorized_roles", serde_json::json!(["soldier", "medic"])),
        ]);
        let query3 = "public == true OR CONTAINS(authorized_roles, 'soldier')";
        assert!(evaluate_custom_query(&doc_with_role, query3));
    }

    // ============================================================================
    // Issue #520: Extended DQL patterns for full syntactic parity
    // ============================================================================

    #[test]
    fn test_custom_query_inequality_string() {
        // Test: field != 'value'
        let doc = create_test_doc(vec![("status", serde_json::json!("active"))]);

        assert!(evaluate_custom_query(&doc, "status != 'inactive'"));
        assert!(!evaluate_custom_query(&doc, "status != 'active'"));
    }

    #[test]
    fn test_custom_query_inequality_boolean() {
        // Test: field != true/false
        let doc_active = create_test_doc(vec![("enabled", serde_json::json!(true))]);
        let doc_inactive = create_test_doc(vec![("enabled", serde_json::json!(false))]);

        assert!(evaluate_custom_query(&doc_active, "enabled != false"));
        assert!(!evaluate_custom_query(&doc_active, "enabled != true"));
        assert!(evaluate_custom_query(&doc_inactive, "enabled != true"));
        assert!(!evaluate_custom_query(&doc_inactive, "enabled != false"));
    }

    #[test]
    fn test_custom_query_inequality_numeric() {
        // Test: field != number
        let doc = create_test_doc(vec![("count", serde_json::json!(42))]);

        assert!(evaluate_custom_query(&doc, "count != 0"));
        assert!(evaluate_custom_query(&doc, "count != 100"));
        assert!(!evaluate_custom_query(&doc, "count != 42"));
    }

    #[test]
    fn test_custom_query_like_prefix() {
        // Test: field LIKE 'prefix%'
        let doc = create_test_doc(vec![("name", serde_json::json!("squad-alpha-1"))]);

        assert!(evaluate_custom_query(&doc, "name LIKE 'squad%'"));
        assert!(evaluate_custom_query(&doc, "name like 'squad%'")); // Case insensitive
        assert!(!evaluate_custom_query(&doc, "name LIKE 'platoon%'"));
    }

    #[test]
    fn test_custom_query_like_suffix() {
        // Test: field LIKE '%suffix'
        let doc = create_test_doc(vec![("filename", serde_json::json!("report.pdf"))]);

        assert!(evaluate_custom_query(&doc, "filename LIKE '%.pdf'"));
        assert!(!evaluate_custom_query(&doc, "filename LIKE '%.doc'"));
    }

    #[test]
    fn test_custom_query_like_contains() {
        // Test: field LIKE '%middle%'
        let doc = create_test_doc(vec![(
            "description",
            serde_json::json!("This is a tactical mission report"),
        )]);

        assert!(evaluate_custom_query(&doc, "description LIKE '%tactical%'"));
        assert!(evaluate_custom_query(&doc, "description LIKE '%mission%'"));
        assert!(!evaluate_custom_query(
            &doc,
            "description LIKE '%strategic%'"
        ));
    }

    #[test]
    fn test_custom_query_like_complex() {
        // Test: field LIKE 'prefix%middle%suffix'
        let doc = create_test_doc(vec![("path", serde_json::json!("squad-alpha-report.json"))]);

        assert!(evaluate_custom_query(&doc, "path LIKE 'squad%report%'")); // prefix and middle
        assert!(evaluate_custom_query(&doc, "path LIKE '%alpha%json'")); // middle and suffix
        assert!(evaluate_custom_query(&doc, "path LIKE 'squad%.json'")); // prefix and suffix
    }

    #[test]
    fn test_custom_query_in_strings() {
        // Test: field IN ['a', 'b', 'c']
        let doc = create_test_doc(vec![("role", serde_json::json!("soldier"))]);

        assert!(evaluate_custom_query(
            &doc,
            "role IN ['soldier', 'medic', 'engineer']"
        ));
        assert!(!evaluate_custom_query(
            &doc,
            "role IN ['general', 'colonel']"
        ));
    }

    #[test]
    fn test_custom_query_in_numbers() {
        // Test: field IN [1, 2, 3]
        let doc = create_test_doc(vec![("priority", serde_json::json!(2))]);

        assert!(evaluate_custom_query(&doc, "priority IN [1, 2, 3]"));
        assert!(!evaluate_custom_query(&doc, "priority IN [4, 5, 6]"));
    }

    #[test]
    fn test_custom_query_in_case_insensitive() {
        // Test: IN keyword is case insensitive
        let doc = create_test_doc(vec![("status", serde_json::json!("active"))]);

        assert!(evaluate_custom_query(
            &doc,
            "status in ['active', 'pending']"
        ));
        assert!(evaluate_custom_query(
            &doc,
            "status IN ['active', 'pending']"
        ));
    }

    #[test]
    fn test_custom_query_not_expression() {
        // Test: NOT (expr)
        let doc = create_test_doc(vec![("enabled", serde_json::json!(false))]);

        assert!(evaluate_custom_query(&doc, "NOT (enabled == true)"));
        assert!(!evaluate_custom_query(&doc, "NOT (enabled == false)"));
    }

    #[test]
    fn test_custom_query_not_without_parens() {
        // Test: NOT expr (without parentheses)
        let doc = create_test_doc(vec![("status", serde_json::json!("inactive"))]);

        assert!(evaluate_custom_query(&doc, "NOT status == 'active'"));
        assert!(!evaluate_custom_query(&doc, "NOT status == 'inactive'"));
    }

    #[test]
    fn test_custom_query_not_case_insensitive() {
        // Test: not is case insensitive
        let doc = create_test_doc(vec![("flag", serde_json::json!(true))]);

        assert!(evaluate_custom_query(&doc, "not (flag == false)"));
        assert!(evaluate_custom_query(&doc, "NOT (flag == false)"));
    }

    #[test]
    fn test_custom_query_is_null() {
        // Test: field IS NULL
        let doc_with_null = create_test_doc(vec![("optional", serde_json::Value::Null)]);
        let doc_without_field = create_test_doc(vec![("other", serde_json::json!("value"))]);
        let doc_with_value = create_test_doc(vec![("optional", serde_json::json!("present"))]);

        assert!(evaluate_custom_query(&doc_with_null, "optional IS NULL"));
        assert!(evaluate_custom_query(
            &doc_without_field,
            "optional IS NULL"
        ));
        assert!(!evaluate_custom_query(&doc_with_value, "optional IS NULL"));
    }

    #[test]
    fn test_custom_query_is_not_null() {
        // Test: field IS NOT NULL
        let doc_with_value = create_test_doc(vec![("required", serde_json::json!("value"))]);
        let doc_with_null = create_test_doc(vec![("required", serde_json::Value::Null)]);
        let doc_missing = create_test_doc(vec![("other", serde_json::json!("x"))]);

        assert!(evaluate_custom_query(
            &doc_with_value,
            "required IS NOT NULL"
        ));
        assert!(!evaluate_custom_query(
            &doc_with_null,
            "required IS NOT NULL"
        ));
        assert!(!evaluate_custom_query(&doc_missing, "required IS NOT NULL"));
    }

    #[test]
    fn test_custom_query_is_null_case_insensitive() {
        // Test: IS NULL is case insensitive
        let doc = create_test_doc(vec![("field", serde_json::Value::Null)]);

        assert!(evaluate_custom_query(&doc, "field is null"));
        assert!(evaluate_custom_query(&doc, "field IS NULL"));
        assert!(evaluate_custom_query(&doc, "field Is Null"));
    }

    #[test]
    fn test_custom_query_nested_field_equality() {
        // Test: nested.field == 'value'
        let doc = create_test_doc(vec![(
            "address",
            serde_json::json!({"city": "San Francisco", "state": "CA"}),
        )]);

        assert!(evaluate_custom_query(
            &doc,
            "address.city == 'San Francisco'"
        ));
        assert!(evaluate_custom_query(&doc, "address.state == 'CA'"));
        assert!(!evaluate_custom_query(&doc, "address.city == 'New York'"));
    }

    #[test]
    fn test_custom_query_nested_field_deep() {
        // Test: deeply nested field access
        let doc = create_test_doc(vec![(
            "data",
            serde_json::json!({"level1": {"level2": {"value": "deep"}}}),
        )]);

        assert!(evaluate_custom_query(
            &doc,
            "data.level1.level2.value == 'deep'"
        ));
        assert!(!evaluate_custom_query(
            &doc,
            "data.level1.level2.value == 'shallow'"
        ));
    }

    #[test]
    fn test_custom_query_nested_field_is_null() {
        // Test: nested.field IS NULL
        let doc = create_test_doc(vec![(
            "config",
            serde_json::json!({"enabled": true, "optional": null}),
        )]);

        assert!(evaluate_custom_query(&doc, "config.optional IS NULL"));
        assert!(evaluate_custom_query(&doc, "config.missing IS NULL"));
        assert!(!evaluate_custom_query(&doc, "config.enabled IS NULL"));
    }

    #[test]
    fn test_custom_query_nested_field_in() {
        // Test: nested.field IN [...]
        let doc = create_test_doc(vec![(
            "user",
            serde_json::json!({"role": "admin", "level": 5}),
        )]);

        assert!(evaluate_custom_query(
            &doc,
            "user.role IN ['admin', 'superuser']"
        ));
        assert!(evaluate_custom_query(&doc, "user.level IN [1, 5, 10]"));
        assert!(!evaluate_custom_query(
            &doc,
            "user.role IN ['guest', 'user']"
        ));
    }

    #[test]
    fn test_custom_query_compound_with_new_patterns() {
        // Test: combining new patterns with AND/OR
        let doc = create_test_doc(vec![
            ("status", serde_json::json!("active")),
            ("priority", serde_json::json!(1)),
            ("optional", serde_json::Value::Null),
        ]);

        // status != 'deleted' AND priority IN [1, 2, 3]
        assert!(evaluate_custom_query(
            &doc,
            "status != 'deleted' AND priority IN [1, 2, 3]"
        ));

        // optional IS NULL OR status LIKE 'act%'
        assert!(evaluate_custom_query(
            &doc,
            "optional IS NULL OR status LIKE 'act%'"
        ));

        // NOT (status == 'inactive') AND priority != 0
        assert!(evaluate_custom_query(
            &doc,
            "NOT (status == 'inactive') AND priority != 0"
        ));
    }

    #[test]
    fn test_match_like_pattern_unit() {
        // Unit tests for match_like_pattern helper function
        assert!(match_like_pattern("hello world", "%world"));
        assert!(match_like_pattern("hello world", "hello%"));
        assert!(match_like_pattern("hello world", "%lo wo%"));
        assert!(match_like_pattern("hello world", "%"));
        assert!(match_like_pattern("hello world", "%%"));
        assert!(match_like_pattern("hello world", "hello world"));
        assert!(!match_like_pattern("hello world", "goodbye%"));
        assert!(!match_like_pattern("hello world", "%goodbye"));
        assert!(!match_like_pattern("hello", "hello world"));
    }

    // ============================================================================
    // Issue #518: Counter and Nested Object Tests
    // ============================================================================

    #[test]
    fn test_automerge_scalar_counter_extraction() {
        // Test that Counter values are properly extracted
        use automerge::ScalarValue;

        // Create a counter with value 42
        let counter = ScalarValue::counter(42);

        // Extract it using our function
        if let ScalarValue::Counter(c) = &counter {
            let value: i64 = i64::from(c);
            assert_eq!(value, 42, "Counter value should be 42");
        } else {
            panic!("Expected Counter variant");
        }
    }

    #[test]
    fn test_automerge_scalar_to_json_all_types() {
        // Test all scalar types convert correctly
        use automerge::ScalarValue;

        // String
        let result = AutomergeBackend::automerge_scalar_to_json(&ScalarValue::Str("hello".into()));
        assert_eq!(result, Some(serde_json::json!("hello")));

        // Integer
        let result = AutomergeBackend::automerge_scalar_to_json(&ScalarValue::Int(-42));
        assert_eq!(result, Some(serde_json::json!(-42)));

        // Unsigned integer
        let result = AutomergeBackend::automerge_scalar_to_json(&ScalarValue::Uint(42));
        assert_eq!(result, Some(serde_json::json!(42)));

        // Float (use arbitrary value to avoid clippy::approx_constant)
        let result = AutomergeBackend::automerge_scalar_to_json(&ScalarValue::F64(1.234));
        assert!(result.is_some());
        if let Some(serde_json::Value::Number(n)) = result {
            assert!((n.as_f64().unwrap() - 1.234).abs() < 0.001);
        }

        // Boolean
        let result = AutomergeBackend::automerge_scalar_to_json(&ScalarValue::Boolean(true));
        assert_eq!(result, Some(serde_json::json!(true)));

        // Null
        let result = AutomergeBackend::automerge_scalar_to_json(&ScalarValue::Null);
        assert_eq!(result, Some(serde_json::Value::Null));

        // Timestamp
        let result =
            AutomergeBackend::automerge_scalar_to_json(&ScalarValue::Timestamp(1234567890));
        assert_eq!(result, Some(serde_json::json!(1234567890)));

        // Counter (Issue #518)
        let counter = ScalarValue::counter(100);
        if let ScalarValue::Counter(c) = &counter {
            let result =
                AutomergeBackend::automerge_scalar_to_json(&ScalarValue::Counter(c.clone()));
            assert_eq!(
                result,
                Some(serde_json::json!(100)),
                "Counter should return actual value, not 0"
            );
        }

        // Bytes
        let result = AutomergeBackend::automerge_scalar_to_json(&ScalarValue::Bytes(vec![1, 2, 3]));
        assert_eq!(result, Some(serde_json::json!([1, 2, 3])));
    }

    #[tokio::test]
    async fn test_nested_object_roundtrip() {
        // Test that nested objects survive the roundtrip through Automerge
        let backend = AutomergeBackend::new();
        backend.initialize(deletion_test_config()).await.unwrap();

        // Create a document with nested structure
        let nested_doc = Document::new(
            vec![
                ("name".to_string(), serde_json::json!("test")),
                (
                    "metadata".to_string(),
                    serde_json::json!({
                        "version": 1,
                        "author": "test_user"
                    }),
                ),
                ("items".to_string(), serde_json::json!([1, 2, 3])),
            ]
            .into_iter()
            .collect(),
        );

        let doc_id = backend
            .document_store()
            .upsert("nested_test", nested_doc)
            .await
            .unwrap();

        // Retrieve and verify
        let retrieved = backend
            .document_store()
            .get("nested_test", &doc_id)
            .await
            .unwrap()
            .expect("Document should exist");

        assert_eq!(
            retrieved.fields.get("name"),
            Some(&serde_json::json!("test"))
        );

        // Verify nested object (Issue #518)
        if let Some(metadata) = retrieved.fields.get("metadata") {
            assert!(metadata.is_object(), "metadata should be an object");
            if let Some(version) = metadata.get("version") {
                assert_eq!(version, &serde_json::json!(1));
            }
            if let Some(author) = metadata.get("author") {
                assert_eq!(author, &serde_json::json!("test_user"));
            }
        }

        // Verify array
        if let Some(items) = retrieved.fields.get("items") {
            assert!(items.is_array(), "items should be an array");
            assert_eq!(items, &serde_json::json!([1, 2, 3]));
        }
    }
}