brain-db-sdk 0.2.1

Rust client SDK for the Brain memory database. Speaks Brain's BRN0 wire protocol directly over TCP.
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
//! Wire payload structs for the handshake + the v1 verbs + the
//! typed-graph ops the conformance corpus exercises.
//!
//! Field names, field order, and serde attributes match the server's
//! payload structs exactly, because CBOR struct encoding is field-order
//! sensitive and the corpus pins it byte-for-byte. The seam is the
//! `(struct, Option<vector>)` shape: only `EncodeVectorDirectRequest`
//! carries a trailing raw-vector section; every other payload is pure
//! CBOR.

// The types below mirror the server's wire structs one-for-one: same names,
// same field names, same order. Their documentation is the protocol itself —
// `conformance/protocol.json` carries every field's type and serde attributes,
// and the corpus pins the bytes. A doc comment on each of ~2000 fields would
// restate the field name and nothing more, and the ones that DO carry meaning
// beyond their name (written below) would be lost in the noise.
#![allow(missing_docs)]

use serde::{Deserialize, Serialize};

/// 16-byte UUID-shaped identifier (space id, request id, txn id, …).
pub type WireUuid = [u8; 16];
/// `SessionId` on the wire — a `u64`.
pub type WireSessionId = u64;
/// Packed `MemoryId` — a `u128`.
pub type WireMemoryId = u128;

// ===========================================================================
// Shared enums.
// ===========================================================================

/// Durable memory kind. Integer discriminant on the wire.
#[derive(
    Clone, Copy, Debug, Eq, PartialEq, serde_repr::Serialize_repr, serde_repr::Deserialize_repr,
)]
#[repr(u8)]
pub enum MemoryKindWire {
    Episodic = 0,
    Semantic = 1,
    Consolidated = 2,
}

/// Edge kind for memory-to-memory links. Integer discriminant on the wire.
#[derive(
    Clone, Copy, Debug, Eq, PartialEq, serde_repr::Serialize_repr, serde_repr::Deserialize_repr,
)]
#[repr(u8)]
pub enum EdgeKindWire {
    Caused = 0,
    FollowedBy = 1,
    DerivedFrom = 2,
    SimilarTo = 3,
    Contradicts = 4,
    Supports = 5,
    References = 6,
    PartOf = 7,
}

/// Soft tombstone vs. hard erase. Integer discriminant on the wire.
#[derive(
    Clone, Copy, Debug, Eq, PartialEq, serde_repr::Serialize_repr, serde_repr::Deserialize_repr,
)]
#[repr(u8)]
pub enum ForgetMode {
    Soft = 0,
    Hard = 1,
}

/// Background stage a write queues. Integer discriminant on the wire.
#[derive(
    Clone, Copy, Debug, Eq, PartialEq, serde_repr::Serialize_repr, serde_repr::Deserialize_repr,
)]
#[repr(u8)]
pub enum StageKind {
    AutoEdge = 0,
    TemporalEdge = 1,
    Extractor = 2,
    Hype = 3,
}

// ===========================================================================
// Handshake.
// ===========================================================================

/// Feature flags exchanged during the handshake.
#[derive(Clone, Copy, Debug, Eq, PartialEq, Serialize, Deserialize)]
pub struct HelloCapabilities {
    pub streaming: bool,
    pub compression_zstd: bool,
    pub server_push: bool,
}

/// Authentication method. Integer discriminant on the wire.
#[derive(
    Clone, Copy, Debug, Eq, PartialEq, serde_repr::Serialize_repr, serde_repr::Deserialize_repr,
)]
#[repr(u8)]
pub enum AuthMethod {
    Token = 0,
    Mtls = 1,
}

/// Credentials carried in an AUTH frame. Externally-tagged enum (CBOR
/// map keyed by the variant name), matching the server.
#[derive(Clone, Debug, Eq, PartialEq, Serialize, Deserialize)]
pub enum AuthCredentials {
    Token(Vec<u8>),
    Mtls(MtlsClaim),
}

/// mTLS claim accompanying an mTLS auth.
#[derive(Clone, Debug, Eq, PartialEq, Serialize, Deserialize)]
pub struct MtlsClaim {
    #[serde(with = "serde_bytes")]
    pub cert_fingerprint: [u8; 32],
    pub asserted_subject: String,
}

/// Agent permissions confirmed in AUTH_OK.
#[derive(Clone, Copy, Debug, Eq, PartialEq, Serialize, Deserialize)]
pub struct SpacePermissions {
    pub can_encode: bool,
    pub can_recall: bool,
    pub can_plan: bool,
    pub can_reason: bool,
    pub can_forget: bool,
    pub can_admin: bool,
    /// Authorizes the connection to run an op *on behalf of another identity*
    /// via the per-request `act_as` field. Held only by a trusted service
    /// principal (an edge / gateway); a normal agent's key never carries it,
    /// and it does not widen what the connection's own agent may do.
    pub can_act_as: bool,
}

/// Server-declared parameters carried in WELCOME.
#[derive(Clone, Debug, Eq, PartialEq, Serialize, Deserialize)]
pub struct ServerFeatures {
    pub max_payload_size: u32,
    pub max_concurrent_streams: u32,
    pub idle_timeout_seconds: u32,
    pub auth_methods: Vec<AuthMethod>,
}

/// HELLO (`0x0001`) — first client frame after connect.
#[derive(Clone, Debug, Eq, PartialEq, Serialize, Deserialize)]
pub struct HelloPayload {
    pub client_id: String,
    pub supported_versions: Vec<u8>,
    pub capabilities: HelloCapabilities,
    /// Reserved for connection resumption; `None` encodes as CBOR null.
    #[serde(with = "serde_bytes")]
    pub client_connection_token: Option<[u8; 32]>,
}

/// WELCOME (`0x0081`) — server reply to HELLO.
#[derive(Clone, Debug, Eq, PartialEq, Serialize, Deserialize)]
pub struct WelcomePayload {
    pub server_id: String,
    pub chosen_version: u8,
    /// 16 cryptographically-random bytes; per-connection identifier.
    #[serde(with = "serde_bytes")]
    pub connection_id: [u8; 16],
    pub capabilities: HelloCapabilities,
    pub server_features: ServerFeatures,
}

/// AUTH (`0x0002`) — client credentials. The client never claims an identity:
/// the server resolves `(namespace, space, permissions)` from the credential
/// alone and echoes the assignment in AUTH_OK.
#[derive(Clone, Debug, Eq, PartialEq, Serialize, Deserialize)]
pub struct AuthPayload {
    pub method: AuthMethod,
    pub credentials: AuthCredentials,
}

/// AUTH_OK (`0x0082`) — server acknowledgment.
#[derive(Clone, Debug, Eq, PartialEq, Serialize, Deserialize)]
pub struct AuthOkPayload {
    #[serde(with = "serde_bytes")]
    pub space_id: WireUuid,
    pub bound_shard_id: u16,
    pub permissions: SpacePermissions,
    /// Owning tenant the connection resolved to (server-derived from auth).
    /// Empty when the connection resolves to the reserved `brain` system
    /// namespace. The client only surfaces this — it never sends a namespace.
    pub namespace: String,
    pub server_time_unix_nanos: u64,
}

// ===========================================================================
// Per-request effective identity (`act_as`).
// ===========================================================================

/// Per-request effective-identity selector carried on data-plane op requests.
/// When present, the op runs as this `(namespace, space_id)` on behalf of the
/// authenticated connection principal; when the field is absent (the common
/// case, omitted on the wire) the op runs as the connection's own key-bound
/// identity.
///
/// Honored server-side only when the connection principal holds `can_act_as`
/// and `namespace` lies within its granted allowlist — otherwise the op is
/// rejected with [`ErrorCodeWire::ActAsDenied`]. This is the wire form only;
/// the trust model is enforced by the server, not this codec.
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
pub struct ActAs {
    /// Effective namespace. Must be within the principal's allowlist.
    pub namespace: String,
    /// Structured, opaque effective-space selector (e.g.
    /// `"support-bot:user123"`) — a CBOR text string on the wire. The server
    /// derives the 16-byte storage space id from it at ingress. An empty
    /// string selects the connection's key-bound space.
    pub space_id: String,
    /// Extra capability bits granted to the effective caller for this op,
    /// on top of the standard space mask. Only `SCHEMA_UPLOAD` (`1 << 4`)
    /// and `ADMIN` (`1 << 5`) are grantable, and only when the connection
    /// principal holds them itself. `0` is omitted on the wire, so a
    /// grant-less selector encodes byte-identically to the pre-grant form.
    #[serde(default, skip_serializing_if = "is_zero_u32")]
    pub grant: u32,
}

/// Grantable [`ActAs::grant`] bits.
pub mod act_as_grant {
    /// May upload / validate-and-apply schema documents.
    pub const SCHEMA_UPLOAD: u32 = 1 << 4;
    /// May run destructive admin ops (`SCHEMA_REPLACE`, `SCHEMA_DROP`).
    pub const ADMIN: u32 = 1 << 5;
}

#[allow(clippy::trivially_copy_pass_by_ref)] // serde's skip_serializing_if passes &T
fn is_zero_u32(v: &u32) -> bool {
    *v == 0
}

// ===========================================================================
// ENCODE / ENCODE_VECTOR_DIRECT.
// ===========================================================================

/// Edge attached to an ENCODE request.
#[derive(Clone, Copy, Debug, PartialEq, Serialize, Deserialize)]
pub struct EdgeRequest {
    pub target: WireMemoryId,
    pub kind: EdgeKindWire,
    pub weight: f32,
}

/// Write-completion mode — how long a write op blocks before it returns.
///
/// API convention: writes take `wait` (this enum); reads take `trace: bool`.
/// They are never both on one op. On a write, waiting and the trace payload are
/// one decision — the only reason to wait for async derivation is to observe it —
/// so a single `wait` knob controls both. On a read there is no async to wait
/// for, so `trace` is a pure observability toggle with no timing effect.
#[derive(
    Clone,
    Copy,
    Debug,
    Default,
    Eq,
    PartialEq,
    serde_repr::Serialize_repr,
    serde_repr::Deserialize_repr,
)]
#[repr(u8)]
pub enum WaitMode {
    /// Return after the durable sync ack; async derivation runs in the
    /// background. The fast default (omitted from the wire map).
    #[default]
    Ack = 0,
    /// Block until async derivation completes, then return the full trace.
    Derived = 1,
}

impl WaitMode {
    /// `true` for the default [`WaitMode::Ack`] — used to omit the field from
    /// the wire map in the common case.
    #[must_use]
    pub fn is_ack(&self) -> bool {
        matches!(self, WaitMode::Ack)
    }
}

/// ENCODE (`0x0020`).
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct EncodeRequest {
    pub text: String,
    pub session_id: WireSessionId,
    #[serde(with = "serde_bytes")]
    pub request_id: WireUuid,
    #[serde(with = "crate::wire::cbor::opt_byte_array16")]
    pub txn_id: Option<WireUuid>,
    pub occurred_at_unix_nanos: Option<u64>,
    /// Effective identity this encode runs as. `None` (omitted on the wire)
    /// means the op runs as the connection's own key-bound identity.
    #[serde(skip_serializing_if = "Option::is_none", default)]
    pub act_as: Option<ActAs>,
    /// How long the write blocks before replying. This is the single completion
    /// knob for writes (reads use `trace` instead — see [`WaitMode`]).
    ///
    /// - [`WaitMode::Ack`] (the default, omitted on the wire): return as soon as
    ///   the WAL record is durable; async derivation runs in the background and
    ///   the response's `trace` is `None`.
    /// - [`WaitMode::Derived`]: block until async derivation completes, then
    ///   return a populated `trace: EncodeTrace`.
    #[serde(default, skip_serializing_if = "WaitMode::is_ack")]
    pub wait: WaitMode,
    /// Opt out of content dedup and force a distinct memory. Default `false`:
    /// Brain dedupes text ENCODE on `(space_id, session_id, BLAKE3(text))` — a
    /// repeat of byte-identical text returns the existing MemoryId
    /// (`was_deduplicated = true`) and writes nothing new. Set `true` when the
    /// same text is a genuinely distinct observation that must coexist (e.g. the
    /// same fact re-stated at a different `occurred_at`). Omitted on the wire in
    /// the default (dedup-on) case.
    #[serde(default, skip_serializing_if = "is_false")]
    pub allow_duplicates: bool,
}

/// `skip_serializing_if` predicate — omit `false` from the CBOR map so the
/// default (dedup-on) encode stays byte-minimal and wire-compatible.
#[allow(clippy::trivially_copy_pass_by_ref)]
fn is_false(b: &bool) -> bool {
    !*b
}

/// ENCODE_VECTOR_DIRECT (`0x002A`). The embedding rides the trailing raw
/// little-endian f32 section, never the CBOR map, so `vector` is skipped
/// from CBOR and reattached at the payload codec seam.
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct EncodeVectorDirectRequest {
    pub text: String,
    /// Carried in the trailing raw section, not the CBOR map.
    #[serde(skip, default)]
    pub vector: Vec<f32>,
    #[serde(with = "serde_bytes")]
    pub model_fingerprint: [u8; 16],
    pub session_id: WireSessionId,
    pub kind: MemoryKindWire,
    pub salience_hint: f32,
    pub edges: Vec<EdgeRequest>,
    #[serde(with = "serde_bytes")]
    pub request_id: WireUuid,
    #[serde(with = "crate::wire::cbor::opt_byte_array16")]
    pub txn_id: Option<WireUuid>,
    pub deduplicate: bool,
}

/// ENCODE_RESP (`0x00A0`).
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct EncodeResponse {
    pub memory_id: WireMemoryId,
    pub was_deduplicated: bool,
    pub salience: f32,
    pub auto_edges_added: u32,
    pub lsn: u64,
    #[serde(with = "serde_bytes")]
    pub space_id: WireUuid,
    pub session_id: WireSessionId,
    pub kind: MemoryKindWire,
    pub created_at_unix_nanos: u64,
    pub edges_out_count: u32,
    #[serde(with = "serde_bytes")]
    pub embedding_model_fp: [u8; 16],
    pub pending_stages: Vec<StageKind>,
    pub has_active_schema: bool,
    /// Full synchronous write-analysis trace, present only when the request
    /// set `trace = true`; `None` otherwise (and absent from the wire map).
    /// The same async stages are also observable on SUBSCRIBE keyed by `lsn`
    /// + `pending_stages`; this field is the one-response alternative.
    #[serde(skip_serializing_if = "Option::is_none", default)]
    pub trace: Option<EncodeTrace>,
}

/// Full synchronous write-analysis trace for one ENCODE, present when the
/// request opted in with `trace = true`. The ENCODE analog of `RecallTrace`:
/// `stages` is the per-phase timeline (synchronous phases plus async
/// derivation stages), and `artifacts` is what the write produced.
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct EncodeTrace {
    pub stages: Vec<EncodeTraceStage>,
    pub artifacts: EncodeTraceArtifacts,
    pub total_latency_us: u64,
}

/// One phase in an `EncodeTrace` timeline.
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct EncodeTraceStage {
    pub name: String,
    pub status: EncodeTraceStageStatus,
    pub latency_us: u64,
    pub detail: String,
    /// The concrete data this stage produced (embed → vector, persist →
    /// record, extractor → graph, …). Present only when the caller set
    /// `trace = true` and the stage produced inspectable output; absent from
    /// the wire map otherwise.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub artifact: Option<EncodeStageArtifact>,
}

/// Terminal status of an `EncodeTrace` phase.
#[derive(
    Clone, Copy, Debug, Eq, PartialEq, serde_repr::Serialize_repr, serde_repr::Deserialize_repr,
)]
#[repr(u8)]
pub enum EncodeTraceStageStatus {
    Ok = 0,
    Skipped = 1,
    Failed = 2,
    Timeout = 3,
}

/// What an ENCODE produced, resolved after the async stages drained.
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct EncodeTraceArtifacts {
    pub entities: Vec<EncodeTraceEntity>,
    pub statements: Vec<EncodeTraceStatement>,
    pub relations: Vec<EncodeTraceRelation>,
    pub indexes: Vec<EncodeTraceIndex>,
    pub dedup: EncodeTraceDedup,
}

/// One entity artifact in an `EncodeTrace`.
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct EncodeTraceEntity {
    #[serde(with = "serde_bytes")]
    pub id: [u8; 16],
    pub name: String,
    pub type_qname: String,
}

/// One statement artifact in an `EncodeTrace`.
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct EncodeTraceStatement {
    #[serde(with = "serde_bytes")]
    pub id: [u8; 16],
    pub subject_name: String,
    pub predicate: String,
    pub object_name: String,
    pub confidence: f32,
    /// When the statement's EVENT happened, in unix nanos — the reified
    /// Time slot of an Event-kind statement. Absent from the wire map for
    /// a statement with no event time.
    #[serde(skip_serializing_if = "Option::is_none", default)]
    pub event_at_unix_nanos: Option<u64>,
}

/// One relation artifact in an `EncodeTrace`.
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct EncodeTraceRelation {
    pub source_name: String,
    pub predicate: String,
    pub target_name: String,
}

/// One index the write landed in.
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct EncodeTraceIndex {
    pub name: String,
    pub status: EncodeTraceStageStatus,
}

/// The dedup verdict carried on an `EncodeTrace`.
#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)]
pub struct EncodeTraceDedup {
    pub was_deduplicated: bool,
    #[serde(with = "crate::wire::cbor::opt_byte_array16")]
    pub matched_memory_id: Option<[u8; 16]>,
}

// ===========================================================================
// Per-stage write artifacts — the concrete data each ENCODE stage produced.
// Shared shape for the live `trace = true` per-stage `artifact` AND the
// durable `MEMORY_INSPECT` bundle. Every field is optional and omitted from
// the wire map when empty/absent (matches the server's `skip_serializing_if`).
// ===========================================================================

/// The concrete output one ENCODE stage produced (embed → vector, persist →
/// record, HyPE → questions, text-index → keyword terms, extractor → graph).
#[derive(Clone, Debug, Default, PartialEq, Serialize, Deserialize)]
pub struct EncodeStageArtifact {
    #[serde(default, skip_serializing_if = "Vec::is_empty")]
    pub vector: Vec<f32>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub record: Option<EncodeStageRecord>,
    #[serde(default, skip_serializing_if = "Vec::is_empty")]
    pub hype_questions: Vec<String>,
    #[serde(default, skip_serializing_if = "Vec::is_empty")]
    pub keyword_fields: Vec<EncodeStageKeywordField>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub graph: Option<EncodeStageGraph>,
}

/// The durable metadata row a `persist` stage wrote.
#[derive(Clone, Copy, Debug, PartialEq, Serialize, Deserialize)]
pub struct EncodeStageRecord {
    #[serde(with = "serde_bytes")]
    pub memory_id: [u8; 16],
    pub kind: u8,
    pub salience: f32,
    pub created_at_unix_nanos: u64,
    pub occurred_at_unix_nanos: u64,
    pub vector_dim: u32,
    pub text_len: u32,
    pub lsn: u64,
}

/// One text-index field and the analyzed terms the write produced for it.
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct EncodeStageKeywordField {
    pub field: String,
    pub terms: Vec<String>,
}

/// A node in the knowledge graph an ENCODE produced.
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct EncodeGraphNode {
    #[serde(with = "serde_bytes")]
    pub id: [u8; 16],
    pub name: String,
    pub kind: String,
    pub type_qname: String,
}

/// A directed edge in the knowledge graph an ENCODE produced.
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct EncodeGraphEdge {
    #[serde(with = "serde_bytes")]
    pub source: [u8; 16],
    #[serde(with = "serde_bytes")]
    pub target: [u8; 16],
    pub predicate: String,
    pub kind: String,
    pub confidence: f32,
    /// When the EVENT this edge records happened, in unix nanos —
    /// denormalised from the backing statement. Absent from the wire map
    /// for an undated statement and for every non-statement edge kind.
    #[serde(skip_serializing_if = "Option::is_none", default)]
    pub event_at_unix_nanos: Option<u64>,
}

/// The knowledge graph an ENCODE produced — nodes + directed edges.
#[derive(Clone, Debug, Default, PartialEq, Serialize, Deserialize)]
pub struct EncodeStageGraph {
    pub nodes: Vec<EncodeGraphNode>,
    pub edges: Vec<EncodeGraphEdge>,
}

// ===========================================================================
// MEMORY_INSPECT — one memory's durable write-artifact bundle.
// ===========================================================================

/// `MEMORY_INSPECT_REQ` — fetch the durable write-artifact bundle for one
/// memory. Single-shot (not paginated).
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct MemoryInspectRequest {
    #[serde(with = "serde_bytes")]
    pub memory_id: [u8; 16],
    #[serde(skip_serializing_if = "Option::is_none", default)]
    pub act_as: Option<ActAs>,
}

/// `MEMORY_INSPECT_RESP` — the durable per-memory artifact bundle plus text.
/// `found = false` (with an empty `artifact`) when no memory / no bundle
/// exists for the id under the caller's scope.
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct MemoryInspectResponse {
    pub found: bool,
    #[serde(with = "serde_bytes")]
    pub memory_id: [u8; 16],
    pub text: String,
    pub artifact: EncodeStageArtifact,
}

// ===========================================================================
// RECALL.
// ===========================================================================

/// What kind of answer a RECALL produced. Serializes as the variant name
/// string, matching the server.
#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)]
pub enum AnswerKindWire {
    Single,
    Many,
    None,
}

/// RECALL scope selector. `Space` (default) serves the caller's single
/// `(namespace, space)` on its shard; `Namespace` spans every space in the
/// caller's namespace via the server's cross-shard fan-out + global merge, and
/// never crosses namespaces. Mirrors the server's `RecallScopeWire`.
///
/// Encoded as the variant name string (`"Space"` / `"Namespace"`), matching the
/// server. The [`RecallRequest::scope`] field is always present on the wire,
/// exactly as the server serializes it — a plain recall carries `"Space"`.
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Serialize, Deserialize)]
pub enum RecallScopeWire {
    /// The caller's single space (default).
    #[default]
    Space,
    /// Every space in the caller's namespace (cross-shard fan-out + merge).
    Namespace,
}

/// RECALL (`0x0021`).
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct RecallRequest {
    pub cue_text: String,
    pub subject_name: String,
    pub max_results: u32,
    pub confidence_threshold: f32,
    pub session_filter: Option<Vec<WireSessionId>>,
    pub age_bound_unix_nanos: Option<u64>,
    pub as_of_record_time_unix_nanos: Option<u64>,
    pub kind_filter: Option<Vec<MemoryKindWire>>,
    pub salience_floor: f32,
    pub include_edges: bool,
    pub include_graph: bool,
    pub include_text: bool,
    #[serde(with = "crate::wire::cbor::opt_byte_array16")]
    pub request_id: Option<WireUuid>,
    #[serde(with = "crate::wire::cbor::opt_byte_array16")]
    pub txn_id: Option<WireUuid>,
    /// Opt-in per-stage observability. When `true`, the final response frame
    /// carries a populated `trace: RecallTrace`; when `false` (the default)
    /// the field is absent and the read pays nothing.
    #[serde(default)]
    pub trace: bool,
    /// Effective identity this recall runs as. `None` (omitted on the wire)
    /// means the op runs as the connection's own key-bound identity.
    #[serde(skip_serializing_if = "Option::is_none", default)]
    pub act_as: Option<ActAs>,
    /// Recall scope: the caller's single space (default) or every space in its
    /// namespace. Always serialized, exactly as the server does (`#[serde(default)]`,
    /// no skip) — a plain recall carries `scope: "Space"`.
    #[serde(default)]
    pub scope: RecallScopeWire,
}

/// One streaming RECALL_RESP frame (`0x00A1`).
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct RecallResponseFrame {
    pub answer_kind: AnswerKindWire,
    pub memories: Vec<MemoryResult>,
    pub is_final: bool,
    pub cumulative_count: u32,
    pub estimated_remaining: Option<u32>,
    /// Per-stage read-pipeline trace, present only on the final frame and only
    /// when the request set `trace = true`; `None` otherwise.
    #[serde(skip_serializing_if = "Option::is_none", default)]
    pub trace: Option<RecallTrace>,
}

/// Per-stage observability for one RECALL, surfaced on the final frame when
/// the request opted in with `trace = true`.
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct RecallTrace {
    pub retrievers: Vec<RecallTraceRetriever>,
    pub filter_chain: RecallTraceFilterChain,
    pub rerank: Option<RecallTraceRerank>,
    pub total_latency_ms: f64,
    /// Full-detail mode only: per-fused-item score breakdown by
    /// contributing lane. `None` when trace detail wasn't requested or
    /// fusion produced nothing.
    pub fusion: Option<RecallTraceFusion>,
}

/// What one retriever lane did during a traced RECALL.
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct RecallTraceRetriever {
    pub name: RetrieverNameWire,
    pub status: RecallTraceRetrieverStatus,
    /// Skip reason for `Skipped`, error message for `Failure`; empty otherwise.
    pub status_detail: String,
    pub latency_ms: f64,
    pub candidate_count: u32,
    /// Only populated in full-detail mode: the raw candidates this lane
    /// contributed before fusion, in the lane's own rank order.
    pub candidates: Vec<RecallTraceCandidate>,
}

/// One retriever-lane candidate surfaced in full-detail trace mode.
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct RecallTraceCandidate {
    /// Raw id of the surfaced item — a memory, statement, entity, or relation
    /// id depending on `kind`. All are `u128` on the wire.
    pub item_id: WireMemoryId,
    /// How to interpret `item_id`.
    pub kind: RecallCandidateKind,
    /// A human-readable label — memory text, entity name, or a rendered
    /// statement/relation. Full-detail mode only; truncated server-side.
    pub text: String,
    /// This lane's raw score for this item.
    pub score: f32,
}

/// The kind of typed-graph item a retriever lane surfaced. The graph lane emits
/// entities and relations (not memories), so a candidate is not always a memory
/// — `kind` tells the client how to interpret `RecallTraceCandidate::item_id`.
#[derive(
    Clone, Copy, Debug, Eq, PartialEq, serde_repr::Serialize_repr, serde_repr::Deserialize_repr,
)]
#[repr(u8)]
pub enum RecallCandidateKind {
    Memory = 0,
    Statement = 1,
    Entity = 2,
    Relation = 3,
}

/// Terminal status of a retriever lane in a RECALL trace.
#[derive(
    Clone, Copy, Debug, Eq, PartialEq, serde_repr::Serialize_repr, serde_repr::Deserialize_repr,
)]
#[repr(u8)]
pub enum RecallTraceRetrieverStatus {
    Success = 0,
    Skipped = 1,
    Timeout = 2,
    Failure = 3,
}

/// Kind of a [`RecallTraceDroppedId`], disambiguating which id-space the
/// paired `id` belongs to. Mirrors the pipeline-internal `RankedItemId`,
/// which the supersession/as-of filter steps and the final limit truncation
/// can drop items from — unlike the type/temporal/confidence/tombstone
/// steps, supersession, as-of, and limit can drop `Statement` and
/// `Relation` items, not just `Memory` ones, so a plain (untagged)
/// `WireMemoryId` can't represent what those three steps removed.
#[derive(
    Clone, Copy, Debug, Eq, PartialEq, serde_repr::Serialize_repr, serde_repr::Deserialize_repr,
)]
#[repr(u8)]
pub enum RankedItemKindWire {
    Memory = 0,
    Statement = 1,
    Entity = 2,
    Relation = 3,
}

/// One id a filter-chain step dropped, tagged with which id-space it came
/// from. Used where a step can drop non-`Memory` items (supersession,
/// as-of, and the final limit truncation all operate on the fused
/// `RankedItemId` set, which includes `Statement`/`Relation`/`Entity`
/// alongside `Memory`).
#[derive(Clone, Copy, Debug, PartialEq, Serialize, Deserialize)]
pub struct RecallTraceDroppedId {
    pub kind: RankedItemKindWire,
    pub id: u128,
}

/// Filter-chain survivor counts after each step.
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct RecallTraceFilterChain {
    pub before: u32,
    pub after_type: u32,
    pub after_temporal: u32,
    pub after_confidence: u32,
    pub after_tombstone: u32,
    pub after_supersession: u32,
    pub after_as_of: u32,
    pub after_limit: u32,
    /// Only populated in full-detail mode: which memory ids were removed
    /// by this specific filter step (empty = nothing dropped here).
    pub dropped_by_type: Vec<WireMemoryId>,
    /// Only populated in full-detail mode: which memory ids were removed
    /// by this specific filter step (empty = nothing dropped here).
    pub dropped_by_temporal: Vec<WireMemoryId>,
    /// Only populated in full-detail mode: which memory ids were removed
    /// by this specific filter step (empty = nothing dropped here).
    pub dropped_by_confidence: Vec<WireMemoryId>,
    /// Only populated in full-detail mode: which memory ids were removed
    /// by this specific filter step (empty = nothing dropped here).
    pub dropped_by_tombstone: Vec<WireMemoryId>,
    /// Only populated in full-detail mode: which ids were removed by
    /// supersession, kind-tagged since this step drops `Statement` and
    /// `Relation` items, not just `Memory` ones (empty = nothing dropped
    /// here).
    pub dropped_by_supersession: Vec<RecallTraceDroppedId>,
    /// Only populated in full-detail mode: which ids the bi-temporal
    /// as-of filter removed, kind-tagged since this step drops `Statement`
    /// items (empty = nothing dropped here).
    pub dropped_by_as_of: Vec<RecallTraceDroppedId>,
    /// Only populated in full-detail mode: which ids the final `limit`
    /// truncation removed, kind-tagged since the truncated tail can
    /// contain any item kind (empty = nothing dropped here).
    pub dropped_by_limit: Vec<RecallTraceDroppedId>,
}

/// Outcome of the cross-encoder rerank stage in a RECALL trace.
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct RecallTraceRerank {
    pub applied: bool,
    pub candidates: u32,
    pub latency_ms: f64,
    /// Full-detail mode only: the fused (pre-rerank) order, so the client
    /// can show exactly what the cross-encoder moved.
    pub before_order: Vec<WireMemoryId>,
    /// Full-detail mode only: the post-rerank order, so the client can show
    /// exactly what the cross-encoder moved.
    pub after_order: Vec<WireMemoryId>,
}

/// Per-fused-item RRF score plus the per-lane component scores that
/// contributed to it, surfaced on a `RecallTrace` when the request opted
/// into tracing.
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct RecallTraceFusion {
    pub items: Vec<RecallTraceFusionItem>,
}

/// One fused item's RRF score plus the per-lane component scores that
/// contributed to it.
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct RecallTraceFusionItem {
    pub memory_id: WireMemoryId,
    pub rrf_score: f32,
    pub lane_scores: Vec<(RetrieverNameWire, f32)>,
}

/// A single recalled memory.
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct MemoryResult {
    pub memory_id: WireMemoryId,
    pub text: String,
    pub similarity_score: f32,
    pub confidence: f32,
    pub salience: f32,
    pub kind: MemoryKindWire,
    #[serde(with = "serde_bytes")]
    pub space_id: WireUuid,
    pub session_id: WireSessionId,
    pub created_at_unix_nanos: u64,
    pub last_accessed_at_unix_nanos: u64,
    pub edges: Option<Vec<EdgeView>>,
    pub contributing_retrievers: Vec<RetrieverNameWire>,
    pub fused_score: f32,
    pub rerank_score: Option<f32>,
    pub salience_initial: f32,
    pub access_count: u32,
    pub lsn: u64,
    pub flags: u32,
    pub consolidated_at_unix_nanos: Option<u64>,
    pub occurred_at_unix_nanos: Option<u64>,
    pub edges_out_count: u32,
    pub edges_in_count: u32,
    pub graph: Option<GraphEnrichment>,
}

/// Retriever family that surfaced a memory. Integer discriminant.
#[derive(
    Clone, Copy, Debug, Eq, PartialEq, serde_repr::Serialize_repr, serde_repr::Deserialize_repr,
)]
#[repr(u8)]
pub enum RetrieverNameWire {
    Semantic = 0,
    Lexical = 1,
    Graph = 2,
}

/// Outgoing edge view on a recalled memory.
#[derive(Clone, Copy, Debug, PartialEq, Serialize, Deserialize)]
pub struct EdgeView {
    pub target: WireMemoryId,
    pub kind: EdgeKindWire,
    pub weight: f32,
}

/// Per-hit typed-graph enrichment.
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct GraphEnrichment {
    pub entities: Vec<EnrichedEntity>,
    pub statements: Vec<EnrichedStatement>,
    pub relations: Vec<EnrichedRelation>,
}

/// A typed entity attached to a recall hit by [`GraphEnrichment`]: the resolved
/// entity id, its display name, and its schema type qname.
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct EnrichedEntity {
    #[serde(with = "serde_bytes")]
    pub id: [u8; 16],
    pub name: String,
    pub type_qname: String,
}

/// A typed statement attached to a recall hit by [`GraphEnrichment`], flattened
/// to display strings (subject name, predicate, object label) plus its
/// confidence.
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct EnrichedStatement {
    #[serde(with = "serde_bytes")]
    pub id: [u8; 16],
    pub subject_name: String,
    pub predicate: String,
    pub object_label: String,
    /// The object's entity id when the object IS an entity; `None` for a
    /// literal value.
    ///
    /// `object_label` alone cannot answer "is this an entity?" — it
    /// stringifies both cases — so a consumer had to guess by matching the
    /// label against known entity names, and that guess is wrong exactly when
    /// a literal's text equals an entity's name. Optional on the wire, so a
    /// peer that omits it still decodes; absent means "no entity object".
    #[serde(default, with = "crate::wire::cbor::opt_byte_array16")]
    pub object_entity_id: Option<[u8; 16]>,
    pub confidence: f32,
    /// When the statement's EVENT happened, in unix nanos — the reified
    /// Time slot of an Event-kind statement. Absent from the wire map for
    /// a statement with no event time.
    #[serde(skip_serializing_if = "Option::is_none", default)]
    pub event_at_unix_nanos: Option<u64>,
}

/// A typed relation attached to a recall hit by [`GraphEnrichment`], flattened
/// to the two endpoint names and the connecting predicate.
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct EnrichedRelation {
    pub from_name: String,
    pub predicate: String,
    pub to_name: String,
}

// ===========================================================================
// FORGET.
// ===========================================================================

/// FORGET (`0x0024`).
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
pub struct ForgetRequest {
    pub memory_id: WireMemoryId,
    pub mode: ForgetMode,
    #[serde(with = "serde_bytes")]
    pub request_id: WireUuid,
    #[serde(with = "crate::wire::cbor::opt_byte_array16")]
    pub txn_id: Option<WireUuid>,
    /// Effective identity this forget runs as. `None` (omitted on the wire)
    /// means the op runs as the connection's own key-bound identity.
    #[serde(skip_serializing_if = "Option::is_none", default)]
    pub act_as: Option<ActAs>,
}

/// FORGET_RESP (`0x00A4`).
#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)]
pub struct ForgetResponse {
    pub memory_id: WireMemoryId,
    pub was_already_forgotten: bool,
    pub edges_removed: u32,
}

// ===========================================================================
// LINK / UNLINK.
// ===========================================================================

/// LINK (`0x0025`). Creates (or reweights) an edge between two memories.
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct LinkRequest {
    pub source: WireMemoryId,
    pub target: WireMemoryId,
    pub kind: EdgeKindWire,
    /// `[0, 1]` for most kinds; `[-1, 1]` for `Contradicts`.
    pub weight: f32,
    #[serde(with = "serde_bytes")]
    pub request_id: WireUuid,
    #[serde(with = "crate::wire::cbor::opt_byte_array16")]
    pub txn_id: Option<WireUuid>,
    /// Effective identity this link runs as. `None` (omitted on the wire)
    /// means the op runs as the connection's own key-bound identity.
    #[serde(skip_serializing_if = "Option::is_none", default)]
    pub act_as: Option<ActAs>,
}

/// LINK_RESP (`0x00A5`).
#[derive(Clone, Copy, Debug, PartialEq, Serialize, Deserialize)]
pub struct LinkResponse {
    pub source: WireMemoryId,
    pub target: WireMemoryId,
    pub kind: EdgeKindWire,
    pub weight: f32,
    pub created_at_unix_nanos: u64,
    /// `true` if the edge already existed (LINK overwrote its weight);
    /// `false` if newly created.
    pub already_existed: bool,
}

/// UNLINK (`0x0026`). Removes the edge identified by the
/// `(source, kind, target)` triple.
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct UnlinkRequest {
    pub source: WireMemoryId,
    pub target: WireMemoryId,
    pub kind: EdgeKindWire,
    #[serde(with = "serde_bytes")]
    pub request_id: WireUuid,
    #[serde(with = "crate::wire::cbor::opt_byte_array16")]
    pub txn_id: Option<WireUuid>,
    /// Effective identity this unlink runs as. `None` (omitted on the wire)
    /// means the op runs as the connection's own key-bound identity.
    #[serde(skip_serializing_if = "Option::is_none", default)]
    pub act_as: Option<ActAs>,
}

/// UNLINK_RESP (`0x00A6`).
#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)]
pub struct UnlinkResponse {
    pub source: WireMemoryId,
    pub target: WireMemoryId,
    pub kind: EdgeKindWire,
    /// `true` if the edge existed and was removed; `false` if it didn't
    /// exist (UNLINK is idempotent — non-existent = no-op).
    pub removed: bool,
}

// ===========================================================================
// MEMORY_LIST.
// ===========================================================================

/// Sort axis for MEMORY_LIST. Integer discriminant on the wire. v1 supports
/// only `Created` end-to-end; the others are reserved wire values.
#[derive(
    Clone, Copy, Debug, Eq, PartialEq, serde_repr::Serialize_repr, serde_repr::Deserialize_repr,
)]
#[repr(u8)]
pub enum MemoryListSortWire {
    Created = 0,
    Salience = 1,
    Occurred = 2,
    LastAccessed = 3,
}

/// Sort direction for MEMORY_LIST. Integer discriminant on the wire.
#[derive(
    Clone, Copy, Debug, Eq, PartialEq, serde_repr::Serialize_repr, serde_repr::Deserialize_repr,
)]
#[repr(u8)]
pub enum MemoryListDirWire {
    Asc = 0,
    Desc = 1,
}

/// Which time field a MEMORY_LIST `from`/`to` range filters on. Integer
/// discriminant on the wire. v1 supports only `Created`.
#[derive(
    Clone, Copy, Debug, Eq, PartialEq, serde_repr::Serialize_repr, serde_repr::Deserialize_repr,
)]
#[repr(u8)]
pub enum MemoryListTimeAxisWire {
    Created = 0,
    Occurred = 1,
}

/// MEMORY_LIST (`0x0027`) — a paginated enumeration of the caller's
/// `(namespace, space)` memories. This is not RECALL: no query, no ranking.
/// It walks the tenant timeline in a stable order and returns a page plus an
/// opaque keyset cursor. Empty/zero fields mean "no filter". v1 supports
/// `sort = Created` (Asc/Desc); other sorts, the text filter, and the
/// occurred axis are rejected with InvalidRequest.
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct MemoryListRequest {
    pub sort: MemoryListSortWire,
    pub dir: MemoryListDirWire,
    /// Page size, validated server-side to `1..=100`.
    pub limit: u32,
    /// Empty on first page; opaque continuation token otherwise.
    pub cursor: Vec<u8>,
    /// Empty = all kinds; otherwise only these memory kinds are returned.
    pub kinds: Vec<MemoryKindWire>,
    /// When false, tombstoned memories are excluded; when true, both active
    /// and tombstoned rows are enumerated.
    pub include_tombstoned: bool,
    /// Which time field the `from`/`to` bounds apply to.
    pub time_axis: MemoryListTimeAxisWire,
    /// Inclusive lower time bound in unix-nanos; `0` = no lower bound.
    pub from_unix_nanos: u64,
    /// Inclusive upper time bound in unix-nanos; `0` = no upper bound.
    pub to_unix_nanos: u64,
    /// Inclusive salience floor in `[0, 1]`.
    pub salience_min: f32,
    /// Inclusive salience ceiling in `[0, 1]`.
    pub salience_max: f32,
    /// Substring/token filter over memory text; empty = no filter.
    pub text_contains: String,
    /// Effective identity this list runs as. `None` (omitted on the wire) means
    /// the op runs as the connection's own key-bound identity. Honored only when
    /// the connection principal holds the `ACT_AS` grant and the target
    /// namespace is in its `may_act` allowlist.
    #[serde(skip_serializing_if = "Option::is_none", default)]
    pub act_as: Option<ActAs>,
}

/// One memory in a MEMORY_LIST response batch. Carries the
/// enumeration-relevant fields plus relationship-handle counts.
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct MemoryListItem {
    #[serde(with = "serde_bytes")]
    pub memory_id: [u8; 16],
    /// Owner space (16-byte storage key) the row belongs to.
    #[serde(with = "serde_bytes")]
    pub space_id: [u8; 16],
    /// Session (conversation) the memory was encoded under; `0` = default.
    pub session_id: WireSessionId,
    pub text: String,
    /// Raw memory-kind byte (0 = Episodic, 1 = Semantic, 2 = Consolidated).
    pub kind: u8,
    /// Lifecycle state byte (0 = active, 1 = tombstoned).
    pub state: u8,
    pub created_at_unix_nanos: u64,
    /// Client-supplied event time; `0` when the memory has none.
    pub occurred_at_unix_nanos: u64,
    pub last_accessed_at_unix_nanos: u64,
    /// Point-in-time salience snapshot (it decays).
    pub salience: f32,
    pub access_count: u32,
    #[serde(with = "serde_bytes")]
    pub source_request_id: [u8; 16],
    pub statement_count: u32,
    pub entity_count: u32,
    pub relation_count: u32,
}

/// One streaming MEMORY_LIST_RESP frame (`0x00A7`). The last frame carries
/// `is_final = true`. Empty `next_cursor` on the final frame means "exhausted";
/// non-empty means "more pages available, resume with this".
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct MemoryListResponseFrame {
    pub items: Vec<MemoryListItem>,
    pub next_cursor: Vec<u8>,
    pub cumulative_count: u32,
    pub is_final: bool,
}

// ===========================================================================
// GRAPH_FETCH — full-space typed-graph export.
// ===========================================================================

/// One graph node. `id` is the 16-byte entity / statement / memory id; `kind`
/// says which id-space it is (0 = Entity, 1 = Statement, 2 = Memory).
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct GraphNode {
    #[serde(with = "serde_bytes")]
    pub id: [u8; 16],
    pub kind: u8,
    pub label: String,
    /// Entity type qname (e.g. `brain:Person`); empty for non-entity nodes.
    pub type_qname: String,
}

/// One graph edge. `kind`: 0 = Relation, 1 = Fact, 2 = HasStatement,
/// 3 = Mentions, 4..=11 = the memory↔memory builtin kinds in `EdgeKind` order
/// (`4 + EdgeKind as u8`), i.e. 4 = Caused, 5 = FollowedBy, 6 = DerivedFrom,
/// 7 = SimilarTo, 8 = Contradicts, 9 = Supports, 10 = References, 11 = PartOf.
/// The kind byte alone identifies the link — there is no companion field.
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct GraphEdge {
    #[serde(with = "serde_bytes")]
    pub from_id: [u8; 16],
    #[serde(with = "serde_bytes")]
    pub to_id: [u8; 16],
    pub kind: u8,
    /// Predicate / relation-type label; empty for `Mentions`.
    pub label: String,
}

/// GRAPH_FETCH (`0x0163`) — a paginated export of the caller's whole
/// `(namespace, space)` typed graph as a node/edge set. Default layer is the
/// concept map (entity nodes + Relation/Fact edges); `include_statements` adds
/// value-object statement nodes, `include_memories` adds source-memory nodes,
/// `include_memory_edges` adds the stored memory↔memory links between them.
/// The cursor is opaque, signed over the layer toggles.
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct GraphFetchRequest {
    /// Page size, validated server-side to `1..=500`.
    pub limit: u32,
    /// Empty on first page; opaque continuation token otherwise.
    pub cursor: Vec<u8>,
    /// Emit value-object statement nodes + their `HasStatement` edges.
    pub include_statements: bool,
    /// Emit source memory nodes + their `Mentions` edges.
    pub include_memories: bool,
    /// Emit the stored memory↔memory edges (`SimilarTo`, `FollowedBy`, …)
    /// incident to the page's memory nodes. Requires `include_memories` —
    /// setting it alone is rejected, because the edges would have no rendered
    /// endpoints. A far endpoint outside the page is emitted as a memory node
    /// so no edge dangles.
    pub include_memory_edges: bool,
    /// Include tombstoned statements/relations. Default false.
    pub include_tombstoned: bool,
    /// Effective identity this export runs as. `None` (omitted on the wire)
    /// runs as the connection's own key-bound identity.
    #[serde(skip_serializing_if = "Option::is_none", default)]
    pub act_as: Option<ActAs>,
}

/// One streaming GRAPH_FETCH_RESP frame (`0x01E3`). Nodes/edges may repeat
/// across pages (completeness, not disjointness) — dedup by id. Empty
/// `next_cursor` means exhausted.
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct GraphFetchResponseFrame {
    pub nodes: Vec<GraphNode>,
    pub edges: Vec<GraphEdge>,
    pub next_cursor: Vec<u8>,
    pub is_final: bool,
}

// ===========================================================================
// PLAN.
// ===========================================================================

/// Plan-strategy hint. Integer discriminant on the wire.
#[derive(
    Clone, Copy, Debug, Eq, PartialEq, serde_repr::Serialize_repr, serde_repr::Deserialize_repr,
)]
#[repr(u8)]
pub enum PlanStrategy {
    Auto = 0,
    AStar = 1,
    Mcts = 2,
    AttractorRollout = 3,
}

/// Plan endpoint specification. Externally-tagged enum (CBOR map keyed by
/// the variant name), matching the server.
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub enum PlanState {
    ByMemoryId(WireMemoryId),
    ByText(String),
    ByVector { offset: u32, dim: u16 },
}

/// Plan budget.
#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)]
pub struct PlanBudget {
    pub max_steps: u32,
    pub max_wall_time_ms: u32,
    pub max_branches_explored: u32,
}

/// PLAN (`0x0022`).
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct PlanRequest {
    pub start: PlanState,
    pub goal: PlanState,
    pub budget: PlanBudget,
    pub strategy_hint: Option<PlanStrategy>,
    pub session_filter: Option<Vec<WireSessionId>>,
    #[serde(with = "crate::wire::cbor::opt_byte_array16")]
    pub request_id: Option<WireUuid>,
    #[serde(with = "crate::wire::cbor::opt_byte_array16")]
    pub txn_id: Option<WireUuid>,
    /// Opt-in per-stage observability. When `true`, the final response frame
    /// carries a populated `trace: PlanTrace` describing every node the
    /// bidirectional BFS visited (in both directions) and every meeting
    /// point found, including the ones dropped by the `max_paths` cap. When
    /// `false` (the default) the field is absent and the plan pays nothing.
    /// Mirrors `RecallRequest.trace`.
    #[serde(default)]
    pub trace: bool,
    /// Effective identity this plan runs as. `None` (omitted on the wire)
    /// means the op runs as the connection's own key-bound identity.
    #[serde(skip_serializing_if = "Option::is_none", default)]
    pub act_as: Option<ActAs>,
}

/// Plan terminal status, set on the final frame only. Integer discriminant.
#[derive(
    Clone, Copy, Debug, Eq, PartialEq, serde_repr::Serialize_repr, serde_repr::Deserialize_repr,
)]
#[repr(u8)]
pub enum PlanStatus {
    GoalReached = 0,
    BudgetExhausted = 1,
    NoPathFound = 2,
    Cancelled = 3,
}

/// Transition kind between plan steps. Externally-tagged enum, matching the
/// server (`Other` carries a free-form string).
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub enum TransitionKind {
    Initial,
    Causal,
    Temporal,
    Similarity,
    Other(String),
}

/// One step in a plan.
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct PlanStep {
    pub step_index: u32,
    pub memory_id: WireMemoryId,
    pub text: String,
    pub transition_kind: TransitionKind,
    pub confidence: f32,
    pub estimated_distance_to_goal: f32,
}

/// One streaming PLAN_RESP frame (`0x00A2`). The last frame carries
/// `is_final = true` and a populated `plan_status`.
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct PlanResponseFrame {
    pub steps: Vec<PlanStep>,
    pub is_final: bool,
    pub plan_status: Option<PlanStatus>,
    /// Per-stage bidirectional-search trace. Populated only on the final
    /// frame and only when the request set `trace = true`; `None` otherwise
    /// (and omitted from the wire map so `trace = false` plans pay
    /// nothing). Mirrors `RecallResponseFrame.trace`.
    #[serde(skip_serializing_if = "Option::is_none", default)]
    pub trace: Option<PlanTrace>,
}

/// Per-stage observability for one PLAN, surfaced on the final frame when
/// the request opted in with `trace = true`. `trace = true` means full
/// detail — there is no separate knob — so every field below is populated
/// whenever this struct is present at all. Surfaces the full bidirectional
/// BFS visited-map contents from both directions (not just a scalar
/// explored-node count) and every meeting point found, flagging which
/// survived the `max_paths` cap.
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct PlanTrace {
    /// Every node the bidirectional BFS visited, in both directions.
    pub explored: Vec<PlanTraceNode>,
    /// Every meeting point the BFS found, flagging which ones survived the
    /// `max_paths` cap and made it into the returned path(s).
    pub meeting_points: Vec<PlanTraceMeetingPoint>,
}

/// Which direction of the bidirectional BFS a `PlanTraceNode` was visited
/// from. Integer discriminant on the wire.
#[derive(
    Clone, Copy, Debug, Eq, PartialEq, serde_repr::Serialize_repr, serde_repr::Deserialize_repr,
)]
#[repr(u8)]
pub enum PlanTraceDirection {
    /// Visited by the forward search, rooted at `start`.
    Forward = 0,
    /// Visited by the backward search, rooted at `goal`.
    Backward = 1,
}

/// One node the bidirectional BFS visited, from either direction.
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct PlanTraceNode {
    pub memory_id: WireMemoryId,
    pub text: String,
    pub direction: PlanTraceDirection,
    pub depth: u32,
    /// The edge this node was reached through. `None` for the root
    /// (`start` in the forward direction, `goal` in the backward
    /// direction).
    pub parent_edge: Option<WireMemoryId>,
    /// The goal-proximity alignment score computed for this node, when one
    /// was computed.
    pub alignment_score: Option<f32>,
}

/// One meeting point the bidirectional BFS found where the forward and
/// backward frontiers connected.
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct PlanTraceMeetingPoint {
    pub memory_id: WireMemoryId,
    pub text: String,
    /// `true` when this meeting point survived the `max_paths` cap and
    /// contributed a path to the response; `false` when it was found but
    /// dropped by the cap.
    pub included_in_result: bool,
}

// ===========================================================================
// REASON.
// ===========================================================================

/// What to reason about. Externally-tagged enum, matching the server.
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub enum ObservationInput {
    ByMemoryId(WireMemoryId),
    ByText(String),
}

/// REASON (`0x0023`).
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct ReasonRequest {
    pub observation: ObservationInput,
    pub depth: u32,
    pub confidence_threshold: f32,
    pub session_filter: Option<Vec<WireSessionId>>,
    pub max_inferences: u32,
    pub budget_wall_time_ms: u32,
    #[serde(with = "crate::wire::cbor::opt_byte_array16")]
    pub request_id: Option<WireUuid>,
    #[serde(with = "crate::wire::cbor::opt_byte_array16")]
    pub txn_id: Option<WireUuid>,
    /// Opt-in per-stage observability. When `true`, the final response frame
    /// carries a populated `trace: ReasonTrace` describing the full
    /// base-candidate set, every edge the outward walk considered (and why
    /// each was pruned), the un-collapsed per-item score components, and
    /// whether topic-alignment centroid computation ran. When `false` (the
    /// default) the field is absent and the reason pays nothing. Mirrors
    /// `RecallRequest.trace`.
    #[serde(default)]
    pub trace: bool,
    /// Effective identity this reason runs as. `None` (omitted on the wire)
    /// means the op runs as the connection's own key-bound identity.
    #[serde(skip_serializing_if = "Option::is_none", default)]
    pub act_as: Option<ActAs>,
}

/// Reason terminal status, set on the final frame only. Integer discriminant.
#[derive(
    Clone, Copy, Debug, Eq, PartialEq, serde_repr::Serialize_repr, serde_repr::Deserialize_repr,
)]
#[repr(u8)]
pub enum ReasonStatus {
    Complete = 0,
    BudgetExhausted = 1,
    DepthLimitReached = 2,
    Cancelled = 3,
}

/// Inference kind. Externally-tagged enum, matching the server (`Other`
/// carries a free-form string).
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub enum InferenceKind {
    CausalExplanation,
    EvidenceAccumulation,
    AnalogicalInference,
    Other(String),
}

/// One inference step.
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct InferenceStep {
    pub step_index: u32,
    pub claim: String,
    pub supporting_memories: Vec<WireMemoryId>,
    pub contradicting_memories: Vec<WireMemoryId>,
    pub confidence: f32,
    pub inference_kind: InferenceKind,
}

/// One streaming REASON_RESP frame (`0x00A3`). The last frame carries
/// `is_final = true` and a populated `reason_status`.
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct ReasonResponseFrame {
    pub inferences: Vec<InferenceStep>,
    pub is_final: bool,
    pub reason_status: Option<ReasonStatus>,
    /// Per-stage read-pipeline trace. Populated only on the final frame and
    /// only when the request set `trace = true`; `None` otherwise (and
    /// omitted from the wire map so `trace = false` reasons pay nothing).
    /// Mirrors `RecallResponseFrame.trace`.
    #[serde(skip_serializing_if = "Option::is_none", default)]
    pub trace: Option<ReasonTrace>,
}

/// Per-stage observability for one REASON, surfaced on the final frame when
/// the request opted in with `trace = true`. `trace = true` means full
/// detail — there is no separate knob — so every field below is populated
/// whenever this struct is present at all. Mirrors `RecallTrace`'s
/// per-stage-detail precedent, applied to the outward evidence walk instead
/// of the retriever fan-out.
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct ReasonTrace {
    /// The full HNSW hit set the base observation resolved to, not just the
    /// subset that seeded the walk.
    pub base: ReasonTraceBase,
    /// Everything the outward evidence walk touched: considered edges and
    /// every prune reason, one bucket per prune point.
    pub walk: ReasonTraceWalk,
    /// Un-collapsed score components for every surviving evidence item.
    pub scoring: Vec<ReasonTraceScoreBreakdown>,
    /// Whether topic-alignment centroid computation ran, and why not when
    /// it didn't.
    pub centroid: ReasonTraceCentroid,
}

/// The base observation's resolved candidate set, before any evidence walk.
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct ReasonTraceBase {
    pub candidates: Vec<ReasonTraceCandidate>,
}

/// One base-candidate hit surfaced in a REASON trace.
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct ReasonTraceCandidate {
    pub memory_id: WireMemoryId,
    pub text: String,
    pub score: f32,
}

/// Everything the outward evidence walk considered and every reason an edge
/// or item was pruned before becoming a surviving `InferenceStep`.
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct ReasonTraceWalk {
    /// Every edge the walk visited at each node, before any pruning — the
    /// direct analogue of `RecallTraceRetriever.candidates`.
    pub considered: Vec<ReasonTraceEdgeCandidate>,
    /// Edges pruned by the edge-kind filter.
    pub dropped_by_edge_kind: Vec<ReasonTraceEdgeCandidate>,
    /// Edges pruned because the target memory was tombstoned.
    pub dropped_by_tombstone: Vec<ReasonTraceIdWithText>,
    /// Edges pruned because the target memory was already visited.
    pub dropped_by_visited: Vec<ReasonTraceIdWithText>,
    /// Evidence items pruned by `confidence_threshold`.
    pub dropped_by_confidence: Vec<ReasonTraceScoredId>,
    /// Supporting-evidence items dropped by the per-inference trim cap.
    pub dropped_by_max_supporting: Vec<ReasonTraceIdWithText>,
    /// Contradicting-evidence items dropped by the per-inference trim cap.
    pub dropped_by_max_contradicting: Vec<ReasonTraceIdWithText>,
}

/// One edge the outward walk visited, considered or dropped.
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct ReasonTraceEdgeCandidate {
    pub memory_id: WireMemoryId,
    pub text: String,
    pub edge_kind: EdgeKindWire,
    pub depth: u32,
    pub from_memory_id: WireMemoryId,
    pub raw_score: f32,
}

/// A memory id plus its stored text, with no other payload — the shared
/// shape for the walk's plain id-dropped buckets (tombstone / visited /
/// trim-cap) so an opaque id is never surfaced without the content that
/// explains the drop.
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct ReasonTraceIdWithText {
    pub memory_id: WireMemoryId,
    pub text: String,
}

/// A memory id paired with the score it was dropped at.
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct ReasonTraceScoredId {
    pub memory_id: WireMemoryId,
    pub text: String,
    pub score: f32,
}

/// The un-collapsed multiplicative score components combined into one
/// `InferenceStep.confidence` value.
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct ReasonTraceScoreBreakdown {
    pub memory_id: WireMemoryId,
    pub text: String,
    pub base_similarity: f32,
    pub decay: f32,
    pub weight_product: f32,
    pub alignment: f32,
    /// Structural-fit nudge from VSA analogical inference (bind/bundle/
    /// `analogy_query` over the item's statement-graph triple against the
    /// observation's own triple). Neutral `1.0` when no triple is
    /// resolvable for the item — a re-rank nudge only, never a gate.
    pub analogical_fit: f32,
    pub final_score: f32,
}

/// Whether topic-alignment centroid computation ran for this REASON. The
/// server's centroid step silently skips several paths (singleton base,
/// text-only observation, missing text, embed error); this makes that
/// outcome visible on the wire instead of a debug-log-only signal.
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct ReasonTraceCentroid {
    pub computed: bool,
    /// Populated when `computed = false`; empty otherwise.
    pub skipped_reason: Option<String>,
}

// ===========================================================================
// ERROR.
// ===========================================================================

/// Error category — the retry axis. Integer discriminant on the wire.
#[derive(
    Clone, Copy, Debug, Eq, PartialEq, serde_repr::Serialize_repr, serde_repr::Deserialize_repr,
)]
#[repr(u8)]
pub enum ErrorCategoryWire {
    Protocol = 0,
    Authentication = 1,
    Authorization = 2,
    Validation = 3,
    NotFound = 4,
    Conflict = 5,
    ResourceExhausted = 6,
    Internal = 7,
    Unavailable = 8,
}

/// Wire error code (`u16`). Carried in an ERROR frame; the integer value
/// is the stable programmatic handle.
/// Fine-grained wire error code.
///
/// ## Forward compatibility
///
/// Decoding is **total**: a code this build does not know maps to
/// [`ErrorCodeWire::Unknown`] rather than failing the frame. That matters
/// because the server adds codes over time, and the Python and TypeScript
/// SDKs both model `code` as a plain integer — so a newer server's ERROR
/// frame is readable there. Before this, Rust derived `Deserialize_repr` with
/// no catch-all, so a single unrecognised code made the whole ERROR frame
/// undecodable and the client reported a parse failure instead of the
/// server's actual error. That is a divergence from the other two SDKs, not a
/// deliberate choice.
///
/// `Unknown` deliberately carries no payload so the enum keeps its `repr(u16)`
/// and every `as u16` cast still works. Callers that need to distinguish an
/// unrecognised code use [`ErrorResponse::code_is_unknown`].
#[derive(Clone, Copy, Debug, Eq, PartialEq, serde_repr::Serialize_repr)]
#[repr(u16)]
pub enum ErrorCodeWire {
    // Protocol.
    BadMagic = 0x0001,
    BadHeaderCrc = 0x0002,
    BadPayloadCrc = 0x0003,
    BadOpcode = 0x0004,
    BadVersion = 0x0005,
    BadFrame = 0x0006,
    OversizePayload = 0x0007,
    ReservedFieldNonZero = 0x0008,
    BadFlagCombination = 0x0009,
    MalformedPayload = 0x000A,
    MalformedVector = 0x000B,
    // Connection / handshake.
    VersionNotSupported = 0x0020,
    NoSuchAuthMethod = 0x0021,
    Unauthenticated = 0x0022,
    NotAuthenticated = 0x0023,
    AuthBackendUnavailable = 0x0024,
    SessionExpired = 0x0025,
    // Authorization.
    PermissionDenied = 0x0030,
    AdminPermissionRequired = 0x0031,
    WrongShard = 0x0032,
    ActAsDenied = 0x0033,
    // Validation.
    InvalidArgument = 0x0040,
    MissingRequiredField = 0x0041,
    TextTooLarge = 0x0042,
    TextEmpty = 0x0043,
    BadSessionId = 0x0044,
    BadMemoryKind = 0x0045,
    BadEdgeKind = 0x0046,
    BadStrategyHint = 0x0047,
    TopKOutOfRange = 0x0048,
    BudgetTooLarge = 0x0049,
    BadModelFingerprint = 0x004A,
    PredicateNotInSchema = 0x004B,
    RelationTypeNotInSchema = 0x004C,
    // Not found.
    MemoryNotFound = 0x0050,
    ContextNotFound = 0x0051,
    SubscriptionNotFound = 0x0052,
    SnapshotNotFound = 0x0053,
    TxnNotFound = 0x0054,
    // Conflict.
    IdempotencyConflict = 0x0060,
    TransactionConflict = 0x0061,
    TransactionTimeout = 0x0062,
    StreamIdInUse = 0x0063,
    SubscriptionLsnTooOld = 0x0064,
    CardinalityViolation = 0x0065,
    /// The write's namespace has no usable LLM provider credential.
    /// **Terminal** — do not retry; the tenant must register a key.
    LlmCredentialMissing = 0x0066,
    // Resource exhausted.
    OutOfSlots = 0x0070,
    OutOfDisk = 0x0071,
    OutOfMemory = 0x0072,
    RateLimited = 0x0073,
    StreamLimitExceeded = 0x0074,
    ConnectionLimitExceeded = 0x0075,
    TransactionLimitExceeded = 0x0076,
    TransactionTooLarge = 0x0077,
    // Internal.
    Internal = 0x0080,
    StorageError = 0x0081,
    IndexError = 0x0082,
    EmbeddingError = 0x0083,
    MetadataError = 0x0084,
    Cancelled = 0x0085,
    // Unavailable.
    ShardUnavailable = 0x0090,
    Overloaded = 0x0091,
    Restarting = 0x0092,
    Maintenance = 0x0093,
    RetrieverDegraded = 0x0094,
    /// The namespace's LLM credential could not be resolved right now —
    /// broker unreachable, timed out, or transiently failing. **Retryable.**
    LlmCredentialUnavailable = 0x0095,
    // Typed-graph.
    SchemaInvalid = 0x0120,
    SchemaMigrationRequired = 0x0121,
    EntityNotFound = 0x0130,
    EntityTypeMismatch = 0x0131,
    EntityAmbiguous = 0x0132,
    EntityMergeConflict = 0x0133,
    StatementNotFound = 0x0140,
    StatementObjectTypeMismatch = 0x0141,
    StatementContradictsExisting = 0x0142,
    QueryTimeout = 0x0160,
    QueryOverBudget = 0x0161,
    ExtractorDisabled = 0x0170,
    ExtractorBudgetExceeded = 0x0171,
    ExtractionFailed = 0x0172,
    /// A code this build does not recognise. See the type docs: decoding is
    /// total so a newer server cannot make an ERROR frame unreadable.
    Unknown = 0xFFFF,
}

impl ErrorCodeWire {
    /// Map a raw wire value to a known code, or [`Self::Unknown`].
    ///
    /// Exhaustive over every code this build knows; anything else is
    /// `Unknown`, which is what makes decoding total.
    #[must_use]
    pub fn from_raw(raw: u16) -> Self {
        match raw {
            0x0001 => Self::BadMagic,
            0x0002 => Self::BadHeaderCrc,
            0x0003 => Self::BadPayloadCrc,
            0x0004 => Self::BadOpcode,
            0x0005 => Self::BadVersion,
            0x0006 => Self::BadFrame,
            0x0007 => Self::OversizePayload,
            0x0008 => Self::ReservedFieldNonZero,
            0x0009 => Self::BadFlagCombination,
            0x000A => Self::MalformedPayload,
            0x000B => Self::MalformedVector,
            0x0020 => Self::VersionNotSupported,
            0x0021 => Self::NoSuchAuthMethod,
            0x0022 => Self::Unauthenticated,
            0x0023 => Self::NotAuthenticated,
            0x0024 => Self::AuthBackendUnavailable,
            0x0025 => Self::SessionExpired,
            0x0030 => Self::PermissionDenied,
            0x0031 => Self::AdminPermissionRequired,
            0x0032 => Self::WrongShard,
            0x0033 => Self::ActAsDenied,
            0x0040 => Self::InvalidArgument,
            0x0041 => Self::MissingRequiredField,
            0x0042 => Self::TextTooLarge,
            0x0043 => Self::TextEmpty,
            0x0044 => Self::BadSessionId,
            0x0045 => Self::BadMemoryKind,
            0x0046 => Self::BadEdgeKind,
            0x0047 => Self::BadStrategyHint,
            0x0048 => Self::TopKOutOfRange,
            0x0049 => Self::BudgetTooLarge,
            0x004A => Self::BadModelFingerprint,
            0x004B => Self::PredicateNotInSchema,
            0x004C => Self::RelationTypeNotInSchema,
            0x0050 => Self::MemoryNotFound,
            0x0051 => Self::ContextNotFound,
            0x0052 => Self::SubscriptionNotFound,
            0x0053 => Self::SnapshotNotFound,
            0x0054 => Self::TxnNotFound,
            0x0060 => Self::IdempotencyConflict,
            0x0061 => Self::TransactionConflict,
            0x0062 => Self::TransactionTimeout,
            0x0063 => Self::StreamIdInUse,
            0x0064 => Self::SubscriptionLsnTooOld,
            0x0065 => Self::CardinalityViolation,
            0x0070 => Self::OutOfSlots,
            0x0071 => Self::OutOfDisk,
            0x0072 => Self::OutOfMemory,
            0x0073 => Self::RateLimited,
            0x0074 => Self::StreamLimitExceeded,
            0x0075 => Self::ConnectionLimitExceeded,
            0x0076 => Self::TransactionLimitExceeded,
            0x0077 => Self::TransactionTooLarge,
            0x0080 => Self::Internal,
            0x0081 => Self::StorageError,
            0x0082 => Self::IndexError,
            0x0083 => Self::EmbeddingError,
            0x0084 => Self::MetadataError,
            0x0085 => Self::Cancelled,
            0x0090 => Self::ShardUnavailable,
            0x0091 => Self::Overloaded,
            0x0092 => Self::Restarting,
            0x0093 => Self::Maintenance,
            0x0094 => Self::RetrieverDegraded,
            0x0120 => Self::SchemaInvalid,
            0x0121 => Self::SchemaMigrationRequired,
            0x0130 => Self::EntityNotFound,
            0x0131 => Self::EntityTypeMismatch,
            0x0132 => Self::EntityAmbiguous,
            0x0133 => Self::EntityMergeConflict,
            0x0140 => Self::StatementNotFound,
            0x0141 => Self::StatementObjectTypeMismatch,
            0x0142 => Self::StatementContradictsExisting,
            0x0160 => Self::QueryTimeout,
            0x0161 => Self::QueryOverBudget,
            0x0170 => Self::ExtractorDisabled,
            0x0171 => Self::ExtractorBudgetExceeded,
            0x0172 => Self::ExtractionFailed,
            0x0066 => Self::LlmCredentialMissing,
            0x0095 => Self::LlmCredentialUnavailable,
            _ => Self::Unknown,
        }
    }
}

impl<'de> serde::Deserialize<'de> for ErrorCodeWire {
    fn deserialize<D: serde::Deserializer<'de>>(d: D) -> Result<Self, D::Error> {
        Ok(Self::from_raw(u16::deserialize(d)?))
    }
}

/// Structured detail attached to an error.
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
pub struct ErrorDetails {
    pub field: Option<String>,
    pub expected: Option<String>,
    pub actual: Option<String>,
}

/// ERROR (`0x00FF`).
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct ErrorResponse {
    pub code: ErrorCodeWire,
    pub category: ErrorCategoryWire,
    pub message: String,
    pub details: Option<ErrorDetails>,
    pub retry_after_ms: Option<u32>,
}

impl ErrorResponse {
    /// True when the server sent a code this build does not know. Callers
    /// should fall back to [`Self::category`], which is the field the wire
    /// contract guarantees is always meaningful.
    #[must_use]
    pub fn code_is_unknown(&self) -> bool {
        self.code == ErrorCodeWire::Unknown
    }
}

// ===========================================================================
// Typed-graph payloads exercised by the corpus.
// ===========================================================================

/// Statement kind. The fieldless variants encode as a CBOR **string** unit
/// variant (plain serde, not an integer discriminant); `Custom(u8)` encodes
/// as a single-entry CBOR map `{"Custom": <byte>}` — the server does the
/// same. The storage-byte mapping is `0 = Fact`, `1 = Preference`,
/// `2 = Event`, `3 = Attribute`, `4 = Relation`, `5 = Directive`, and any
/// byte `>= 6` is a `Custom(byte)`.
#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)]
pub enum StatementKindWire {
    Fact,
    Preference,
    Event,
    Attribute,
    Relation,
    Directive,
    Custom(u8),
}

impl StatementKindWire {
    /// The storage discriminant byte for this kind.
    #[must_use]
    pub fn to_storage_byte(self) -> u8 {
        match self {
            StatementKindWire::Fact => 0,
            StatementKindWire::Preference => 1,
            StatementKindWire::Event => 2,
            StatementKindWire::Attribute => 3,
            StatementKindWire::Relation => 4,
            StatementKindWire::Directive => 5,
            StatementKindWire::Custom(b) => b,
        }
    }

    /// The kind for a storage discriminant byte. Bytes `>= 6` map to
    /// `Custom(byte)`.
    #[must_use]
    pub fn from_storage_byte(byte: u8) -> Self {
        match byte {
            0 => StatementKindWire::Fact,
            1 => StatementKindWire::Preference,
            2 => StatementKindWire::Event,
            3 => StatementKindWire::Attribute,
            4 => StatementKindWire::Relation,
            5 => StatementKindWire::Directive,
            b => StatementKindWire::Custom(b),
        }
    }
}

/// Scalar object value. Externally-tagged.
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub enum StatementValueWire {
    Text(String),
    Integer(i64),
    Float(f64),
    Bool(bool),
    UnixNanos(u64),
    Blob(Vec<u8>),
}

/// Statement object. Each id variant is a CBOR byte string.
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub enum StatementObjectWire {
    EntityRef(#[serde(with = "serde_bytes")] WireUuid),
    Value(StatementValueWire),
    MemoryRef(#[serde(with = "serde_bytes")] [u8; 16]),
    StatementRef(#[serde(with = "serde_bytes")] WireUuid),
}

/// Evidence reference. `Inline` is an array of byte-string memory ids.
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub enum EvidenceRefWire {
    Inline(#[serde(with = "crate::wire::cbor::vec_byte_array16")] Vec<[u8; 16]>),
    Overflow(#[serde(with = "serde_bytes")] WireUuid),
}

/// ENTITY_CREATE (`0x0130`).
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct EntityCreateRequest {
    pub entity_type_id: u32,
    pub canonical_name: String,
    pub aliases: Vec<String>,
    pub attributes_blob: Vec<u8>,
    /// Session that first mentions this entity; `0` = default session.
    /// First-mention provenance only — entity identity is session-agnostic.
    #[serde(default)]
    pub session_id: WireSessionId,
    #[serde(with = "serde_bytes")]
    pub request_id: WireUuid,
    /// Effective identity this entity-create runs as. `None` (omitted on the
    /// wire) means the op runs as the connection's own key-bound identity.
    #[serde(skip_serializing_if = "Option::is_none", default)]
    pub act_as: Option<ActAs>,
}

/// ENTITY_UPDATE (`0x0132`). Replace an entity's name, aliases, and
/// attribute blob wholesale — the way an agent revises what it knows about a
/// thing as new detail arrives.
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct EntityUpdateRequest {
    #[serde(with = "serde_bytes")]
    pub entity_id: WireUuid,
    pub canonical_name: String,
    pub aliases: Vec<String>,
    pub attributes_blob: Vec<u8>,
    #[serde(with = "serde_bytes")]
    pub request_id: WireUuid,
}

/// ENTITY_UPDATE_RESP (`0x01B2`). The post-update view.
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct EntityUpdateResponse {
    pub entity: EntityView,
}

/// ENTITY_RENAME (`0x0133`). Change only the canonical name. `move_to_alias`
/// keeps the old name reachable as an alias instead of dropping it, so a
/// rename never silently loses a name the graph already links by.
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct EntityRenameRequest {
    #[serde(with = "serde_bytes")]
    pub entity_id: WireUuid,
    pub new_canonical_name: String,
    pub move_to_alias: bool,
    #[serde(with = "serde_bytes")]
    pub request_id: WireUuid,
}

/// ENTITY_RENAME_RESP (`0x01B3`). The post-rename view.
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct EntityRenameResponse {
    pub entity: EntityView,
}

/// ENTITY_MERGE (`0x0134`). Fold `merged` into `survivor` when they turn out
/// to be the same real-world entity. The merge is reversible within a grace
/// window (see the response), so a wrong merge is recoverable rather than
/// destructive.
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct EntityMergeRequest {
    #[serde(with = "serde_bytes")]
    pub survivor: WireUuid,
    #[serde(with = "serde_bytes")]
    pub merged: WireUuid,
    pub confidence: f32,
    pub reason: String,
    #[serde(with = "serde_bytes")]
    pub request_id: WireUuid,
}

/// ENTITY_MERGE_RESP (`0x01B4`). `audit_id` is the merge record (not an
/// entity id); `grace_period_seconds` is how long an unmerge can still undo it.
#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)]
pub struct EntityMergeResponse {
    #[serde(with = "serde_bytes")]
    pub audit_id: WireUuid,
    pub grace_period_seconds: u64,
}

/// ENTITY_UNMERGE (`0x0135`). Undo a merge, restoring the folded-away entity
/// as its own row again. Only valid inside the merge's grace window.
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct EntityUnmergeRequest {
    #[serde(with = "serde_bytes")]
    pub merged_entity: WireUuid,
    #[serde(with = "serde_bytes")]
    pub request_id: WireUuid,
}

/// ENTITY_UNMERGE_RESP (`0x01B5`). The id the restored entity now lives under.
#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)]
pub struct EntityUnmergeResponse {
    #[serde(with = "serde_bytes")]
    pub restored_entity_id: WireUuid,
}

/// ENTITY_TOMBSTONE (`0x0138`). Retire an entity with a reason for the audit
/// trail. Tombstoning is soft — the row survives (recoverable) but drops out
/// of resolution and traversal.
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct EntityTombstoneRequest {
    #[serde(with = "serde_bytes")]
    pub entity_id: WireUuid,
    pub reason: String,
    #[serde(with = "serde_bytes")]
    pub request_id: WireUuid,
}

/// ENTITY_TOMBSTONE_RESP (`0x01B8`). When the retirement took effect.
#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)]
pub struct EntityTombstoneResponse {
    pub tombstoned_at_unix_nanos: u64,
}

/// ENTITY_CREATE_RESP (`0x01B0`). The id is a plain CBOR array of bytes,
/// not a byte string — the server's response struct omits `serde_bytes`
/// on this field.
#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)]
pub struct EntityCreateResponse {
    #[serde(with = "serde_bytes")]
    pub entity_id: WireUuid,
}

/// STATEMENT_CREATE (`0x0140`).
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct StatementCreateRequest {
    pub kind: StatementKindWire,
    #[serde(with = "serde_bytes")]
    pub subject: WireUuid,
    pub predicate: String,
    pub object: StatementObjectWire,
    pub confidence: f32,
    pub evidence: EvidenceRefWire,
    pub extractor_id: u32,
    pub valid_from_unix_nanos: u64,
    pub valid_to_unix_nanos: u64,
    pub event_at_unix_nanos: u64,
    pub schema_version: u32,
    /// Conversation/run this statement belongs to; `0` = default session.
    /// A grouping key, not an isolation boundary.
    #[serde(default)]
    pub session_id: WireSessionId,
    #[serde(with = "serde_bytes")]
    pub request_id: WireUuid,
    /// Effective identity this statement-create runs as. `None` (omitted on
    /// the wire) means the op runs as the connection's own key-bound identity.
    #[serde(skip_serializing_if = "Option::is_none", default)]
    pub act_as: Option<ActAs>,
}

/// STATEMENT_CREATE_RESP (`0x01C0`). All ids encode as CBOR byte strings
/// (major type 2), matching the server's uniform 16-byte id encoding.
#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)]
pub struct StatementCreateResponse {
    #[serde(with = "serde_bytes")]
    pub statement_id: WireUuid,
    #[serde(with = "serde_bytes")]
    pub auto_superseded: WireUuid,
    #[serde(with = "serde_bytes")]
    pub chain_root: WireUuid,
}

/// STATEMENT_SUPERSEDE (`0x0142`). Replace an existing claim with a revised
/// one, keeping both linked on the same supersession chain so history stays
/// intact — the way an agent updates a belief without erasing what it used to
/// hold.
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct StatementSupersedeRequest {
    #[serde(with = "serde_bytes")]
    pub old_statement_id: WireUuid,
    pub new_statement: StatementCreateRequest,
    #[serde(with = "serde_bytes")]
    pub request_id: WireUuid,
}

/// STATEMENT_SUPERSEDE_RESP (`0x01C2`). The new statement plus its chain root
/// and monotonically-increasing version.
#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)]
pub struct StatementSupersedeResponse {
    #[serde(with = "serde_bytes")]
    pub new_statement_id: WireUuid,
    #[serde(with = "serde_bytes")]
    pub chain_root: WireUuid,
    pub version: u32,
}

/// STATEMENT_TOMBSTONE (`0x0143`). Retire a statement with a coded reason for
/// the audit trail. Soft: the row survives (recoverable) but stops answering.
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct StatementTombstoneRequest {
    #[serde(with = "serde_bytes")]
    pub statement_id: WireUuid,
    pub reason: u8,
    pub reason_message: String,
    #[serde(with = "serde_bytes")]
    pub request_id: WireUuid,
}

/// STATEMENT_TOMBSTONE_RESP (`0x01C3`). When the retirement took effect.
#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)]
pub struct StatementTombstoneResponse {
    pub tombstoned_at_unix_nanos: u64,
}

/// STATEMENT_RETRACT (`0x0144`). Assert a claim was wrong (not merely
/// superseded). Retraction schedules a hard-zero after a window, so a genuine
/// mistake can be scrubbed rather than left tombstoned forever.
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct StatementRetractRequest {
    #[serde(with = "serde_bytes")]
    pub statement_id: WireUuid,
    pub reason: u8,
    pub reason_message: String,
    #[serde(with = "serde_bytes")]
    pub request_id: WireUuid,
}

/// STATEMENT_RETRACT_RESP (`0x01C4`). When it was retracted, and when the
/// scheduled hard-zero will scrub it.
#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)]
pub struct StatementRetractResponse {
    pub retracted_at_unix_nanos: u64,
    pub will_zero_at_unix_nanos: u64,
}

/// STATEMENT_HISTORY (`0x0145`). Walk every version on a claim's supersession
/// chain. A read, so it carries no `request_id`. Keyset-paginated on the
/// immutable chain `version`: `limit` in `1..=1000`, `cursor` opaque — empty on
/// the first page, then the `next_cursor` echoed from the previous response.
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct StatementHistoryRequest {
    #[serde(with = "serde_bytes")]
    pub anchor_id: WireUuid,
    pub include_tombstoned: bool,
    pub limit: u32,
    pub cursor: Vec<u8>,
}

/// STATEMENT_HISTORY_RESP (`0x01C5`), one streamed frame. `is_final` marks the
/// last frame; `total_versions` is the chain length. `next_cursor` is the opaque
/// keyset token to resume from, empty when the chain is exhausted.
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct StatementHistoryResponseFrame {
    pub items: Vec<StatementView>,
    #[serde(with = "serde_bytes")]
    pub chain_root: WireUuid,
    pub total_versions: u32,
    pub next_cursor: Vec<u8>,
    pub is_final: bool,
}

/// RELATION_CREATE (`0x0150`).
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct RelationCreateRequest {
    pub relation_type: String,
    #[serde(with = "serde_bytes")]
    pub from_entity: WireUuid,
    #[serde(with = "serde_bytes")]
    pub to_entity: WireUuid,
    pub properties_blob: Vec<u8>,
    pub evidence: EvidenceRefWire,
    pub extractor_id: u32,
    pub confidence: f32,
    pub valid_from_unix_nanos: u64,
    pub valid_to_unix_nanos: u64,
    /// Conversation/run this relation belongs to; `0` = default session.
    /// A grouping key, not an isolation boundary.
    #[serde(default)]
    pub session_id: WireSessionId,
    #[serde(with = "serde_bytes")]
    pub request_id: WireUuid,
    /// Effective identity this relation-create runs as. `None` (omitted on the
    /// wire) means the op runs as the connection's own key-bound identity.
    #[serde(skip_serializing_if = "Option::is_none", default)]
    pub act_as: Option<ActAs>,
}

/// RELATION_CREATE_RESP (`0x01D0`).
#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)]
pub struct RelationCreateResponse {
    #[serde(with = "serde_bytes")]
    pub relation_id: WireUuid,
}

/// SCHEMA_UPLOAD (`0x0120`).
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
pub struct SchemaUploadRequest {
    pub schema_document: String,
    pub dry_run: bool,
    pub allow_breaking: bool,
    #[serde(with = "serde_bytes")]
    pub request_id: WireUuid,
    /// Run as a tenant on a shared-pool connection (see [`ActAs`]).
    #[serde(skip_serializing_if = "Option::is_none", default)]
    pub act_as: Option<ActAs>,
}

/// One structured schema parse/validate error.
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
pub struct SchemaValidationErrorWire {
    pub code: String,
    pub message: String,
    pub line: u32,
    pub column: u32,
    pub length: u32,
    pub severity: u8,
}

/// SCHEMA_UPLOAD_RESP (`0x01A0`).
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
pub struct SchemaUploadResponse {
    pub namespace: String,
    pub schema_version: u32,
    pub validation_errors: Vec<SchemaValidationErrorWire>,
    pub backward_compatible: bool,
    pub migration_summary_blob: Vec<u8>,
}

/// Target kinds for a [`SchemaDropRequest`]. `target_kind` MUST be one of
/// these; the server rejects any other discriminant with `InvalidRequest`.
///
/// Entity types are deliberately absent: they are global in the v1 storage
/// model, so dropping one would race rows in other namespaces that reference
/// the same shared type — the same reason `SCHEMA_REPLACE` never drops them.
pub mod schema_drop_target {
    /// Drop a declared predicate.
    pub const PREDICATE: u8 = 0;
    /// Drop a declared relation_type.
    pub const RELATION_TYPE: u8 = 1;
}

/// `SCHEMA_DROP` (`0x0125`) — surgical narrow of a single declared type.
///
/// The per-type counterpart to the namespace-wide `SCHEMA_REPLACE`: removes one
/// declared predicate or relation_type from the active schema set, then bumps
/// the namespace to a new version whose document no longer declares it. Existing
/// rows on the dropped type survive as orphans — readable as plain memories, no
/// longer enriched from the typed-graph tables.
///
/// `force` is required only when the target still has live (non-tombstoned)
/// rows: `false` with live rows present is rejected with `Conflict` and mutates
/// nothing. A type with no live rows drops without `force`.
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
pub struct SchemaDropRequest {
    /// Namespace the target lives in. MUST equal the caller's own namespace,
    /// or the server rejects with `Unauthorized`.
    pub namespace: String,
    /// One of [`schema_drop_target`]. Any other value → `InvalidRequest`.
    pub target_kind: u8,
    /// Local name of the predicate / relation_type to drop (the qname is
    /// `{namespace}:{target_name}`).
    pub target_name: String,
    /// Confirmation flag required only when the target still has live rows.
    pub force: bool,
    #[serde(with = "serde_bytes")]
    pub request_id: WireUuid,
    /// Run as a tenant on a shared-pool connection (see [`ActAs`]).
    #[serde(skip_serializing_if = "Option::is_none", default)]
    pub act_as: Option<ActAs>,
}

/// `SCHEMA_DROP_RESP` (`0x01A5`).
///
/// `schema_version` is the new active version after the narrow, or `0` when
/// nothing was dropped or the drop was rejected. `dropped` is `true` only when
/// a declared row was actually removed. `live_rows` is the count of live rows
/// found referencing the target — non-zero with `dropped == false` means the
/// drop was refused for lack of `force`.
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
pub struct SchemaDropResponse {
    pub namespace: String,
    pub schema_version: u32,
    pub target_kind: u8,
    pub target_name: String,
    pub dropped: bool,
    pub live_rows: u32,
    pub validation_errors: Vec<SchemaValidationErrorWire>,
}

/// `SCHEMA_REPLACE` (`0x0127`) — destructive namespace swap.
///
/// Unlike `SCHEMA_UPLOAD`, this DROPS every declared row in the namespace
/// before the new document lands. Entities whose type disappears survive as
/// orphans: still readable as plain memories, no longer enriched from the
/// typed-graph tables.
///
/// `force_drop_existing` MUST be `true` — the server rejects `false` with
/// `InvalidRequest`. It is a confirmation step for an irreversible operation,
/// not a mode switch, which is why the SDK does not default it.
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
pub struct SchemaReplaceRequest {
    /// Schema DSL source. Must declare the same namespace as the connection's,
    /// or the server rejects with `InvalidRequest`.
    pub schema_document: String,
    /// MUST be `true`.
    pub force_drop_existing: bool,
    #[serde(with = "serde_bytes")]
    pub request_id: WireUuid,
    /// Run as a tenant on a shared-pool connection (see [`ActAs`]).
    #[serde(skip_serializing_if = "Option::is_none", default)]
    pub act_as: Option<ActAs>,
}

/// `SCHEMA_REPLACE_RESP` (`0x01A7`).
///
/// `dropped_count` is how many declared rows were removed before the new
/// schema took effect. `schema_version` is always greater than the
/// pre-replace version.
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
pub struct SchemaReplaceResponse {
    pub namespace: String,
    pub schema_version: u32,
    pub dropped_count: u32,
    pub validation_errors: Vec<SchemaValidationErrorWire>,
}

/// Why a stream was cancelled. Carried by [`CancelStreamRequest`].
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
pub enum CancellationReason {
    /// The caller no longer needs the results — the ordinary case when a
    /// consumer breaks out of a `recall` loop early.
    ClientUnneeded,
    /// A client-side deadline elapsed.
    Timeout,
    /// Anything else, with a free-text explanation.
    Other(String),
}

/// `CANCEL_STREAM` (`0x0050`) — stop an in-flight stream.
///
/// Sent on a NEW stream id, naming the stream to cancel in
/// `target_stream_id`; the server answers `CANCEL_STREAM_ACK` and stops
/// emitting frames for the target. Without this a consumer that abandons a
/// streamed `recall` leaves the server producing frames nobody reads.
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
pub struct CancelStreamRequest {
    pub target_stream_id: u32,
    pub reason: CancellationReason,
}

/// `CANCEL_STREAM_ACK` (`0x00D0`).
#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)]
pub struct CancelStreamAck {
    pub target_stream_id: u32,
    pub cancelled_at_unix_nanos: u64,
}

/// Time window for a query. `None` bounds are open-ended.
#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)]
pub struct TimeRangeWire {
    pub from_unix_ms: Option<u64>,
    pub to_unix_ms: Option<u64>,
}

/// Retriever family selector, as carried inside [`RetrieverSelectionWire`].
///
/// Encodes as the **variant-name string**, not the discriminant. `#[repr(u8)]`
/// is a memory-layout hint; serde ignores it because this derives plain
/// `Serialize`, not `serde_repr::Serialize_repr`. So
/// `Explicit([Semantic, Graph])` goes on the wire as
/// `{"Explicit": ["Semantic", "Graph"]}`.
///
/// The discriminants are kept because the server pins them for its own storage,
/// and because [`RetrieverNameWire`] — the response-side twin that really is an
/// integer — shares them. Reading `#[repr(u8)]` as "this is an integer on the
/// wire" is what previously made the Python and TypeScript SDKs send `0`/`2`
/// here, which the server cannot deserialize.
#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)]
#[repr(u8)]
pub enum RetrieverWire {
    Semantic = 0,
    Lexical = 1,
    Graph = 2,
}

/// Auto-routing vs explicit retriever list. Externally tagged (`"Auto"`
/// string or `{"Explicit": [...]}` map), matching the server.
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
pub enum RetrieverSelectionWire {
    Auto,
    Explicit(Vec<RetrieverWire>),
}

/// Per-query fusion override.
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct FusionConfigWire {
    pub k: u32,
    pub semantic_weight: f32,
    pub lexical_weight: f32,
    pub graph_weight: f32,
}

/// The retriever/fusion selection carried by a query. Embedded by the
/// `QUERY_EXPLAIN` / `QUERY_TRACE` debug ops.
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct QueryRequest {
    pub text: String,
    #[serde(with = "crate::wire::cbor::opt_byte_array16")]
    pub entity_anchor: Option<WireUuid>,
    pub kind_filter: Vec<u8>,
    pub predicate_filter: Vec<String>,
    /// Sessions to scope the query to. `None` or empty = no restriction
    /// (every session in the caller's space). Mirrors
    /// [`RecallRequest::session_filter`].
    pub session_filter: Option<Vec<WireSessionId>>,
    pub time_filter: Option<TimeRangeWire>,
    pub as_of_record_time_unix_nanos: Option<u64>,
    pub confidence_min: Option<f32>,
    pub include_tombstoned: bool,
    pub include_superseded: bool,
    pub limit: u32,
    pub retrievers: RetrieverSelectionWire,
    pub fusion_config: Option<FusionConfigWire>,
    #[serde(with = "serde_bytes")]
    pub request_id: WireUuid,
}

/// MATERIALIZE_PROCEDURAL (`0x0164`).
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct MaterializeProceduralRequest {
    #[serde(with = "serde_bytes")]
    pub space_id: WireUuid,
    pub session_filter: Option<Vec<WireSessionId>>,
    pub top_k: u32,
    pub min_confidence: f32,
    pub categories: Vec<String>,
    #[serde(with = "serde_bytes")]
    pub request_id: WireUuid,
}

/// MATERIALIZE_PROCEDURAL_RESP (`0x01E4`).
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct MaterializeProceduralResponse {
    pub system_block: String,
    /// Each id encodes as a CBOR byte string (major type 2) inside the
    /// array, matching the server's uniform 16-byte id encoding.
    #[serde(with = "crate::wire::cbor::vec_byte_array16")]
    pub statement_ids: Vec<WireUuid>,
    pub total_candidates: u32,
    pub trimmed_by_budget: bool,
}

// ===========================================================================
// SPACE registry — SPACE_CREATE / SPACE_LIST / SPACE_DELETE.
// ===========================================================================

/// One space row in a [`SpaceListResponse`]. `space_id` is the
/// human-readable structured space string from the registry (a CBOR text
/// string), not the derived 16-byte storage id.
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
pub struct SpaceView {
    pub space_id: String,
    pub created_at_unix_nanos: u64,
    pub last_active_unix_nanos: u64,
    pub memory_count: u64,
    pub session_count: u32,
}

/// SPACE_CREATE (`0x0070`). Provisions the caller's effective space
/// explicitly; idempotent (a create for an existing space returns the
/// existing row with `created = false`).
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
pub struct SpaceCreateRequest {
    /// Opaque caller metadata blob (quota hints, labels). `None` for a bare
    /// provision (omitted on the wire).
    #[serde(skip_serializing_if = "Option::is_none", default)]
    pub metadata: Option<Vec<u8>>,
    #[serde(with = "serde_bytes")]
    pub request_id: WireUuid,
    #[serde(skip_serializing_if = "Option::is_none", default)]
    pub act_as: Option<ActAs>,
}

/// SPACE_CREATE_RESP (`0x00F0`). `space_id` is the human-readable structured
/// space string this create resolved to (a CBOR text string).
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
pub struct SpaceCreateResponse {
    pub space_id: String,
    /// `false` on an idempotent replay of an existing space.
    pub created: bool,
    pub created_at_unix_nanos: u64,
    pub last_active_unix_nanos: u64,
    pub memory_count: u64,
    pub session_count: u32,
}

/// SPACE_LIST (`0x0071`). Lists the caller's namespace's spaces. `limit == 0`
/// means "no cap".
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
pub struct SpaceListRequest {
    pub limit: u32,
    #[serde(skip_serializing_if = "Option::is_none", default)]
    pub act_as: Option<ActAs>,
}

/// SPACE_LIST_RESP (`0x00F1`).
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
pub struct SpaceListResponse {
    pub spaces: Vec<SpaceView>,
    /// `true` when the listing covers every shard. v1 lists only the
    /// caller-shard's spaces, so this is `false` until cross-shard
    /// scatter-gather lands — treat `false` as "partial".
    pub cross_shard_complete: bool,
}

/// SPACE_DELETE (`0x0072`). GDPR erasure of the caller's effective space:
/// removes every row under `(namespace, space)`. Hard/immediate.
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
pub struct SpaceDeleteRequest {
    #[serde(with = "serde_bytes")]
    pub request_id: WireUuid,
    #[serde(skip_serializing_if = "Option::is_none", default)]
    pub act_as: Option<ActAs>,
}

/// SPACE_DELETE_RESP (`0x00F2`). `space_id` is the human-readable structured
/// space string this delete targeted (a CBOR text string).
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
pub struct SpaceDeleteResponse {
    pub space_id: String,
    /// `false` when the space had no registry row.
    pub existed: bool,
    /// Number of memories tombstoned by the cascade.
    pub memories_forgotten: u64,
}

// ===========================================================================
// SESSION registry — SESSION_CREATE / SESSION_LIST / SESSION_DELETE.
// ===========================================================================

/// One session row in a [`SessionListResponse`].
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
pub struct SessionView {
    pub session_id: WireSessionId,
    pub created_at_unix_nanos: u64,
    pub last_active_unix_nanos: u64,
    #[serde(skip_serializing_if = "Option::is_none", default)]
    pub title: Option<String>,
    pub memory_count: u32,
}

/// SESSION_CREATE (`0x0073`). Provisions a session under the caller's
/// effective space explicitly; idempotent.
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
pub struct SessionCreateRequest {
    pub session_id: WireSessionId,
    #[serde(skip_serializing_if = "Option::is_none", default)]
    pub title: Option<String>,
    #[serde(with = "serde_bytes")]
    pub request_id: WireUuid,
    #[serde(skip_serializing_if = "Option::is_none", default)]
    pub act_as: Option<ActAs>,
}

/// SESSION_CREATE_RESP (`0x00F3`). `space_id` is the derived 16-byte storage
/// id (a CBOR byte string).
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
pub struct SessionCreateResponse {
    #[serde(with = "serde_bytes")]
    pub space_id: WireUuid,
    pub session_id: WireSessionId,
    /// `false` on an idempotent replay of an existing session.
    pub created: bool,
    pub created_at_unix_nanos: u64,
    pub last_active_unix_nanos: u64,
    pub memory_count: u32,
}

/// SESSION_LIST (`0x0074`). Lists one `(namespace, space)`'s sessions
/// newest-first. `limit == 0` means "no cap".
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
pub struct SessionListRequest {
    pub limit: u32,
    #[serde(skip_serializing_if = "Option::is_none", default)]
    pub act_as: Option<ActAs>,
}

/// SESSION_LIST_RESP (`0x00F4`). `space_id` is the derived 16-byte storage id
/// (a CBOR byte string).
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
pub struct SessionListResponse {
    #[serde(with = "serde_bytes")]
    pub space_id: WireUuid,
    pub sessions: Vec<SessionView>,
}

/// SESSION_DELETE (`0x0075`). Removes a session's memories + graph rows.
/// Defaults to soft (7-day grace); `hard = true` zeroes immediately. The
/// default session (`session_id = 0`) is non-deletable.
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
pub struct SessionDeleteRequest {
    pub session_id: WireSessionId,
    /// `true` ⇒ hard tombstone (immediate); `false` (default) ⇒ soft.
    #[serde(default)]
    pub hard: bool,
    #[serde(with = "serde_bytes")]
    pub request_id: WireUuid,
    #[serde(skip_serializing_if = "Option::is_none", default)]
    pub act_as: Option<ActAs>,
}

/// SESSION_DELETE_RESP (`0x00F5`). `space_id` is the derived 16-byte storage
/// id (a CBOR byte string).
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
pub struct SessionDeleteResponse {
    #[serde(with = "serde_bytes")]
    pub space_id: WireUuid,
    pub session_id: WireSessionId,
    /// `false` when the session had no registry row.
    pub existed: bool,
    /// Number of memories tombstoned by the cascade.
    pub memories_forgotten: u64,
}

// ===========================================================================
// TXN_BEGIN / TXN_COMMIT / TXN_ABORT.
// ===========================================================================

/// TXN_BEGIN (`0x0040`). The client mints the `txn_id`; the server binds the
/// transaction to it for the duration of the session.
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
pub struct TxnBeginRequest {
    #[serde(with = "serde_bytes")]
    pub txn_id: WireUuid,
    pub timeout_seconds: u32,
    /// Effective identity every write buffered in this transaction commits as.
    /// Delegation is fixed at begin and applies to the whole txn; `TXN_COMMIT`
    /// carries no `act_as` of its own. `None` (omitted on the wire) means the
    /// txn commits as the connection's own key-bound identity.
    #[serde(skip_serializing_if = "Option::is_none", default)]
    pub act_as: Option<ActAs>,
}

/// TXN_BEGIN_RESP (`0x00C0`).
#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)]
pub struct TxnBeginResponse {
    #[serde(with = "serde_bytes")]
    pub txn_id: WireUuid,
    pub timeout_seconds: u32,
    pub started_at_unix_nanos: u64,
}

/// TXN_COMMIT (`0x0041`).
#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)]
pub struct TxnCommitRequest {
    #[serde(with = "serde_bytes")]
    pub txn_id: WireUuid,
}

/// TXN_COMMIT_RESP (`0x00C1`).
#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)]
pub struct TxnCommitResponse {
    #[serde(with = "serde_bytes")]
    pub txn_id: WireUuid,
    pub committed_at_unix_nanos: u64,
    pub operations_applied: u32,
}

/// TXN_ABORT (`0x0042`).
#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)]
pub struct TxnAbortRequest {
    #[serde(with = "serde_bytes")]
    pub txn_id: WireUuid,
}

/// TXN_ABORT_RESP (`0x00C2`).
#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)]
pub struct TxnAbortResponse {
    #[serde(with = "serde_bytes")]
    pub txn_id: WireUuid,
    pub operations_discarded: u32,
}

// ===========================================================================
// SUBSCRIBE / UNSUBSCRIBE + the subscription event union.
// ===========================================================================

/// Subscription event kind. Integer discriminant on the wire (mirrors the
/// server's `EventType`). The four cognitive variants populate the
/// `SubscriptionEvent` cognitive fields; the typed-graph variants zero-fill
/// them and carry their body in `graph_payload`.
#[derive(
    Clone, Copy, Debug, Eq, PartialEq, serde_repr::Serialize_repr, serde_repr::Deserialize_repr,
)]
#[repr(u8)]
pub enum EventType {
    // Cognitive events.
    Encoded = 0,
    Forgotten = 1,
    Reclaimed = 2,
    KindChanged = 3,

    // Typed-graph events (graph_payload populated).
    EntityCreated = 16,
    EntityUpdated = 17,
    EntityRenamed = 18,
    EntityMerged = 19,
    EntityUnmerged = 20,
    EntityTombstoned = 21,
    StatementCreated = 22,
    StatementSuperseded = 23,
    StatementTombstoned = 24,
    RelationCreated = 25,
    RelationSuperseded = 26,
    StageCompleted = 27,
    SchemaUpdated = 29,
    RelationTombstoned = 30,

    // Unified-edge change feed (edge_payload populated).
    EdgeAdded = 31,
    EdgeRemoved = 32,
    EdgeSuperseded = 33,
}

/// Verdict of a completed background stage. Integer discriminant.
#[derive(
    Clone, Copy, Debug, Eq, PartialEq, serde_repr::Serialize_repr, serde_repr::Deserialize_repr,
)]
#[repr(u8)]
pub enum StageOutcome {
    Ok = 0,
    Empty = 1,
    Failed = 2,
}

/// Audit verdict for an extractor stage. Integer discriminant.
#[derive(
    Clone, Copy, Debug, Eq, PartialEq, serde_repr::Serialize_repr, serde_repr::Deserialize_repr,
)]
#[repr(u8)]
pub enum StageAuditStatus {
    Succeeded = 0,
    PartiallyApplied = 1,
    Failed = 2,
    Skipped = 3,
}

/// [`StagePayload::AutoEdge`] body: how many similarity edges the auto-edge
/// stage wrote for the source memory.
#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)]
pub struct StageAutoEdgePayload {
    pub edges_written: u32,
}

/// [`StagePayload::TemporalEdge`] body: how many temporal (followed-by) edges
/// the temporal-edge stage wrote.
#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)]
pub struct StageTemporalEdgePayload {
    pub edges_written: u32,
}

/// [`StagePayload::Extractor`] body: the typed-graph rows the extractor stage
/// produced (entity / statement / relation counts) plus its audit verdict.
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
pub struct StageExtractorPayload {
    pub entity_count: u32,
    pub statement_count: u32,
    pub relation_count: u32,
    pub audit_status: StageAuditStatus,
    /// Populated only when `audit_status == Failed`; empty otherwise.
    pub error_message: String,
}

/// [`StagePayload::Hype`] body: hypothetical questions generated for the new
/// memory (write-time HyPE), embedded and inserted into the memory HNSW
/// index.
#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)]
pub struct StageHypePayload {
    /// How many hypothetical questions were embedded, persisted, and
    /// inserted into the memory HNSW index.
    pub questions_written: u32,
    /// LLM micro-USD spent generating the questions (`0` on a cache hit).
    pub cost_micro_usd: u64,
}

/// Per-stage detail sidecar on `StageCompleted` events. Externally-tagged
/// enum (CBOR map keyed by the variant name), matching the server.
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
pub enum StagePayload {
    AutoEdge(StageAutoEdgePayload),
    TemporalEdge(StageTemporalEdgePayload),
    Extractor(StageExtractorPayload),
    Hype(StageHypePayload),
}

/// Vector-similarity subscription filter.
#[derive(Clone, Copy, Debug, PartialEq, Serialize, Deserialize)]
pub struct SimilarityFilter {
    pub reference_memory_id: WireMemoryId,
    pub threshold: f32,
}

/// Selects which events a subscription receives. All fields `None`/empty
/// means "everything routed to this shard".
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct SubscriptionFilter {
    pub session_filter: Option<Vec<WireSessionId>>,
    pub kinds: Option<Vec<MemoryKindWire>>,
    pub similar_to: Option<SimilarityFilter>,
    /// Subset of space ids whose events the subscriber wants. `None` or
    /// empty = all spaces on the shard.
    #[serde(with = "crate::wire::cbor::opt_vec_byte_array16")]
    pub spaces: Option<Vec<WireUuid>>,
    /// Subset of memory ids whose events the subscriber wants. `None` or
    /// empty = all memories. Lets a client scope a subscription to a single
    /// in-flight write (e.g. to watch that write's async derivation stages
    /// complete) without seeing unrelated traffic on a busy shard.
    pub memory_ids: Option<Vec<WireMemoryId>>,
}

/// SUBSCRIBE (`0x0030`). Opens a long-lived push stream; the server emits
/// `SUBSCRIBE_EVENT` (`0x00B0`) frames on the subscription's stream id until
/// the client sends `UNSUBSCRIBE` (`0x0031`).
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct SubscribeRequest {
    pub filter: SubscriptionFilter,
    pub include_history: bool,
    pub from_lsn: Option<u64>,
    pub max_inflight: u32,
    /// Effective identity this subscription runs as, on behalf of the
    /// authenticated connection principal. `None` (the common case, and
    /// omitted on the wire) means the op runs as the connection's own
    /// key-bound identity.
    #[serde(skip_serializing_if = "Option::is_none", default)]
    pub act_as: Option<ActAs>,
}

/// Side-channel payload on an `EdgeAdded` / `EdgeRemoved` / `EdgeSuperseded`
/// event. Covers both memory-graph edges and typed-graph relations.
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct EdgeEventPayload {
    /// `0` = Memory, `1` = Entity.
    pub from_kind: u8,
    #[serde(with = "serde_bytes")]
    pub from_id: WireUuid,
    pub to_kind: u8,
    #[serde(with = "serde_bytes")]
    pub to_id: WireUuid,
    /// `0` = Builtin memory-graph kind, `1` = Mentions, `2` = Typed relation.
    pub edge_kind_tag: u8,
    pub edge_kind_byte: u8,
    /// `Some(_)` for typed-relation events.
    pub relation_type_id: Option<u32>,
    pub weight: f32,
    #[serde(with = "crate::wire::cbor::opt_byte_array16")]
    pub relation_id: Option<WireUuid>,
    #[serde(with = "crate::wire::cbor::opt_byte_array16")]
    pub superseded_relation_id: Option<WireUuid>,
    /// `0` = EXPLICIT, `1` = AUTO_DERIVED.
    pub origin: u8,
}

/// SUBSCRIBE_EVENT (`0x00B0`) — a single server-push event frame.
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct SubscriptionEvent {
    pub event_type: EventType,
    pub memory_id: WireMemoryId,
    pub session_id: WireSessionId,
    pub text: String,
    pub kind: MemoryKindWire,
    pub salience: f32,
    pub timestamp_unix_nanos: u64,
    pub lsn: u64,
    /// `None` for cognitive events; `Some(_)` for typed-graph events.
    pub graph_payload: Option<GraphEventPayload>,
    /// `Some(_)` for `EdgeAdded` / `EdgeRemoved` / `EdgeSuperseded`.
    pub edge_payload: Option<EdgeEventPayload>,
    /// `Some(_)` when `event_type == StageCompleted`.
    pub stage_kind: Option<StageKind>,
    pub stage_outcome: Option<StageOutcome>,
    pub stage_payload: Option<StagePayload>,
}

/// UNSUBSCRIBE (`0x0031`). `target_stream_id` is the stream id of the
/// subscription to tear down.
#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)]
pub struct UnsubscribeRequest {
    pub target_stream_id: u32,
}

/// UNSUBSCRIBE_RESP (`0x00B1`).
#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)]
pub struct UnsubscribeResponse {
    pub target_stream_id: u32,
    pub final_lsn: u64,
}

// ---------------------------------------------------------------------------
// Typed-graph subscription event bodies.
// ---------------------------------------------------------------------------

/// Typed payload for a typed-graph SUBSCRIBE event. Externally-tagged enum
/// (CBOR map keyed by the variant name), matching the server. Discriminated
/// at the application level by [`SubscriptionEvent::event_type`].
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub enum GraphEventPayload {
    EntityCreated(EntityCreatedEvent),
    EntityUpdated(EntityUpdatedEvent),
    EntityRenamed(EntityRenamedEvent),
    EntityMerged(EntityMergedEvent),
    EntityUnmerged(EntityUnmergedEvent),
    EntityTombstoned(EntityTombstonedEvent),
    StatementCreated(StatementCreatedEvent),
    StatementSuperseded(StatementSupersededEvent),
    StatementTombstoned(StatementTombstonedEvent),
    RelationCreated(RelationCreatedEvent),
    RelationSuperseded(RelationSupersededEvent),
    RelationTombstoned(RelationTombstonedEvent),
    SchemaUpdated(SchemaUpdatedEvent),
}

/// [`GraphEventPayload::EntityCreated`] body: a new typed entity was created.
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct EntityCreatedEvent {
    #[serde(with = "serde_bytes")]
    pub entity_id: WireUuid,
    pub entity_type_id: u32,
    pub canonical_name: String,
}

/// [`GraphEventPayload::EntityUpdated`] body: an entity's attributes changed;
/// `embedding_version_changed` flags whether its vector was re-embedded.
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct EntityUpdatedEvent {
    #[serde(with = "serde_bytes")]
    pub entity_id: WireUuid,
    pub entity_type_id: u32,
    pub canonical_name: String,
    pub embedding_version_changed: bool,
}

/// [`GraphEventPayload::EntityRenamed`] body: an entity's canonical name
/// changed; `old_moved_to_alias` says whether the old name was kept as an alias.
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct EntityRenamedEvent {
    #[serde(with = "serde_bytes")]
    pub entity_id: WireUuid,
    pub old_canonical_name: String,
    pub new_canonical_name: String,
    pub old_moved_to_alias: bool,
}

/// [`GraphEventPayload::EntityMerged`] body: two entities were unified into
/// `survivor`; reports how many statements and relations were rerouted.
#[derive(Clone, Copy, Debug, PartialEq, Serialize, Deserialize)]
pub struct EntityMergedEvent {
    #[serde(with = "serde_bytes")]
    pub survivor: WireUuid,
    #[serde(with = "serde_bytes")]
    pub merged: WireUuid,
    #[serde(with = "serde_bytes")]
    pub audit_id: WireUuid,
    pub confidence: f32,
    pub statements_rerouted: u32,
    pub relations_rerouted: u32,
}

/// [`GraphEventPayload::EntityUnmerged`] body: a prior merge was reversed,
/// splitting `restored_entity_id` back out of `from_survivor`.
#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)]
pub struct EntityUnmergedEvent {
    #[serde(with = "serde_bytes")]
    pub restored_entity_id: WireUuid,
    #[serde(with = "serde_bytes")]
    pub from_survivor: WireUuid,
    #[serde(with = "serde_bytes")]
    pub audit_id: WireUuid,
}

/// [`GraphEventPayload::EntityTombstoned`] body: an entity was soft-deleted, with
/// the operator-supplied reason.
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct EntityTombstonedEvent {
    #[serde(with = "serde_bytes")]
    pub entity_id: WireUuid,
    pub reason: String,
}

/// [`GraphEventPayload::StatementCreated`] body: a new typed statement was
/// asserted about `subject`.
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct StatementCreatedEvent {
    #[serde(with = "serde_bytes")]
    pub statement_id: WireUuid,
    /// 1=Fact, 2=Preference, 3=Event.
    pub kind: u8,
    #[serde(with = "serde_bytes")]
    pub subject: WireUuid,
    pub predicate: String,
    pub confidence: f32,
}

/// [`GraphEventPayload::StatementSuperseded`] body: `new_statement_id` replaced
/// `old_statement_id`; `chain_root` identifies the supersession chain's origin.
#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)]
pub struct StatementSupersededEvent {
    #[serde(with = "serde_bytes")]
    pub old_statement_id: WireUuid,
    #[serde(with = "serde_bytes")]
    pub new_statement_id: WireUuid,
    #[serde(with = "serde_bytes")]
    pub chain_root: WireUuid,
}

/// [`GraphEventPayload::StatementTombstoned`] body: a statement was soft-deleted,
/// with the operator-supplied reason.
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct StatementTombstonedEvent {
    #[serde(with = "serde_bytes")]
    pub statement_id: WireUuid,
    pub reason: String,
}

/// [`GraphEventPayload::RelationCreated`] body: a new typed relation was created
/// from `from` to `to`.
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct RelationCreatedEvent {
    #[serde(with = "serde_bytes")]
    pub relation_id: WireUuid,
    pub relation_type: String,
    #[serde(with = "serde_bytes")]
    pub from: WireUuid,
    #[serde(with = "serde_bytes")]
    pub to: WireUuid,
}

/// [`GraphEventPayload::RelationSuperseded`] body: `new_relation_id` replaced
/// `old_relation_id`.
#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)]
pub struct RelationSupersededEvent {
    #[serde(with = "serde_bytes")]
    pub old_relation_id: WireUuid,
    #[serde(with = "serde_bytes")]
    pub new_relation_id: WireUuid,
}

/// [`GraphEventPayload::RelationTombstoned`] body: a relation was soft-deleted,
/// with the operator-supplied reason.
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct RelationTombstonedEvent {
    #[serde(with = "serde_bytes")]
    pub relation_id: WireUuid,
    pub reason: String,
}

/// [`GraphEventPayload::SchemaUpdated`] body: a namespace's schema advanced from
/// `from_version` to `to_version` (via SCHEMA_UPLOAD or SCHEMA_REPLACE).
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
pub struct SchemaUpdatedEvent {
    pub namespace: String,
    pub from_version: u32,
    pub to_version: u32,
    /// Always `true` in v1.
    pub backward_compatible: bool,
}

// ===========================================================================
// GET_CAPABILITIES.
// ===========================================================================

/// GET_CAPABILITIES (`0x0032`). Empty request — capabilities are
/// server-side state, so the client has nothing to send. Kept as a
/// struct (not a unit type) so the encoding matches every other request
/// body (a CBOR map, here empty).
#[derive(Clone, Debug, Default, PartialEq, Eq, Serialize, Deserialize)]
pub struct GetCapabilitiesRequest {
    /// Run as a tenant on a shared-pool connection: the server then filters
    /// `schema_namespaces` to the effective namespace. Absent → `0xA0`.
    #[serde(skip_serializing_if = "Option::is_none", default)]
    pub act_as: Option<ActAs>,
}

/// Capability snapshot returned by the server.
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
pub struct Capabilities {
    /// True when the cross-encoder reranker is loaded on this shard.
    pub rerank: bool,
    /// True when the LLM extractor tier is enabled.
    pub llm_extractor: bool,
    /// True when the classifier (GLiNER) extractor tier is enabled.
    pub classifier_extractor: bool,
    /// True when the pattern extractor tier is enabled.
    pub pattern_extractor: bool,
    /// User schema namespaces currently active on the shard (excludes the
    /// always-on `brain` system namespace).
    pub schema_namespaces: Vec<String>,
    /// Embedding vector dimensionality the shard's embedder produces.
    pub vector_dim: u16,
}

/// GET_CAPABILITIES_RESP (`0x00B2`).
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
pub struct GetCapabilitiesResponse {
    pub capabilities: Capabilities,
}

// ===========================================================================
// EXTRACTOR_LIST.
// ===========================================================================

/// EXTRACTOR_LIST (`0x0124`). Empty request — extraction is always-on and
/// takes no arguments, so every registered extractor is returned. Kept as a
/// struct (not a unit type) so the encoding matches every other request body
/// (a CBOR map, here empty).
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Serialize, Deserialize)]
pub struct ExtractorListRequest {}

/// One registered extractor row in [`ExtractorListResponseFrame`].
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
pub struct ExtractorListItem {
    pub extractor_id: u32,
    pub namespace: String,
    pub name: String,
    /// `0`=pattern, `1`=classifier, `2`=llm.
    pub kind: u8,
    pub schema_version: u32,
    pub created_at_unix_nanos: u64,
}

/// EXTRACTOR_LIST_RESP (`0x01A4`). Single-frame snapshot of the always-on
/// extractor registry.
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
pub struct ExtractorListResponseFrame {
    pub items: Vec<ExtractorListItem>,
    pub total: u32,
    pub is_final: bool,
}

// ===========================================================================
// ENTITY_GET / ENTITY_LIST.
// ===========================================================================

/// Read-side view of an entity. Mirrors the server's `EntityView`.
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct EntityView {
    #[serde(with = "serde_bytes")]
    pub entity_id: WireUuid,
    pub entity_type_id: u32,
    pub canonical_name: String,
    pub normalized_name: String,
    pub aliases: Vec<String>,
    pub attributes_blob: Vec<u8>,
    pub mention_count: u32,
    pub created_at_unix_nanos: u64,
    pub updated_at_unix_nanos: u64,
    /// `[0; 16]` when not merged; consumers treat all-zero as None.
    #[serde(with = "serde_bytes")]
    pub merged_into: WireUuid,
    pub embedding_version: u32,
    pub flags: u32,
}

/// ENTITY_GET (`0x0131`).
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
pub struct EntityGetRequest {
    #[serde(with = "serde_bytes")]
    pub entity_id: WireUuid,
    /// Effective identity this get runs as. `None` (omitted on the wire) means
    /// the op runs as the connection's own key-bound identity. Honored only when
    /// the connection principal holds the `ACT_AS` grant and the target
    /// namespace is in its `may_act` allowlist.
    #[serde(skip_serializing_if = "Option::is_none", default)]
    pub act_as: Option<ActAs>,
}

/// ENTITY_GET_RESP (`0x01B1`).
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct EntityGetResponse {
    pub entity: EntityView,
    /// Merge audit trail: the chain of redirect ids the GET walked through to
    /// reach `entity` (the surviving row), in order, EXCLUDING the survivor
    /// itself. Empty on a direct hit (the requested id was live). For
    /// `A → B → C`, `ENTITY_GET(A)` returns `entity = C` and
    /// `resolved_from = [A, B]`. Each id encodes as a CBOR array of 16 ints
    /// (plain `[u8; 16]`), matching the server's default serde encoding for
    /// this field.
    pub resolved_from: Vec<WireUuid>,
}

/// ENTITY_LIST (`0x0137`). Empty/zero fields mean "no filter".
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct EntityListRequest {
    /// `0` = no filter; otherwise an entity type id.
    pub entity_type_id: u32,
    /// Empty = no filter.
    pub name_prefix: String,
    pub mention_count_min: u32,
    pub include_tombstoned: bool,
    pub include_merged: bool,
    /// 1..=1000.
    pub limit: u32,
    /// Empty on first page; opaque continuation token otherwise.
    pub cursor: Vec<u8>,
    /// Effective identity this list runs as. `None` (omitted on the wire) means
    /// the op runs as the connection's own key-bound identity. Honored only when
    /// the connection principal holds the `ACT_AS` grant and the target
    /// namespace is in its `may_act` allowlist.
    #[serde(skip_serializing_if = "Option::is_none", default)]
    pub act_as: Option<ActAs>,
}

/// One entity in an ENTITY_LIST response batch.
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct EntityListItem {
    pub entity: EntityView,
}

/// One streaming ENTITY_LIST_RESP frame (`0x01B7`). The last frame carries
/// `is_final = true`. Mirrors `RecallResponseFrame`'s streaming shape.
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct EntityListResponseFrame {
    pub items: Vec<EntityListItem>,
    /// Empty `next_cursor` on the final frame means "exhausted"; non-empty
    /// means "more pages available, resume with this".
    pub next_cursor: Vec<u8>,
    pub cumulative_count: u32,
    pub is_final: bool,
}

// ===========================================================================
// ENTITY_RESOLVE.
// ===========================================================================

/// ENTITY_RESOLVE (`0x0136`). Resolves a candidate name to an existing entity
/// (and optionally creates one). The server currently requires
/// `entity_type_hint != 0` and resolves by exact canonical name (tier 1).
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
pub struct EntityResolveRequest {
    pub candidate_name: String,
    pub resolution_context: String,
    /// `0` = no hint; otherwise an entity type id.
    pub entity_type_hint: u32,
    pub allow_create: bool,
    #[serde(with = "serde_bytes")]
    pub request_id: WireUuid,
    /// Effective identity this resolve runs as. `None` (omitted on the wire)
    /// means the op runs as the connection's own key-bound identity. Honored
    /// only when the connection principal holds the `ACT_AS` grant and the
    /// target namespace is in its `may_act` allowlist.
    #[serde(skip_serializing_if = "Option::is_none", default)]
    pub act_as: Option<ActAs>,
}

/// Resolution outcome. Integer discriminant on the wire (`1`-based, mirroring
/// the server's `ResolutionOutcomeWire`).
#[derive(
    Clone, Copy, Debug, Eq, PartialEq, serde_repr::Serialize_repr, serde_repr::Deserialize_repr,
)]
#[repr(u8)]
pub enum ResolutionOutcomeWire {
    Resolved = 1,
    Created = 2,
    Ambiguous = 3,
    NotFound = 4,
}

/// ENTITY_RESOLVE_RESP (`0x01B6`).
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct EntityResolveResponse {
    pub outcome: ResolutionOutcomeWire,
    /// Which tier resolved (1..=5; 0 if unresolved).
    pub tier: u8,
    pub confidence: f32,
    /// Populated when `outcome == Resolved | Created` (single id);
    /// `[0; 16]` for `Ambiguous | NotFound`.
    #[serde(with = "serde_bytes")]
    pub resolved_entity: WireUuid,
    /// Populated when `outcome == Ambiguous`; ranked by score.
    #[serde(with = "crate::wire::cbor::vec_byte_array16")]
    pub candidate_ids: Vec<WireUuid>,
    /// `[0; 16]` unless an ambiguity audit was written.
    #[serde(with = "serde_bytes")]
    pub audit_id: WireUuid,
}

// ===========================================================================
// STATEMENT_GET / STATEMENT_LIST.
// ===========================================================================

/// Read-side projection of a statement. Mirrors the server's
/// `StatementView`. Optional value-side fields collapse to sentinel zero
/// (`[0; 16]` for ids, `0` for nanos).
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct StatementView {
    #[serde(with = "serde_bytes")]
    pub statement_id: WireUuid,
    pub kind: StatementKindWire,
    #[serde(with = "serde_bytes")]
    pub subject: WireUuid,
    #[serde(with = "serde_bytes")]
    pub subject_pending_audit_id: WireUuid,
    pub predicate: String,
    pub object: StatementObjectWire,
    pub confidence: f32,
    pub evidence: EvidenceRefWire,
    pub extractor_id: u32,
    pub extracted_at_unix_nanos: u64,
    pub schema_version: u32,
    pub valid_from_unix_nanos: u64,
    pub valid_to_unix_nanos: u64,
    pub event_at_unix_nanos: u64,
    pub version: u32,
    #[serde(with = "serde_bytes")]
    pub superseded_by: WireUuid,
    #[serde(with = "serde_bytes")]
    pub supersedes: WireUuid,
    #[serde(with = "serde_bytes")]
    pub chain_root: WireUuid,
    pub tombstoned: bool,
    pub tombstoned_at_unix_nanos: u64,
    pub tombstone_reason: u8,
    pub flags: u32,
    /// `true` iff this statement is stateful.
    pub is_stateful: bool,
}

/// STATEMENT_GET (`0x0141`).
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
pub struct StatementGetRequest {
    #[serde(with = "serde_bytes")]
    pub statement_id: WireUuid,
    /// If `true` and the row is superseded, the server returns the current
    /// statement in the chain (with `returned_via_supersession = true`).
    pub follow_supersession: bool,
    /// Effective identity this get runs as. `None` (omitted on the wire) means
    /// the op runs as the connection's own key-bound identity. Honored only when
    /// the connection principal holds the `ACT_AS` grant and the target
    /// namespace is in its `may_act` allowlist.
    #[serde(skip_serializing_if = "Option::is_none", default)]
    pub act_as: Option<ActAs>,
}

/// STATEMENT_GET_RESP (`0x01C1`).
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct StatementGetResponse {
    pub statement: StatementView,
    /// `true` iff `follow_supersession` redirected to a later chain entry.
    pub returned_via_supersession: bool,
}

/// STATEMENT_LIST (`0x0146`). Empty/zero fields mean "no filter".
/// `kind == 0` = no kind filter; otherwise `1 = Fact / 2 = Preference /
/// 3 = Event`.
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct StatementListRequest {
    #[serde(with = "serde_bytes")]
    pub subject: WireUuid,
    pub predicate: String,
    pub kind: u8,
    pub min_confidence: f32,
    pub time_range_start_unix_nanos: u64,
    pub time_range_end_unix_nanos: u64,
    pub only_current: bool,
    pub include_tombstoned: bool,
    pub limit: u32,
    pub cursor: Vec<u8>,
    /// Effective identity this list runs as. `None` (omitted on the wire) means
    /// the op runs as the connection's own key-bound identity. Honored only when
    /// the connection principal holds the `ACT_AS` grant and the target
    /// namespace is in its `may_act` allowlist.
    #[serde(skip_serializing_if = "Option::is_none", default)]
    pub act_as: Option<ActAs>,
}

/// One streaming STATEMENT_LIST_RESP frame (`0x01C6`).
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct StatementListResponseFrame {
    pub items: Vec<StatementView>,
    pub next_cursor: Vec<u8>,
    pub cumulative_count: u32,
    pub is_final: bool,
}

// ===========================================================================
// RELATION_LIST_FROM / RELATION_LIST_TO.
// ===========================================================================

/// Read-side projection of a relation. Mirrors the server's
/// `RelationView`. `flags` bit 0 = `is_symmetric`.
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct RelationView {
    #[serde(with = "serde_bytes")]
    pub relation_id: WireUuid,
    #[serde(with = "serde_bytes")]
    pub chain_root: WireUuid,
    pub relation_type: String,
    #[serde(with = "serde_bytes")]
    pub from_entity: WireUuid,
    #[serde(with = "serde_bytes")]
    pub to_entity: WireUuid,
    pub properties_blob: Vec<u8>,
    pub evidence: EvidenceRefWire,
    pub extractor_id: u32,
    pub extracted_at_unix_nanos: u64,
    pub confidence: f32,
    pub valid_from_unix_nanos: u64,
    pub valid_to_unix_nanos: u64,
    pub version: u32,
    #[serde(with = "serde_bytes")]
    pub superseded_by: WireUuid,
    #[serde(with = "serde_bytes")]
    pub supersedes: WireUuid,
    pub tombstoned: bool,
    pub tombstoned_at_unix_nanos: u64,
    pub flags: u32,
}

/// RELATION_LIST_FROM (`0x0154`). `relation_type_filter == ""` → any type;
/// `time_range_*_unix_nanos == 0` → no time bound.
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct RelationListFromRequest {
    #[serde(with = "serde_bytes")]
    pub from_entity: WireUuid,
    pub relation_type_filter: String,
    pub time_range_start_unix_nanos: u64,
    pub time_range_end_unix_nanos: u64,
    pub include_superseded: bool,
    pub include_tombstoned: bool,
    pub limit: u32,
    pub cursor: Vec<u8>,
    /// Effective identity this list runs as. `None` (omitted on the wire) means
    /// the op runs as the connection's own key-bound identity.
    #[serde(skip_serializing_if = "Option::is_none", default)]
    pub act_as: Option<ActAs>,
}

/// One streaming RELATION_LIST_FROM_RESP frame (`0x01D4`).
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct RelationListFromResponseFrame {
    pub items: Vec<RelationView>,
    pub next_cursor: Vec<u8>,
    pub cumulative_count: u32,
    pub is_final: bool,
}

/// RELATION_LIST_TO (`0x0155`). Identical shape to LIST_FROM but filters on
/// `to_entity`.
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct RelationListToRequest {
    #[serde(with = "serde_bytes")]
    pub to_entity: WireUuid,
    pub relation_type_filter: String,
    pub time_range_start_unix_nanos: u64,
    pub time_range_end_unix_nanos: u64,
    pub include_superseded: bool,
    pub include_tombstoned: bool,
    pub limit: u32,
    pub cursor: Vec<u8>,
    /// Effective identity this list runs as. `None` (omitted on the wire) means
    /// the op runs as the connection's own key-bound identity.
    #[serde(skip_serializing_if = "Option::is_none", default)]
    pub act_as: Option<ActAs>,
}

/// One streaming RELATION_LIST_TO_RESP frame (`0x01D5`).
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct RelationListToResponseFrame {
    pub items: Vec<RelationView>,
    pub next_cursor: Vec<u8>,
    pub cumulative_count: u32,
    pub is_final: bool,
}

// ===========================================================================
// SCHEMA_GET / SCHEMA_LIST / SCHEMA_VALIDATE.
// ===========================================================================

/// SCHEMA_GET (`0x0121`). `version == 0` → active version.
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
pub struct SchemaGetRequest {
    pub namespace: String,
    pub version: u32,
    /// Run as a tenant on a shared-pool connection (see [`ActAs`]).
    #[serde(skip_serializing_if = "Option::is_none", default)]
    pub act_as: Option<ActAs>,
}

/// SCHEMA_GET_RESP (`0x01A1`).
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
pub struct SchemaGetResponse {
    pub namespace: String,
    pub schema_version: u32,
    /// Verbatim DSL text if uploaded as such; empty for programmatic uploads.
    pub schema_document: String,
    /// `serde_json::to_vec(&Schema)` of the parsed AST.
    pub source_blob: Vec<u8>,
    pub uploaded_at_unix_nanos: u64,
    pub validator_version: u32,
}

/// SCHEMA_LIST (`0x0122`). `limit == 0` → unlimited (server-capped).
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
pub struct SchemaListRequest {
    pub namespace: String,
    pub limit: u32,
    pub cursor: Vec<u8>,
    /// Run as a tenant on a shared-pool connection (see [`ActAs`]).
    #[serde(skip_serializing_if = "Option::is_none", default)]
    pub act_as: Option<ActAs>,
}

/// One entry in a SCHEMA_LIST response.
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
pub struct SchemaListItemWire {
    pub schema_version: u32,
    pub uploaded_at_unix_nanos: u64,
    pub validator_version: u32,
    pub has_source_text: bool,
}

/// One streaming SCHEMA_LIST_RESP frame (`0x01A2`). Items are newest first.
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
pub struct SchemaListResponseFrame {
    pub namespace: String,
    pub items: Vec<SchemaListItemWire>,
    pub total: u32,
    pub next_cursor: Vec<u8>,
    pub is_final: bool,
}

/// SCHEMA_VALIDATE (`0x0123`). Dry-run; never touches storage.
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
pub struct SchemaValidateRequest {
    pub schema_document: String,
    /// Run as a tenant on a shared-pool connection (see [`ActAs`]).
    #[serde(skip_serializing_if = "Option::is_none", default)]
    pub act_as: Option<ActAs>,
}

/// SCHEMA_VALIDATE_RESP (`0x01A3`).
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
pub struct SchemaValidateResponse {
    /// Namespace parsed from the document; `""` if parse failed before
    /// reaching `namespace`.
    pub namespace: String,
    /// `current_active + 1` if validation passed; `0` otherwise.
    pub would_be_version: u32,
    pub validation_errors: Vec<SchemaValidationErrorWire>,
}

// ---------------------------------------------------------------------------
// Keepalive (PING / PONG / SERVER_PING / CLIENT_PONG).
//
// Field names are the CBOR map keys on the wire, so they must match the
// server's `brain-protocol` definitions byte-for-byte.
// ---------------------------------------------------------------------------

/// BYE (`0x001F`) — end the session cleanly.
///
/// A goodbye is a CBOR map, **not** an empty payload. All three SDKs used to
/// send zero bytes here, which the server cannot decode as a `ByeRequest`; it
/// tolerates it today rather than rejecting, but the corpus `req_bye` vector
/// pins the correct form.
#[derive(Clone, Debug, Default, PartialEq, Eq, Serialize, Deserialize)]
pub struct ByeRequest {
    /// Serialized unconditionally, as `null` when absent — the server declares
    /// this field with no serde attributes, and every other `Option` in this
    /// SDK mirrors the server's declaration exactly so the manifest comparison
    /// stays free of exceptions. A reason-less goodbye is therefore
    /// `{"reason": null}`, not an empty map; the server accepts either, since
    /// serde visits `none` for a missing `Option` field.
    pub reason: Option<String>,
}

/// PING (`0x0010`, client→server) — RTT probe.
#[derive(Clone, Copy, Debug, Eq, PartialEq, Serialize, Deserialize)]
pub struct PingRequest {
    pub client_timestamp_unix_nanos: u64,
}

/// PONG (`0x0090`, server→client) — reply to PING, echoes the client's
/// timestamp and adds the server's so the client can measure RTT.
#[derive(Clone, Copy, Debug, Eq, PartialEq, Serialize, Deserialize)]
pub struct PongResponse {
    pub client_timestamp_unix_nanos: u64,
    pub server_timestamp_unix_nanos: u64,
}

/// SERVER_PING (`0x0091`, server→client) — the server's idle-timer
/// heartbeat. The client MUST answer with `CLIENT_PONG` or the server
/// closes the connection after its ping timeout.
#[derive(Clone, Copy, Debug, Eq, PartialEq, Serialize, Deserialize)]
pub struct ServerPingResponse {
    pub server_timestamp_unix_nanos: u64,
}

/// CLIENT_PONG (`0x0011`, client→server) — reply to `SERVER_PING`,
/// echoing the server's timestamp plus the client's own.
#[derive(Clone, Copy, Debug, Eq, PartialEq, Serialize, Deserialize)]
pub struct ClientPongRequest {
    pub server_timestamp_unix_nanos: u64,
    pub client_timestamp_unix_nanos: u64,
}

// ---------------------------------------------------------------------------
// Relation lifecycle + traversal — fetch one (get), revise (supersede), retire
// (tombstone), or walk the graph from an entity (traverse).
// ---------------------------------------------------------------------------

/// RELATION_GET (`0x0151`). `follow_supersession` returns the current head of a
/// superseded relation's chain rather than the (retired) id asked for.
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct RelationGetRequest {
    #[serde(with = "serde_bytes")]
    pub relation_id: WireUuid,
    pub follow_supersession: bool,
    /// Effective identity this get runs as. `None` (omitted on the wire) means
    /// the op runs as the connection's own key-bound identity.
    #[serde(skip_serializing_if = "Option::is_none", default)]
    pub act_as: Option<ActAs>,
}

/// RELATION_GET_RESP (`0x01D1`). `returned_via_supersession` flags that the
/// view is the chain head, not the exact id requested.
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct RelationGetResponse {
    pub relation: RelationView,
    pub returned_via_supersession: bool,
}

/// RELATION_SUPERSEDE (`0x0152`). Revise a relation, keeping both on one chain.
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct RelationSupersedeRequest {
    #[serde(with = "serde_bytes")]
    pub old_relation_id: WireUuid,
    pub new_relation: RelationCreateRequest,
    #[serde(with = "serde_bytes")]
    pub request_id: WireUuid,
}

/// RELATION_SUPERSEDE_RESP (`0x01D2`). New id + monotonic version.
#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)]
pub struct RelationSupersedeResponse {
    #[serde(with = "serde_bytes")]
    pub new_relation_id: WireUuid,
    pub version: u32,
}

/// RELATION_TOMBSTONE (`0x0153`). Soft-retire a relation with a reason.
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct RelationTombstoneRequest {
    #[serde(with = "serde_bytes")]
    pub relation_id: WireUuid,
    pub reason: String,
    #[serde(with = "serde_bytes")]
    pub request_id: WireUuid,
}

/// RELATION_TOMBSTONE_RESP (`0x01D3`).
#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)]
pub struct RelationTombstoneResponse {
    pub tombstoned_at_unix_nanos: u64,
}

/// One hop in a traversal path: the relation edge crossed and its endpoints.
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct TraversalStepWire {
    #[serde(with = "serde_bytes")]
    pub relation_id: WireUuid,
    #[serde(with = "serde_bytes")]
    pub from: WireUuid,
    #[serde(with = "serde_bytes")]
    pub to: WireUuid,
    pub relation_type: String,
    pub depth: u32,
}

/// One path the traversal found, as an ordered list of steps.
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct TraversalPathWire {
    pub steps: Vec<TraversalStepWire>,
}

/// RELATION_TRAVERSE (`0x0156`). Multi-hop walk of the relation graph from
/// `start_entity`. `direction` is outgoing/incoming/both; the bounds cap the
/// search; `time_at_unix_nanos` walks the graph as it stood at a record time.
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct RelationTraverseRequest {
    #[serde(with = "serde_bytes")]
    pub start_entity: WireUuid,
    pub relation_types: Vec<String>,
    pub direction: u8,
    pub max_depth: u32,
    pub max_nodes: u32,
    pub time_at_unix_nanos: u64,
    pub include_superseded: bool,
    #[serde(with = "serde_bytes")]
    pub request_id: WireUuid,
    /// Effective identity this traversal runs as. `None` (omitted on the wire)
    /// means the op runs as the connection's own key-bound identity. Honored
    /// only when the connection principal holds the `ACT_AS` grant and the
    /// target namespace is in its `may_act` allowlist.
    #[serde(skip_serializing_if = "Option::is_none", default)]
    pub act_as: Option<ActAs>,
}

/// RELATION_TRAVERSE_RESP (`0x01D6`), one streamed frame. `is_final` marks the
/// last; `truncated` flags a bound was hit before the graph was exhausted.
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct RelationTraverseResponseFrame {
    pub paths: Vec<TraversalPathWire>,
    pub total_paths: u32,
    pub truncated: bool,
    pub is_final: bool,
}

// ---------------------------------------------------------------------------
// Query introspection debug surface — the plan (explain) and execution trace.
// ---------------------------------------------------------------------------

/// QUERY_EXPLAIN (`0x0161`). Ask for the plan of a query without running it.
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct QueryExplainRequest {
    pub query: QueryRequest,
}

/// QUERY_EXPLAIN_RESP (`0x01E1`). The plan plus an estimated cost.
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct QueryExplainResponse {
    pub plan_text: String,
    pub estimated_cost_ms: f32,
}

/// QUERY_TRACE (`0x0162`). Run a query and return its per-stage execution trace.
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct QueryTraceRequest {
    pub query: QueryRequest,
}

/// QUERY_TRACE_RESP (`0x01E2`). The trace plus total latency.
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct QueryTraceResponse {
    pub trace_text: String,
    pub total_latency_ms: f64,
}

#[cfg(test)]
mod error_code_forward_compat_tests {
    use super::*;

    #[test]
    fn known_codes_round_trip_through_from_raw() {
        assert_eq!(
            ErrorCodeWire::from_raw(0x0033),
            ErrorCodeWire::ActAsDenied,
            "an existing code must still decode to its own variant"
        );
        assert_eq!(
            ErrorCodeWire::from_raw(0x0066),
            ErrorCodeWire::LlmCredentialMissing
        );
        assert_eq!(
            ErrorCodeWire::from_raw(0x0095),
            ErrorCodeWire::LlmCredentialUnavailable
        );
    }

    #[test]
    fn an_unrecognised_code_decodes_to_unknown_instead_of_failing() {
        // The defect this closes: `Deserialize_repr` with no catch-all made a
        // single unrecognised code fail the WHOLE ErrorResponse, so a client
        // talking to a newer server reported a parse error instead of the
        // server's actual error. Python and TypeScript both model `code` as a
        // plain integer and never had this problem.
        assert_eq!(ErrorCodeWire::from_raw(0xDEAD), ErrorCodeWire::Unknown);
        assert_eq!(ErrorCodeWire::from_raw(0x7FFF), ErrorCodeWire::Unknown);
    }

    #[test]
    fn an_error_response_carrying_an_unknown_code_still_decodes() {
        // End-to-end: the frame must remain readable, and `category` — the
        // field the wire contract guarantees is always meaningful — must
        // survive so the client can still decide whether to retry.
        let json = serde_json::json!({
            "code": 0xDEAD_u16,
            "category": 8,
            "message": "from a newer server",
            "details": null,
            "retry_after_ms": null,
        });
        let decoded: ErrorResponse =
            serde_json::from_value(json).expect("an unknown code must not break the frame");
        assert!(decoded.code_is_unknown());
        assert_eq!(decoded.category, ErrorCategoryWire::Unavailable);
        assert_eq!(decoded.message, "from a newer server");
    }
}