ai-memory 0.7.1

AI-agnostic persistent memory system — MCP server, HTTP API, and CLI for any AI platform
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135
3136
3137
3138
3139
3140
3141
3142
3143
3144
3145
3146
3147
3148
3149
3150
3151
3152
3153
3154
3155
3156
3157
3158
3159
3160
3161
3162
3163
3164
3165
3166
3167
3168
3169
3170
3171
3172
3173
3174
3175
3176
3177
3178
3179
3180
3181
3182
3183
3184
3185
3186
3187
3188
3189
3190
3191
3192
3193
3194
3195
3196
3197
3198
3199
3200
3201
3202
3203
3204
3205
3206
3207
3208
3209
3210
3211
3212
3213
3214
3215
3216
3217
3218
3219
3220
3221
3222
3223
3224
3225
3226
3227
3228
3229
3230
3231
3232
3233
3234
3235
3236
3237
3238
3239
3240
3241
3242
3243
3244
3245
3246
3247
3248
3249
3250
3251
3252
3253
3254
3255
3256
3257
3258
3259
3260
3261
3262
3263
3264
3265
3266
3267
3268
3269
3270
3271
3272
3273
3274
3275
3276
3277
3278
3279
3280
3281
3282
3283
3284
3285
3286
3287
3288
3289
3290
3291
3292
3293
3294
3295
3296
3297
3298
3299
3300
3301
3302
3303
3304
3305
3306
3307
3308
3309
3310
3311
3312
3313
3314
3315
3316
3317
3318
3319
3320
3321
3322
3323
3324
3325
3326
3327
3328
3329
3330
3331
3332
3333
3334
3335
3336
3337
3338
3339
3340
3341
3342
3343
3344
3345
3346
3347
3348
3349
3350
3351
3352
3353
3354
3355
3356
3357
3358
3359
3360
3361
3362
3363
3364
3365
3366
3367
3368
3369
3370
3371
3372
3373
3374
3375
3376
3377
3378
3379
3380
3381
3382
3383
3384
3385
3386
3387
3388
3389
3390
3391
3392
3393
3394
3395
3396
3397
3398
3399
3400
3401
3402
3403
3404
3405
3406
3407
3408
3409
3410
3411
3412
3413
3414
3415
3416
3417
3418
3419
3420
3421
3422
3423
3424
3425
3426
3427
3428
3429
3430
3431
3432
3433
3434
3435
3436
3437
3438
3439
3440
3441
3442
3443
3444
3445
3446
3447
3448
3449
3450
3451
3452
3453
3454
3455
3456
3457
3458
3459
3460
3461
3462
3463
3464
3465
3466
3467
3468
3469
3470
3471
3472
3473
3474
3475
3476
3477
3478
3479
3480
3481
3482
3483
3484
3485
3486
3487
3488
3489
3490
3491
3492
3493
3494
3495
3496
3497
3498
3499
3500
3501
3502
3503
3504
3505
3506
3507
3508
3509
3510
3511
3512
3513
3514
3515
3516
3517
3518
3519
3520
3521
3522
3523
3524
3525
3526
3527
3528
3529
3530
3531
3532
3533
3534
3535
3536
3537
3538
3539
3540
3541
3542
3543
3544
3545
3546
3547
3548
3549
3550
3551
3552
3553
3554
3555
3556
3557
3558
3559
3560
3561
3562
3563
3564
3565
3566
3567
3568
3569
3570
3571
3572
3573
3574
3575
3576
3577
3578
3579
3580
3581
3582
3583
3584
3585
3586
3587
3588
3589
3590
3591
3592
3593
3594
3595
3596
3597
3598
3599
3600
3601
3602
3603
3604
3605
3606
3607
3608
3609
3610
3611
3612
3613
3614
3615
3616
3617
3618
3619
3620
3621
3622
3623
3624
3625
3626
3627
3628
3629
3630
3631
3632
3633
3634
3635
3636
3637
3638
3639
3640
3641
3642
3643
3644
3645
3646
3647
3648
3649
3650
3651
3652
3653
3654
3655
3656
3657
3658
3659
3660
3661
3662
3663
3664
3665
3666
3667
3668
3669
3670
3671
3672
3673
3674
3675
3676
3677
3678
3679
3680
3681
3682
3683
3684
3685
3686
3687
3688
3689
3690
3691
3692
3693
3694
3695
3696
3697
3698
3699
3700
3701
3702
3703
3704
3705
3706
3707
3708
3709
3710
3711
3712
3713
3714
3715
3716
3717
3718
3719
3720
3721
3722
3723
3724
3725
3726
3727
3728
3729
3730
3731
3732
3733
3734
3735
3736
3737
3738
3739
3740
3741
3742
3743
3744
3745
3746
3747
3748
3749
3750
3751
3752
3753
3754
3755
3756
3757
3758
3759
3760
3761
3762
3763
3764
3765
3766
3767
3768
3769
3770
3771
3772
3773
3774
3775
3776
3777
3778
3779
3780
3781
3782
3783
3784
3785
3786
3787
3788
3789
3790
3791
3792
3793
3794
3795
3796
3797
3798
3799
3800
3801
3802
3803
3804
3805
3806
3807
3808
3809
3810
3811
3812
3813
3814
3815
3816
3817
3818
3819
3820
3821
3822
3823
3824
3825
3826
3827
3828
3829
3830
3831
3832
3833
3834
3835
3836
3837
3838
3839
3840
3841
3842
3843
3844
3845
3846
3847
3848
3849
3850
3851
3852
3853
3854
3855
3856
3857
3858
3859
3860
3861
3862
3863
3864
3865
3866
3867
3868
3869
3870
3871
3872
3873
3874
3875
3876
3877
3878
3879
3880
3881
3882
3883
3884
3885
3886
3887
3888
3889
3890
3891
3892
3893
3894
3895
3896
3897
3898
3899
3900
3901
3902
3903
3904
3905
3906
3907
3908
3909
3910
3911
3912
3913
3914
3915
3916
3917
3918
3919
3920
3921
3922
3923
3924
3925
3926
3927
3928
3929
3930
3931
3932
3933
3934
3935
3936
3937
3938
3939
3940
3941
3942
3943
3944
3945
3946
3947
3948
3949
3950
3951
3952
3953
3954
3955
3956
3957
3958
3959
3960
3961
3962
3963
3964
3965
3966
3967
3968
3969
3970
3971
3972
3973
3974
3975
3976
3977
3978
3979
3980
3981
3982
3983
3984
3985
3986
3987
3988
3989
3990
3991
3992
3993
3994
3995
3996
3997
3998
3999
4000
4001
4002
4003
4004
4005
4006
4007
4008
4009
4010
4011
4012
4013
4014
4015
4016
4017
4018
4019
4020
4021
4022
4023
4024
4025
4026
4027
4028
4029
4030
4031
4032
4033
4034
4035
4036
4037
4038
4039
4040
4041
4042
4043
4044
4045
4046
4047
4048
4049
4050
4051
4052
4053
4054
4055
4056
4057
4058
4059
4060
4061
4062
4063
4064
4065
4066
4067
4068
4069
4070
4071
4072
4073
4074
4075
4076
4077
4078
4079
4080
4081
4082
4083
4084
4085
4086
4087
4088
4089
4090
4091
4092
4093
4094
4095
4096
4097
4098
4099
4100
4101
4102
4103
4104
4105
4106
4107
4108
4109
4110
4111
4112
4113
4114
4115
4116
4117
4118
4119
4120
4121
4122
4123
4124
4125
4126
4127
4128
4129
4130
4131
4132
4133
4134
4135
4136
4137
4138
4139
4140
4141
4142
4143
4144
4145
4146
4147
4148
4149
4150
4151
4152
4153
4154
4155
4156
4157
4158
4159
4160
4161
4162
4163
4164
4165
4166
4167
4168
4169
4170
4171
4172
4173
4174
4175
4176
4177
4178
4179
4180
4181
4182
4183
4184
4185
4186
4187
4188
4189
4190
4191
4192
4193
4194
4195
4196
4197
4198
4199
4200
4201
4202
4203
4204
4205
4206
4207
4208
4209
4210
4211
4212
4213
4214
4215
4216
4217
4218
4219
4220
4221
4222
4223
4224
4225
4226
4227
4228
4229
4230
4231
4232
4233
4234
4235
4236
4237
4238
4239
4240
4241
4242
4243
4244
4245
4246
4247
4248
4249
4250
4251
4252
4253
4254
4255
4256
4257
4258
4259
4260
4261
4262
4263
4264
4265
4266
4267
4268
4269
4270
4271
4272
4273
4274
4275
4276
4277
4278
4279
4280
4281
4282
4283
4284
4285
4286
4287
4288
4289
4290
4291
4292
4293
4294
4295
4296
4297
4298
4299
4300
4301
4302
4303
4304
4305
4306
4307
4308
4309
4310
4311
4312
4313
4314
4315
4316
4317
4318
4319
4320
4321
4322
4323
4324
4325
4326
4327
4328
4329
4330
4331
4332
4333
4334
4335
4336
4337
4338
4339
4340
4341
4342
4343
4344
4345
4346
4347
4348
4349
4350
4351
4352
4353
4354
4355
4356
4357
4358
4359
4360
4361
4362
4363
4364
4365
4366
4367
4368
4369
4370
4371
4372
4373
4374
4375
4376
4377
4378
4379
4380
4381
4382
4383
4384
4385
4386
4387
4388
4389
4390
4391
4392
4393
4394
4395
4396
4397
4398
4399
4400
4401
4402
4403
4404
4405
4406
4407
4408
4409
4410
4411
4412
4413
4414
4415
4416
4417
4418
4419
4420
4421
4422
4423
4424
4425
4426
4427
4428
4429
4430
4431
4432
4433
4434
4435
4436
4437
4438
4439
4440
4441
4442
4443
4444
4445
4446
4447
4448
4449
4450
4451
4452
4453
4454
4455
4456
4457
4458
4459
4460
4461
4462
4463
4464
4465
4466
4467
4468
4469
4470
4471
4472
4473
4474
4475
4476
4477
4478
4479
4480
4481
4482
4483
4484
4485
4486
4487
4488
4489
4490
4491
4492
4493
4494
4495
4496
4497
4498
4499
4500
4501
4502
4503
4504
4505
4506
4507
4508
4509
4510
4511
4512
4513
4514
4515
4516
4517
4518
4519
4520
4521
4522
4523
4524
4525
4526
4527
4528
4529
4530
4531
4532
4533
4534
4535
4536
4537
4538
4539
4540
4541
4542
4543
4544
4545
4546
4547
4548
4549
4550
4551
4552
4553
4554
4555
4556
4557
4558
4559
4560
4561
4562
4563
4564
4565
4566
4567
4568
4569
4570
4571
4572
4573
4574
4575
4576
4577
4578
4579
4580
4581
4582
4583
4584
4585
4586
4587
4588
4589
4590
4591
4592
4593
4594
4595
4596
4597
4598
4599
4600
4601
4602
4603
4604
4605
4606
4607
4608
4609
4610
4611
4612
4613
4614
4615
4616
4617
4618
4619
4620
4621
4622
4623
4624
4625
4626
4627
4628
4629
4630
4631
4632
4633
4634
4635
4636
4637
4638
4639
4640
4641
4642
4643
4644
4645
4646
4647
4648
4649
4650
4651
4652
4653
4654
4655
4656
4657
4658
4659
4660
4661
4662
4663
4664
4665
4666
4667
4668
4669
4670
4671
4672
4673
4674
4675
4676
4677
4678
4679
4680
4681
4682
4683
4684
4685
4686
4687
4688
4689
4690
4691
4692
4693
4694
4695
4696
4697
4698
4699
4700
4701
4702
4703
4704
4705
4706
4707
4708
4709
4710
4711
4712
4713
4714
4715
4716
4717
4718
4719
4720
4721
4722
4723
4724
4725
4726
4727
4728
4729
4730
4731
4732
4733
4734
4735
4736
4737
4738
4739
4740
4741
4742
4743
4744
4745
4746
4747
4748
4749
4750
4751
4752
4753
4754
4755
4756
4757
4758
4759
4760
4761
4762
4763
4764
4765
4766
4767
4768
4769
4770
4771
4772
4773
4774
4775
4776
4777
4778
4779
4780
4781
4782
4783
4784
4785
4786
4787
4788
4789
4790
4791
4792
4793
4794
4795
4796
4797
4798
4799
4800
4801
4802
4803
4804
4805
4806
4807
4808
4809
4810
4811
4812
4813
4814
4815
4816
4817
4818
4819
4820
4821
4822
4823
4824
4825
4826
4827
4828
4829
4830
4831
4832
4833
4834
4835
4836
4837
4838
4839
4840
4841
4842
4843
4844
4845
4846
4847
4848
4849
4850
4851
4852
4853
4854
4855
4856
4857
4858
4859
4860
4861
4862
4863
4864
4865
4866
4867
4868
4869
4870
4871
4872
4873
4874
4875
4876
4877
4878
4879
4880
4881
4882
4883
4884
4885
4886
4887
4888
4889
4890
4891
4892
4893
4894
4895
4896
4897
4898
4899
4900
4901
4902
4903
4904
4905
4906
4907
4908
4909
4910
4911
4912
4913
4914
4915
4916
4917
4918
4919
4920
4921
4922
4923
4924
4925
4926
4927
4928
4929
4930
4931
4932
4933
4934
4935
4936
4937
4938
4939
4940
4941
4942
4943
4944
4945
4946
4947
4948
4949
4950
4951
4952
4953
4954
4955
4956
4957
4958
4959
4960
4961
4962
4963
4964
4965
4966
4967
4968
4969
4970
4971
4972
4973
4974
4975
4976
4977
4978
4979
4980
4981
4982
4983
4984
4985
4986
4987
4988
4989
4990
4991
4992
4993
4994
4995
4996
4997
4998
4999
5000
5001
5002
5003
5004
5005
5006
5007
5008
5009
5010
5011
5012
5013
5014
5015
5016
5017
5018
5019
5020
5021
5022
5023
5024
5025
5026
5027
5028
5029
5030
5031
5032
5033
5034
5035
5036
5037
5038
5039
5040
5041
5042
5043
5044
5045
5046
5047
5048
5049
5050
5051
5052
5053
5054
5055
5056
5057
5058
5059
5060
5061
5062
5063
5064
5065
5066
5067
5068
5069
5070
5071
5072
5073
5074
5075
5076
5077
5078
5079
5080
5081
5082
5083
5084
5085
5086
5087
5088
5089
5090
5091
5092
5093
5094
5095
5096
5097
5098
5099
5100
5101
5102
5103
5104
5105
5106
5107
5108
5109
5110
5111
5112
5113
5114
5115
5116
5117
5118
5119
5120
5121
5122
5123
5124
5125
5126
5127
5128
5129
5130
5131
5132
5133
5134
5135
5136
5137
5138
5139
5140
5141
5142
5143
5144
5145
5146
5147
5148
5149
5150
5151
5152
5153
5154
5155
5156
5157
5158
5159
5160
5161
5162
5163
5164
5165
5166
5167
5168
5169
5170
5171
5172
5173
5174
5175
5176
5177
5178
5179
5180
5181
5182
5183
5184
5185
5186
5187
5188
5189
5190
5191
5192
5193
5194
5195
5196
5197
5198
5199
5200
5201
5202
5203
5204
5205
5206
5207
5208
5209
5210
5211
5212
5213
5214
5215
5216
5217
5218
5219
5220
5221
5222
5223
5224
5225
5226
5227
5228
5229
5230
5231
5232
5233
5234
5235
5236
5237
5238
5239
5240
5241
5242
5243
5244
5245
5246
5247
5248
5249
5250
5251
5252
5253
5254
5255
5256
5257
5258
5259
5260
5261
5262
5263
5264
5265
5266
5267
5268
5269
5270
5271
5272
5273
5274
5275
5276
5277
5278
5279
5280
5281
5282
5283
5284
5285
5286
5287
5288
5289
5290
5291
5292
5293
5294
5295
5296
5297
5298
5299
5300
5301
5302
5303
5304
5305
5306
5307
5308
5309
5310
5311
5312
5313
5314
5315
5316
5317
5318
5319
5320
5321
5322
5323
5324
5325
5326
5327
5328
5329
5330
5331
5332
5333
5334
5335
5336
5337
5338
5339
5340
5341
5342
5343
5344
5345
5346
5347
5348
5349
5350
5351
5352
5353
5354
5355
5356
5357
5358
5359
5360
5361
5362
5363
5364
5365
5366
5367
5368
5369
5370
5371
5372
5373
5374
5375
5376
5377
5378
5379
5380
5381
5382
5383
5384
5385
5386
5387
5388
5389
5390
5391
5392
5393
5394
5395
5396
5397
5398
5399
5400
5401
5402
5403
5404
5405
5406
5407
5408
5409
5410
5411
5412
5413
5414
5415
5416
5417
5418
5419
5420
5421
5422
5423
5424
5425
5426
5427
5428
5429
5430
5431
5432
5433
5434
5435
5436
5437
5438
5439
5440
5441
5442
5443
5444
5445
5446
5447
5448
5449
5450
5451
5452
5453
5454
5455
5456
5457
5458
5459
5460
5461
5462
5463
5464
5465
5466
5467
5468
5469
5470
5471
5472
5473
5474
5475
5476
5477
5478
5479
5480
5481
5482
5483
5484
5485
5486
5487
5488
5489
5490
5491
5492
5493
5494
5495
5496
5497
5498
5499
5500
5501
5502
5503
5504
5505
5506
5507
5508
5509
5510
5511
5512
5513
5514
5515
5516
5517
5518
5519
5520
5521
5522
5523
5524
5525
5526
5527
5528
5529
5530
5531
5532
5533
5534
5535
5536
5537
5538
5539
5540
5541
5542
5543
5544
5545
5546
5547
5548
5549
5550
5551
5552
5553
5554
5555
5556
5557
5558
5559
5560
5561
5562
5563
5564
5565
5566
5567
5568
5569
5570
5571
5572
5573
5574
5575
5576
5577
5578
5579
5580
5581
5582
5583
5584
5585
5586
5587
5588
5589
5590
5591
5592
5593
5594
5595
5596
5597
5598
5599
5600
5601
5602
5603
5604
5605
5606
5607
5608
5609
5610
5611
5612
5613
5614
5615
5616
5617
5618
5619
5620
5621
5622
5623
5624
5625
5626
5627
5628
5629
5630
5631
5632
5633
5634
5635
5636
5637
5638
5639
5640
5641
5642
5643
5644
5645
5646
5647
5648
5649
5650
5651
5652
5653
5654
5655
5656
5657
5658
5659
5660
5661
5662
5663
5664
5665
5666
5667
5668
5669
5670
5671
5672
5673
5674
5675
5676
5677
5678
5679
5680
5681
5682
5683
5684
5685
5686
5687
5688
5689
5690
5691
5692
5693
5694
5695
5696
5697
5698
5699
5700
5701
5702
5703
5704
5705
5706
5707
5708
5709
5710
5711
5712
5713
5714
5715
5716
5717
5718
5719
5720
5721
5722
5723
5724
5725
5726
5727
5728
5729
5730
5731
5732
5733
5734
5735
5736
5737
5738
5739
5740
5741
5742
5743
5744
5745
5746
5747
5748
5749
5750
5751
5752
5753
5754
5755
5756
5757
5758
5759
5760
5761
5762
5763
5764
5765
5766
5767
5768
5769
5770
5771
5772
5773
5774
5775
5776
5777
5778
5779
5780
5781
5782
5783
5784
5785
5786
5787
5788
5789
5790
5791
5792
5793
5794
5795
5796
5797
5798
5799
5800
5801
5802
5803
5804
5805
5806
5807
5808
5809
5810
5811
5812
5813
5814
5815
5816
5817
5818
5819
5820
5821
5822
5823
5824
5825
5826
5827
5828
5829
5830
5831
5832
5833
5834
5835
5836
5837
5838
5839
5840
5841
5842
5843
5844
5845
5846
5847
5848
5849
5850
5851
5852
5853
5854
5855
5856
5857
5858
5859
5860
5861
5862
5863
5864
5865
5866
5867
5868
5869
5870
5871
5872
5873
5874
5875
5876
5877
5878
5879
5880
5881
5882
5883
5884
5885
5886
5887
5888
5889
5890
5891
5892
5893
5894
5895
5896
5897
5898
5899
5900
5901
5902
5903
5904
5905
5906
5907
5908
5909
5910
5911
5912
5913
5914
5915
5916
5917
5918
5919
5920
5921
5922
5923
5924
5925
5926
5927
5928
5929
5930
5931
5932
5933
5934
5935
5936
5937
5938
5939
5940
5941
5942
5943
5944
5945
5946
5947
5948
5949
5950
5951
5952
5953
5954
5955
5956
5957
5958
5959
5960
5961
5962
5963
5964
5965
5966
5967
5968
5969
5970
5971
5972
5973
5974
5975
5976
5977
5978
5979
5980
5981
5982
5983
5984
5985
5986
5987
5988
5989
5990
5991
5992
5993
5994
5995
5996
5997
5998
5999
6000
6001
6002
6003
6004
6005
6006
6007
6008
6009
6010
6011
6012
6013
6014
6015
6016
6017
6018
6019
6020
6021
6022
6023
6024
6025
6026
6027
6028
6029
6030
6031
6032
6033
6034
6035
6036
6037
6038
6039
6040
6041
6042
6043
6044
6045
6046
6047
6048
6049
6050
6051
6052
6053
6054
6055
6056
6057
6058
6059
6060
6061
6062
6063
6064
6065
6066
6067
6068
6069
6070
6071
6072
6073
6074
6075
6076
6077
6078
6079
6080
6081
6082
6083
6084
6085
6086
6087
6088
6089
6090
6091
6092
6093
6094
6095
6096
6097
6098
6099
6100
6101
6102
6103
6104
6105
6106
6107
6108
6109
6110
6111
6112
6113
6114
6115
6116
6117
6118
6119
6120
6121
6122
6123
6124
6125
6126
6127
6128
6129
6130
6131
6132
6133
6134
6135
6136
6137
6138
6139
6140
6141
6142
6143
6144
6145
6146
6147
6148
6149
6150
6151
6152
6153
6154
6155
6156
6157
6158
6159
6160
6161
6162
6163
6164
6165
6166
6167
6168
6169
6170
6171
6172
6173
6174
6175
6176
6177
6178
6179
6180
6181
6182
6183
6184
6185
6186
6187
6188
6189
6190
6191
6192
6193
6194
6195
6196
6197
6198
6199
6200
6201
6202
6203
6204
6205
6206
6207
6208
6209
6210
6211
6212
6213
6214
6215
6216
6217
6218
6219
6220
6221
6222
6223
6224
6225
6226
6227
6228
6229
6230
6231
6232
6233
6234
6235
6236
6237
6238
6239
6240
6241
6242
6243
6244
6245
6246
6247
6248
6249
6250
6251
6252
6253
6254
6255
6256
6257
6258
6259
6260
6261
6262
6263
6264
6265
6266
6267
6268
6269
6270
6271
6272
6273
6274
6275
6276
6277
6278
6279
6280
6281
6282
6283
6284
6285
6286
6287
6288
6289
6290
6291
6292
6293
6294
6295
6296
6297
6298
6299
6300
6301
6302
6303
6304
6305
6306
6307
6308
6309
6310
6311
6312
6313
6314
6315
6316
6317
6318
6319
6320
6321
6322
6323
6324
6325
6326
6327
6328
6329
6330
6331
6332
6333
6334
6335
6336
6337
6338
6339
6340
6341
6342
6343
6344
6345
6346
6347
6348
6349
6350
6351
6352
6353
6354
6355
6356
6357
6358
6359
6360
6361
6362
6363
6364
6365
6366
6367
6368
6369
6370
6371
6372
6373
6374
6375
6376
6377
6378
6379
6380
6381
6382
6383
6384
6385
6386
6387
6388
6389
6390
6391
6392
6393
6394
6395
6396
6397
6398
6399
6400
6401
6402
6403
6404
6405
6406
6407
6408
6409
6410
6411
6412
6413
6414
6415
6416
6417
6418
6419
6420
6421
6422
6423
6424
6425
6426
6427
6428
6429
6430
6431
6432
6433
6434
6435
6436
6437
6438
6439
6440
6441
6442
6443
6444
6445
6446
6447
6448
6449
6450
6451
6452
6453
6454
6455
6456
6457
6458
6459
6460
6461
6462
6463
6464
6465
6466
6467
6468
6469
6470
6471
6472
6473
6474
6475
6476
6477
6478
6479
6480
6481
6482
6483
6484
6485
6486
6487
6488
6489
6490
6491
6492
6493
6494
6495
6496
6497
6498
6499
6500
6501
6502
6503
6504
6505
6506
6507
6508
6509
6510
6511
6512
6513
6514
6515
6516
6517
6518
6519
6520
6521
6522
6523
6524
6525
6526
6527
6528
6529
6530
6531
6532
6533
6534
6535
6536
6537
6538
6539
6540
6541
6542
6543
6544
6545
6546
6547
6548
6549
6550
6551
6552
6553
6554
6555
6556
6557
6558
6559
6560
6561
6562
6563
6564
6565
6566
6567
6568
6569
6570
6571
6572
6573
6574
6575
6576
6577
6578
6579
6580
6581
6582
6583
6584
6585
6586
6587
6588
6589
6590
6591
6592
6593
6594
6595
6596
6597
6598
6599
6600
6601
6602
6603
6604
6605
6606
6607
6608
6609
6610
6611
6612
6613
6614
6615
6616
6617
6618
6619
6620
6621
6622
6623
6624
6625
6626
6627
6628
6629
6630
6631
6632
6633
6634
6635
6636
6637
6638
6639
6640
6641
6642
6643
6644
6645
6646
6647
6648
6649
6650
6651
6652
6653
6654
6655
6656
6657
6658
6659
6660
6661
6662
6663
6664
6665
6666
6667
6668
6669
6670
6671
6672
6673
6674
6675
6676
6677
6678
6679
6680
6681
6682
6683
6684
6685
6686
6687
6688
6689
6690
6691
6692
6693
6694
6695
6696
6697
6698
6699
6700
6701
6702
6703
6704
6705
6706
6707
6708
6709
6710
6711
6712
6713
6714
6715
6716
6717
6718
6719
6720
6721
6722
6723
6724
6725
6726
6727
6728
6729
6730
6731
6732
6733
6734
6735
6736
6737
6738
6739
6740
6741
6742
6743
6744
6745
6746
6747
6748
6749
6750
6751
6752
6753
6754
6755
6756
6757
6758
6759
6760
6761
6762
6763
6764
6765
6766
6767
6768
6769
6770
6771
6772
6773
6774
6775
6776
6777
6778
6779
6780
6781
6782
6783
6784
6785
6786
6787
6788
6789
6790
6791
6792
6793
6794
6795
6796
6797
6798
6799
6800
6801
6802
6803
6804
6805
6806
6807
6808
6809
6810
6811
6812
6813
6814
6815
6816
6817
6818
6819
6820
6821
6822
6823
6824
6825
6826
6827
6828
6829
6830
6831
6832
6833
6834
6835
6836
6837
6838
6839
6840
6841
6842
6843
6844
6845
6846
6847
6848
6849
6850
6851
6852
6853
6854
6855
6856
6857
6858
6859
6860
6861
6862
6863
6864
6865
6866
6867
6868
6869
6870
6871
6872
6873
6874
6875
6876
6877
6878
6879
6880
6881
6882
6883
6884
6885
6886
6887
6888
6889
6890
6891
6892
6893
6894
6895
6896
6897
6898
6899
6900
6901
6902
6903
6904
6905
6906
6907
6908
6909
6910
6911
6912
6913
6914
6915
6916
6917
6918
6919
6920
6921
6922
6923
6924
6925
6926
6927
6928
6929
6930
6931
6932
6933
6934
6935
6936
6937
6938
6939
6940
6941
6942
6943
6944
6945
6946
6947
6948
6949
6950
6951
6952
6953
6954
6955
6956
6957
6958
6959
6960
6961
6962
6963
6964
6965
6966
6967
6968
6969
6970
6971
6972
6973
6974
6975
6976
6977
6978
6979
6980
6981
6982
6983
6984
6985
6986
6987
6988
6989
6990
6991
6992
6993
6994
6995
6996
6997
6998
6999
7000
7001
7002
7003
7004
7005
7006
7007
7008
7009
7010
7011
7012
7013
7014
7015
7016
7017
7018
7019
7020
7021
7022
7023
7024
7025
7026
7027
7028
7029
7030
7031
7032
7033
7034
7035
7036
7037
7038
7039
7040
7041
7042
7043
7044
7045
7046
7047
7048
7049
7050
7051
7052
7053
7054
7055
7056
7057
7058
7059
7060
7061
7062
7063
7064
7065
7066
7067
7068
7069
7070
7071
7072
7073
7074
7075
7076
7077
7078
7079
7080
7081
7082
7083
7084
7085
7086
7087
7088
7089
7090
7091
7092
7093
7094
7095
7096
7097
7098
7099
7100
7101
7102
7103
7104
7105
7106
7107
7108
7109
7110
7111
7112
7113
7114
7115
7116
7117
7118
7119
7120
7121
7122
7123
7124
7125
7126
7127
7128
7129
7130
7131
7132
7133
7134
7135
7136
7137
7138
7139
7140
7141
7142
7143
7144
7145
7146
7147
7148
7149
7150
7151
7152
7153
7154
7155
7156
7157
7158
7159
7160
7161
7162
7163
7164
7165
7166
7167
7168
7169
7170
7171
7172
7173
7174
7175
7176
7177
7178
7179
7180
7181
7182
7183
7184
7185
7186
7187
7188
7189
7190
7191
7192
7193
7194
7195
7196
7197
7198
7199
7200
7201
7202
7203
7204
7205
7206
7207
7208
7209
7210
7211
7212
7213
7214
7215
7216
7217
7218
7219
7220
7221
7222
7223
7224
7225
7226
7227
7228
7229
7230
7231
7232
7233
7234
7235
7236
7237
7238
7239
7240
7241
7242
7243
7244
7245
7246
7247
7248
7249
7250
7251
7252
7253
7254
7255
7256
7257
7258
7259
7260
7261
7262
7263
7264
7265
7266
7267
7268
7269
7270
7271
7272
7273
7274
7275
7276
7277
7278
7279
7280
7281
7282
7283
7284
7285
7286
7287
7288
7289
7290
7291
7292
7293
7294
7295
7296
7297
7298
7299
7300
7301
7302
7303
7304
7305
7306
7307
7308
7309
7310
7311
7312
7313
7314
7315
7316
7317
7318
7319
7320
7321
7322
7323
7324
7325
7326
7327
7328
7329
7330
7331
7332
7333
7334
7335
7336
7337
7338
7339
7340
7341
7342
7343
7344
7345
7346
7347
7348
7349
7350
7351
7352
7353
7354
7355
7356
7357
7358
7359
7360
7361
7362
7363
7364
7365
7366
7367
7368
7369
7370
7371
7372
7373
7374
7375
7376
7377
7378
7379
7380
7381
7382
7383
7384
7385
7386
7387
7388
7389
7390
7391
7392
7393
7394
7395
7396
7397
7398
7399
7400
7401
7402
7403
7404
7405
7406
7407
7408
7409
7410
7411
7412
7413
7414
7415
7416
7417
7418
7419
7420
7421
7422
7423
7424
7425
7426
7427
7428
7429
7430
7431
7432
7433
7434
7435
7436
7437
7438
7439
7440
7441
7442
7443
7444
7445
7446
7447
7448
7449
7450
7451
7452
7453
7454
7455
7456
7457
7458
7459
7460
7461
7462
7463
7464
7465
7466
7467
7468
7469
7470
7471
7472
7473
7474
7475
7476
7477
7478
7479
7480
7481
7482
7483
7484
7485
7486
7487
7488
7489
7490
7491
7492
7493
7494
7495
7496
7497
7498
7499
7500
7501
7502
7503
7504
7505
7506
7507
7508
7509
7510
7511
7512
7513
7514
7515
7516
7517
7518
7519
7520
7521
7522
7523
7524
7525
7526
7527
7528
7529
7530
7531
7532
7533
7534
7535
7536
7537
7538
7539
7540
7541
7542
7543
7544
7545
7546
7547
7548
7549
7550
7551
7552
7553
7554
7555
7556
7557
7558
7559
7560
7561
7562
7563
7564
7565
7566
7567
7568
7569
7570
7571
7572
7573
7574
7575
7576
7577
7578
7579
7580
7581
7582
7583
7584
7585
7586
7587
7588
7589
7590
7591
7592
7593
7594
7595
7596
7597
7598
7599
7600
7601
7602
7603
7604
7605
7606
7607
7608
7609
7610
7611
7612
7613
7614
7615
7616
7617
7618
7619
7620
7621
7622
7623
7624
7625
7626
7627
7628
7629
7630
7631
7632
7633
7634
7635
7636
7637
7638
7639
7640
7641
7642
7643
7644
7645
7646
7647
7648
7649
7650
7651
7652
7653
7654
7655
7656
7657
7658
7659
7660
7661
7662
7663
7664
7665
7666
7667
7668
7669
7670
7671
7672
7673
7674
7675
7676
7677
7678
7679
7680
7681
7682
7683
7684
7685
7686
7687
7688
7689
7690
7691
7692
7693
7694
7695
7696
7697
7698
7699
7700
7701
7702
7703
7704
7705
7706
7707
7708
7709
7710
7711
7712
7713
7714
7715
7716
7717
7718
7719
7720
7721
7722
7723
7724
7725
7726
7727
7728
7729
7730
7731
7732
7733
7734
7735
7736
7737
7738
7739
7740
7741
7742
7743
7744
7745
7746
7747
7748
7749
7750
7751
7752
7753
7754
7755
7756
7757
7758
7759
7760
7761
7762
7763
7764
7765
7766
7767
7768
7769
7770
7771
7772
7773
7774
7775
7776
7777
7778
7779
7780
7781
7782
7783
7784
7785
7786
7787
7788
7789
7790
7791
7792
7793
7794
7795
7796
7797
7798
7799
7800
7801
7802
7803
7804
7805
7806
7807
7808
7809
7810
7811
7812
7813
7814
7815
7816
7817
7818
7819
7820
7821
7822
7823
7824
7825
7826
7827
7828
7829
7830
7831
7832
7833
7834
7835
7836
7837
7838
7839
7840
7841
7842
7843
7844
7845
7846
7847
7848
7849
7850
7851
7852
7853
7854
7855
7856
7857
7858
7859
7860
7861
7862
7863
7864
7865
7866
7867
7868
7869
7870
7871
7872
7873
7874
7875
7876
7877
7878
7879
7880
7881
7882
7883
7884
7885
7886
7887
7888
7889
7890
7891
7892
7893
7894
7895
7896
7897
7898
7899
7900
7901
7902
7903
7904
7905
7906
7907
7908
7909
7910
7911
7912
7913
7914
7915
7916
7917
7918
7919
7920
7921
7922
7923
7924
7925
7926
7927
7928
7929
7930
7931
7932
7933
7934
7935
7936
7937
7938
7939
7940
7941
7942
7943
7944
7945
7946
7947
7948
7949
7950
7951
7952
7953
7954
7955
7956
7957
7958
7959
7960
7961
7962
7963
7964
7965
7966
7967
7968
7969
7970
7971
7972
7973
7974
7975
7976
7977
7978
7979
7980
7981
7982
7983
7984
7985
7986
7987
7988
7989
7990
7991
7992
7993
7994
7995
7996
7997
7998
7999
8000
8001
8002
8003
8004
8005
8006
8007
8008
8009
8010
8011
8012
8013
8014
8015
8016
8017
8018
8019
8020
8021
8022
8023
8024
8025
8026
8027
8028
8029
8030
8031
8032
8033
8034
8035
8036
8037
8038
8039
8040
8041
8042
8043
8044
8045
8046
8047
8048
8049
8050
8051
8052
8053
8054
8055
8056
8057
8058
8059
8060
8061
8062
8063
8064
8065
8066
8067
8068
8069
8070
8071
8072
8073
8074
8075
8076
8077
8078
8079
8080
8081
8082
8083
8084
8085
8086
8087
8088
8089
8090
8091
8092
8093
8094
8095
8096
8097
8098
8099
8100
8101
8102
8103
8104
8105
8106
8107
8108
8109
8110
8111
8112
8113
8114
8115
8116
8117
8118
8119
8120
8121
8122
8123
8124
8125
8126
8127
8128
8129
8130
8131
8132
8133
8134
8135
8136
8137
8138
8139
8140
8141
8142
8143
8144
8145
8146
8147
8148
8149
8150
8151
8152
8153
8154
8155
8156
8157
8158
8159
8160
8161
8162
8163
8164
8165
8166
8167
8168
8169
8170
8171
8172
8173
8174
8175
8176
8177
8178
8179
8180
8181
8182
8183
8184
8185
8186
8187
8188
8189
8190
8191
8192
8193
8194
8195
8196
8197
8198
8199
8200
8201
8202
8203
8204
8205
8206
8207
8208
8209
8210
8211
8212
8213
8214
8215
8216
8217
8218
8219
8220
8221
8222
8223
8224
8225
8226
8227
8228
8229
8230
8231
8232
8233
8234
8235
8236
8237
8238
8239
8240
8241
8242
8243
8244
8245
8246
8247
8248
8249
8250
8251
8252
8253
8254
8255
8256
8257
8258
8259
8260
8261
8262
8263
8264
8265
8266
8267
8268
8269
8270
8271
8272
8273
8274
8275
8276
8277
8278
8279
8280
8281
8282
8283
8284
8285
8286
8287
8288
8289
8290
8291
8292
8293
8294
8295
8296
8297
8298
8299
8300
8301
8302
8303
8304
8305
8306
8307
8308
8309
8310
8311
8312
8313
8314
8315
8316
8317
8318
8319
8320
8321
8322
8323
8324
8325
8326
8327
8328
8329
8330
8331
8332
8333
8334
8335
8336
8337
8338
8339
8340
8341
8342
8343
8344
8345
8346
8347
8348
8349
8350
8351
8352
8353
8354
8355
8356
8357
8358
8359
8360
8361
8362
8363
8364
8365
8366
8367
8368
8369
8370
8371
8372
8373
8374
8375
8376
8377
8378
8379
8380
8381
8382
8383
8384
8385
8386
8387
8388
8389
8390
8391
8392
8393
8394
8395
8396
8397
8398
8399
8400
8401
8402
8403
8404
8405
8406
8407
8408
8409
8410
8411
8412
8413
8414
8415
8416
8417
8418
8419
8420
8421
8422
8423
8424
8425
8426
8427
8428
8429
8430
8431
8432
8433
8434
8435
8436
8437
8438
8439
8440
8441
8442
8443
8444
8445
8446
8447
8448
8449
8450
8451
8452
8453
8454
8455
8456
8457
8458
8459
8460
8461
8462
8463
8464
8465
8466
8467
8468
8469
8470
8471
8472
8473
8474
8475
8476
8477
8478
8479
8480
8481
8482
8483
8484
8485
8486
8487
8488
8489
8490
8491
8492
8493
8494
8495
8496
8497
8498
8499
8500
8501
8502
8503
8504
8505
8506
8507
8508
8509
8510
8511
8512
8513
8514
8515
8516
8517
8518
8519
8520
8521
8522
8523
8524
8525
8526
8527
8528
8529
8530
8531
8532
8533
8534
8535
8536
8537
8538
8539
8540
8541
8542
8543
8544
8545
8546
8547
8548
8549
8550
8551
8552
8553
8554
8555
8556
8557
8558
8559
8560
8561
8562
8563
8564
8565
8566
8567
8568
8569
8570
8571
8572
8573
8574
8575
8576
8577
8578
8579
8580
8581
8582
8583
8584
8585
8586
8587
8588
8589
8590
8591
8592
8593
8594
8595
8596
8597
8598
8599
8600
8601
8602
8603
8604
8605
8606
8607
8608
8609
8610
8611
8612
8613
8614
8615
8616
8617
8618
8619
8620
8621
8622
8623
8624
8625
8626
8627
8628
8629
8630
8631
8632
8633
8634
8635
8636
8637
8638
8639
8640
8641
8642
8643
8644
8645
8646
8647
8648
8649
8650
8651
8652
8653
8654
8655
8656
8657
8658
8659
8660
8661
8662
8663
8664
8665
8666
8667
8668
8669
8670
8671
8672
8673
8674
8675
8676
8677
8678
8679
8680
8681
8682
8683
8684
8685
8686
8687
8688
8689
8690
8691
8692
8693
8694
8695
8696
8697
8698
8699
8700
8701
8702
8703
8704
8705
8706
8707
8708
8709
8710
8711
8712
8713
8714
8715
8716
8717
8718
8719
8720
8721
8722
8723
8724
8725
8726
8727
8728
8729
8730
8731
8732
8733
8734
8735
8736
8737
8738
8739
8740
8741
8742
8743
8744
8745
8746
8747
8748
8749
8750
8751
8752
8753
8754
8755
8756
8757
8758
8759
8760
8761
8762
8763
8764
8765
8766
8767
8768
8769
8770
8771
8772
8773
8774
8775
8776
8777
8778
8779
8780
8781
8782
8783
8784
8785
8786
8787
8788
8789
8790
8791
8792
8793
8794
8795
8796
8797
8798
8799
8800
8801
8802
8803
8804
8805
8806
8807
8808
8809
8810
8811
8812
8813
8814
8815
8816
8817
8818
8819
8820
8821
8822
8823
8824
8825
8826
8827
8828
8829
8830
8831
8832
8833
8834
8835
8836
8837
8838
8839
8840
8841
8842
8843
8844
8845
8846
8847
8848
8849
8850
8851
8852
8853
8854
8855
8856
8857
8858
8859
8860
8861
8862
8863
8864
8865
8866
8867
8868
8869
8870
8871
8872
8873
8874
8875
8876
8877
8878
8879
8880
8881
8882
8883
8884
8885
8886
8887
8888
8889
8890
8891
8892
8893
8894
8895
8896
8897
8898
8899
8900
8901
8902
8903
8904
8905
8906
8907
8908
8909
8910
8911
8912
8913
8914
8915
8916
8917
8918
8919
8920
8921
8922
8923
8924
8925
8926
8927
8928
8929
8930
8931
8932
8933
8934
8935
8936
8937
8938
8939
8940
8941
8942
8943
8944
8945
8946
8947
8948
8949
8950
8951
8952
8953
8954
8955
8956
8957
8958
8959
8960
8961
8962
8963
8964
8965
8966
8967
8968
8969
8970
8971
8972
8973
8974
8975
8976
8977
8978
8979
8980
8981
8982
8983
8984
8985
8986
8987
8988
8989
8990
8991
8992
8993
8994
8995
8996
8997
8998
8999
9000
9001
9002
9003
9004
9005
9006
9007
9008
9009
9010
9011
9012
9013
9014
9015
9016
9017
9018
9019
9020
9021
9022
9023
9024
9025
9026
9027
9028
9029
9030
9031
9032
9033
9034
9035
9036
9037
9038
9039
9040
9041
9042
9043
9044
9045
9046
9047
9048
9049
9050
9051
9052
9053
9054
9055
9056
9057
9058
9059
9060
9061
9062
9063
9064
9065
9066
9067
9068
9069
9070
9071
9072
9073
9074
9075
9076
9077
9078
9079
9080
9081
9082
9083
9084
9085
9086
9087
9088
9089
9090
9091
9092
9093
9094
9095
9096
9097
9098
9099
9100
9101
9102
9103
9104
9105
9106
9107
9108
9109
9110
9111
9112
9113
9114
9115
9116
9117
9118
9119
9120
9121
9122
9123
9124
9125
9126
9127
9128
9129
9130
9131
9132
9133
9134
9135
9136
9137
9138
9139
9140
9141
9142
9143
9144
9145
9146
9147
9148
9149
9150
9151
9152
9153
9154
9155
9156
9157
9158
9159
9160
9161
9162
9163
9164
9165
9166
9167
9168
9169
9170
9171
9172
9173
9174
9175
9176
9177
9178
9179
9180
9181
9182
9183
9184
9185
9186
9187
9188
9189
9190
9191
9192
9193
9194
9195
9196
9197
9198
9199
9200
9201
9202
9203
9204
9205
9206
9207
9208
9209
9210
9211
9212
9213
9214
9215
9216
9217
9218
9219
9220
9221
9222
9223
9224
9225
9226
9227
9228
9229
9230
9231
9232
9233
9234
9235
9236
9237
9238
9239
9240
9241
9242
9243
9244
9245
9246
9247
9248
9249
9250
9251
9252
9253
9254
9255
9256
9257
9258
9259
9260
9261
9262
9263
9264
9265
9266
9267
9268
9269
9270
9271
9272
9273
9274
9275
9276
9277
9278
9279
9280
9281
9282
9283
9284
9285
9286
9287
9288
9289
9290
9291
9292
9293
9294
9295
9296
9297
9298
9299
9300
9301
9302
9303
9304
9305
9306
9307
9308
9309
9310
9311
9312
9313
9314
9315
9316
9317
9318
9319
9320
9321
9322
9323
9324
9325
9326
9327
9328
9329
9330
9331
9332
9333
9334
9335
9336
9337
9338
9339
9340
9341
9342
9343
9344
9345
9346
9347
9348
9349
9350
9351
9352
9353
9354
9355
9356
9357
9358
9359
9360
9361
9362
9363
9364
9365
9366
9367
9368
9369
9370
9371
9372
9373
9374
9375
9376
9377
9378
9379
9380
9381
9382
9383
9384
9385
9386
9387
9388
9389
9390
9391
9392
9393
9394
9395
9396
9397
9398
9399
9400
9401
9402
9403
9404
9405
9406
9407
9408
9409
9410
9411
9412
9413
9414
9415
9416
9417
9418
9419
9420
9421
9422
9423
9424
9425
9426
9427
9428
9429
9430
9431
9432
9433
9434
9435
9436
9437
9438
9439
9440
9441
9442
9443
9444
9445
9446
9447
9448
9449
9450
9451
9452
9453
9454
9455
9456
9457
9458
9459
9460
9461
9462
9463
9464
9465
9466
9467
9468
9469
9470
9471
9472
9473
9474
9475
9476
9477
9478
9479
9480
9481
9482
9483
9484
9485
9486
9487
9488
9489
9490
9491
9492
9493
9494
9495
9496
9497
9498
9499
9500
9501
9502
9503
9504
9505
9506
9507
9508
9509
9510
9511
9512
9513
9514
9515
9516
9517
9518
9519
9520
9521
9522
9523
9524
9525
9526
9527
9528
9529
9530
9531
9532
9533
9534
9535
9536
9537
9538
9539
9540
9541
9542
9543
9544
9545
9546
9547
9548
9549
9550
9551
9552
9553
9554
9555
9556
9557
9558
9559
9560
9561
9562
9563
9564
9565
9566
9567
9568
9569
9570
9571
9572
9573
9574
9575
9576
9577
9578
9579
9580
9581
9582
9583
9584
9585
9586
9587
9588
9589
9590
9591
9592
9593
9594
9595
9596
9597
9598
9599
9600
9601
9602
9603
9604
9605
9606
9607
9608
9609
9610
9611
9612
9613
9614
9615
9616
9617
9618
9619
9620
9621
9622
9623
9624
9625
9626
9627
9628
9629
9630
9631
9632
9633
9634
9635
9636
9637
9638
9639
9640
9641
9642
9643
9644
9645
9646
9647
9648
9649
9650
9651
9652
9653
9654
9655
9656
9657
9658
9659
9660
9661
9662
9663
9664
9665
9666
9667
9668
9669
9670
9671
9672
9673
9674
9675
9676
9677
9678
9679
9680
9681
9682
9683
9684
9685
9686
9687
9688
9689
9690
9691
9692
9693
9694
9695
9696
9697
9698
9699
9700
9701
9702
9703
9704
9705
9706
9707
9708
9709
9710
9711
9712
9713
9714
9715
9716
9717
9718
9719
9720
9721
9722
9723
9724
9725
9726
9727
9728
9729
9730
9731
9732
9733
9734
9735
9736
9737
9738
9739
9740
9741
9742
9743
9744
9745
9746
9747
9748
9749
9750
9751
9752
9753
9754
9755
9756
9757
9758
9759
9760
9761
9762
9763
9764
9765
9766
9767
9768
9769
9770
9771
9772
9773
9774
9775
9776
9777
9778
9779
9780
9781
9782
9783
9784
9785
9786
9787
9788
9789
9790
9791
9792
9793
9794
9795
9796
9797
9798
9799
9800
9801
9802
9803
9804
9805
9806
9807
9808
9809
9810
9811
9812
9813
9814
9815
9816
9817
9818
9819
9820
9821
9822
9823
9824
9825
9826
9827
9828
9829
9830
9831
9832
9833
9834
9835
9836
9837
9838
9839
9840
9841
9842
9843
9844
9845
9846
9847
9848
9849
9850
9851
9852
9853
9854
9855
9856
9857
9858
9859
9860
9861
9862
9863
9864
9865
9866
9867
9868
9869
9870
9871
9872
9873
9874
9875
9876
9877
9878
9879
9880
9881
9882
9883
9884
9885
9886
9887
9888
9889
9890
9891
9892
9893
9894
9895
9896
9897
9898
9899
9900
9901
9902
9903
9904
9905
9906
9907
9908
9909
9910
9911
9912
9913
9914
9915
9916
9917
9918
9919
9920
9921
9922
9923
9924
9925
9926
9927
9928
9929
9930
9931
9932
9933
9934
9935
9936
9937
9938
9939
9940
9941
9942
9943
9944
9945
9946
9947
9948
9949
9950
9951
9952
9953
9954
9955
9956
9957
9958
9959
9960
9961
9962
9963
9964
9965
9966
9967
9968
9969
9970
9971
9972
9973
9974
9975
9976
9977
9978
9979
9980
9981
9982
9983
9984
9985
9986
9987
9988
9989
9990
9991
9992
9993
9994
9995
9996
9997
9998
9999
10000
10001
10002
10003
10004
10005
10006
10007
10008
10009
10010
10011
10012
10013
10014
10015
10016
10017
10018
10019
10020
10021
10022
10023
10024
10025
10026
10027
10028
10029
10030
10031
10032
10033
10034
10035
10036
10037
10038
10039
10040
10041
10042
10043
10044
10045
10046
10047
10048
10049
10050
10051
10052
10053
10054
10055
10056
10057
10058
10059
10060
10061
10062
10063
10064
10065
10066
10067
10068
10069
10070
10071
10072
10073
10074
10075
10076
10077
10078
10079
10080
10081
10082
10083
10084
10085
10086
10087
10088
10089
10090
10091
10092
10093
10094
10095
10096
10097
10098
10099
10100
10101
10102
10103
10104
10105
10106
10107
10108
10109
10110
10111
10112
10113
10114
10115
10116
10117
10118
10119
10120
10121
10122
10123
10124
10125
10126
10127
10128
10129
10130
10131
10132
10133
10134
10135
10136
10137
10138
10139
10140
10141
10142
10143
10144
10145
10146
10147
10148
10149
10150
10151
10152
10153
10154
10155
10156
10157
10158
10159
10160
10161
10162
10163
10164
10165
10166
10167
10168
10169
10170
10171
10172
10173
10174
10175
10176
10177
10178
10179
10180
10181
10182
10183
10184
10185
10186
10187
10188
10189
10190
10191
10192
10193
10194
10195
10196
10197
10198
10199
10200
10201
10202
10203
10204
10205
10206
10207
10208
10209
10210
10211
10212
10213
10214
10215
10216
10217
10218
10219
10220
10221
10222
10223
10224
10225
10226
10227
10228
10229
10230
10231
10232
10233
10234
10235
10236
10237
10238
10239
10240
10241
10242
10243
10244
10245
10246
10247
10248
10249
10250
10251
10252
10253
10254
10255
10256
10257
10258
10259
10260
10261
10262
10263
10264
10265
10266
10267
10268
10269
10270
10271
10272
10273
10274
10275
10276
10277
10278
10279
10280
10281
10282
10283
10284
10285
10286
10287
10288
10289
10290
10291
10292
10293
10294
10295
10296
10297
10298
10299
10300
10301
10302
10303
10304
10305
10306
10307
10308
10309
10310
10311
10312
10313
10314
10315
10316
10317
10318
10319
10320
10321
10322
10323
10324
10325
10326
10327
10328
10329
10330
10331
10332
10333
10334
10335
10336
10337
10338
10339
10340
10341
10342
10343
10344
10345
10346
10347
10348
10349
10350
10351
10352
10353
10354
10355
10356
10357
10358
10359
10360
10361
10362
10363
10364
10365
10366
10367
10368
10369
10370
10371
10372
10373
10374
10375
10376
10377
10378
10379
10380
10381
10382
10383
10384
10385
10386
10387
10388
10389
10390
10391
10392
10393
10394
10395
10396
10397
10398
10399
10400
10401
10402
10403
10404
10405
10406
10407
10408
10409
10410
10411
10412
10413
10414
10415
10416
10417
10418
10419
10420
10421
10422
10423
10424
10425
10426
10427
10428
10429
10430
10431
10432
10433
10434
10435
10436
10437
10438
10439
10440
10441
10442
10443
10444
10445
10446
10447
10448
10449
10450
10451
10452
10453
10454
10455
10456
10457
10458
10459
10460
10461
10462
10463
10464
10465
10466
10467
10468
10469
10470
10471
10472
10473
10474
10475
10476
10477
10478
10479
10480
10481
10482
10483
10484
10485
10486
10487
10488
10489
10490
10491
10492
10493
10494
10495
10496
10497
10498
10499
10500
10501
10502
10503
10504
10505
10506
10507
10508
10509
10510
10511
10512
10513
10514
10515
10516
10517
10518
10519
10520
10521
10522
10523
10524
10525
10526
10527
10528
10529
10530
10531
10532
10533
10534
10535
10536
10537
10538
10539
10540
10541
10542
10543
10544
10545
10546
10547
10548
10549
10550
10551
10552
10553
10554
10555
10556
10557
10558
10559
10560
10561
10562
10563
10564
10565
10566
10567
10568
10569
10570
10571
10572
10573
10574
10575
10576
10577
10578
10579
10580
10581
10582
10583
10584
10585
10586
10587
10588
10589
10590
10591
10592
10593
10594
10595
10596
10597
10598
10599
10600
10601
10602
10603
10604
10605
10606
10607
10608
10609
10610
10611
10612
10613
10614
10615
10616
10617
10618
10619
10620
10621
10622
10623
10624
10625
10626
10627
10628
10629
10630
10631
10632
10633
10634
10635
10636
10637
10638
10639
10640
10641
10642
10643
10644
10645
10646
10647
10648
10649
10650
10651
10652
10653
10654
10655
10656
10657
10658
10659
10660
10661
10662
10663
10664
10665
10666
10667
10668
10669
10670
10671
10672
10673
10674
10675
10676
10677
10678
10679
10680
10681
10682
10683
10684
10685
10686
10687
10688
10689
10690
10691
10692
10693
10694
10695
10696
10697
10698
10699
10700
10701
10702
10703
10704
10705
10706
10707
10708
10709
10710
10711
10712
10713
10714
10715
10716
10717
10718
10719
10720
10721
10722
10723
10724
10725
10726
10727
10728
10729
10730
10731
10732
10733
10734
10735
10736
10737
10738
10739
10740
10741
10742
10743
10744
10745
10746
10747
10748
10749
10750
10751
10752
10753
10754
10755
10756
10757
10758
10759
10760
10761
10762
10763
10764
10765
10766
10767
10768
10769
10770
10771
10772
10773
10774
10775
10776
10777
10778
10779
10780
10781
10782
10783
10784
10785
10786
10787
10788
10789
10790
10791
10792
10793
10794
10795
10796
10797
10798
10799
10800
10801
10802
10803
10804
10805
10806
10807
10808
10809
10810
10811
10812
10813
10814
10815
10816
10817
10818
10819
10820
10821
10822
10823
10824
10825
10826
10827
10828
10829
10830
10831
10832
10833
10834
10835
10836
10837
10838
10839
10840
10841
10842
10843
10844
10845
10846
10847
10848
10849
10850
10851
10852
10853
10854
10855
10856
10857
10858
10859
10860
10861
10862
10863
10864
10865
10866
10867
10868
10869
10870
10871
10872
10873
10874
10875
10876
10877
10878
10879
10880
10881
10882
10883
10884
10885
10886
10887
10888
10889
10890
10891
10892
10893
10894
10895
10896
10897
10898
10899
10900
10901
10902
10903
10904
10905
10906
10907
10908
10909
10910
10911
10912
10913
10914
10915
10916
10917
10918
10919
10920
10921
10922
10923
10924
10925
10926
10927
10928
10929
10930
10931
10932
10933
10934
10935
10936
10937
10938
10939
10940
10941
10942
10943
10944
10945
10946
10947
10948
10949
10950
10951
10952
10953
10954
10955
10956
10957
10958
10959
10960
10961
10962
10963
10964
10965
10966
10967
10968
10969
10970
10971
10972
10973
10974
10975
10976
10977
10978
10979
10980
10981
10982
10983
10984
10985
10986
10987
10988
10989
10990
10991
10992
10993
10994
10995
10996
10997
10998
10999
11000
11001
11002
11003
11004
11005
11006
11007
11008
11009
11010
11011
11012
11013
11014
11015
11016
11017
11018
11019
11020
11021
11022
11023
11024
11025
11026
11027
11028
11029
11030
11031
11032
11033
11034
11035
11036
11037
11038
11039
11040
11041
11042
11043
11044
11045
11046
11047
11048
11049
11050
11051
11052
11053
11054
11055
11056
11057
11058
11059
11060
11061
11062
11063
11064
11065
11066
11067
11068
11069
11070
11071
11072
11073
11074
11075
11076
11077
11078
11079
11080
11081
11082
11083
11084
11085
11086
11087
11088
11089
11090
11091
11092
11093
11094
11095
11096
11097
11098
11099
11100
11101
11102
11103
11104
11105
11106
11107
11108
11109
11110
11111
11112
11113
11114
11115
11116
11117
11118
11119
11120
11121
11122
11123
11124
11125
11126
11127
11128
11129
11130
11131
11132
11133
11134
11135
11136
11137
11138
11139
11140
11141
11142
11143
11144
11145
11146
11147
11148
11149
11150
11151
11152
11153
11154
11155
11156
11157
11158
11159
11160
11161
11162
11163
11164
11165
11166
11167
11168
11169
11170
11171
11172
11173
11174
11175
11176
11177
11178
11179
11180
11181
11182
11183
11184
11185
11186
11187
11188
11189
11190
11191
11192
11193
11194
11195
11196
11197
11198
11199
11200
11201
11202
11203
11204
11205
11206
11207
11208
11209
11210
11211
11212
11213
11214
11215
11216
11217
11218
11219
11220
11221
11222
11223
11224
11225
11226
11227
11228
11229
11230
11231
11232
11233
11234
11235
11236
11237
11238
11239
11240
11241
11242
11243
11244
11245
11246
11247
11248
11249
11250
11251
11252
11253
11254
11255
11256
11257
11258
11259
11260
11261
11262
11263
11264
11265
11266
11267
11268
11269
11270
11271
11272
11273
11274
11275
11276
11277
11278
11279
11280
11281
11282
11283
11284
11285
11286
11287
11288
11289
11290
11291
11292
11293
11294
11295
11296
11297
11298
11299
11300
11301
11302
11303
11304
11305
11306
11307
11308
11309
11310
11311
11312
11313
11314
11315
11316
11317
11318
11319
11320
11321
11322
11323
11324
11325
11326
11327
11328
11329
11330
11331
11332
11333
11334
11335
11336
11337
11338
11339
11340
11341
11342
11343
11344
11345
11346
11347
11348
11349
11350
11351
11352
11353
11354
11355
11356
11357
11358
11359
11360
11361
11362
11363
11364
11365
11366
11367
11368
11369
11370
11371
11372
11373
11374
11375
11376
11377
11378
11379
11380
11381
11382
11383
11384
11385
11386
11387
11388
11389
11390
11391
11392
11393
11394
11395
11396
11397
11398
11399
11400
11401
11402
11403
11404
11405
11406
11407
11408
11409
11410
11411
11412
11413
11414
11415
11416
11417
11418
11419
11420
11421
11422
11423
11424
11425
11426
11427
11428
11429
11430
11431
11432
11433
11434
11435
11436
11437
11438
11439
11440
11441
11442
11443
11444
11445
11446
11447
11448
11449
11450
11451
11452
11453
11454
11455
11456
11457
11458
11459
11460
11461
11462
11463
11464
11465
11466
11467
11468
11469
11470
11471
11472
11473
11474
11475
11476
11477
11478
11479
11480
11481
11482
11483
11484
11485
11486
11487
11488
11489
11490
11491
11492
11493
11494
11495
11496
11497
11498
11499
11500
11501
11502
11503
11504
11505
11506
11507
11508
11509
11510
11511
11512
11513
11514
11515
11516
11517
11518
11519
11520
11521
11522
11523
11524
11525
11526
11527
11528
11529
11530
11531
11532
11533
11534
11535
11536
11537
11538
11539
11540
11541
11542
11543
11544
11545
11546
11547
11548
11549
11550
11551
11552
11553
11554
11555
11556
11557
11558
11559
11560
11561
11562
11563
11564
11565
11566
11567
11568
11569
11570
11571
11572
11573
11574
11575
11576
11577
11578
11579
11580
11581
11582
11583
11584
11585
11586
11587
11588
11589
11590
11591
11592
11593
11594
11595
11596
11597
11598
11599
11600
11601
11602
11603
11604
11605
11606
11607
11608
11609
11610
11611
11612
11613
11614
11615
11616
11617
11618
11619
11620
11621
11622
11623
11624
11625
11626
11627
11628
11629
11630
11631
11632
11633
11634
11635
11636
11637
11638
11639
11640
11641
11642
11643
11644
11645
11646
11647
11648
11649
11650
11651
11652
11653
11654
11655
11656
11657
11658
11659
11660
11661
11662
11663
11664
11665
11666
11667
11668
11669
11670
11671
11672
11673
11674
11675
11676
11677
11678
11679
11680
11681
11682
11683
11684
11685
11686
11687
11688
11689
11690
11691
11692
11693
11694
11695
11696
11697
11698
11699
11700
11701
11702
11703
11704
11705
11706
11707
11708
11709
11710
11711
11712
11713
11714
11715
11716
11717
11718
11719
11720
11721
11722
11723
11724
11725
11726
11727
11728
11729
11730
11731
11732
11733
11734
11735
11736
11737
11738
11739
11740
11741
11742
11743
11744
11745
11746
11747
11748
11749
11750
11751
11752
11753
11754
11755
11756
11757
11758
11759
11760
11761
11762
11763
11764
11765
11766
11767
11768
11769
11770
11771
11772
11773
11774
11775
11776
11777
11778
11779
11780
11781
11782
11783
11784
11785
11786
11787
11788
11789
11790
11791
11792
11793
11794
11795
11796
11797
11798
11799
11800
11801
11802
11803
11804
11805
11806
11807
11808
11809
11810
11811
11812
11813
11814
11815
11816
11817
11818
11819
11820
11821
11822
11823
11824
11825
11826
11827
11828
11829
11830
11831
11832
11833
11834
11835
11836
11837
11838
11839
11840
11841
11842
11843
11844
11845
11846
11847
11848
11849
11850
11851
11852
11853
11854
11855
11856
11857
11858
11859
11860
11861
11862
11863
11864
11865
11866
11867
11868
11869
11870
11871
11872
11873
11874
11875
11876
11877
11878
11879
11880
11881
11882
11883
11884
11885
11886
11887
11888
11889
11890
11891
11892
11893
11894
11895
11896
11897
11898
11899
11900
11901
11902
11903
11904
11905
11906
11907
11908
11909
11910
11911
11912
11913
11914
11915
11916
11917
11918
11919
11920
11921
11922
11923
11924
11925
11926
11927
11928
11929
11930
11931
11932
11933
11934
11935
11936
11937
11938
11939
11940
11941
11942
11943
11944
11945
11946
11947
11948
11949
11950
11951
11952
11953
11954
11955
11956
11957
11958
11959
11960
11961
11962
11963
11964
11965
11966
11967
11968
11969
11970
11971
11972
11973
11974
11975
11976
11977
11978
11979
11980
11981
11982
11983
11984
11985
11986
11987
11988
11989
11990
11991
11992
11993
11994
11995
11996
11997
11998
11999
12000
12001
12002
12003
12004
12005
12006
12007
12008
12009
12010
12011
12012
12013
12014
12015
12016
12017
12018
12019
12020
12021
12022
12023
12024
12025
12026
12027
12028
12029
12030
12031
12032
12033
12034
12035
12036
12037
12038
12039
12040
12041
12042
12043
12044
12045
12046
12047
12048
12049
12050
12051
12052
12053
12054
12055
12056
12057
12058
12059
12060
12061
12062
12063
12064
12065
12066
12067
12068
12069
12070
12071
12072
12073
12074
12075
12076
12077
12078
12079
12080
12081
12082
12083
12084
12085
12086
12087
12088
12089
12090
12091
12092
12093
12094
12095
12096
12097
12098
12099
12100
12101
12102
12103
12104
12105
12106
12107
12108
12109
12110
12111
12112
12113
12114
12115
12116
12117
12118
12119
12120
12121
12122
12123
12124
12125
12126
12127
12128
12129
12130
12131
12132
12133
12134
12135
12136
12137
12138
12139
12140
12141
12142
12143
12144
12145
12146
12147
12148
12149
12150
12151
12152
12153
12154
12155
12156
12157
12158
12159
12160
12161
12162
12163
12164
12165
12166
12167
12168
12169
12170
12171
12172
12173
12174
12175
12176
12177
12178
12179
12180
12181
12182
12183
12184
12185
12186
12187
12188
12189
12190
12191
12192
12193
12194
12195
12196
12197
12198
12199
12200
12201
12202
12203
12204
12205
12206
12207
12208
12209
12210
12211
12212
12213
12214
12215
12216
12217
12218
12219
12220
12221
12222
12223
12224
12225
12226
12227
12228
12229
12230
12231
12232
12233
12234
12235
12236
12237
12238
12239
12240
12241
12242
12243
12244
12245
12246
12247
12248
12249
12250
12251
12252
12253
12254
12255
12256
12257
12258
12259
12260
12261
12262
12263
12264
12265
12266
12267
12268
12269
12270
12271
12272
12273
12274
12275
12276
12277
12278
12279
12280
12281
12282
12283
12284
12285
12286
12287
12288
12289
12290
12291
12292
12293
12294
12295
12296
12297
12298
12299
12300
12301
12302
12303
12304
12305
12306
12307
12308
12309
12310
12311
12312
12313
12314
12315
12316
12317
12318
12319
12320
12321
12322
12323
12324
12325
12326
12327
12328
12329
12330
12331
12332
12333
12334
12335
12336
12337
12338
12339
12340
12341
12342
12343
12344
12345
12346
12347
12348
12349
12350
12351
12352
12353
12354
12355
12356
12357
12358
12359
12360
12361
12362
12363
12364
12365
12366
12367
12368
12369
12370
12371
12372
12373
12374
12375
12376
12377
12378
12379
12380
12381
12382
12383
12384
12385
12386
12387
12388
12389
12390
12391
12392
12393
12394
12395
12396
12397
12398
12399
12400
12401
12402
12403
12404
12405
12406
12407
12408
12409
12410
12411
12412
12413
12414
12415
12416
12417
12418
12419
12420
12421
12422
12423
12424
12425
12426
12427
12428
12429
12430
12431
12432
12433
12434
12435
12436
12437
12438
12439
12440
12441
12442
12443
12444
12445
12446
12447
12448
12449
12450
12451
12452
12453
12454
12455
12456
12457
12458
12459
12460
12461
12462
12463
12464
12465
12466
12467
12468
12469
12470
12471
12472
12473
12474
12475
12476
12477
12478
12479
12480
12481
12482
12483
12484
12485
12486
12487
12488
12489
12490
12491
12492
12493
12494
12495
12496
12497
12498
12499
12500
12501
12502
12503
12504
12505
12506
12507
12508
12509
12510
12511
12512
12513
12514
12515
12516
12517
12518
12519
12520
12521
12522
12523
12524
12525
12526
12527
12528
12529
12530
12531
12532
12533
12534
12535
12536
12537
12538
12539
12540
12541
12542
12543
12544
12545
12546
12547
12548
12549
12550
12551
12552
12553
12554
12555
12556
12557
12558
12559
12560
12561
12562
12563
12564
12565
12566
12567
12568
12569
12570
12571
12572
12573
12574
12575
12576
12577
12578
12579
12580
12581
12582
12583
12584
12585
12586
12587
12588
12589
12590
12591
12592
12593
12594
12595
12596
12597
12598
12599
12600
12601
12602
12603
12604
12605
12606
12607
12608
12609
12610
12611
12612
12613
12614
12615
12616
12617
12618
12619
12620
12621
12622
12623
12624
12625
12626
12627
12628
12629
12630
12631
12632
12633
12634
12635
12636
12637
12638
12639
12640
12641
12642
12643
12644
12645
12646
12647
12648
12649
12650
12651
12652
12653
12654
12655
12656
12657
12658
12659
12660
12661
12662
12663
12664
12665
12666
12667
12668
12669
12670
12671
12672
12673
12674
12675
12676
12677
12678
12679
12680
12681
12682
12683
12684
12685
12686
12687
12688
12689
12690
12691
12692
12693
12694
12695
12696
12697
12698
12699
12700
12701
12702
12703
12704
12705
12706
12707
12708
12709
12710
12711
12712
12713
12714
12715
12716
12717
12718
12719
12720
12721
12722
12723
12724
12725
12726
12727
12728
12729
12730
12731
12732
12733
12734
12735
12736
12737
12738
12739
12740
12741
12742
12743
12744
12745
12746
12747
12748
12749
12750
12751
12752
12753
12754
12755
12756
12757
12758
12759
12760
12761
12762
12763
12764
12765
12766
12767
12768
12769
12770
12771
12772
12773
12774
12775
12776
12777
12778
12779
12780
12781
12782
12783
12784
12785
12786
12787
12788
12789
12790
12791
12792
12793
12794
12795
12796
12797
12798
12799
12800
12801
12802
12803
12804
12805
12806
12807
12808
12809
12810
12811
12812
12813
12814
12815
12816
12817
12818
12819
12820
12821
12822
12823
12824
12825
12826
12827
12828
12829
12830
12831
12832
12833
12834
12835
12836
12837
12838
12839
12840
12841
12842
12843
12844
12845
12846
12847
12848
12849
12850
12851
12852
12853
12854
12855
12856
12857
12858
12859
12860
12861
12862
12863
12864
12865
12866
12867
12868
12869
12870
12871
12872
12873
12874
12875
12876
12877
12878
12879
12880
12881
12882
12883
12884
12885
12886
12887
12888
12889
12890
12891
12892
12893
12894
12895
12896
12897
12898
12899
12900
12901
12902
12903
12904
12905
12906
12907
12908
12909
12910
12911
12912
12913
12914
12915
12916
12917
12918
12919
12920
12921
12922
12923
12924
12925
12926
12927
12928
12929
12930
12931
12932
12933
12934
12935
12936
12937
12938
12939
12940
12941
12942
12943
12944
12945
12946
12947
12948
12949
12950
12951
12952
12953
12954
12955
12956
12957
12958
12959
12960
12961
12962
12963
12964
12965
12966
12967
12968
12969
12970
12971
12972
12973
12974
12975
12976
12977
12978
12979
12980
12981
12982
12983
12984
12985
12986
12987
12988
12989
12990
12991
12992
12993
12994
12995
12996
12997
12998
12999
13000
13001
13002
13003
13004
13005
13006
13007
13008
13009
13010
13011
13012
13013
13014
13015
13016
13017
13018
13019
13020
13021
13022
13023
13024
13025
13026
13027
13028
13029
13030
13031
13032
13033
13034
13035
13036
13037
13038
13039
13040
13041
13042
13043
13044
13045
13046
13047
13048
13049
13050
13051
13052
13053
13054
13055
13056
13057
13058
13059
13060
13061
13062
13063
13064
13065
13066
13067
13068
13069
13070
13071
13072
13073
13074
13075
13076
13077
13078
13079
13080
13081
13082
13083
13084
13085
13086
13087
13088
13089
13090
13091
13092
13093
13094
13095
13096
13097
13098
13099
13100
13101
13102
13103
13104
13105
13106
13107
13108
13109
13110
13111
13112
13113
13114
13115
13116
13117
13118
13119
13120
13121
13122
13123
13124
13125
13126
13127
13128
13129
13130
13131
13132
13133
13134
13135
13136
13137
13138
13139
13140
13141
13142
13143
13144
13145
13146
13147
13148
13149
13150
13151
13152
13153
13154
13155
13156
13157
13158
13159
13160
13161
13162
13163
13164
13165
13166
13167
13168
13169
13170
13171
13172
13173
13174
13175
13176
13177
13178
13179
13180
13181
13182
13183
13184
13185
13186
13187
13188
13189
13190
13191
13192
13193
13194
13195
13196
13197
13198
13199
13200
13201
13202
13203
13204
13205
13206
13207
13208
13209
13210
13211
13212
13213
13214
13215
13216
13217
13218
13219
13220
13221
13222
13223
13224
13225
13226
13227
13228
13229
13230
13231
13232
13233
13234
13235
13236
13237
13238
13239
13240
13241
13242
13243
13244
13245
13246
13247
13248
13249
13250
13251
13252
13253
13254
13255
13256
13257
13258
13259
13260
13261
13262
13263
13264
13265
13266
13267
13268
13269
13270
13271
13272
13273
13274
13275
13276
13277
13278
13279
13280
13281
13282
13283
13284
13285
13286
13287
13288
13289
13290
13291
13292
13293
13294
13295
13296
13297
13298
13299
13300
13301
13302
13303
13304
13305
13306
13307
13308
13309
13310
13311
13312
13313
13314
13315
13316
13317
13318
13319
13320
13321
13322
13323
13324
13325
13326
13327
13328
13329
13330
13331
13332
13333
13334
13335
13336
13337
13338
13339
13340
13341
13342
13343
13344
13345
13346
13347
13348
13349
13350
13351
13352
13353
13354
13355
13356
13357
13358
13359
13360
13361
13362
13363
13364
13365
13366
13367
13368
13369
13370
13371
13372
13373
13374
13375
13376
13377
13378
13379
13380
13381
13382
13383
13384
13385
13386
13387
13388
13389
13390
13391
13392
13393
13394
13395
13396
13397
13398
13399
13400
13401
13402
13403
13404
13405
13406
13407
13408
13409
13410
13411
13412
13413
13414
13415
13416
13417
13418
13419
13420
13421
13422
13423
13424
13425
13426
13427
13428
13429
13430
13431
13432
13433
13434
13435
13436
13437
13438
13439
13440
13441
13442
13443
13444
13445
13446
13447
13448
13449
13450
13451
13452
13453
13454
13455
13456
13457
13458
13459
13460
13461
13462
13463
13464
13465
13466
13467
13468
13469
13470
13471
13472
13473
13474
13475
13476
13477
13478
13479
13480
13481
13482
13483
13484
13485
13486
13487
13488
13489
13490
13491
13492
13493
13494
13495
13496
13497
13498
13499
13500
13501
13502
13503
13504
13505
13506
13507
13508
13509
13510
13511
13512
13513
13514
13515
13516
13517
13518
13519
13520
13521
13522
13523
13524
13525
13526
13527
13528
13529
13530
13531
13532
13533
13534
13535
13536
13537
13538
13539
13540
13541
13542
13543
13544
13545
13546
13547
13548
13549
13550
13551
13552
13553
13554
13555
13556
13557
13558
13559
13560
13561
13562
13563
13564
13565
13566
13567
13568
13569
13570
13571
13572
13573
13574
13575
13576
13577
13578
13579
13580
13581
13582
13583
13584
13585
13586
13587
13588
13589
13590
13591
13592
13593
13594
13595
13596
13597
13598
13599
13600
13601
13602
13603
13604
13605
13606
13607
13608
13609
13610
13611
13612
13613
13614
13615
13616
13617
13618
13619
13620
13621
13622
13623
13624
13625
13626
13627
13628
13629
13630
13631
13632
13633
13634
13635
13636
13637
13638
13639
13640
13641
13642
13643
13644
13645
13646
13647
13648
13649
13650
13651
13652
13653
13654
13655
13656
13657
13658
13659
13660
13661
13662
13663
13664
13665
13666
13667
13668
13669
13670
13671
13672
13673
13674
13675
13676
13677
13678
13679
13680
13681
13682
13683
13684
13685
13686
13687
13688
13689
13690
13691
13692
13693
13694
13695
13696
13697
13698
13699
13700
13701
13702
13703
13704
13705
13706
13707
13708
13709
13710
13711
13712
13713
13714
13715
13716
13717
13718
13719
13720
13721
13722
13723
13724
13725
13726
13727
13728
13729
13730
13731
13732
13733
13734
13735
13736
13737
13738
13739
13740
13741
13742
13743
13744
13745
13746
13747
13748
13749
13750
13751
13752
13753
13754
13755
13756
13757
13758
13759
13760
13761
13762
13763
13764
13765
13766
13767
13768
13769
13770
13771
13772
13773
13774
13775
13776
13777
13778
13779
13780
13781
13782
13783
13784
13785
13786
13787
13788
13789
13790
13791
13792
13793
13794
13795
13796
13797
13798
13799
13800
13801
13802
13803
13804
13805
13806
13807
13808
13809
13810
13811
13812
13813
13814
13815
13816
13817
13818
13819
13820
13821
13822
13823
13824
13825
13826
13827
13828
13829
13830
13831
13832
13833
13834
13835
13836
13837
13838
13839
13840
13841
13842
13843
13844
13845
13846
13847
13848
13849
13850
13851
13852
13853
13854
13855
13856
13857
13858
13859
13860
13861
13862
13863
13864
13865
13866
13867
13868
13869
13870
13871
13872
13873
13874
13875
13876
13877
13878
13879
13880
13881
13882
13883
13884
13885
13886
13887
13888
13889
13890
13891
13892
13893
13894
13895
13896
13897
13898
13899
13900
13901
13902
13903
13904
13905
13906
13907
13908
13909
13910
13911
13912
13913
13914
13915
13916
13917
13918
13919
13920
13921
13922
13923
13924
13925
13926
13927
13928
13929
13930
13931
13932
13933
13934
13935
13936
13937
13938
13939
13940
13941
13942
13943
13944
13945
13946
13947
13948
13949
13950
13951
13952
13953
13954
13955
13956
13957
13958
13959
13960
13961
13962
13963
13964
13965
13966
13967
13968
13969
13970
13971
13972
13973
13974
13975
13976
13977
13978
13979
13980
13981
13982
13983
13984
13985
13986
13987
13988
13989
13990
13991
13992
13993
13994
13995
13996
13997
13998
13999
14000
14001
14002
14003
14004
14005
14006
14007
14008
14009
14010
14011
14012
14013
14014
14015
14016
14017
14018
14019
14020
14021
14022
14023
14024
14025
14026
14027
14028
14029
14030
14031
14032
14033
14034
14035
14036
14037
14038
14039
14040
14041
14042
14043
14044
14045
14046
14047
14048
14049
14050
14051
14052
14053
14054
14055
14056
14057
14058
14059
14060
14061
14062
14063
14064
14065
14066
14067
14068
14069
14070
14071
14072
14073
14074
14075
14076
14077
14078
14079
14080
14081
14082
14083
14084
14085
14086
14087
14088
14089
14090
14091
14092
14093
14094
14095
14096
14097
14098
14099
14100
14101
14102
14103
14104
14105
14106
14107
14108
14109
14110
14111
14112
14113
14114
14115
14116
14117
14118
14119
14120
14121
14122
14123
14124
14125
14126
14127
14128
14129
14130
14131
14132
14133
14134
14135
14136
14137
14138
14139
14140
14141
14142
14143
14144
14145
14146
14147
14148
14149
14150
14151
14152
14153
14154
14155
14156
14157
14158
14159
14160
14161
14162
14163
14164
14165
14166
14167
14168
14169
14170
14171
14172
14173
14174
14175
14176
14177
14178
14179
14180
14181
14182
14183
14184
14185
14186
14187
14188
14189
14190
14191
14192
14193
14194
14195
14196
14197
14198
14199
14200
14201
14202
14203
14204
14205
14206
14207
14208
14209
14210
14211
14212
14213
14214
14215
14216
14217
14218
14219
14220
14221
14222
14223
14224
14225
14226
14227
14228
14229
14230
14231
14232
14233
14234
14235
14236
14237
14238
14239
14240
14241
14242
14243
14244
14245
14246
14247
14248
14249
14250
14251
14252
14253
14254
14255
14256
14257
14258
14259
14260
14261
14262
14263
14264
14265
14266
14267
14268
14269
14270
14271
14272
14273
14274
14275
14276
14277
14278
14279
14280
14281
14282
14283
14284
14285
14286
14287
14288
14289
14290
14291
14292
14293
14294
14295
14296
14297
14298
14299
14300
14301
14302
14303
14304
14305
14306
14307
14308
14309
14310
14311
14312
14313
14314
14315
14316
14317
14318
14319
14320
14321
14322
14323
14324
14325
14326
14327
14328
14329
14330
14331
14332
14333
14334
14335
14336
14337
14338
14339
14340
14341
14342
14343
14344
14345
14346
14347
14348
14349
14350
14351
14352
14353
14354
14355
14356
14357
14358
14359
14360
14361
14362
14363
14364
14365
14366
14367
14368
14369
14370
14371
14372
14373
14374
14375
14376
14377
14378
14379
14380
14381
14382
14383
14384
14385
14386
14387
14388
14389
14390
14391
14392
14393
14394
14395
14396
14397
14398
14399
14400
14401
14402
14403
14404
14405
14406
14407
14408
14409
14410
14411
14412
14413
14414
14415
14416
14417
14418
14419
14420
14421
14422
14423
14424
14425
14426
14427
14428
14429
14430
14431
14432
14433
14434
14435
14436
14437
14438
14439
14440
14441
14442
14443
14444
14445
14446
14447
14448
14449
14450
14451
14452
14453
14454
14455
14456
14457
14458
14459
14460
14461
14462
14463
14464
14465
14466
14467
14468
14469
14470
14471
14472
14473
14474
14475
14476
14477
14478
14479
14480
14481
14482
14483
14484
14485
14486
14487
14488
14489
14490
14491
14492
14493
14494
14495
14496
14497
14498
14499
14500
14501
14502
14503
14504
14505
14506
14507
14508
14509
14510
14511
14512
14513
14514
14515
14516
14517
14518
14519
14520
14521
14522
14523
14524
14525
14526
14527
14528
14529
14530
14531
14532
14533
14534
14535
14536
14537
14538
14539
14540
14541
14542
14543
14544
14545
14546
14547
14548
14549
14550
14551
14552
14553
14554
14555
14556
14557
14558
14559
14560
14561
14562
14563
14564
14565
14566
14567
14568
14569
14570
14571
14572
14573
14574
14575
14576
14577
14578
14579
14580
14581
14582
14583
14584
14585
14586
14587
14588
14589
14590
14591
14592
14593
14594
14595
14596
14597
14598
14599
14600
14601
14602
14603
14604
14605
14606
14607
14608
14609
14610
14611
14612
14613
14614
14615
14616
14617
14618
14619
14620
14621
14622
14623
14624
14625
14626
14627
14628
14629
14630
14631
14632
14633
14634
14635
14636
14637
14638
14639
14640
14641
14642
14643
14644
14645
14646
14647
14648
14649
14650
14651
14652
14653
14654
14655
14656
14657
14658
14659
14660
14661
14662
14663
14664
14665
14666
14667
14668
14669
14670
14671
14672
14673
14674
14675
14676
14677
14678
14679
14680
14681
14682
14683
14684
14685
14686
14687
14688
14689
14690
14691
14692
14693
14694
14695
14696
14697
14698
14699
14700
14701
14702
14703
14704
14705
14706
14707
14708
14709
14710
14711
14712
14713
14714
14715
14716
14717
14718
14719
14720
14721
14722
14723
14724
14725
14726
14727
14728
14729
14730
14731
14732
14733
14734
14735
14736
14737
14738
14739
14740
14741
14742
14743
14744
14745
14746
14747
14748
14749
14750
14751
14752
14753
14754
14755
14756
14757
14758
14759
14760
14761
14762
14763
14764
14765
14766
14767
14768
14769
14770
14771
14772
14773
14774
14775
14776
14777
14778
14779
14780
14781
14782
14783
14784
14785
14786
14787
14788
14789
14790
14791
14792
14793
14794
14795
14796
14797
14798
14799
14800
14801
14802
14803
14804
14805
14806
14807
14808
14809
14810
14811
14812
14813
14814
14815
14816
14817
14818
14819
14820
14821
14822
14823
14824
14825
14826
14827
14828
14829
14830
14831
14832
14833
14834
14835
14836
14837
14838
14839
14840
14841
14842
14843
14844
14845
14846
14847
14848
14849
14850
14851
14852
14853
14854
14855
14856
14857
14858
14859
14860
14861
14862
14863
14864
14865
14866
14867
14868
14869
14870
14871
14872
14873
14874
14875
14876
14877
14878
14879
14880
14881
14882
14883
14884
14885
14886
14887
14888
14889
14890
14891
14892
14893
14894
14895
14896
14897
14898
14899
14900
14901
14902
14903
14904
14905
14906
14907
14908
14909
14910
14911
14912
14913
14914
14915
14916
14917
14918
14919
14920
14921
14922
14923
14924
14925
14926
14927
14928
14929
14930
14931
14932
14933
14934
14935
14936
14937
14938
14939
14940
14941
14942
14943
14944
14945
14946
14947
14948
14949
14950
14951
14952
14953
14954
14955
14956
14957
14958
14959
14960
14961
14962
14963
14964
14965
14966
14967
14968
14969
14970
14971
14972
14973
14974
14975
14976
14977
14978
14979
14980
14981
14982
14983
14984
14985
14986
14987
14988
14989
14990
14991
14992
14993
14994
14995
14996
14997
14998
14999
15000
15001
15002
15003
15004
15005
15006
15007
15008
15009
15010
15011
15012
15013
15014
15015
15016
15017
15018
15019
15020
15021
15022
15023
15024
15025
15026
15027
15028
15029
15030
15031
15032
15033
15034
15035
15036
15037
15038
15039
15040
15041
15042
15043
15044
15045
15046
15047
15048
15049
15050
15051
15052
15053
15054
15055
15056
15057
15058
15059
15060
15061
15062
15063
15064
15065
15066
15067
15068
15069
15070
15071
15072
15073
15074
15075
15076
15077
15078
15079
15080
15081
15082
15083
15084
15085
15086
15087
15088
15089
15090
15091
15092
15093
15094
15095
15096
15097
15098
15099
15100
15101
15102
15103
15104
15105
15106
15107
15108
15109
15110
15111
15112
15113
15114
15115
15116
15117
15118
15119
15120
15121
15122
15123
15124
15125
15126
15127
15128
15129
15130
15131
15132
15133
15134
15135
15136
15137
15138
15139
15140
15141
15142
15143
15144
15145
15146
15147
15148
15149
15150
15151
15152
15153
15154
15155
15156
15157
15158
15159
15160
15161
15162
15163
15164
15165
15166
15167
15168
15169
15170
15171
15172
15173
15174
15175
15176
15177
15178
15179
15180
15181
15182
15183
15184
15185
15186
15187
15188
15189
15190
15191
15192
15193
15194
15195
15196
15197
15198
15199
15200
15201
15202
15203
15204
15205
15206
15207
15208
15209
15210
15211
15212
15213
15214
15215
15216
15217
15218
15219
15220
15221
15222
15223
15224
15225
15226
15227
15228
15229
15230
15231
15232
15233
15234
15235
15236
15237
15238
15239
15240
15241
15242
15243
15244
15245
15246
15247
15248
15249
15250
15251
15252
15253
15254
15255
15256
15257
15258
15259
15260
15261
15262
15263
15264
15265
15266
15267
15268
15269
15270
15271
15272
15273
15274
15275
15276
15277
15278
15279
15280
15281
15282
15283
15284
15285
15286
15287
15288
15289
15290
15291
15292
15293
15294
15295
15296
15297
15298
15299
15300
15301
15302
15303
15304
15305
15306
15307
15308
15309
15310
15311
15312
15313
15314
15315
15316
15317
15318
15319
15320
15321
15322
15323
15324
15325
15326
15327
15328
15329
15330
15331
15332
15333
15334
15335
15336
15337
15338
15339
15340
15341
15342
15343
15344
15345
15346
15347
15348
15349
15350
15351
15352
15353
15354
15355
15356
15357
15358
15359
15360
15361
15362
15363
15364
15365
15366
15367
15368
15369
15370
15371
15372
15373
15374
15375
15376
15377
15378
15379
15380
15381
15382
15383
15384
15385
15386
15387
15388
15389
15390
15391
15392
15393
15394
15395
15396
15397
15398
15399
15400
15401
15402
15403
15404
15405
15406
15407
15408
15409
15410
15411
15412
15413
15414
15415
15416
15417
15418
15419
15420
15421
15422
15423
15424
15425
15426
15427
15428
15429
15430
15431
15432
15433
15434
15435
15436
15437
15438
15439
15440
15441
15442
15443
15444
15445
15446
15447
15448
15449
15450
15451
15452
15453
15454
15455
15456
15457
15458
15459
15460
15461
15462
15463
15464
15465
15466
15467
15468
15469
15470
15471
15472
15473
15474
15475
15476
15477
15478
15479
15480
15481
15482
15483
15484
15485
15486
15487
15488
15489
15490
15491
15492
15493
15494
15495
15496
15497
15498
15499
15500
15501
15502
15503
15504
15505
15506
15507
15508
15509
15510
15511
15512
15513
15514
15515
15516
15517
15518
15519
15520
15521
15522
15523
15524
15525
15526
15527
15528
15529
15530
15531
15532
15533
15534
15535
15536
15537
15538
15539
15540
15541
15542
15543
15544
15545
15546
15547
15548
15549
15550
15551
15552
15553
15554
15555
15556
15557
15558
15559
15560
15561
15562
15563
15564
15565
15566
15567
15568
15569
15570
15571
15572
15573
15574
15575
15576
15577
15578
15579
15580
15581
15582
15583
15584
15585
15586
15587
15588
15589
15590
15591
15592
15593
15594
15595
15596
15597
15598
15599
15600
15601
15602
15603
15604
15605
15606
15607
15608
15609
15610
15611
15612
15613
15614
15615
15616
15617
15618
15619
15620
15621
15622
15623
15624
15625
15626
15627
15628
15629
15630
15631
15632
15633
15634
15635
15636
15637
15638
15639
15640
15641
15642
15643
15644
15645
15646
15647
15648
15649
15650
15651
15652
15653
15654
15655
15656
15657
15658
15659
15660
15661
15662
15663
15664
15665
15666
15667
15668
15669
15670
15671
15672
15673
15674
15675
15676
15677
15678
15679
15680
15681
15682
15683
15684
15685
15686
15687
15688
15689
15690
15691
15692
15693
15694
15695
15696
15697
15698
15699
15700
15701
15702
15703
15704
15705
15706
15707
15708
15709
15710
15711
15712
15713
15714
15715
15716
15717
15718
15719
15720
15721
15722
15723
15724
15725
15726
15727
15728
15729
15730
15731
15732
15733
15734
15735
15736
15737
15738
15739
15740
15741
15742
15743
15744
15745
15746
15747
15748
15749
15750
15751
15752
15753
15754
15755
15756
15757
15758
15759
15760
15761
15762
15763
15764
15765
15766
15767
15768
15769
15770
15771
15772
15773
15774
15775
15776
15777
15778
15779
15780
15781
15782
15783
15784
15785
15786
15787
15788
15789
15790
15791
15792
15793
15794
15795
15796
15797
15798
15799
15800
15801
15802
15803
15804
15805
15806
15807
15808
15809
15810
15811
15812
15813
15814
15815
15816
15817
15818
15819
15820
15821
15822
15823
15824
15825
15826
15827
15828
15829
15830
15831
15832
15833
15834
15835
15836
15837
15838
15839
15840
15841
15842
15843
15844
15845
15846
15847
15848
15849
15850
15851
15852
15853
15854
15855
15856
15857
15858
15859
15860
15861
15862
15863
15864
15865
15866
15867
15868
15869
15870
15871
15872
15873
15874
15875
15876
15877
15878
15879
15880
15881
15882
15883
15884
15885
15886
15887
15888
15889
15890
15891
15892
15893
15894
15895
15896
15897
15898
15899
15900
15901
15902
15903
15904
15905
15906
15907
15908
15909
15910
15911
15912
15913
15914
15915
15916
15917
15918
15919
15920
15921
15922
15923
15924
15925
15926
15927
15928
15929
15930
15931
15932
15933
15934
15935
15936
15937
15938
15939
15940
15941
15942
15943
15944
15945
15946
15947
15948
15949
15950
15951
15952
15953
15954
15955
15956
15957
15958
15959
15960
15961
15962
15963
15964
15965
15966
15967
15968
15969
15970
15971
15972
15973
15974
15975
15976
15977
15978
15979
15980
15981
15982
15983
15984
15985
15986
15987
15988
15989
15990
15991
15992
15993
15994
15995
15996
15997
15998
15999
16000
16001
16002
16003
16004
16005
16006
16007
16008
16009
16010
16011
16012
16013
16014
16015
16016
16017
16018
16019
16020
16021
16022
16023
16024
16025
16026
16027
16028
16029
16030
16031
16032
16033
16034
16035
16036
16037
16038
16039
16040
16041
16042
16043
16044
16045
16046
16047
16048
16049
16050
16051
16052
16053
16054
16055
16056
16057
16058
16059
16060
16061
16062
16063
16064
16065
16066
16067
16068
16069
16070
16071
16072
16073
16074
16075
16076
16077
16078
16079
16080
16081
16082
16083
16084
16085
16086
16087
16088
16089
16090
16091
16092
16093
16094
16095
16096
16097
16098
16099
16100
16101
16102
16103
16104
16105
16106
16107
16108
16109
16110
16111
16112
16113
16114
16115
16116
16117
16118
16119
16120
16121
16122
16123
16124
16125
16126
16127
16128
16129
16130
16131
16132
16133
16134
16135
16136
16137
16138
16139
16140
16141
16142
16143
16144
16145
16146
16147
16148
16149
16150
16151
16152
16153
16154
16155
16156
16157
16158
16159
16160
16161
16162
16163
16164
16165
16166
16167
16168
16169
16170
16171
16172
16173
16174
16175
16176
16177
16178
16179
16180
16181
16182
16183
16184
16185
16186
16187
16188
16189
16190
16191
16192
16193
16194
16195
16196
16197
16198
16199
16200
16201
16202
16203
16204
16205
16206
16207
16208
16209
16210
16211
16212
16213
16214
16215
16216
16217
16218
16219
16220
16221
16222
16223
16224
16225
16226
16227
16228
16229
16230
16231
16232
16233
16234
16235
16236
16237
16238
16239
16240
16241
16242
16243
16244
16245
16246
16247
16248
16249
16250
16251
16252
16253
16254
16255
16256
16257
16258
16259
16260
16261
16262
16263
16264
16265
16266
16267
16268
16269
16270
16271
16272
16273
16274
16275
16276
16277
16278
16279
16280
16281
16282
16283
16284
16285
16286
16287
16288
16289
16290
16291
16292
16293
16294
16295
16296
16297
16298
16299
16300
16301
16302
16303
16304
16305
16306
16307
16308
16309
16310
16311
16312
16313
16314
16315
16316
16317
16318
16319
16320
16321
16322
16323
16324
16325
16326
16327
16328
16329
16330
16331
16332
16333
16334
16335
16336
16337
16338
16339
16340
16341
16342
16343
16344
16345
16346
16347
16348
16349
16350
16351
16352
16353
16354
16355
16356
16357
16358
16359
16360
16361
16362
16363
16364
16365
16366
16367
16368
16369
16370
16371
16372
16373
16374
16375
16376
16377
16378
16379
16380
16381
16382
16383
16384
16385
16386
16387
16388
16389
16390
16391
16392
16393
16394
16395
16396
16397
16398
16399
16400
16401
16402
16403
16404
16405
16406
16407
16408
16409
16410
16411
16412
16413
16414
16415
16416
16417
16418
16419
16420
16421
16422
16423
16424
16425
16426
16427
16428
16429
16430
16431
16432
16433
16434
16435
16436
16437
16438
16439
16440
16441
16442
16443
16444
16445
16446
16447
16448
16449
16450
16451
16452
16453
16454
16455
16456
16457
16458
16459
16460
16461
16462
16463
16464
16465
16466
16467
16468
16469
16470
16471
16472
16473
16474
16475
16476
16477
16478
16479
16480
16481
16482
16483
16484
16485
16486
16487
16488
16489
16490
16491
16492
16493
16494
16495
16496
16497
16498
16499
16500
16501
16502
16503
16504
16505
16506
16507
16508
16509
16510
16511
16512
16513
16514
16515
16516
16517
16518
16519
16520
16521
16522
16523
16524
16525
16526
16527
16528
16529
16530
16531
16532
16533
16534
16535
16536
16537
16538
16539
16540
16541
16542
16543
16544
16545
16546
16547
16548
16549
16550
16551
16552
16553
16554
16555
16556
16557
16558
16559
16560
16561
16562
16563
16564
16565
16566
16567
16568
16569
16570
16571
16572
16573
16574
16575
16576
16577
16578
16579
16580
16581
16582
16583
16584
16585
16586
16587
16588
16589
16590
16591
16592
16593
16594
16595
16596
16597
16598
16599
16600
16601
16602
16603
16604
16605
16606
16607
16608
16609
16610
16611
16612
16613
16614
16615
16616
16617
16618
16619
16620
16621
16622
16623
16624
16625
16626
16627
16628
16629
16630
16631
16632
16633
16634
16635
16636
16637
16638
16639
16640
16641
16642
16643
16644
16645
16646
16647
16648
16649
16650
16651
16652
16653
16654
16655
16656
16657
16658
16659
16660
16661
16662
16663
16664
16665
16666
16667
16668
16669
16670
16671
16672
16673
16674
16675
16676
16677
16678
16679
16680
16681
16682
16683
16684
16685
16686
16687
16688
16689
16690
16691
16692
16693
16694
16695
16696
16697
16698
16699
16700
16701
16702
16703
16704
16705
16706
16707
16708
16709
16710
16711
16712
16713
16714
16715
16716
16717
16718
16719
16720
16721
16722
16723
16724
16725
16726
16727
16728
16729
16730
16731
16732
16733
16734
16735
16736
16737
16738
16739
16740
16741
16742
16743
16744
16745
16746
16747
16748
16749
16750
16751
16752
16753
16754
16755
16756
16757
16758
16759
16760
16761
16762
16763
16764
16765
16766
16767
16768
16769
16770
16771
16772
16773
16774
16775
16776
16777
16778
16779
16780
16781
16782
16783
16784
16785
16786
16787
16788
16789
16790
16791
16792
16793
16794
16795
16796
16797
16798
16799
16800
16801
16802
16803
16804
16805
16806
16807
16808
16809
16810
16811
16812
16813
16814
16815
16816
16817
16818
16819
16820
16821
16822
16823
16824
16825
16826
16827
16828
16829
16830
16831
16832
16833
16834
16835
16836
16837
16838
16839
16840
16841
16842
16843
16844
16845
16846
16847
16848
16849
16850
16851
16852
16853
16854
16855
16856
16857
16858
16859
16860
16861
16862
16863
16864
16865
16866
16867
16868
16869
16870
16871
16872
16873
16874
16875
16876
16877
16878
16879
16880
16881
16882
16883
16884
16885
16886
16887
16888
16889
16890
16891
16892
16893
16894
16895
16896
16897
16898
16899
16900
16901
16902
16903
16904
16905
16906
16907
16908
16909
16910
16911
16912
16913
16914
16915
16916
16917
16918
16919
16920
16921
16922
16923
16924
16925
16926
16927
16928
16929
16930
16931
16932
16933
16934
16935
16936
16937
16938
16939
16940
16941
16942
16943
16944
16945
16946
16947
16948
16949
16950
16951
16952
16953
16954
16955
16956
16957
16958
16959
16960
16961
16962
16963
16964
16965
16966
16967
16968
16969
16970
16971
16972
16973
16974
16975
16976
16977
16978
16979
16980
16981
16982
16983
16984
16985
16986
16987
16988
16989
16990
16991
16992
16993
16994
16995
16996
16997
16998
16999
17000
17001
17002
17003
17004
17005
17006
17007
17008
17009
17010
17011
17012
17013
17014
17015
17016
17017
17018
17019
17020
17021
17022
17023
17024
17025
17026
17027
17028
17029
17030
17031
17032
17033
17034
17035
17036
17037
17038
17039
17040
17041
17042
17043
17044
17045
17046
17047
17048
17049
17050
17051
17052
17053
17054
17055
17056
17057
17058
17059
17060
17061
17062
17063
17064
17065
17066
17067
17068
17069
17070
17071
17072
17073
17074
17075
17076
17077
17078
17079
17080
17081
17082
17083
17084
17085
17086
17087
17088
17089
17090
17091
17092
17093
17094
17095
17096
17097
17098
17099
17100
17101
17102
17103
17104
17105
17106
17107
17108
17109
17110
17111
17112
17113
17114
17115
17116
17117
17118
17119
17120
17121
17122
17123
17124
17125
17126
17127
17128
17129
17130
17131
17132
17133
17134
17135
17136
17137
17138
17139
17140
17141
17142
17143
17144
17145
17146
17147
17148
17149
17150
17151
17152
17153
17154
17155
17156
17157
17158
17159
17160
17161
17162
17163
17164
17165
17166
17167
17168
17169
17170
17171
17172
17173
17174
17175
17176
17177
17178
17179
17180
17181
17182
17183
17184
17185
17186
17187
17188
17189
17190
17191
17192
17193
17194
17195
17196
17197
17198
17199
17200
17201
17202
17203
17204
17205
17206
17207
17208
17209
17210
17211
17212
17213
17214
17215
17216
17217
17218
17219
17220
17221
17222
17223
17224
17225
17226
17227
17228
17229
17230
17231
17232
17233
17234
17235
17236
17237
17238
17239
17240
17241
17242
17243
17244
17245
17246
17247
17248
17249
17250
17251
17252
17253
17254
17255
17256
17257
17258
17259
17260
17261
17262
17263
17264
17265
17266
17267
17268
17269
17270
17271
17272
17273
17274
17275
17276
17277
17278
17279
17280
17281
17282
17283
17284
17285
17286
17287
17288
17289
17290
17291
17292
17293
17294
17295
17296
17297
17298
17299
17300
17301
17302
17303
17304
17305
17306
17307
17308
17309
17310
17311
17312
17313
17314
17315
17316
17317
17318
17319
17320
17321
17322
17323
17324
17325
17326
17327
17328
17329
17330
17331
17332
17333
17334
17335
17336
17337
17338
17339
17340
17341
17342
17343
17344
17345
17346
17347
17348
17349
17350
17351
17352
17353
17354
17355
17356
17357
17358
17359
17360
17361
17362
17363
17364
17365
17366
17367
17368
17369
17370
17371
17372
17373
17374
17375
17376
17377
17378
17379
17380
17381
17382
17383
17384
17385
17386
17387
17388
17389
17390
17391
17392
17393
17394
17395
17396
17397
17398
17399
17400
17401
17402
17403
17404
17405
17406
17407
17408
17409
17410
17411
17412
17413
17414
17415
17416
17417
17418
17419
17420
17421
17422
17423
17424
17425
17426
17427
17428
17429
17430
17431
17432
17433
17434
17435
17436
17437
17438
17439
17440
17441
17442
17443
17444
17445
17446
17447
17448
17449
17450
17451
17452
17453
17454
17455
17456
17457
17458
17459
17460
17461
17462
17463
17464
17465
17466
17467
17468
17469
17470
17471
17472
17473
17474
17475
17476
17477
17478
17479
17480
17481
17482
17483
17484
17485
17486
17487
17488
17489
17490
17491
17492
17493
17494
17495
17496
17497
17498
17499
17500
17501
17502
17503
17504
17505
17506
17507
17508
17509
17510
17511
17512
17513
17514
17515
17516
17517
17518
17519
17520
17521
17522
17523
17524
17525
17526
17527
17528
17529
17530
17531
17532
17533
17534
17535
17536
17537
17538
17539
17540
17541
17542
17543
17544
17545
17546
17547
17548
17549
17550
17551
17552
17553
17554
17555
17556
17557
17558
17559
17560
17561
17562
17563
17564
17565
17566
17567
17568
17569
17570
17571
17572
17573
17574
17575
17576
17577
17578
17579
17580
17581
17582
17583
17584
17585
17586
17587
17588
17589
17590
17591
17592
17593
17594
17595
17596
17597
17598
17599
17600
17601
17602
17603
17604
17605
17606
17607
17608
17609
17610
17611
17612
17613
17614
17615
17616
17617
17618
17619
17620
17621
17622
17623
17624
17625
17626
17627
17628
17629
17630
17631
17632
17633
17634
17635
17636
17637
17638
17639
17640
17641
17642
17643
17644
17645
17646
17647
17648
17649
17650
17651
17652
17653
17654
17655
17656
17657
17658
17659
17660
17661
17662
17663
17664
17665
17666
17667
17668
17669
17670
17671
17672
17673
17674
17675
17676
17677
17678
17679
17680
17681
17682
17683
17684
17685
17686
17687
17688
17689
17690
17691
17692
17693
17694
17695
17696
17697
17698
17699
17700
17701
17702
17703
17704
17705
17706
17707
17708
17709
17710
17711
17712
17713
17714
17715
17716
17717
17718
17719
17720
17721
17722
17723
17724
17725
17726
17727
17728
17729
17730
17731
17732
17733
17734
17735
17736
17737
17738
17739
17740
17741
17742
17743
17744
17745
17746
17747
17748
17749
17750
17751
17752
17753
17754
17755
17756
17757
17758
17759
17760
17761
17762
17763
17764
17765
17766
17767
17768
17769
17770
17771
17772
17773
17774
17775
17776
17777
17778
17779
17780
17781
17782
17783
17784
17785
17786
17787
17788
17789
17790
17791
17792
17793
17794
17795
17796
17797
17798
17799
17800
17801
17802
17803
17804
17805
17806
17807
17808
17809
17810
17811
17812
17813
17814
17815
17816
17817
17818
17819
17820
17821
17822
17823
17824
17825
17826
17827
17828
17829
17830
17831
17832
17833
17834
17835
17836
17837
17838
17839
17840
17841
17842
17843
17844
17845
17846
17847
17848
17849
17850
17851
17852
17853
17854
17855
17856
17857
17858
17859
17860
17861
17862
17863
17864
17865
17866
17867
17868
17869
17870
17871
17872
17873
17874
17875
17876
17877
17878
17879
17880
17881
17882
17883
17884
17885
17886
17887
17888
17889
17890
17891
17892
17893
17894
17895
17896
17897
17898
17899
// Copyright 2026 AlphaOne LLC
// SPDX-License-Identifier: Apache-2.0

//! Postgres + pgvector adapter for the Storage Abstraction Layer (v0.7).
//!
//! Gated behind the `sal-postgres` cargo feature, which layers on top of
//! the base `sal` feature. Default builds do not pull sqlx or pgvector.
//!
//! # Schema
//!
//! The adapter owns its schema (CREATE TABLE IF NOT EXISTS at init) —
//! no manual DBA step required. The embedding column is `vector(384)`
//! to match the default `MiniLmL6V2` model; adapters configured for
//! `NomicEmbedV15` need to drop the column and recreate with
//! `vector(768)` (tooling for that will land with the migration helper
//! in a follow-up).
//!
//! The full schema — parity with the SQLite backend including
//! memories, memory_links, archived_memories, namespace_meta,
//! pending_actions, sync_state, subscriptions — lives at
//! `src/store/postgres_schema.sql`.
//!
//! Key semantic choices at the SQL layer (matching SQLite):
//! - Upsert contract is `ON CONFLICT (title, namespace)`
//!   (UNIQUE INDEX `memories_title_ns_uidx`).
//! - `metadata.agent_id` is immutable across UPSERT and UPDATE via
//!   `jsonb_set` preserving the original agent_id when present.
//! - Tier never downgrades: UPSERT and UPDATE apply `tier_rank()`
//!   precedence so `Long → *` and `Mid → Short` are refused at the
//!   SQL layer.
//!
//! # Capabilities
//!
//! This adapter advertises `TRANSACTIONS | NATIVE_VECTOR | FULLTEXT |
//! DURABLE | STRONG_CONSISTENCY | ATOMIC_MULTI_WRITE`. It does **not**
//! currently advertise `TTL_NATIVE` — expiry sweeps still run
//! application-side to match `SqliteStore` semantics.
//!
//! # Testing
//!
//! Integration tests in `tests/sal_postgres.rs` run iff
//! `AI_MEMORY_TEST_POSTGRES_URL` is set (typically pointed at the
//! `docker compose -f packaging/docker-compose.postgres.yml up`
//! fixture). Unit tests in this module exercise only the SQL-builder
//! helpers that don't need a running Postgres.

use crate::models::ConfidenceSource;
use crate::models::field_names;
use std::time::Duration;

use async_trait::async_trait;
use chrono::{DateTime, Utc};
use sqlx::postgres::{PgConnectOptions, PgPoolOptions};
use sqlx::{PgPool, Row};

use super::{
    CallerContext, Capabilities, CaptureTurnResult, CaptureTurnWrite, Filter, KgBackend,
    KgInvalidateRow, KgQueryRow, KgTimelineRow, MemoryStore, StoreError, StoreResult, UpdatePatch,
    VerifyFilter, VerifyLinkReport, VerifyReport, is_visible_to_caller,
};
use crate::models::{AgentRegistration, Memory, MemoryLink, Tier};

/// Tracing target for postgres-SAL events. Pre-#1562 these were
/// emitted as a FIELD (`target = `), which RUST_LOG target filtering
/// cannot match; now the real metadata target via `target:`.
const TRACE_TARGET: &str = "store::postgres";

/// Tracing target for the postgres KG (Apache AGE) subsystem.
const TRACE_TARGET_KG: &str = "store::postgres::kg";

use crate::quotas::{QuotaStatus, quota_defaults};

// ── #1558 batch 6 — file-local SQL / context-label SSOT ────────────────
// Duplicated literals in this adapter hoisted to named consts per the
// pm-v3.1 hardcoded-literal lint-gate (scripts/check-hardcoded-literals.sh).
const SQL_DELETE_MEMORY_BY_ID: &str = "DELETE FROM memories WHERE id = $1";
/// #1642 — postgres twin of `storage::SQL_DELETE_NAMESPACE_META_BY_STANDARD_ID`
/// (`src/storage/mod.rs`): deleting a memory that serves as a namespace
/// standard must also remove the `namespace_meta` row that points at it,
/// or the namespace keeps enforcing a standard whose backing memory is gone.
const SQL_DELETE_NAMESPACE_META_BY_STANDARD_ID: &str =
    "DELETE FROM namespace_meta WHERE standard_id = $1";
const SQL_SELECT_MEMORY_ID_BY_ID: &str = "SELECT id FROM memories WHERE id = $1";
const SQL_SELECT_METADATA_BY_NS_TITLE: &str =
    "SELECT metadata FROM memories WHERE namespace = $1 AND title = $2";
const SQL_LOAD_AGE: &str = "LOAD 'age'";
const SQL_SET_AGE_SEARCH_PATH: &str = "SET LOCAL search_path = ag_catalog, \"$user\", public";
/// AGE graph bootstrap — shared with `ai-memory schema-init`
/// (`src/cli/schema_init.rs`).
pub(crate) const SQL_CREATE_AGE_GRAPH: &str = "SELECT create_graph('memory_graph')";
/// Postgres duplicate-object message fragment — the idempotent-create guard,
/// shared with `ai-memory schema-init`.
pub(crate) const PG_ERR_ALREADY_EXISTS: &str = "already exists";
const CTX_BEGIN_AGE_TX: &str = "begin AGE tx";
const CTX_COMMIT_AGE_TX: &str = "commit AGE tx";
const CTX_SET_SEARCH_PATH: &str = "set search_path";
const CTX_VERIFY_LINK_SELECT: &str = "verify_link select";
const COL_CONTENT_LEN: &str = "content_len";
const TABLE_ARCHIVED_MEMORIES: &str = "archived_memories";

/// Bootstrap schema run at adapter init — idempotent via IF NOT EXISTS.
const INIT_SCHEMA: &str = include_str!("postgres_schema.sql");

/// v0.7.0 Task 1/8 (recursive learning) — add `memories.reflection_depth`.
/// Mirrors the SQLite v29 migration in `src/db.rs`. The body is in a
/// separate SQL file so operators can inspect and replay the DDL outside
/// the daemon if needed; the migration runner pipes it through
/// `sqlx::raw_sql` inside the v31 transaction.
const MIGRATION_V31_REFLECTION_DEPTH: &str =
    include_str!("../../migrations/postgres/0013_v0700_reflection_depth.sql");

/// v0.7.0 v0.7.1-fold (#687/#688) — SQL-side CHECK constraint on
/// `memory_links.relation`. Postgres supports `ALTER TABLE ADD
/// CONSTRAINT` for CHECK clauses directly, so the migration is a
/// one-liner gated behind a `pg_constraint` probe (idempotent).
/// Mirrors the SQLite full-table-rebuild migration that lands the
/// same constraint on the SQLite backend.
const MIGRATION_V32_LINK_RELATION_CHECK: &str =
    include_str!("../../migrations/postgres/0014_v07_memory_links_relation_check.sql");

/// v0.7.0 V-4 closeout (#698) — SQL-side cross-row hash chain on
/// `signed_events`. Adds `prev_hash BYTEA` + `sequence BIGINT`
/// columns plus a UNIQUE INDEX on `sequence`. Mirrors SQLite schema
/// v34. Postgres supports `ADD COLUMN IF NOT EXISTS` so the DDL is a
/// pure idempotent batch.
const MIGRATION_V33_SIGNED_EVENTS_CHAIN: &str =
    include_str!("../../migrations/postgres/0015_v07_signed_events_chain.sql");

/// v0.7.0 QW-3 — context-offload substrate primitive (`offloaded_blobs`
/// table + namespace and TTL indexes). Mirrors SQLite schema v35.
/// CREATE TABLE IF NOT EXISTS + CREATE INDEX IF NOT EXISTS — fully
/// idempotent. v0.8.0 short-term-context-compression will build on
/// this plumbing.
const MIGRATION_V34_OFFLOADED_BLOBS: &str =
    include_str!("../../migrations/postgres/0016_v07_offloaded_blobs.sql");

/// v0.7.0 WT-1-A — schema v35 (postgres) atomisation foundation.
/// Mirrors SQLite schema v36. Adds two nullable columns on `memories`
/// (`atomised_into INTEGER` + `atom_of TEXT REFERENCES memories(id)`)
/// plus extends the `memory_links.relation` closed-taxonomy CHECK
/// constraint with `derives_from` for atomisation provenance edges.
/// Postgres supports `ADD COLUMN IF NOT EXISTS` (14+) so this is a
/// pure idempotent DDL batch.
const MIGRATION_V35_ATOMISATION: &str =
    include_str!("../../migrations/postgres/0017_v07_atomisation.sql");

/// v0.7.0 QW-2 — Persona-as-artifact substrate primitive. Adds
/// `memories.entity_id TEXT NULL` + `memories.persona_version
/// INTEGER NULL` columns plus the partial index
/// `idx_personas_by_entity`. Mirrors SQLite schema v37. Postgres
/// supports `ADD COLUMN IF NOT EXISTS` so the DDL is a pure
/// idempotent batch.
const MIGRATION_V36_PERSONA: &str = include_str!("../../migrations/postgres/0018_v07_persona.sql");

/// v0.7.0 Form 4 — fact-provenance closeout (issue #757). Adds
/// `memories.citations TEXT NOT NULL DEFAULT '[]'` (JSON array of
/// Citation objects), `memories.source_uri TEXT NULL` (first-class
/// URI-form pointer to the cited source body), and
/// `memories.source_span TEXT NULL` (JSON `{start,end}` byte-range
/// into the parent source body). Mirrors SQLite schema v38. Postgres
/// supports `ADD COLUMN IF NOT EXISTS` so the DDL is a pure
/// idempotent batch.
const MIGRATION_V37_FORM4_PROVENANCE: &str =
    include_str!("../../migrations/postgres/0019_v07_form4_provenance.sql");

/// v0.7.0 Form 5 — auto-confidence + shadow-mode + calibration tooling
/// (issue #758). Adds `memories.confidence_source TEXT NOT NULL
/// DEFAULT 'caller_provided'`, `memories.confidence_signals TEXT NULL`,
/// `memories.confidence_decayed_at TEXT NULL` plus the
/// `confidence_shadow_observations` table backing per-recall telemetry.
/// Mirrors SQLite schema v39. Pure additive ADD COLUMN IF NOT EXISTS +
/// CREATE TABLE IF NOT EXISTS — no backfill needed (the auto-derive
/// engine is opt-in via `AI_MEMORY_AUTO_CONFIDENCE=1`).
const MIGRATION_V38_FORM5_CONFIDENCE: &str =
    include_str!("../../migrations/postgres/0020_v07_form5_confidence_calibration.sql");

/// v0.7.0 Cluster-C SEC-3 closeout (issue #767) — `signed_events_dlq`
/// table backing the deferred-audit drainer's dead-letter-queue path.
/// Mirrors SQLite schema v40. Pure additive CREATE TABLE IF NOT EXISTS
/// + indexes — fully idempotent.
const MIGRATION_V39_SIGNED_EVENTS_DLQ: &str =
    include_str!("../../migrations/postgres/0021_v07_signed_events_dlq.sql");

/// v0.7.0 Cluster G — shadow-mode retention + denormalised `source`
/// column + compound `(namespace, source, observed_at)` index
/// supporting the calibration scan (issue #767, PERF-4 + PERF-12).
/// Mirrors SQLite schema v41. Adds a denormalised `source` column on
/// `confidence_shadow_observations` (backfilled from the joined
/// `memories.source` row) plus the compound index so the calibration
/// sweep streams a single-table SQL aggregation instead of materialising
/// the full window into Rust memory. Pure additive ADD COLUMN IF NOT
/// EXISTS + UPDATE backfill + CREATE INDEX IF NOT EXISTS — idempotent.
const MIGRATION_V40_SHADOW_RETENTION: &str =
    include_str!("../../migrations/postgres/0022_v07_shadow_retention.sql");

/// v0.7.0 polish PERF-8 (issue #781) — auto-persona indexed entity-id
/// column replacing the SQLite content-LIKE full-table scan in the
/// auto-persona matcher. Mirrors SQLite schema v42. Adds
/// `memories.mentioned_entity_id TEXT` + partial index. Backfill
/// (extracting the entity descriptor from `metadata.entity_id` or a
/// `[entity:X]` title marker on pre-existing reflection rows) is
/// folded into the SQL batch. Pure additive ADD COLUMN IF NOT EXISTS
/// + UPDATE + CREATE INDEX IF NOT EXISTS — idempotent.
///
/// The auto-persona executor itself is SQLite-only (it threads a
/// `rusqlite::Connection`); the Postgres column lands here for schema
/// parity so a future PG-native implementation can read the same
/// indexed column without a second migration.
const MIGRATION_V41_AUTO_PERSONA_ENTITY_ID: &str =
    include_str!("../../migrations/postgres/0023_v07_auto_persona_entity_id.sql");

/// v0.7.0 Provenance Gap 1 (issue #884) — postgres v42 mirror of SQLite
/// schema v45. Adds `memories.version BIGINT NOT NULL DEFAULT 1` so
/// every memory row carries an optimistic-concurrency counter. The
/// `version` column is bumped on every mutation by
/// [`PostgresStore::update_with_expected_version`]; concurrent updates
/// pass `expected_version` and receive a typed `VersionConflict`
/// envelope when the stored version has drifted.
const MIGRATION_V42_MEMORY_VERSION: &str =
    include_str!("../../migrations/postgres/0025_v07_memory_version.sql");

/// v0.7.0 Provenance Gap 2 (issue #885) — postgres v43 mirror of SQLite
/// schema v46. Re-asserts `memories.source_uri TEXT NULL` + partial
/// index `idx_memories_source_uri` for legacy upgrades, then backfills
/// the column from `metadata.source_uri` and `citations[0].uri` for
/// pre-Form-4 rows. The column itself + partial index originally
/// shipped at postgres v37 (`0019_v07_form4_provenance.sql`); this arm
/// covers the upgrade path for installs that pre-dated v37.
const MIGRATION_V43_SOURCE_URI_UPGRADE: &str =
    include_str!("../../migrations/postgres/0026_v07_source_uri_upgrade.sql");

/// v0.7.0 Gap 3 (issue #886) — postgres v44 mirror of SQLite schema v47.
/// Adds the `recall_observations` ledger keyed by
/// `(recall_id, memory_id)`, carrying retriever / rank / score plus
/// the consumed_at + consumed_by_memory_id columns set when a
/// `memory_store` or `memory_link` request cites a prior `recall_id`.
/// CASCADE-deletes alongside the referenced memory rows. Pure additive
/// `CREATE TABLE IF NOT EXISTS` + three index `CREATE INDEX IF NOT
/// EXISTS` statements — fully idempotent.
const MIGRATION_V44_RECALL_OBSERVATIONS: &str =
    include_str!("../../migrations/postgres/0027_v07_recall_observations.sql");

/// v0.7.0 Provenance Gap 5 (issue #888) — postgres v45 mirror of the
/// SQLite Gap-5 split-write surface. The `archive_reason` column has no
/// CHECK clause so `'superseded'` lands without DDL; this arm adds two
/// performance indexes the Gap-5 audit + lineage read paths rely on:
/// `idx_archived_reason` for time-bounded "what got superseded in the
/// last day" scans, and `idx_memories_metadata_superseded` for the
/// reciprocal "find the live row that superseded archived X" lookup.
const MIGRATION_V45_EDIT_SOURCE_ARCHIVE: &str =
    include_str!("../../migrations/postgres/0028_v07_edit_source_archive_metadata.sql");

/// v0.7.0 issue #860 — postgres v46 mirror of the SQLite Gap-7 surface.
/// Defensive belt-and-braces `ADD COLUMN IF NOT EXISTS` on the four
/// temporal-validity + attestation columns
/// (`valid_from`, `valid_until`, `observed_by`, `attest_level`) on
/// `memory_links`, all of which already ship inline in
/// `postgres_schema.sql:283-291` for greenfield deploys. Re-asserts
/// the matching indexes via `CREATE INDEX IF NOT EXISTS` so a legacy
/// DB that was created before those declarations picks them up.
const MIGRATION_V46_LINKS_TEMPORAL_COLUMNS: &str =
    include_str!("../../migrations/postgres/0029_v07_links_temporal_columns.sql");

/// v47 — Persona signing atomicity CHECK constraint on `memory_links`
/// (sqlite parity via `migrations/sqlite/0037_v07_persona_signing_atomicity.sql`).
/// Closes #902: the file existed at `0024_v07_persona_signing_atomicity.sql`
/// but was orphaned (never registered in the ladder). Without it, postgres
/// accepts `attest_level IN ('self_signed','peer_attested')` rows with NULL
/// or wrong-length signature; sqlite correctly rejects.
const MIGRATION_V47_PERSONA_SIGNING_ATOMICITY: &str =
    include_str!("../../migrations/postgres/0024_v07_persona_signing_atomicity.sql");

/// v48 — Federation push DLQ table (Track D #933).
///
/// Adds `federation_push_dlq` so per-peer fanout failures inside
/// `broadcast_store_quorum` can be replayed by the new
/// `replay_federation_push_dlq` worker (spawned alongside the catchup
/// loop in `daemon_runtime::spawn_catchup_loop_with_store`). The table
/// also ships inline in `postgres_schema.sql` for greenfield installs;
/// this migration covers legacy-upgrade paths. Pure additive CREATE
/// TABLE IF NOT EXISTS + indexes — fully idempotent. Mirrors SQLite
/// schema v48 / `migrations/sqlite/0041_v07_federation_push_dlq.sql`.
const MIGRATION_V48_FEDERATION_PUSH_DLQ: &str =
    include_str!("../../migrations/postgres/0030_v07_federation_push_dlq.sql");

/// Current schema version. Matches SQLite CURRENT_SCHEMA_VERSION (crate::storage::migrations::CURRENT_SCHEMA_VERSION).
/// Incremented on each migration step.
///
/// v15 — Temporal-validity columns on `memory_links` + `entity_aliases`.
/// v17 — `metadata.governance.inherit` backfill (mirrors SQLite v17).
/// v18 — Data-integrity hardening (`embedding_dim`, archive lossless,
///       endianness header backfill — SQLite v18 / Postgres
///       0011_v0631_data_integrity).
/// v19 — Webhook `event_types` JSON array on subscriptions + index.
/// v20 — `audit_log` table for capability-expansion observability.
/// v21 — `pending_actions.default_timeout_seconds` + `expired_at`
///       columns plus the (status, requested_at) sweep index.
/// v22 — `memory_transcripts` substrate (attested-cortex epic I1).
/// v23 — `memory_links.attest_level` for signed-link writes (H2).
/// v24 — `memory_transcript_links` join table (I2) + the F6 SAL KG
///       SQL surfaces (`kg_query_view` / `kg_timeline_view` /
///       `kg_find_paths()`).
/// v25 — `memory_transcripts.archived_at` for archive→prune lifecycle (I3).
/// v26 — `signed_events` append-only audit table (H5).
/// v27 — A2A correlation IDs + DLQ (`subscription_events`,
///       `subscription_dlq`) (K6).
/// v28 — `agent_quotas` per-agent rate + storage caps (K8).
/// v29 — In-place `vector(N)` conversion helper + parameterised
///       `embedding` column dim. Connect-time migration is a no-op
///       stamp pass; the actual `vector(384) → vector(768)` (or
///       similar) conversion only runs when the operator explicitly
///       invokes `ai-memory schema-init --embedding-dim <N>` with a
///       value that differs from the current column declaration. The
///       conversion is destructive on the embedding column (rows have
///       their `embedding` NULLed and the HNSW indexes dropped +
///       recreated) — re-embedding is required after the migration.
/// v30 — `memories_metadata_is_object` CHECK constraint (M15). The
///       `scope_idx` / `agent_id_idx` generated columns extract via
///       `->>` which silently returns NULL for non-object metadata
///       (array / scalar / NULL); the CHECK rejects malformed
///       metadata at the write boundary instead of degrading to
///       null-scope rows.
// v31 = v0.7.0 Task 1/8 (recursive learning) — `memories.reflection_depth`
//       INTEGER NOT NULL DEFAULT 0 column, mirroring SQLite schema v29.
//       `ADD COLUMN IF NOT EXISTS` keeps the migration idempotent on
//       Postgres 14+; the base schema in `postgres_schema.sql` carries
//       the column inline so fresh installs land it without the
//       migration step running.
// v32 = v0.7.0 v0.7.1-fold (#687/#688) — SQL-side CHECK constraint
//       on `memory_links.relation` (closed taxonomy:
//       related_to/supersedes/contradicts/derived_from/reflects_on).
//       Mirrors SQLite schema v33 (#687 + #688) but uses Postgres's
//       native `ALTER TABLE ADD CONSTRAINT` rather than the SQLite
//       full-table-rebuild dance. Idempotent via pg_constraint probe.
//       Fresh installs inherit the constraint inline from
//       `postgres_schema.sql`.
// v33 = v0.7.0 V-4 closeout (#698) — SQL-side cross-row hash chain
//       on `signed_events`. Adds `prev_hash BYTEA` + `sequence
//       BIGINT` columns plus a UNIQUE INDEX. Mirrors SQLite schema
//       v34. Per-row Ed25519 signatures remain as defense-in-depth;
//       the cross-row chain becomes the LOAD-BEARING tamper-evidence
//       property. Backfill runs application-side in `migrate_v33` so
//       both backends share the canonical-bytes encoding from
//       `signed_events::canonical_chain_bytes`.
// v34 = v0.7.0 QW-3 — context-offload substrate primitive. Adds the
//       `offloaded_blobs` table backing `src/offload/mod.rs`.
//       Mirrors SQLite schema v35. Pure idempotent CREATE TABLE IF
//       NOT EXISTS + CREATE INDEX IF NOT EXISTS — no application-
//       side backfill needed.
// v35 = v0.7.0 WT-1-A — substrate-level atomisation foundation.
//       Adds `memories.atomised_into INTEGER` + `memories.atom_of
//       TEXT REFERENCES memories(id)` columns plus extends the
//       `memory_links.relation` closed-taxonomy CHECK constraint
//       with `derives_from` for atomisation provenance edges
//       (atom -> parent). Mirrors SQLite schema v36. Postgres
//       supports `ADD COLUMN IF NOT EXISTS` so the migration is a
//       pure idempotent DDL batch; the constraint drop-add is gated
//       on a pg_constraint probe so re-running is a no-op. First
//       hard prereq for WT-1-B through WT-1-G.
// v36 = v0.7.0 QW-2 — Persona-as-artifact substrate primitive. Adds
//       `memories.entity_id TEXT NULL` + `memories.persona_version
//       INTEGER NULL` plus the partial index
//       `idx_personas_by_entity`. Mirrors SQLite schema v37. Pure
//       idempotent ADD COLUMN IF NOT EXISTS + CREATE INDEX IF NOT
//       EXISTS — no backfill needed (non-Persona rows keep NULL).
// v37 = v0.7.0 Form 4 — fact-provenance closeout (issue #757). Adds
//       `memories.citations TEXT NOT NULL DEFAULT '[]'`,
//       `memories.source_uri TEXT NULL`, and
//       `memories.source_span TEXT NULL` plus the
//       `idx_memories_source_uri` partial index covering the
//       `--source-uri-prefix` recall filter. Mirrors SQLite schema
//       v38. Pure additive ADD COLUMN IF NOT EXISTS + CREATE INDEX
//       IF NOT EXISTS — no backfill required (legacy rows default to
//       empty citations array and NULL URI/span).
// v38 = v0.7.0 Form 5 — auto-confidence + shadow-mode + calibration
//       tooling closeout (issue #758). Adds three columns on
//       `memories` (`confidence_source TEXT NOT NULL DEFAULT
//       'caller_provided'`, `confidence_signals TEXT NULL`,
//       `confidence_decayed_at TEXT NULL`) plus the
//       `confidence_shadow_observations` table backing the shadow-mode
//       telemetry pipeline. Mirrors SQLite schema v39. Pure additive
//       ADD COLUMN IF NOT EXISTS + CREATE TABLE IF NOT EXISTS — no
//       backfill required (every pre-Form-5 row stays at the
//       `caller_provided` baseline; the auto-derive engine is opt-in
//       via `AI_MEMORY_AUTO_CONFIDENCE=1`).
// v39 = v0.7.0 Cluster-C SEC-3 closeout (issue #767) — adds the
//       `signed_events_dlq` table backing the deferred-audit drainer's
//       dead-letter-queue path. Pure additive CREATE TABLE IF NOT
//       EXISTS + indexes — fully idempotent. Mirrors SQLite v40.
// v40 = v0.7.0 Cluster G — shadow-mode retention + denormalised
//       `source` column + compound `(namespace, source, observed_at)`
//       index supporting the calibration scan (issue #767, PERF-4 +
//       PERF-12). Mirrors SQLite schema v41. Postgres supports
//       `ADD COLUMN IF NOT EXISTS` so the ALTER + backfill UPDATE +
//       index live in one idempotent SQL batch
//       (`migrations/postgres/0022_v07_shadow_retention.sql`).
//       (Renumbered from v39 to v40 during rebase onto trunk: Cluster C
//       SEC-3 closeout #770 landed first and claimed v39 for the
//       `signed_events_dlq` table.)
// v41 = v0.7.0 polish PERF-8 (issue #781) — auto-persona indexed
//       entity-id column. Adds `memories.mentioned_entity_id TEXT` +
//       partial index `WHERE mentioned_entity_id IS NOT NULL`. Mirrors
//       SQLite schema v42. Postgres supports `ADD COLUMN IF NOT EXISTS`
//       so the ALTER + backfill + index live in one idempotent SQL
//       batch (`migrations/postgres/0023_v07_auto_persona_entity_id.sql`).
//       Schema parity only — the auto-persona executor is SQLite-only.
//       Column-name deliberately distinct from QW-2's `entity_id`
//       (Persona-row attribution); PERF-8 reads the OPPOSITE direction
//       (the entity an observation/reflection mentions).
// v42 = v0.7.0 Provenance Gap 1 (issue #884) — `memories.version
//       BIGINT NOT NULL DEFAULT 1` optimistic-concurrency counter.
//       Mirrors SQLite schema v45. Pure additive ADD COLUMN IF NOT
//       EXISTS — fully idempotent. The new
//       `PostgresStore::update_with_expected_version` bumps the
//       column atomically and refuses an update whose
//       expected_version has drifted via the typed
//       `VersionConflict` envelope.
// v43 = v0.7.0 Provenance Gap 2 (issue #885) — re-asserts
//       `memories.source_uri TEXT` + partial index
//       `idx_memories_source_uri` for upgrade paths that pre-date
//       the v37 Form-4 migration, then backfills the column from
//       `metadata.source_uri` and `citations[0].uri` for pre-Form-4
//       rows. Mirrors SQLite schema v46. Pure additive +
//       guarded UPDATE — fully idempotent.
// v44 = v0.7.0 Gap 3 (issue #886) — `recall_observations` ledger
//       table keyed by (recall_id, memory_id). Mirrors SQLite
//       schema v47. Pure additive CREATE TABLE IF NOT EXISTS +
//       three indexes — fully idempotent.
// v45 = v0.7.0 Provenance Gap 5 (issue #888) — append-and-archive
//       Gap-5 support indexes (`idx_archived_reason` +
//       `idx_memories_metadata_superseded`). No CHECK on
//       archive_reason to expand (free-form TEXT column). Pure
//       additive CREATE INDEX IF NOT EXISTS — fully idempotent.
// v46 = v0.7.0 issue #860 — defensive `ADD COLUMN IF NOT EXISTS` on
//       the four temporal-validity + attestation columns on
//       `memory_links` (valid_from, valid_until, observed_by,
//       attest_level). All four already ship inline in
//       postgres_schema.sql for greenfield; this migration covers
//       legacy upgrade paths. Pure additive — fully idempotent.
// v47 = v0.7.0 #902 — register the orphaned `memory_links` persona-
//       signing atomicity CHECK constraint via the SAL ladder.
// v48 = v0.7.0 Track D #933 — `federation_push_dlq` table backing the
//       quorum-broadcast fanout dead-letter queue (parity with SQLite
//       v48 / `migrations/sqlite/0041_v07_federation_push_dlq.sql`).
//       Pure additive CREATE TABLE IF NOT EXISTS + indexes — fully
//       idempotent.
//
// v49 = #1025 (CRITICAL, 2026-05-21) — archived_memories full v0.7.0
//       column carry. Adds 14 nullable columns to archived_memories
//       so archive→restore round-trips preserve Form-4 / Form-5 /
//       QW-2 / Gap-1 fields. Pure additive ALTER TABLE ADD COLUMN
//       IF NOT EXISTS — fully idempotent + replay-safe.
// v51 = #1255 (MED, 2026-05-25) — federation_nonce_cache persistence.
//       Postgres-backed daemons keep their nonce cache in the
//       sqlite ai-memory.db (the FederationNonceCache is a daemon-
//       process primitive distinct from the memory store). The
//       postgres ladder version-bumps to keep the SQLite/postgres
//       CURRENT_SCHEMA_VERSION pinned in lockstep — this migration
//       is a no-op DDL stub recording the version reach.
// v53 = R5.F5.2 (#1418, HIGH, 2026-05-30) — scope the `memories_au`
//       FTS5 sync trigger to (title, content, tags) on sqlite.
//       Postgres has no equivalent FTS5 trigger (the postgres
//       backend uses pgvector + tsvector primitives directly with
//       no AFTER-UPDATE sync trigger on the `memories` table), so
//       the postgres twin is a no-op DDL stub that only records
//       the schema-version reach — the SQLite/postgres
//       CURRENT_SCHEMA_VERSION stays pinned in lockstep so a
//       single logical schema number tracks both adapters.
// v55 = #1476 (perf, 2026-06-03) — sargable federation-catchup. The
//       `list_memories_updated_since` predicate is rewritten from the
//       non-sargable `($1 IS NULL OR updated_at > $1)` to a None/Some
//       split (`updated_at > $1`) so the planner gets a true Index Cond
//       range + early-stop under LIMIT. On postgres NO new index is
//       added: the bootstrap schema already ships
//       `memories_updated_at_idx ON memories (updated_at DESC)`, which a
//       bidirectional btree serves via Index Scan Backward — so the
//       postgres twin is a version-stamp only (v51 / v53 precedent). The
//       SQLite backend, which has no pre-existing updated_at index, adds
//       one at v55 (`migrations/sqlite/0046_v55_idx_memories_updated_at.sql`).
//       CURRENT_SCHEMA_VERSION stays pinned in lockstep.
// v56 = #1579 A2 + B6d (perf, 2026-06-10) — composite list / archive
//       ordering indexes on the SQLite side
//       (`migrations/sqlite/0047_v56_list_composite_indexes.sql`), paired
//       with the sargable `storage::list` rewrite so the sqlite planner
//       walks `(priority DESC, updated_at DESC)` in ORDER BY order with
//       early-stop under LIMIT instead of a full-table temp B-tree sort
//       (P1-measured 141 ms -> 0.06 ms at 100k rows). The #1579 A2
//       finding was measured against the sqlite adapter; the postgres
//       list path builds its own SQL against `memories_priority_idx` /
//       `memories_updated_at_idx` and is owned by the postgres
//       workstream — so the postgres twin is a version-stamp only
//       (v51 / v53 / v55 precedent). CURRENT_SCHEMA_VERSION stays
//       pinned in lockstep.
// v57 = #1579 B2 (perf, 2026-06-10) — stored generated tsvector column.
//       `tsv tsvector GENERATED ALWAYS AS (to_tsvector('english',
//       coalesce(title,'')||' '||coalesce(content,''))) STORED` +
//       `memories_tsv_gin` GIN index on the COLUMN; the recall /
//       search / contradiction query shapes read `tsv` for both the
//       `@@` match and `ts_rank`, eliminating the per-matched-row
//       tsvector recompute (~305 of 306 ms at 8k rows, P3 audit). The
//       legacy expression index `memories_content_fts` is dropped.
//       NOTE: the ADD COLUMN takes an ACCESS EXCLUSIVE table rewrite —
//       sub-second at fleet scale (~8k rows), plan a window for very
//       large deployments. SQLite twin is a version-stamp no-op (FTS5
//       already materialises the text in `memories_fts`); lockstep
//       pinned.
const CURRENT_SCHEMA_VERSION: i32 = 57;

/// PostgreSQL session-scoped advisory lock key used to serialize
/// concurrent `migrate()` invocations across processes and across
/// in-process parallel `connect()` calls. Without this lock, racing
/// `CREATE INDEX` / `ADD CONSTRAINT` / `ALTER TYPE` DDL statements
/// across the migration ladder collide and surface as `tuple
/// concurrently updated`, `duplicate key value violates unique
/// constraint "pg_class_relname_nsp_index"`, or `constraint
/// "<name>" already exists` errors.
///
/// Arbitrary i64 namespaced to ai-memory's PostgresStore — picked once
/// at v0.7.0 ship-hardening and frozen thereafter. Changing this value
/// in a future release would risk an in-flight migration on an older
/// daemon being raced by a newer daemon (different lock keys = no
/// serialization between them).
///
/// Hex breakdown: `0x4149_4D45_4D49_4701` — "AIMEMIG\x01" as ASCII.
const MIGRATION_ADVISORY_LOCK_KEY: i64 = 0x4149_4D45_4D49_4701;

/// Default embedding column dimension used when the caller doesn't pass
/// `--embedding-dim` to `ai-memory schema-init`. Matches the v0.7.0
/// baseline schema (`MiniLmL6V2` embedder = 384). Operators upgrading
/// to a 768-dim embedder (`nomic_embed_v15`) must pass the matching
/// `--embedding-dim 768` flag.
pub const DEFAULT_EMBEDDING_DIM: u32 = 384;

/// Supported embedding column dimensions. Mirrors the values returned
/// by `EmbeddingModel::dim()` for the two compiled-in embedders
/// (MiniLmL6V2 = 384, NomicEmbedV15 = 768). The migration helper
/// rejects any other value with a clear error so an operator typo
/// doesn't leave the schema in an unusable state.
const SUPPORTED_EMBEDDING_DIMS: &[i32] = &[384, 768];

/// Placeholder substituted in `postgres_schema.sql` at connect time.
/// The schema file embeds `vector({EMBEDDING_DIM})` everywhere a
/// dim-bearing column is declared (currently `memories.embedding` and
/// `archived_memories.embedding`); [`PostgresStore::connect_with_dim`]
/// runs a single `str::replace` over the bundled template before
/// executing.
const EMBEDDING_DIM_PLACEHOLDER: &str = "{EMBEDDING_DIM}";

/// Substitute the embedding-dim placeholder in the bundled schema
/// template. Pulled out as a free function so the unit test can exercise
/// it without a running Postgres. Returns a fresh `String` — callers
/// pass the result straight to `sqlx::raw_sql`.
#[must_use]
pub fn render_schema_sql(template: &str, dim: u32) -> String {
    template.replace(EMBEDDING_DIM_PLACEHOLDER, &dim.to_string())
}

/// Connection-pool sizing knobs. Defined in the `sal`-gated parent
/// module (`crate::store`) so the daemon's `build_store_handle` can
/// name the type in a `sal`-only build; re-exported here so existing
/// `crate::store::postgres::PoolConfig` references (tests, the connect
/// chain) keep resolving.
pub use crate::store::PoolConfig;

/// v0.7.0 M4 — default connection-level `statement_timeout` (seconds)
/// applied to every postgres connection in the pool. 30s bounds the
/// outer envelope of any single query so a pathological `pg_sleep(60)`,
/// a runaway recursive CTE, or an unbounded sequential scan cannot
/// wedge a connection for the whole pool. Operators with intentionally
/// long maintenance queries from the daemon (`schema-init
/// --embedding-dim`, the AGE seed) override via
/// `AppConfig::postgres_statement_timeout_secs`. Setting the value to
/// 0 disables the limit (postgres `SET` semantics).
pub const DEFAULT_STATEMENT_TIMEOUT_SECS: u64 = 30;

/// v0.7.0 M4 companion — paired `lock_timeout` (seconds). Lock waits
/// over this threshold abort with `lock_not_available` instead of
/// blocking forever behind a DDL or a long-running competing txn. 5s
/// is the standard "I'd rather fail fast than hang" envelope; operators
/// can disable it by setting `postgres_statement_timeout_secs = 0`,
/// which also drops the lock_timeout.
pub const DEFAULT_LOCK_TIMEOUT_SECS: u64 = 5;

/// `PostgresStore` — sqlx + pgvector backend. Owns a connection pool.
#[derive(Clone)]
pub struct PostgresStore {
    pool: PgPool,
    /// Resolved knowledge-graph backend tag — set at [`Self::connect`]
    /// time by probing `pg_extension` for Apache AGE. Substrate for
    /// Track J: J2-J7 dispatch their KG queries on this value, falling
    /// back to the recursive-CTE path when AGE is absent. See
    /// [`Self::kg_backend`].
    kg_backend: KgBackend,
}

/// #1628 — wire-pinned refusal text for legacy rows with no
/// `metadata.agent_id` stamp (write-path verbs). One declaration site
/// per pm-v3.1; consumed by the caller-owns mutation gate.
const REASON_UNSTAMPED_TENANT_WRITE: &str =
    "memory has no agent_id stamp; tenant writes refused (use admin path)";
/// #1628 — delete-verb sibling of [`REASON_UNSTAMPED_TENANT_WRITE`].
const REASON_UNSTAMPED_TENANT_DELETE: &str =
    "memory has no agent_id stamp; tenant deletes refused (use admin path)";

impl PostgresStore {
    /// Connect using a Postgres URL (e.g. `postgres://user:pass@host:5432/db`).
    /// Runs the bootstrap schema on the first connection acquired.
    ///
    /// Bootstraps with [`DEFAULT_EMBEDDING_DIM`] (= 384). Use
    /// [`Self::connect_with_dim`] when initializing a fresh schema for
    /// a 768-dim embedder (`nomic_embed_v15`) — passing the dim here
    /// makes the `vector(N)` column declarations match the embedder
    /// from the very first write.
    ///
    /// # Errors
    ///
    /// Returns `StoreError::BackendUnavailable` if the connection
    /// cannot be established or the schema bootstrap fails.
    pub async fn connect(url: &str) -> StoreResult<Self> {
        Self::connect_with_dim(url, DEFAULT_EMBEDDING_DIM).await
    }

    /// Connect with an explicit `statement_timeout` (seconds). Mirrors
    /// [`Self::connect`] but lets callers override the default 30s
    /// safety envelope — typically driven from
    /// `AppConfig::postgres_statement_timeout_secs`. Setting `secs = 0`
    /// disables the timeout (matches postgres `SET` semantics).
    ///
    /// # Errors
    ///
    /// Same as [`Self::connect`].
    pub async fn connect_with_timeout(url: &str, secs: u64) -> StoreResult<Self> {
        Self::connect_with_dim_and_timeout(url, DEFAULT_EMBEDDING_DIM, secs, PoolConfig::default())
            .await
    }

    /// Connect using a Postgres URL with an explicit embedding column
    /// dimension. Substitutes `{EMBEDDING_DIM}` in the bundled
    /// `postgres_schema.sql` before executing so a fresh init lands
    /// the right `vector(N)` declaration.
    ///
    /// For an existing schema, this call does NOT alter pre-declared
    /// `vector(M)` columns — the operator must invoke the explicit
    /// `migrate_embedding_dim` helper (typically via
    /// `ai-memory schema-init --embedding-dim N`) to perform the
    /// destructive in-place conversion. Calling `connect_with_dim`
    /// against a mismatched schema emits a WARN and falls back to the
    /// existing dim for the lifetime of the pool.
    ///
    /// # Errors
    ///
    /// Returns `StoreError::BackendUnavailable` if the connection
    /// cannot be established, `StoreError::InvalidInput` if `dim` is
    /// not one of the supported values, or schema-bootstrap failures
    /// bubble up unchanged.
    pub async fn connect_with_dim(url: &str, dim: u32) -> StoreResult<Self> {
        Self::connect_with_dim_and_timeout(
            url,
            dim,
            DEFAULT_STATEMENT_TIMEOUT_SECS,
            PoolConfig::default(),
        )
        .await
    }

    /// Connect with an explicit embedding dim, `statement_timeout`
    /// (seconds), and connection-pool sizing ([`PoolConfig`]). The
    /// fully-parameterised entry point — both [`Self::connect`] and
    /// [`Self::connect_with_dim`] delegate here with
    /// [`PoolConfig::default`]. See M4/M7 in
    /// `src/store/postgres.rs::DEFAULT_STATEMENT_TIMEOUT_SECS` for the
    /// rationale on the safety envelope, and `AppConfig::resolve_pg_pool`
    /// for how operators override the pool sizing at the daemon boundary.
    ///
    /// # Errors
    ///
    /// Same as [`Self::connect_with_dim`].
    pub async fn connect_with_dim_and_timeout(
        url: &str,
        dim: u32,
        statement_timeout_secs: u64,
        pool_config: PoolConfig,
    ) -> StoreResult<Self> {
        if !SUPPORTED_EMBEDDING_DIMS.contains(&i32::try_from(dim).unwrap_or(-1)) {
            return Err(StoreError::InvalidInput {
                detail: format!(
                    "unsupported embedding dim {dim}: expected one of {SUPPORTED_EMBEDDING_DIMS:?}"
                ),
            });
        }

        let options: PgConnectOptions =
            url.parse()
                .map_err(|e: sqlx::Error| StoreError::BackendUnavailable {
                    backend: "postgres".to_string(),
                    // #1579 A3 (SECURITY) — sqlx parse errors can
                    // interpolate the raw URL (credential included)
                    // into their Display; scrub any embedded URL's
                    // password before the detail leaves the adapter.
                    detail: crate::logging::redact_urls_in_message(&format!("parse url: {e}")),
                })?;
        // v0.7.0 M4/M7 — `after_connect` hook fires the moment a new
        // connection is acquired. We use it to apply per-session
        // `statement_timeout` + `lock_timeout` so a runaway query
        // cannot wedge the pool indefinitely. `secs = 0` is the
        // postgres-native "disabled" sentinel; we skip the SET in
        // that case to keep the wire silent for operators who
        // explicitly opted out of the safety envelope.
        //
        // POOLER NOTE: this session-level `SET` is correct for a direct
        // Postgres connection and for PgBouncer *session* mode. Under
        // PgBouncer *transaction* mode (the mode the T4+ enterprise
        // topology recommends) the standalone `SET` does NOT persist —
        // PgBouncer runs it on whichever server connection it assigns
        // for that one statement, then releases the connection, so the
        // envelope is lost before the next transaction. Operators
        // fronting the primary with a transaction-mode pooler MUST also
        // pin the envelope at the Postgres role level (`ALTER ROLE
        // aimemory SET statement_timeout = '…'; … SET lock_timeout =
        // '…';`) so every backend inherits it as its server default.
        // See docs/enterprise-deployment.md §5.6.6. We deliberately do
        // NOT use the libpq `options` startup parameter to carry the
        // timeout (PgBouncer < 1.21 rejects it and the daemon would
        // fail to connect), keeping the role-level path the single
        // version-independent pooled-deployment recipe.
        let stmt_secs = statement_timeout_secs;
        let lock_secs = if stmt_secs == 0 {
            0
        } else {
            DEFAULT_LOCK_TIMEOUT_SECS
        };
        let pool = PgPoolOptions::new()
            .max_connections(pool_config.max_connections)
            .min_connections(pool_config.min_connections)
            .acquire_timeout(Duration::from_secs(pool_config.acquire_timeout_secs))
            .after_connect(move |conn, _meta| {
                Box::pin(async move {
                    use sqlx::Executor;
                    if stmt_secs == 0 {
                        return Ok(());
                    }
                    let stmt_ms = stmt_secs.saturating_mul(crate::MILLIS_PER_SEC);
                    let lock_ms = lock_secs.saturating_mul(crate::MILLIS_PER_SEC);
                    let sql =
                        format!("SET statement_timeout = {stmt_ms}; SET lock_timeout = {lock_ms};");
                    conn.execute(sql.as_str()).await.map(|_| ())
                })
            })
            .connect_with(options)
            .await
            .map_err(|e| StoreError::BackendUnavailable {
                backend: "postgres".to_string(),
                detail: format!("connect: {e}"),
            })?;

        // v0.7.0 ship-hardening: acquire MIGRATION_ADVISORY_LOCK_KEY
        // across the entire bootstrap (INIT_SCHEMA + sanity checks +
        // KG detection + migrate) so concurrent connect() callers on
        // a fresh DB cannot race CREATE EXTENSION / CREATE INDEX /
        // ADD CONSTRAINT statements. The legacy retry-on-race loop
        // around INIT_SCHEMA (kept below as defense-in-depth) was
        // insufficient under heavy parallel load — the LAN-parity
        // audit on 2026-05-19 surfaced both "init schema: tuple
        // concurrently updated" and "apply v32 ... constraint already
        // exists" failures.
        //
        // The lock is held on a dedicated PoolConnection for the
        // lifetime of the bootstrap; queue depth = other in-flight
        // callers. Released explicitly via pg_advisory_unlock_all() +
        // implicit drop. Reentrant within the same session, but we
        // acquire ONCE here and switch the inner `store.migrate()`
        // call to the lock-free `store.migrate_locked()` to avoid the
        // second acquire-from-different-session that would deadlock.
        let mut bootstrap_lock_conn =
            pool.acquire()
                .await
                .map_err(|e| StoreError::BackendUnavailable {
                    backend: "postgres".to_string(),
                    detail: format!("acquire bootstrap lock connection: {e}"),
                })?;
        // v0.7.0 ship-hardening (2026-05-19, QC P0): the per-session
        // statement_timeout=30s set in `after_connect` would abort
        // `pg_advisory_lock` itself if a holder takes >30s
        // (plausible on a busy DB for the full v15→v47 ladder).
        // `lock_timeout` is no-op for advisory locks per PG docs but
        // we clear both for clarity. SET LOCAL is session-scoped and
        // is released when the connection drops back to the pool.
        // Multi-statement SQL would trip sqlx's prepared-statement
        // protocol ("cannot insert multiple commands into a prepared
        // statement"); split into two separate executes.
        sqlx::query("SET statement_timeout = 0")
            .execute(&mut *bootstrap_lock_conn)
            .await
            .map_err(|e| StoreError::BackendUnavailable {
                backend: "postgres".to_string(),
                detail: format!("clear statement_timeout on bootstrap lock connection: {e}"),
            })?;
        sqlx::query("SET lock_timeout = 0")
            .execute(&mut *bootstrap_lock_conn)
            .await
            .map_err(|e| StoreError::BackendUnavailable {
                backend: "postgres".to_string(),
                detail: format!("clear lock_timeout on bootstrap lock connection: {e}"),
            })?;
        sqlx::query("SELECT pg_advisory_lock($1)")
            .bind(MIGRATION_ADVISORY_LOCK_KEY)
            .execute(&mut *bootstrap_lock_conn)
            .await
            .map_err(|e| StoreError::BackendUnavailable {
                backend: "postgres".to_string(),
                detail: format!("acquire bootstrap pg_advisory_lock: {e}"),
            })?;

        // Run the full bootstrap inside an async block so we can
        // ALWAYS release the lock — even if any error propagates.
        // `async move` captures `pool` so the final `Self { pool, ... }`
        // construction can consume it. `bootstrap_lock_conn` lives in
        // the outer scope with its own Arc ref to the pool, so the move
        // doesn't invalidate the lock-holding connection.
        let bootstrap_result: StoreResult<Self> = async move {
            // Bootstrap schema — idempotent. The bundled template uses
            // `vector({EMBEDDING_DIM})` for the two vector columns; we
            // substitute the caller's chosen dim here. CREATE TABLE IF NOT
            // EXISTS means the dim only "takes" on first init; subsequent
            // calls against an already-populated schema are no-ops.
            //
            // The retry loop is still in place as defense-in-depth for any
            // residual catalog-level race the advisory lock can't cover
            // (e.g., a third process bypassing the lock entirely).
            let init_sql = render_schema_sql(INIT_SCHEMA, dim);
            let mut last_err: Option<sqlx::Error> = None;
            for attempt in 0..5_u32 {
                match sqlx::raw_sql(&init_sql).execute(&pool).await {
                    Ok(_) => {
                        last_err = None;
                        break;
                    }
                    Err(e) => {
                        let msg = e.to_string();
                        let is_concurrent_init = msg.contains("pg_extension_name_index")
                            || msg.contains("tuple concurrently updated")
                            || msg.contains("duplicate key value")
                            || msg.contains("deadlock detected")
                            || msg.contains("concurrent update")
                            || msg.contains("could not serialize access");
                        if !is_concurrent_init || attempt == 4 {
                            last_err = Some(e);
                            break;
                        }
                        let backoff_ms = 50u64 << attempt;
                        tokio::time::sleep(tokio::time::Duration::from_millis(backoff_ms)).await;
                    }
                }
            }
            if let Some(e) = last_err {
                return Err(StoreError::BackendUnavailable {
                    backend: "postgres".to_string(),
                    detail: format!("init schema: {e}"),
                });
            }

        // Sanity-check pgvector version. We support 0.7.x–0.8.x; older
        // versions have HNSW behaviour differences we haven't tested
        // against. (#302 item 2.)
        let extver: Option<(String,)> =
            sqlx::query_as("SELECT extversion FROM pg_extension WHERE extname = 'vector'")
                .fetch_optional(&pool)
                .await
                .map_err(|e| StoreError::BackendUnavailable {
                    backend: "postgres".to_string(),
                    detail: format!("read pgvector version: {e}"),
                })?;
        if let Some((ver,)) = extver
            && !(ver.starts_with("0.7") || ver.starts_with("0.8"))
        {
            tracing::warn!(
                target: TRACE_TARGET,
                version = %ver,
                "pgvector version outside the tested range 0.7.x–0.8.x; HNSW recall may differ"
            );
        }

        // Sanity-check that the embedding column dimension matches
        // what the caller requested at connect time. A mismatch means
        // an existing schema was created with a different dim (e.g.
        // operator switched from `MiniLmL6V2` to `NomicEmbedV15` but
        // didn't run `ai-memory schema-init --embedding-dim 768`); we
        // log a WARN here so the operator notices before writes start
        // failing on a dim-mismatch insert. (#304 nit; v0.7.0 L3 made
        // the comparand parameterisable.)
        let typmod: Option<(i32,)> = sqlx::query_as(
            "SELECT atttypmod FROM pg_attribute a
             JOIN pg_class c ON c.oid = a.attrelid
             JOIN pg_namespace n ON c.relnamespace = n.oid
             WHERE c.relname = 'memories' AND a.attname = 'embedding'
             AND n.nspname = 'public'",
        )
        .fetch_optional(&pool)
        .await
        .ok()
        .flatten();
        let expected_dim = i32::try_from(dim).unwrap_or(384);
        if let Some((typmod,)) = typmod
            && typmod != expected_dim
        {
            tracing::warn!(
                target: TRACE_TARGET,
                dim = typmod,
                expected = expected_dim,
                "memories.embedding column dimension ({typmod}) does not match the requested embedder dim ({expected_dim}); run `ai-memory schema-init --store-url <url> --embedding-dim {expected_dim}` to convert in place"
            );
        }

        // v0.7 J1 — detect Apache AGE so Track J can dispatch
        // knowledge-graph traversals through Cypher when the extension
        // is installed. Falls back to the recursive-CTE path on
        // missing extension OR query error: AGE is opt-in, never a
        // bootstrap blocker. The resolved tag is surfaced on the SAL
        // handle via [`Self::kg_backend`] for J2-J7.
        let kg_backend = detect_kg_backend(&pool).await;
        tracing::info!(
            target: TRACE_TARGET,
            kg_backend = %kg_backend,
            "Postgres KG backend: {}",
            match kg_backend {
                KgBackend::Age => "AGE",
                KgBackend::Cte => "CTE",
            }
        );

        // v0.7.0.1 G4 — when AGE is the resolved KG backend, ensure
        // the `memory_graph` projection exists at connect time so
        // every subsequent link write can `MERGE` nodes/edges into it
        // without racing the bootstrap. `create_graph` is idempotent
        // by error message ("graph 'memory_graph' already exists" is
        // not a fatal condition); the production J1 graph-prep
        // scripts ran the same call out-of-band before this change.
        //
        // We acquire a ONE-SHOT connection from the pool, apply the
        // bootstrap, then drop the connection so the SET search_path
        // doesn't bleed into any future connection re-checked out
        // from the pool. (sqlx's pool resets stale connections on
        // checkout but the reset only fires on the NEXT use; until
        // then the pool may hand the connection back without
        // clearing GUC state.)
        if matches!(kg_backend, KgBackend::Age)
            && let Err(e) = ensure_memory_graph(&pool).await
        {
            tracing::warn!(
                target: TRACE_TARGET,
                error = %e,
                "ensure memory_graph projection failed at connect; KG link projection will degrade silently"
            );
        }

            // Run schema migrations after bootstrap schema is loaded.
            // We hold the bootstrap advisory lock at the outer scope, so
            // call the lock-free body `migrate_locked()` here to avoid a
            // second acquire-from-different-session that would deadlock.
            let store = Self { pool, kg_backend };
            store.migrate_locked().await?;

            Ok(store)
        }
        .await;

        // Always release the bootstrap advisory lock, even on the error
        // path. pg_advisory_unlock_all() releases all locks held in this
        // session, more robust than pg_advisory_unlock(key) against any
        // accidental re-acquire inside the bootstrap. Best-effort —
        // implicit release on connection drop is the backstop.
        let _ = sqlx::query("SELECT pg_advisory_unlock_all()")
            .execute(&mut *bootstrap_lock_conn)
            .await;
        drop(bootstrap_lock_conn);

        bootstrap_result
    }

    /// Issue #877 (HIGH-SEV): Connect with an explicit embedding dim and
    /// auto-migrate the live `memories.embedding` (+ archive) column to
    /// `vector(<dim>)` when the existing schema disagrees.
    ///
    /// This is the daemon-bootstrap entry point. The plain
    /// [`Self::connect_with_dim`] would WARN and continue if the schema
    /// was created with a different dim (e.g. a fresh container picked up
    /// `DEFAULT_EMBEDDING_DIM` = 384 from a no-flag boot, then the
    /// operator switched the configured embedder to `nomic_embed_v15`
    /// (768)). The result was every HTTP POST `/api/v1/memories` rejected
    /// at pgvector with `expected 384 dimensions, not 768` — a hard
    /// production outage Plan-C retest surfaced.
    ///
    /// Behaviour:
    /// - Connect + bootstrap exactly like [`Self::connect_with_dim_and_timeout`].
    /// - Probe `current_embedding_dim()`. If it equals `dim`, return Ok.
    /// - If it differs (or is missing), invoke
    ///   [`Self::migrate_embedding_dim`] which is destructive on the
    ///   embedding column (existing vectors are NULLed; rows themselves
    ///   survive). Operators must re-embed after.
    /// - The migration is gated to the supported dim set (384, 768); any
    ///   other value bubbles `StoreError::InvalidInput` from the
    ///   sub-call.
    ///
    /// Existing callers ([`Self::connect`], CLI `schema-init`) keep the
    /// non-auto-migrate semantics so a one-shot CLI tool can't silently
    /// destroy embeddings.
    ///
    /// # Errors
    ///
    /// Same as [`Self::connect_with_dim_and_timeout`], plus any error
    /// from the in-place conversion.
    pub async fn connect_with_dim_and_timeout_auto_migrate(
        url: &str,
        dim: u32,
        statement_timeout_secs: u64,
        pool_config: PoolConfig,
    ) -> StoreResult<Self> {
        let store =
            Self::connect_with_dim_and_timeout(url, dim, statement_timeout_secs, pool_config)
                .await?;

        let current = store.current_embedding_dim().await?;
        let target_i32 = i32::try_from(dim).unwrap_or(384);
        match current {
            Some(cur) if cur == target_i32 => Ok(store),
            _ => {
                tracing::warn!(
                    target: TRACE_TARGET,
                    current = ?current,
                    target = target_i32,
                    "issue #877 auto-migrate: existing memories.embedding column dim disagrees \
                     with configured embedder dim ({target_i32}); converting in place. \
                     Existing embeddings will be NULLed — re-embed required after this completes."
                );
                store.migrate_embedding_dim(dim).await?;
                Ok(store)
            }
        }
    }

    /// Knowledge-graph backend resolved at [`Self::connect`] time.
    ///
    /// v0.7 J1 substrate. J2-J7 dispatch on this value so the same
    /// `memory_kg_*` MCP wire shape can route to either Cypher (when
    /// AGE is installed) or the recursive-CTE fallback. The resolution
    /// is sticky for the life of the pool — adapters do not re-probe
    /// per call.
    #[must_use]
    pub fn kg_backend(&self) -> KgBackend {
        self.kg_backend
    }

    /// Borrow the underlying sqlx connection pool.
    ///
    /// v0.7.0 Track D #933 — adapters layered on top of the
    /// `PostgresStore` (notably the federation push DLQ sink in
    /// `src/federation/push_dlq.rs::PostgresDlqSink`) need pool access
    /// to issue raw SQL against tables that aren't yet first-class on
    /// the `MemoryStore` trait surface. Keep this accessor narrow —
    /// new behaviour should land as trait methods so the sqlite path
    /// gets parity automatically.
    #[must_use]
    pub fn pool(&self) -> &PgPool {
        &self.pool
    }

    /// Run schema migrations on the connection. Called after bootstrap schema
    /// is loaded. Reads the current schema_version, then applies all pending
    /// migrations in a transaction per version step (matching SQLite behavior
    /// in crate::storage::migrations::migrate).
    ///
    /// # Errors
    ///
    /// Returns `StoreError::BackendUnavailable` if migration fails.
    async fn migrate(&self) -> StoreResult<()> {
        // v0.7.0 ship-hardening: serialize concurrent migrate() applies
        // across processes (and across in-process parallel connect()
        // calls) via a session-scoped advisory lock. Without it, racing
        // CREATE INDEX / ADD CONSTRAINT / ALTER TYPE DDL statements
        // collide and surface as `tuple concurrently updated`,
        // `pg_class_relname_nsp_index` duplicate key, or `constraint
        // already exists`. Empirically caught during the
        // 2026-05-19 LAN-parity audit (17 of 37 cargo SAL-postgres
        // failures were this race).
        //
        // The lock is acquired on a dedicated connection held for the
        // entire migration ladder. Other callers (other processes OR
        // in-process parallel connects) block on pg_advisory_lock
        // until release, then re-read schema_version inside
        // migrate_locked() and skip via the early-return when
        // current_version >= CURRENT_SCHEMA_VERSION. The session-scoped
        // lock is released explicitly via pg_advisory_unlock_all() and
        // implicitly when the dedicated connection drops.
        let mut lock_conn = self
            .pool
            .acquire()
            .await
            .map_err(|e| to_store_err("acquire migration lock connection", e))?;

        // QC P0: clear statement_timeout / lock_timeout on the lock
        // connection so the `pg_advisory_lock` wait itself isn't
        // aborted under contention (per-session default is 30s from
        // `after_connect`). Split into two separate executes — sqlx
        // prepared-statement protocol rejects multi-statement SQL.
        sqlx::query("SET statement_timeout = 0")
            .execute(&mut *lock_conn)
            .await
            .map_err(|e| to_store_err("clear statement_timeout on migration lock connection", e))?;
        sqlx::query("SET lock_timeout = 0")
            .execute(&mut *lock_conn)
            .await
            .map_err(|e| to_store_err("clear lock_timeout on migration lock connection", e))?;

        sqlx::query("SELECT pg_advisory_lock($1)")
            .bind(MIGRATION_ADVISORY_LOCK_KEY)
            .execute(&mut *lock_conn)
            .await
            .map_err(|e| to_store_err("acquire pg_advisory_lock", e))?;

        // Run the migration body, capturing the result so we can always
        // release the lock even on a per-migration failure.
        let result = self.migrate_locked().await;

        // Release ALL advisory locks held in this session (more robust
        // than pg_advisory_unlock(key) — defends against the body
        // accidentally acquiring further locks). Best-effort: a failure
        // to unlock would still release implicitly on connection close.
        let _ = sqlx::query("SELECT pg_advisory_unlock_all()")
            .execute(&mut *lock_conn)
            .await;
        drop(lock_conn);

        result
    }

    /// The actual migration ladder body. Held under the
    /// `MIGRATION_ADVISORY_LOCK_KEY` advisory lock acquired in
    /// [`Self::migrate`] — do not call directly from outside that
    /// wrapper without holding the lock, or the cross-process
    /// serialization invariant is lost.
    async fn migrate_locked(&self) -> StoreResult<()> {
        // Read the current version from schema_version table — this is
        // re-read under the lock so racers that queued while another
        // process applied the ladder see the up-to-date value and
        // early-return.
        let current_version: Option<i32> =
            sqlx::query_scalar(crate::storage::migrations::SELECT_SCHEMA_VERSION_SQL)
                .fetch_optional(&self.pool)
                .await
                .map_err(|e| to_store_err(crate::errors::msg::READ_SCHEMA_VERSION, e))?;

        let current_version = current_version.unwrap_or(0);

        if current_version >= CURRENT_SCHEMA_VERSION {
            return Ok(());
        }

        // Apply each migration step in its own transaction for idempotence.
        // Versions 15→28 are stamped in order; each migrate_vN function is
        // independently idempotent (column-existence checks + IF NOT EXISTS
        // DDL) so re-running the migrator on a partially-stamped database
        // is safe.
        if current_version < 15 {
            self.migrate_v15().await?;
        }
        // v0.7.0 #1045 (Agent-3 #10) — v16 is intentionally skipped
        // on postgres. SQLite's v16 is `0016_v07_transcripts.sql`
        // (Form-5 conversation-transcript substrate). The postgres
        // adapter inlines the `transcripts` table directly into the
        // fresh-install schema at `src/store/postgres_schema.sql`
        // so an upgraded postgres install lands the table via the
        // schema-init path rather than an incremental ALTER ladder.
        // Skipping the v16 arm keeps the ladder numbering aligned
        // with sqlite (so `CURRENT_SCHEMA_VERSION = N` stays the
        // same value on both backends) without re-applying the
        // transcripts DDL on already-initialised postgres deployments.
        if current_version < 17 {
            self.migrate_v17().await?;
        }
        if current_version < 18 {
            self.migrate_v18().await?;
        }
        if current_version < 19 {
            self.migrate_v19().await?;
        }
        if current_version < 20 {
            self.migrate_v20().await?;
        }
        if current_version < 21 {
            self.migrate_v21().await?;
        }
        if current_version < 22 {
            self.migrate_v22().await?;
        }
        if current_version < 23 {
            self.migrate_v23().await?;
        }
        if current_version < 24 {
            self.migrate_v24().await?;
        }
        if current_version < 25 {
            self.migrate_v25().await?;
        }
        if current_version < 26 {
            self.migrate_v26().await?;
        }
        if current_version < 27 {
            self.migrate_v27().await?;
        }
        if current_version < 28 {
            self.migrate_v28().await?;
        }
        if current_version < 29 {
            // v29 connect-time pass: stamp the version once the
            // schema is conformant. The actual `vector(N)` conversion
            // is operator-initiated via `ai-memory schema-init
            // --embedding-dim <N>`; this no-op pass just records that
            // the daemon understands v29 semantics.
            self.migrate_v29_stamp().await?;
        }
        if current_version < 30 {
            self.migrate_v30().await?;
        }
        if current_version < 31 {
            self.migrate_v31().await?;
        }
        if current_version < 32 {
            self.migrate_v32().await?;
        }
        if current_version < 33 {
            self.migrate_v33().await?;
        }
        if current_version < 34 {
            self.migrate_v34().await?;
        }
        if current_version < 35 {
            self.migrate_v35().await?;
        }
        if current_version < 36 {
            self.migrate_v36().await?;
        }
        if current_version < 37 {
            self.migrate_v37().await?;
        }
        if current_version < 38 {
            self.migrate_v38().await?;
        }
        if current_version < 39 {
            self.migrate_v39().await?;
        }
        if current_version < 40 {
            self.migrate_v40().await?;
        }
        if current_version < 41 {
            self.migrate_v41().await?;
        }
        if current_version < 42 {
            self.migrate_v42().await?;
        }
        if current_version < 43 {
            self.migrate_v43().await?;
        }
        if current_version < 44 {
            self.migrate_v44().await?;
        }
        if current_version < 45 {
            self.migrate_v45().await?;
        }
        if current_version < 46 {
            self.migrate_v46().await?;
        }
        if current_version < 47 {
            self.migrate_v47().await?;
        }
        if current_version < 48 {
            self.migrate_v48().await?;
        }
        if current_version < 49 {
            self.migrate_v49().await?;
        }
        if current_version < 50 {
            self.migrate_v50().await?;
        }
        if current_version < 51 {
            self.migrate_v51().await?;
        }
        if current_version < 52 {
            self.migrate_v52().await?;
        }
        if current_version < 53 {
            self.migrate_v53().await?;
        }
        if current_version < 54 {
            self.migrate_v54().await?;
        }
        if current_version < 55 {
            self.migrate_v55().await?;
        }
        if current_version < 56 {
            self.migrate_v56().await?;
        }
        if current_version < CURRENT_SCHEMA_VERSION {
            self.migrate_v57().await?;
        }

        Ok(())
    }

    /// v30 — `memories_metadata_is_object` CHECK constraint (M15).
    ///
    /// The `scope_idx` and `agent_id_idx` generated columns project from
    /// `metadata` via `->>`; that operator silently returns NULL for
    /// any non-object JSONB (array, scalar, or NULL), which masks
    /// governance/scope-routing misconfiguration as "no scope" rows.
    /// The CHECK constraint closes that gap so a malformed metadata
    /// payload is rejected at the write boundary.
    ///
    /// Idempotent: ADD CONSTRAINT IF NOT EXISTS would be cleaner but
    /// Postgres < 14 doesn't grok that syntax; we probe pg_constraint
    /// first and add only on miss. A pre-flight scan refuses to add the
    /// constraint when existing rows would violate it so the operator
    /// gets a clear error rather than a half-applied migration.
    async fn migrate_v30(&self) -> StoreResult<()> {
        let mut tx = self
            .pool
            .begin()
            .await
            .map_err(|e| to_store_err("begin v30 tx", e))?;

        // Probe whether the constraint already exists (fresh-schema
        // installs inherit it inline from postgres_schema.sql).
        let exists: Option<(String,)> = sqlx::query_as(
            "SELECT conname FROM pg_constraint
              WHERE conname = 'memories_metadata_is_object'
                AND conrelid = 'memories'::regclass",
        )
        .fetch_optional(&mut *tx)
        .await
        .map_err(|e| to_store_err("probe memories_metadata_is_object", e))?;

        if exists.is_none() {
            // Pre-flight: reject the migration if any row would violate
            // the invariant. v0.6.x writes always stamp metadata as an
            // object so this should always be 0 in practice.
            let bad_count: i64 = sqlx::query_scalar(
                "SELECT COUNT(*) FROM memories \
                 WHERE jsonb_typeof(metadata) IS DISTINCT FROM 'object'",
            )
            .fetch_one(&mut *tx)
            .await
            .map_err(|e| to_store_err("count non-object metadata rows", e))?;

            if bad_count > 0 {
                return Err(StoreError::IntegrityFailed {
                    detail: format!(
                        "v30 migration aborted: {bad_count} memories have non-object metadata; \
                         repair them before re-running"
                    ),
                });
            }

            sqlx::query(
                "ALTER TABLE memories \
                 ADD CONSTRAINT memories_metadata_is_object \
                 CHECK (jsonb_typeof(metadata) = 'object') NOT VALID",
            )
            .execute(&mut *tx)
            .await
            .map_err(|e| to_store_err("add memories_metadata_is_object constraint", e))?;

            sqlx::query("ALTER TABLE memories VALIDATE CONSTRAINT memories_metadata_is_object")
                .execute(&mut *tx)
                .await
                .map_err(|e| to_store_err("validate memories_metadata_is_object constraint", e))?;
        }

        record_schema_version(&mut tx, 30).await?;

        tx.commit()
            .await
            .map_err(|e| to_store_err("commit v30 migration", e))?;

        tracing::info!(
            target: TRACE_TARGET,
            "schema migration v30 applied (memories_metadata_is_object CHECK)"
        );
        Ok(())
    }

    /// v31 — `memories.reflection_depth INTEGER NOT NULL DEFAULT 0`
    /// (v0.7.0 Task 1/8, recursive learning).
    ///
    /// Adds the column that tracks each memory's depth in the substrate-
    /// native reflection recursion tree (`0` for caller-minted rows,
    /// positive for synthesised reflections). Mirrors the SQLite v29
    /// migration in `src/db.rs`.
    ///
    /// Idempotent via `ADD COLUMN IF NOT EXISTS` (Postgres 14+) — fresh
    /// schemas pick the column up inline from `postgres_schema.sql`, so
    /// a fresh install never runs this step. The migration body is
    /// pulled from `migrations/postgres/0013_v0700_reflection_depth.sql`
    /// at compile time via `include_str!` so the SQL stays operator-
    /// inspectable alongside the rest of the per-version migration
    /// scripts.
    async fn migrate_v31(&self) -> StoreResult<()> {
        let mut tx = self
            .pool
            .begin()
            .await
            .map_err(|e| to_store_err("begin v31 tx", e))?;

        sqlx::raw_sql(MIGRATION_V31_REFLECTION_DEPTH)
            .execute(&mut *tx)
            .await
            .map_err(|e| to_store_err("apply v31 reflection_depth", e))?;

        record_schema_version(&mut tx, 31).await?;

        tx.commit()
            .await
            .map_err(|e| to_store_err("commit v31 migration", e))?;

        tracing::info!(
            target: TRACE_TARGET,
            "schema migration v31 applied (memories.reflection_depth column)"
        );
        Ok(())
    }

    /// v32 — SQL-side CHECK constraint on `memory_links.relation`
    /// (v0.7.0 v0.7.1-fold, #687/#688).
    ///
    /// Mirrors SQLite schema v33. Postgres's `ALTER TABLE ADD
    /// CONSTRAINT` supports CHECK clauses directly, so this is a
    /// one-statement DDL gated behind a `pg_constraint` probe for
    /// idempotency. Fresh installs inherit the constraint inline from
    /// `postgres_schema.sql`; this migration only fires on a pre-v32
    /// Postgres deployment that already has `memory_links` rows in it.
    ///
    /// The migration body lives in
    /// `migrations/postgres/0014_v07_memory_links_relation_check.sql`
    /// so operators can inspect / replay the DDL outside the daemon.
    async fn migrate_v32(&self) -> StoreResult<()> {
        let mut tx = self
            .pool
            .begin()
            .await
            .map_err(|e| to_store_err("begin v32 tx", e))?;

        sqlx::raw_sql(MIGRATION_V32_LINK_RELATION_CHECK)
            .execute(&mut *tx)
            .await
            .map_err(|e| to_store_err("apply v32 memory_links.relation CHECK", e))?;

        record_schema_version(&mut tx, 32).await?;

        tx.commit()
            .await
            .map_err(|e| to_store_err("commit v32 migration", e))?;

        tracing::info!(
            target: TRACE_TARGET,
            "schema migration v32 applied (memory_links.relation CHECK constraint)"
        );
        Ok(())
    }

    /// v33 — `signed_events.prev_hash` + `signed_events.sequence`
    /// (v0.7.0 V-4 closeout, #698).
    ///
    /// Adds the cross-row hash chain columns + UNIQUE INDEX on
    /// `sequence`, then backfills `prev_hash` and `sequence` on
    /// pre-existing rows using the application-layer canonical-bytes
    /// encoding from `signed_events::canonical_chain_bytes`.
    /// Mirrors SQLite schema v34.
    ///
    /// Idempotent via `ADD COLUMN IF NOT EXISTS` (Postgres 14+) +
    /// `WHERE sequence IS NULL` on the backfill loop. Re-running on
    /// an already-backfilled DB is a no-op. Fresh installs inherit
    /// the columns inline from `postgres_schema.sql`, so this step
    /// only fires on pre-v33 Postgres deployments that already have
    /// `signed_events` rows.
    async fn migrate_v33(&self) -> StoreResult<()> {
        use crate::signed_events::{ZERO_HASH, canonical_chain_bytes};
        use sha2::{Digest, Sha256};

        let mut tx = self
            .pool
            .begin()
            .await
            .map_err(|e| to_store_err("begin v33 tx", e))?;

        // Add columns + UNIQUE INDEX (idempotent).
        sqlx::raw_sql(MIGRATION_V33_SIGNED_EVENTS_CHAIN)
            .execute(&mut *tx)
            .await
            .map_err(|e| to_store_err("apply v33 signed_events chain", e))?;

        // Backfill prev_hash + sequence on rows that still have NULL
        // sequence, ordered by the natural insertion order (the
        // `ctid` row id is reliable here because we only do INSERTs
        // on this table — no UPDATE has moved rows around). We
        // stream rows server-side so the backfill scales even on
        // large pre-existing audit tables.
        let rows: Vec<(
            String,
            String,
            String,
            Vec<u8>,
            Option<Vec<u8>>,
            String,
            chrono::DateTime<chrono::Utc>,
        )> = sqlx::query_as(
            "SELECT id, agent_id, event_type, payload_hash, signature, attest_level, \
                        timestamp \
                 FROM signed_events \
                 WHERE sequence IS NULL \
                 ORDER BY ctid ASC",
        )
        .fetch_all(&mut *tx)
        .await
        .map_err(|e| to_store_err("v33 backfill: select pending", e))?;

        if !rows.is_empty() {
            let mut next_seq: i64 =
                sqlx::query_scalar("SELECT COALESCE(MAX(sequence), 0) FROM signed_events")
                    .fetch_one(&mut *tx)
                    .await
                    .map_err(|e| to_store_err("v33 backfill: read max sequence", e))?;

            let mut prev_hash: [u8; 32] = ZERO_HASH;
            for (id, agent_id, event_type, payload_hash, signature, attest_level, ts_dt) in rows {
                next_seq += 1;
                let event = crate::signed_events::SignedEvent {
                    id: id.clone(),
                    agent_id,
                    event_type,
                    payload_hash,
                    signature,
                    attest_level,
                    timestamp: ts_dt.to_rfc3339(),
                    prev_hash: Vec::new(),
                    sequence: next_seq,
                };
                sqlx::query("UPDATE signed_events SET prev_hash = $1, sequence = $2 WHERE id = $3")
                    .bind(prev_hash.to_vec())
                    .bind(next_seq)
                    .bind(&id)
                    .execute(&mut *tx)
                    .await
                    .map_err(|e| to_store_err("v33 backfill: UPDATE row", e))?;
                let canon = canonical_chain_bytes(&event);
                let mut hasher = Sha256::new();
                hasher.update(&canon);
                prev_hash.copy_from_slice(&hasher.finalize());
            }
        }

        record_schema_version(&mut tx, 33).await?;

        tx.commit()
            .await
            .map_err(|e| to_store_err("commit v33 migration", e))?;

        tracing::info!(
            target: TRACE_TARGET,
            "schema migration v33 applied (signed_events prev_hash + sequence chain)"
        );
        Ok(())
    }

    /// v34 — context-offload substrate primitive (QW-3).
    ///
    /// Creates the `offloaded_blobs` table backing
    /// `src/offload/mod.rs`. Mirrors SQLite schema v35. Pure
    /// idempotent CREATE TABLE / CREATE INDEX — no application-side
    /// backfill.
    ///
    /// #1690 (verified non-gap): this table is created for schema
    /// PARITY only and carries NO live rows on a postgres-backed
    /// deployment. `ContextOffloader` (`src/offload/mod.rs`) is bound to
    /// a rusqlite `Connection` and is reachable solely from the MCP
    /// `memory_offload` / `memory_deref` tools — which are structurally
    /// sqlite-only (#1675/n24) — with NO HTTP route and NO `MemoryStore`
    /// trait method. So offload blobs only ever land in the sqlite
    /// connection, where `crate::offload::sweep_expired` (wired into the
    /// `serve` bootstrap via `background::offload_ttl_sweep`) prunes
    /// them. There is therefore no postgres offload data to sweep and no
    /// postgres SAL offload-sweep method is needed; if a future HTTP/SAL
    /// offload write path lands, it must add one here.
    async fn migrate_v34(&self) -> StoreResult<()> {
        let mut tx = self
            .pool
            .begin()
            .await
            .map_err(|e| to_store_err("begin v34 tx", e))?;

        sqlx::raw_sql(MIGRATION_V34_OFFLOADED_BLOBS)
            .execute(&mut *tx)
            .await
            .map_err(|e| to_store_err("apply v34 offloaded_blobs", e))?;

        record_schema_version(&mut tx, 34).await?;

        tx.commit()
            .await
            .map_err(|e| to_store_err("commit v34 migration", e))?;

        tracing::info!(
            target: TRACE_TARGET,
            "schema migration v34 applied (offloaded_blobs context-offload substrate)"
        );
        Ok(())
    }

    /// v35 — substrate-level atomisation foundation (v0.7.0 WT-1-A).
    ///
    /// Adds two nullable columns to `memories`:
    ///
    /// - `atomised_into INTEGER` — NULL on legacy rows; positive integer
    ///   on rows that have been atomised by the WT-1-B pass.
    /// - `atom_of TEXT REFERENCES memories(id)` — for atom rows, points
    ///   back to the parent memory; NULL on non-atom rows.
    ///
    /// Also extends the `memory_links.relation` closed-taxonomy CHECK
    /// constraint with the new `derives_from` variant (atomisation
    /// provenance edges atom -> parent). Mirrors SQLite schema v36
    /// (`migrations/sqlite/0030_v07_atomisation.sql`).
    ///
    /// Postgres-native `ADD COLUMN IF NOT EXISTS` + `DO $$ ... $$`
    /// block in the SQL file keeps this fully idempotent. Fresh
    /// installs inherit the columns + extended CHECK inline from
    /// `postgres_schema.sql`; this migration only fires on a
    /// pre-v35 Postgres deployment with pre-existing `memories` /
    /// `memory_links` rows.
    async fn migrate_v35(&self) -> StoreResult<()> {
        let mut tx = self
            .pool
            .begin()
            .await
            .map_err(|e| to_store_err("begin v35 tx", e))?;

        sqlx::raw_sql(MIGRATION_V35_ATOMISATION)
            .execute(&mut *tx)
            .await
            .map_err(|e| to_store_err("apply v35 atomisation", e))?;

        record_schema_version(&mut tx, 35).await?;

        tx.commit()
            .await
            .map_err(|e| to_store_err("commit v35 migration", e))?;

        tracing::info!(
            target: TRACE_TARGET,
            "schema migration v35 applied (memories.atomised_into + atom_of columns; \
             memory_links.relation CHECK extended with derives_from)"
        );
        Ok(())
    }

    /// v36 — Persona-as-artifact substrate primitive (QW-2).
    ///
    /// Adds the `memories.entity_id` + `memories.persona_version`
    /// columns plus the partial index `idx_personas_by_entity`
    /// covering Persona-kind rows. Mirrors SQLite schema v37. Pure
    /// idempotent ADD COLUMN IF NOT EXISTS + CREATE INDEX IF NOT
    /// EXISTS — no application-side backfill (non-Persona rows
    /// keep their NULL payloads).
    async fn migrate_v36(&self) -> StoreResult<()> {
        let mut tx = self
            .pool
            .begin()
            .await
            .map_err(|e| to_store_err("begin v36 tx", e))?;

        sqlx::raw_sql(MIGRATION_V36_PERSONA)
            .execute(&mut *tx)
            .await
            .map_err(|e| to_store_err("apply v36 persona", e))?;

        record_schema_version(&mut tx, 36).await?;

        tx.commit()
            .await
            .map_err(|e| to_store_err("commit v36 migration", e))?;

        tracing::info!(
            target: TRACE_TARGET,
            "schema migration v36 applied (persona-as-artifact entity_id + persona_version)"
        );
        Ok(())
    }

    /// v37 — Form 4 fact-provenance closeout (issue #757).
    ///
    /// Adds the `memories.citations` (JSON array of Citation objects,
    /// default `[]`), `memories.source_uri` (first-class URI-form
    /// pointer), and `memories.source_span` (JSON byte-range into
    /// the parent source body) columns plus the partial index
    /// `idx_memories_source_uri` covering the `--source-uri-prefix`
    /// recall filter. Mirrors SQLite schema v38. Pure additive
    /// ADD COLUMN IF NOT EXISTS + CREATE INDEX IF NOT EXISTS — no
    /// application-side backfill (legacy rows take the SQL DEFAULT
    /// for citations and NULL for the URI/span columns).
    async fn migrate_v37(&self) -> StoreResult<()> {
        let mut tx = self
            .pool
            .begin()
            .await
            .map_err(|e| to_store_err("begin v37 tx", e))?;

        sqlx::raw_sql(MIGRATION_V37_FORM4_PROVENANCE)
            .execute(&mut *tx)
            .await
            .map_err(|e| to_store_err("apply v37 form4 provenance", e))?;

        record_schema_version(&mut tx, 37).await?;

        tx.commit()
            .await
            .map_err(|e| to_store_err("commit v37 migration", e))?;

        tracing::info!(
            target: TRACE_TARGET,
            "schema migration v37 applied (form4 fact-provenance citations + source_uri + source_span)"
        );
        Ok(())
    }

    /// v38 — Form 5 auto-confidence + shadow-mode + calibration tooling
    /// closeout (issue #758).
    ///
    /// Adds three columns on `memories` (`confidence_source TEXT NOT NULL
    /// DEFAULT 'caller_provided'`, `confidence_signals TEXT NULL`,
    /// `confidence_decayed_at TEXT NULL`) plus the
    /// `confidence_shadow_observations` table backing per-recall shadow-
    /// mode telemetry. Mirrors SQLite schema v39. Pure additive ADD
    /// COLUMN IF NOT EXISTS + CREATE TABLE IF NOT EXISTS — no
    /// application-side backfill (legacy rows take the SQL DEFAULT for
    /// `confidence_source` and NULL for the signals/decay columns).
    async fn migrate_v38(&self) -> StoreResult<()> {
        let mut tx = self
            .pool
            .begin()
            .await
            .map_err(|e| to_store_err("begin v38 tx", e))?;

        sqlx::raw_sql(MIGRATION_V38_FORM5_CONFIDENCE)
            .execute(&mut *tx)
            .await
            .map_err(|e| to_store_err("apply v38 form5 confidence", e))?;

        record_schema_version(&mut tx, 38).await?;

        tx.commit()
            .await
            .map_err(|e| to_store_err("commit v38 migration", e))?;

        tracing::info!(
            target: TRACE_TARGET,
            "schema migration v38 applied (form5 auto-confidence + shadow-mode + calibration)"
        );
        Ok(())
    }

    /// v39 — Cluster-C SEC-3 closeout (issue #767): `signed_events_dlq`
    /// table backing the deferred-audit drainer's dead-letter-queue
    /// path.
    ///
    /// Pure additive CREATE TABLE IF NOT EXISTS + indexes — fully
    /// idempotent on re-run. Mirrors SQLite schema v40. No backfill
    /// (the DLQ starts empty on every existing deployment).
    async fn migrate_v39(&self) -> StoreResult<()> {
        let mut tx = self
            .pool
            .begin()
            .await
            .map_err(|e| to_store_err("begin v39 tx", e))?;

        sqlx::raw_sql(MIGRATION_V39_SIGNED_EVENTS_DLQ)
            .execute(&mut *tx)
            .await
            .map_err(|e| to_store_err("apply v39 signed_events_dlq", e))?;

        record_schema_version(&mut tx, 39).await?;

        tx.commit()
            .await
            .map_err(|e| to_store_err("commit v39 migration", e))?;

        tracing::info!(
            target: TRACE_TARGET,
            "schema migration v39 applied (signed_events_dlq dead-letter queue)"
        );
        Ok(())
    }

    /// v40 — Cluster G shadow-mode retention + denormalised `source`
    /// column + compound `(namespace, source, observed_at)` index
    /// supporting the calibration scan (issue #767, PERF-4 + PERF-12).
    ///
    /// Adds a `source TEXT NOT NULL DEFAULT 'unknown'` column on
    /// `confidence_shadow_observations`, backfills from the joined
    /// `memories.source` row, and creates the compound index. The SQL
    /// batch is fully idempotent (ADD COLUMN IF NOT EXISTS + UPDATE
    /// guarded by `WHERE source = 'unknown'` + CREATE INDEX IF NOT
    /// EXISTS) so a partial-failure replay is safe.
    async fn migrate_v40(&self) -> StoreResult<()> {
        let mut tx = self
            .pool
            .begin()
            .await
            .map_err(|e| to_store_err("begin v40 tx", e))?;

        sqlx::raw_sql(MIGRATION_V40_SHADOW_RETENTION)
            .execute(&mut *tx)
            .await
            .map_err(|e| to_store_err("apply v40 shadow retention", e))?;

        record_schema_version(&mut tx, 40).await?;

        tx.commit()
            .await
            .map_err(|e| to_store_err("commit v40 migration", e))?;

        tracing::info!(
            target: TRACE_TARGET,
            "schema migration v40 applied (cluster-G shadow retention + denormalised source + compound index)"
        );
        Ok(())
    }

    /// v41 — polish PERF-8 (issue #781) auto-persona indexed entity-id
    /// column replacing the SQLite content-LIKE full-table scan.
    ///
    /// Adds `memories.mentioned_entity_id TEXT` + partial index
    /// `WHERE mentioned_entity_id IS NOT NULL`. Backfill (extracting
    /// the entity descriptor from `metadata.entity_id` or a
    /// `[entity:X]` title marker on pre-existing reflection rows) is
    /// folded into the SQL batch. Pure additive ADD COLUMN IF NOT
    /// EXISTS + UPDATE + CREATE INDEX IF NOT EXISTS — idempotent.
    ///
    /// Schema parity only — the auto-persona executor is SQLite-only
    /// (`PersonaGenerator` + `hooks::post_reflect::auto_persona` thread
    /// a `rusqlite::Connection`). A future PG-native implementation
    /// reads from this same indexed column without a second migration.
    async fn migrate_v41(&self) -> StoreResult<()> {
        let mut tx = self
            .pool
            .begin()
            .await
            .map_err(|e| to_store_err("begin v41 tx", e))?;

        sqlx::raw_sql(MIGRATION_V41_AUTO_PERSONA_ENTITY_ID)
            .execute(&mut *tx)
            .await
            .map_err(|e| to_store_err("apply v41 auto_persona entity-id", e))?;

        record_schema_version(&mut tx, 41).await?;

        tx.commit()
            .await
            .map_err(|e| to_store_err("commit v41 migration", e))?;

        tracing::info!(
            target: TRACE_TARGET,
            "schema migration v41 applied (PERF-8 auto_persona mentioned_entity_id + partial index)"
        );
        Ok(())
    }

    /// v0.7.0 Provenance Gap 1 (issue #884) — adds `memories.version`
    /// optimistic-concurrency counter. Mirrors SQLite schema v45.
    async fn migrate_v42(&self) -> StoreResult<()> {
        let mut tx = self
            .pool
            .begin()
            .await
            .map_err(|e| to_store_err("begin v42 tx", e))?;

        sqlx::raw_sql(MIGRATION_V42_MEMORY_VERSION)
            .execute(&mut *tx)
            .await
            .map_err(|e| to_store_err("apply v42 memory_version", e))?;

        record_schema_version(&mut tx, 42).await?;

        tx.commit()
            .await
            .map_err(|e| to_store_err("commit v42 migration", e))?;

        tracing::info!(
            target: TRACE_TARGET,
            "schema migration v42 applied (Provenance Gap 1: memories.version)"
        );
        Ok(())
    }

    /// v0.7.0 Provenance Gap 2 (issue #885) — re-asserts
    /// `memories.source_uri` column + partial index for legacy upgrade
    /// paths and backfills the column from metadata/citations. Mirrors
    /// SQLite schema v46.
    async fn migrate_v43(&self) -> StoreResult<()> {
        let mut tx = self
            .pool
            .begin()
            .await
            .map_err(|e| to_store_err("begin v43 tx", e))?;

        sqlx::raw_sql(MIGRATION_V43_SOURCE_URI_UPGRADE)
            .execute(&mut *tx)
            .await
            .map_err(|e| to_store_err("apply v43 source_uri upgrade", e))?;

        record_schema_version(&mut tx, 43).await?;

        tx.commit()
            .await
            .map_err(|e| to_store_err("commit v43 migration", e))?;

        tracing::info!(
            target: TRACE_TARGET,
            "schema migration v43 applied (Provenance Gap 2: source_uri upgrade + backfill)"
        );
        Ok(())
    }

    /// v0.7.0 Gap 3 (issue #886) — recall_observations ledger table.
    /// Mirrors SQLite schema v47.
    async fn migrate_v44(&self) -> StoreResult<()> {
        let mut tx = self
            .pool
            .begin()
            .await
            .map_err(|e| to_store_err("begin v44 tx", e))?;

        sqlx::raw_sql(MIGRATION_V44_RECALL_OBSERVATIONS)
            .execute(&mut *tx)
            .await
            .map_err(|e| to_store_err("apply v44 recall_observations", e))?;

        record_schema_version(&mut tx, 44).await?;

        tx.commit()
            .await
            .map_err(|e| to_store_err("commit v44 migration", e))?;

        tracing::info!(
            target: TRACE_TARGET,
            "schema migration v44 applied (Gap 3: recall_observations ledger)"
        );
        Ok(())
    }

    /// v0.7.0 Provenance Gap 5 (issue #888) — Gap-5 append-and-archive
    /// support indexes.
    async fn migrate_v45(&self) -> StoreResult<()> {
        let mut tx = self
            .pool
            .begin()
            .await
            .map_err(|e| to_store_err("begin v45 tx", e))?;

        sqlx::raw_sql(MIGRATION_V45_EDIT_SOURCE_ARCHIVE)
            .execute(&mut *tx)
            .await
            .map_err(|e| to_store_err("apply v45 edit_source archive", e))?;

        record_schema_version(&mut tx, 45).await?;

        tx.commit()
            .await
            .map_err(|e| to_store_err("commit v45 migration", e))?;

        tracing::info!(
            target: TRACE_TARGET,
            "schema migration v45 applied (Provenance Gap 5: archive_reason indexes)"
        );
        Ok(())
    }

    /// v0.7.0 issue #860 — defensive `ADD COLUMN IF NOT EXISTS` on the
    /// four temporal-validity + attestation columns on `memory_links`.
    async fn migrate_v46(&self) -> StoreResult<()> {
        let mut tx = self
            .pool
            .begin()
            .await
            .map_err(|e| to_store_err("begin v46 tx", e))?;

        sqlx::raw_sql(MIGRATION_V46_LINKS_TEMPORAL_COLUMNS)
            .execute(&mut *tx)
            .await
            .map_err(|e| to_store_err("apply v46 links temporal columns", e))?;

        record_schema_version(&mut tx, 46).await?;

        tx.commit()
            .await
            .map_err(|e| to_store_err("commit v46 migration", e))?;

        tracing::info!(
            target: TRACE_TARGET,
            "schema migration v46 applied (#860: memory_links temporal + attest columns)"
        );
        Ok(())
    }

    /// v47 — Apply the orphaned persona-signing-atomicity CHECK constraint
    /// on `memory_links` (#902). Sqlite parity is migration
    /// `0037_v07_persona_signing_atomicity.sql`. The SQL backfills phantom
    /// rows to `attest_level='unsigned'` BEFORE adding the CHECK so legacy
    /// DBs don't trip constraint creation.
    async fn migrate_v47(&self) -> StoreResult<()> {
        let mut tx = self
            .pool
            .begin()
            .await
            .map_err(|e| to_store_err("begin v47 tx", e))?;

        sqlx::raw_sql(MIGRATION_V47_PERSONA_SIGNING_ATOMICITY)
            .execute(&mut *tx)
            .await
            .map_err(|e| to_store_err("apply v47 persona signing atomicity", e))?;

        record_schema_version(&mut tx, 47).await?;

        tx.commit()
            .await
            .map_err(|e| to_store_err("commit v47 migration", e))?;

        tracing::info!(
            target: TRACE_TARGET,
            "schema migration v47 applied (#902: memory_links attest+signature atomic CHECK)"
        );
        Ok(())
    }

    /// v48 — Federation push DLQ table (Track D #933).
    ///
    /// Adds `federation_push_dlq` (id BIGSERIAL, memory_id TEXT, peer_id
    /// TEXT, payload_json JSONB, attempt_count INTEGER, last_error TEXT,
    /// failed_at TIMESTAMPTZ, replayed_at TIMESTAMPTZ NULL) plus three
    /// indexes (pending-rows-by-failed_at, per-peer pending, partial
    /// unique on `(memory_id, peer_id) WHERE replayed_at IS NULL`).
    /// Pure additive CREATE TABLE IF NOT EXISTS — fully idempotent.
    /// Mirrors SQLite schema v48 / `migrations/sqlite/0041_v07_federation_push_dlq.sql`.
    async fn migrate_v48(&self) -> StoreResult<()> {
        let mut tx = self
            .pool
            .begin()
            .await
            .map_err(|e| to_store_err("begin v48 tx", e))?;

        sqlx::raw_sql(MIGRATION_V48_FEDERATION_PUSH_DLQ)
            .execute(&mut *tx)
            .await
            .map_err(|e| to_store_err("apply v48 federation push DLQ", e))?;

        record_schema_version(&mut tx, 48).await?;

        tx.commit()
            .await
            .map_err(|e| to_store_err("commit v48 migration", e))?;

        tracing::info!(
            target: TRACE_TARGET,
            "schema migration v48 applied (#933: federation_push_dlq table)"
        );
        Ok(())
    }

    /// v49 — #1025 (CRITICAL, 2026-05-21): archived_memories full
    /// v0.7.0 column carry. Pre-#1025 archive→restore round-trips
    /// silently erased 14 v0.7.0 fields. Pure additive ALTER TABLE
    /// ADD COLUMN IF NOT EXISTS — fully idempotent + replay-safe.
    /// Columns nullable so already-archived legacy rows stay valid.
    async fn migrate_v49(&self) -> StoreResult<()> {
        let mut tx = self
            .pool
            .begin()
            .await
            .map_err(|e| to_store_err("begin v49 tx", e))?;

        sqlx::raw_sql(
            "ALTER TABLE archived_memories
                ADD COLUMN IF NOT EXISTS reflection_depth INTEGER,
                ADD COLUMN IF NOT EXISTS atomised_into INTEGER,
                ADD COLUMN IF NOT EXISTS atom_of TEXT,
                ADD COLUMN IF NOT EXISTS memory_kind TEXT,
                ADD COLUMN IF NOT EXISTS entity_id TEXT,
                ADD COLUMN IF NOT EXISTS persona_version INTEGER,
                ADD COLUMN IF NOT EXISTS citations TEXT,
                ADD COLUMN IF NOT EXISTS source_uri TEXT,
                ADD COLUMN IF NOT EXISTS source_span TEXT,
                ADD COLUMN IF NOT EXISTS confidence_source TEXT,
                ADD COLUMN IF NOT EXISTS confidence_signals TEXT,
                ADD COLUMN IF NOT EXISTS confidence_decayed_at TEXT,
                ADD COLUMN IF NOT EXISTS mentioned_entity_id TEXT,
                ADD COLUMN IF NOT EXISTS version BIGINT",
        )
        .execute(&mut *tx)
        .await
        .map_err(|e| to_store_err("apply v49 archived_memories column extension", e))?;

        record_schema_version(&mut tx, 49).await?;

        tx.commit()
            .await
            .map_err(|e| to_store_err("commit v49 migration", e))?;

        tracing::info!(
            target: TRACE_TARGET,
            "schema migration v49 applied (#1025: archived_memories full v0.7.0 column carry)"
        );
        Ok(())
    }

    /// v50 — #1156 (2026-05-23): per-namespace K8 quota dimension
    /// extension. Extends the `agent_quotas` PRIMARY KEY from
    /// `(agent_id)` to `(agent_id, namespace)` so per-namespace
    /// allotments hold even when a single agent operates across many
    /// namespaces. Pre-v50 rows backfill to the `_global` namespace
    /// sentinel so historical accounting is preserved verbatim;
    /// callers that don't supply a namespace continue to land on
    /// `_global`, preserving pre-#1156 byte-for-byte behaviour at
    /// the public-API boundary.
    ///
    /// Postgres allows altering an existing PRIMARY KEY in place
    /// (unlike SQLite), so the migration is a straight `ADD COLUMN`
    /// + `DROP CONSTRAINT` + `ADD CONSTRAINT` sequence guarded by
    /// `IF NOT EXISTS` / `IF EXISTS` clauses for idempotency. The
    /// supporting `idx_agent_quotas_namespace` index lights up the
    /// per-namespace query path used by the new MCP tool / HTTP
    /// route surface.
    ///
    /// NSA CSI MCP mapping: recommendation (c) — defense-in-depth
    /// blast-radius controls on a compromised or misbehaving agent.
    async fn migrate_v50(&self) -> StoreResult<()> {
        let mut tx = self
            .pool
            .begin()
            .await
            .map_err(|e| to_store_err("begin v50 tx", e))?;

        // 1. Add the `namespace` column with the `_global` sentinel
        //    default so pre-existing rows backfill in one statement.
        //    `NOT NULL DEFAULT '_global'` is safe because the column
        //    is new — every existing row gets the default during the
        //    ALTER.
        sqlx::raw_sql(
            "ALTER TABLE agent_quotas
                ADD COLUMN IF NOT EXISTS namespace TEXT NOT NULL DEFAULT '_global'",
        )
        .execute(&mut *tx)
        .await
        .map_err(|e| to_store_err("apply v50 add namespace column", e))?;

        // 2. Swap the PRIMARY KEY: drop the old `(agent_id)` PK and
        //    add the compound `(agent_id, namespace)` PK. Postgres
        //    auto-names the original PK `agent_quotas_pkey`. Wrap in
        //    a DO block so the migration is idempotent on replay.
        sqlx::raw_sql(
            "DO $$
             BEGIN
                 IF EXISTS (
                     SELECT 1 FROM pg_constraint
                     WHERE conname = 'agent_quotas_pkey'
                       AND conrelid = 'agent_quotas'::regclass
                       AND pg_get_constraintdef(oid) NOT LIKE '%namespace%'
                 ) THEN
                     ALTER TABLE agent_quotas DROP CONSTRAINT agent_quotas_pkey;
                     ALTER TABLE agent_quotas
                         ADD CONSTRAINT agent_quotas_pkey
                         PRIMARY KEY (agent_id, namespace);
                 END IF;
             END $$",
        )
        .execute(&mut *tx)
        .await
        .map_err(|e| to_store_err("apply v50 swap PK to (agent_id, namespace)", e))?;

        // 3. Index the per-namespace query path (the new MCP tool's
        //    `namespace` arg + the HTTP route's `?namespace=` query).
        sqlx::raw_sql(
            "CREATE INDEX IF NOT EXISTS idx_agent_quotas_namespace
                ON agent_quotas (namespace, agent_id)",
        )
        .execute(&mut *tx)
        .await
        .map_err(|e| to_store_err("create idx_agent_quotas_namespace", e))?;

        record_schema_version(&mut tx, 50).await?;

        tx.commit()
            .await
            .map_err(|e| to_store_err("commit v50 migration", e))?;

        tracing::info!(
            target: TRACE_TARGET,
            "schema migration v50 applied (#1156: agent_quotas per-namespace dimension)"
        );
        Ok(())
    }

    /// v51 (#1255, MED, 2026-05-25) — federation_nonce_cache parity.
    ///
    /// The `FederationNonceCache` is a daemon-process primitive that
    /// persists to the sqlite ai-memory.db regardless of which
    /// backend powers the memory store. Postgres-backed daemons keep
    /// their nonce cache in the sqlite file alongside other
    /// daemon-local state (`audit/`, keys, etc.), so this migration
    /// is intentionally a no-op DDL stub — it only records the
    /// version reach so the postgres ladder stays in lockstep with
    /// the sqlite ladder.
    ///
    /// If a future revision elects to back the nonce cache by
    /// postgres for fully-distributed deployments, the DDL would
    /// land here in this same arm.
    async fn migrate_v51(&self) -> StoreResult<()> {
        let mut tx = self
            .pool
            .begin()
            .await
            .map_err(|e| to_store_err("begin v51 tx", e))?;

        record_schema_version(&mut tx, 51).await?;

        tx.commit()
            .await
            .map_err(|e| to_store_err("commit v51 migration", e))?;

        tracing::info!(
            target: TRACE_TARGET,
            "schema migration v51 applied (#1255: federation_nonce_cache lives in sqlite; no-op postgres DDL)"
        );
        Ok(())
    }

    /// v52 (#1389) — `transcript_line_dedup` table backing the
    /// sha256-keyed idempotency layer for the four-layer capture
    /// architecture (L2 recover-on-boot + L3 substrate watcher +
    /// L4 `memory_capture_turn` MCP tool). Postgres twin of the
    /// SQLite migration at `migrations/sqlite/0044_v52_transcript_line_dedup.sql`.
    ///
    /// Schema parity with SQLite:
    /// - `sha256 BYTEA NOT NULL PRIMARY KEY` — canonical dedup key.
    /// - `memory_id TEXT NOT NULL` — created memory's id; not
    ///   FK-constrained because the recovery paths cross adapters
    ///   and the archive sweep may move the memory.
    /// - `host_kind TEXT NOT NULL` — `claude-code` / `codex` /
    ///   `gemini` / `auto`.
    /// - `transcript_path TEXT` — file path for L2/L3; NULL for L4.
    /// - `host_session_id TEXT`, `host_turn_index BIGINT` — L4
    ///   request envelope fields; NULL for L2/L3.
    /// - `recovered_at BIGINT NOT NULL` — unix epoch ms.
    ///
    /// Indexes mirror the SQLite migration: a partial index over
    /// `(host_session_id, host_turn_index)` for the L4 fast-path
    /// dedup lookup, and a `(recovered_at, host_kind)` index for
    /// operator audit-by-time queries.
    ///
    /// Pure additive — `CREATE TABLE IF NOT EXISTS` + two indexes
    /// — idempotent across re-applies.
    async fn migrate_v52(&self) -> StoreResult<()> {
        let mut tx = self
            .pool
            .begin()
            .await
            .map_err(|e| to_store_err("begin v52 tx", e))?;

        sqlx::query(
            "CREATE TABLE IF NOT EXISTS transcript_line_dedup (\
             sha256          BYTEA NOT NULL PRIMARY KEY,\
             memory_id       TEXT NOT NULL,\
             host_kind       TEXT NOT NULL,\
             transcript_path TEXT,\
             host_session_id TEXT,\
             host_turn_index BIGINT,\
             recovered_at    BIGINT NOT NULL\
             )",
        )
        .execute(&mut *tx)
        .await
        .map_err(|e| to_store_err("create transcript_line_dedup", e))?;

        sqlx::query(
            "CREATE INDEX IF NOT EXISTS idx_transcript_line_dedup_host_turn \
             ON transcript_line_dedup(host_session_id, host_turn_index) \
             WHERE host_session_id IS NOT NULL",
        )
        .execute(&mut *tx)
        .await
        .map_err(|e| to_store_err("create idx_transcript_line_dedup_host_turn", e))?;

        sqlx::query(
            "CREATE INDEX IF NOT EXISTS idx_transcript_line_dedup_recovered_at \
             ON transcript_line_dedup(recovered_at, host_kind)",
        )
        .execute(&mut *tx)
        .await
        .map_err(|e| to_store_err("create idx_transcript_line_dedup_recovered_at", e))?;

        record_schema_version(&mut tx, 52).await?;

        tx.commit()
            .await
            .map_err(|e| to_store_err("commit v52 migration", e))?;

        tracing::info!(
            target: TRACE_TARGET,
            "schema migration v52 applied (#1389: transcript_line_dedup table + indexes for layered-capture idempotency)"
        );
        Ok(())
    }

    /// v53 (R5.F5.2, #1418) — postgres no-op twin of the SQLite
    /// `memories_au` FTS5 trigger column-scoping fix.
    ///
    /// The SQLite ladder narrows the `memories_au` `AFTER UPDATE`
    /// FTS5 sync trigger to the three FTS-mirrored columns
    /// (`title`, `content`, `tags`) so hot-path UPDATEs against
    /// non-FTS columns (`embedding`, `access_count`,
    /// `last_accessed_at`, `confidence_decayed_at`, `version`) no
    /// longer pay 2 unnecessary FTS5 row ops per UPDATE.
    ///
    /// **Why this is a no-op on postgres.** The postgres backend
    /// has no equivalent FTS5 trigger — the SAL adapter uses
    /// pgvector for embeddings + tsvector primitives for full-text
    /// search, with no `AFTER UPDATE` sync trigger on the
    /// `memories` table that mirrors the SQLite `memories_au`
    /// shape. The postgres write path either writes directly to
    /// the indexed tsvector column inline or relies on the
    /// generated-column mechanism, neither of which carries the
    /// "fire on every column" failure mode this fix closes.
    ///
    /// The SQLite/postgres `CURRENT_SCHEMA_VERSION` is pinned in
    /// lockstep so a single logical schema number tracks both
    /// adapters (per the existing v51 federation_nonce_cache
    /// precedent — that migration was sqlite-only too, with the
    /// postgres twin being a version-stamp). This function
    /// records the version-reach via `record_schema_version(53)`
    /// inside a transaction and returns.
    async fn migrate_v53(&self) -> StoreResult<()> {
        let mut tx = self
            .pool
            .begin()
            .await
            .map_err(|e| to_store_err("begin v53 tx", e))?;

        record_schema_version(&mut tx, 53).await?;

        tx.commit()
            .await
            .map_err(|e| to_store_err("commit v53 migration", e))?;

        tracing::info!(
            target: TRACE_TARGET,
            "schema migration v53 applied (#1418: memories_au column-scope is sqlite-only; no-op postgres DDL)"
        );
        Ok(())
    }

    /// v54 (#1466) — backfill tier-default expiry on legacy immortal
    /// rows. Postgres twin of the SQLite v54 backfill: before the
    /// write-path chokepoint fix, every internally-minted mid/short
    /// memory persisted with `expires_at: None` landed with a NULL
    /// expiry that the TTL sweep can never reap. Stamp those rows with
    /// `created_at + tier-default TTL` so they age out on the next sweep.
    ///
    /// The interval is derived from `Tier::default_ttl_secs()` — the
    /// SAME SSOT the write path uses — and bound as a parameter, so the
    /// backfill carries no hardcoded interval literal and can never
    /// drift from the canonical per-tier TTL. `long` rows have no TTL
    /// (`default_ttl_secs() == None`) and are left NULL. Idempotent:
    /// only NULL-expiry rows are touched, so a re-run finds none.
    async fn migrate_v54(&self) -> StoreResult<()> {
        let mut tx = self
            .pool
            .begin()
            .await
            .map_err(|e| to_store_err("begin v54 tx", e))?;

        for tier in [Tier::Mid, Tier::Short, Tier::Long] {
            if let Some(ttl_secs) = tier.default_ttl_secs() {
                sqlx::query(
                    "UPDATE memories \
                        SET expires_at = created_at + ($1 || ' seconds')::interval \
                      WHERE expires_at IS NULL AND tier = $2",
                )
                .bind(ttl_secs.to_string())
                .bind(tier.as_str())
                .execute(&mut *tx)
                .await
                .map_err(|e| to_store_err("v54 backfill expires_at", e))?;
            }
        }

        record_schema_version(&mut tx, 54).await?;

        tx.commit()
            .await
            .map_err(|e| to_store_err("commit v54 migration", e))?;

        tracing::info!(
            target: TRACE_TARGET,
            "schema migration v54 applied (#1466: backfilled tier-default expiry on NULL-expiry mid/short rows)"
        );
        Ok(())
    }

    /// v55 (#1476, perf) — postgres no-op twin of the SQLite
    /// federation-catchup `updated_at` index migration.
    ///
    /// The real fix for `list_memories_updated_since` is the sargable
    /// rewrite of its predicate (the former `($1 IS NULL OR updated_at >
    /// $1)` OR-NULL branch is split into a None path with no predicate
    /// and a Some path with the bare range bound `updated_at > $1`). On
    /// postgres that rewrite is sufficient on its own because the
    /// bootstrap schema **already** ships an index on `updated_at` —
    /// `memories_updated_at_idx ON memories (updated_at DESC)`
    /// (`src/store/postgres_schema.sql`). A btree is bidirectional, so
    /// that DESC index serves `WHERE updated_at > $1 ORDER BY updated_at
    /// ASC LIMIT` via an **Index Scan Backward** with a true
    /// `Index Cond: updated_at > $1` — verified on a 200k-row probe
    /// (`EXPLAIN GENERIC_PLAN`, full-scan cost 2396, identical to a
    /// dedicated ASC index). Adding a second ASC index here would be
    /// redundant write-amplification on the hot write path, so the
    /// postgres twin is a version-stamp only (the v51 / v53 precedent).
    ///
    /// The SQLite backend has no pre-existing `updated_at` index, so its
    /// v55 arm DOES create one
    /// (`migrations/sqlite/0046_v55_idx_memories_updated_at.sql`); the
    /// `CURRENT_SCHEMA_VERSION` stays pinned in lockstep so a single
    /// logical schema number tracks both adapters.
    async fn migrate_v55(&self) -> StoreResult<()> {
        let mut tx = self
            .pool
            .begin()
            .await
            .map_err(|e| to_store_err("begin v55 tx", e))?;

        record_schema_version(&mut tx, 55).await?;

        tx.commit()
            .await
            .map_err(|e| to_store_err("commit v55 migration", e))?;

        tracing::info!(
            target: TRACE_TARGET,
            "schema migration v55 applied (#1476: sargable federation-catchup rewrite; existing memories_updated_at_idx DESC serves the range scan — no new postgres index)"
        );
        Ok(())
    }

    /// v56 (#1579 A2 + B6d) — composite list / archive ordering
    /// indexes. SQLite-only DDL
    /// (`migrations/sqlite/0047_v56_list_composite_indexes.sql`) paired
    /// with the sargable `storage::list` rewrite; the #1579 A2 finding
    /// was measured on the sqlite adapter and the postgres list path
    /// (its own SQL builder over `memories_priority_idx` /
    /// `memories_updated_at_idx`) is owned by the postgres workstream.
    /// The postgres twin is therefore a version-stamp only, per the
    /// v51 / v53 / v55 precedent, keeping the SQLite/postgres
    /// `CURRENT_SCHEMA_VERSION` pinned in lockstep so a single logical
    /// schema number tracks both adapters.
    async fn migrate_v56(&self) -> StoreResult<()> {
        let mut tx = self
            .pool
            .begin()
            .await
            .map_err(|e| to_store_err("begin v56 tx", e))?;

        // Stamp the LITERAL arm version, not CURRENT_SCHEMA_VERSION —
        // post-merge (train #1579 batch-2) CURRENT is 57, and stamping
        // it here would record 57 without ever running the v57 arm on
        // a ladder replay entering below 56 (the same replay-hazard
        // class the v55 literal-stamp fix closed).
        record_schema_version(&mut tx, 56).await?;

        tx.commit()
            .await
            .map_err(|e| to_store_err("commit v56 migration", e))?;

        tracing::info!(
            target: TRACE_TARGET,
            "schema migration v56 applied (#1579: composite list/archive indexes are sqlite-only; no-op postgres DDL)"
        );
        Ok(())
    }

    /// v57 (#1579 B2, perf) — stored generated tsvector column for the
    /// full-text search + recall surfaces.
    ///
    /// Pre-v57 the recall/search/contradiction queries ranked with
    /// `ts_rank(to_tsvector('english', title || ' ' || content), …)`:
    /// the GIN **expression** index (`memories_content_fts`) only ever
    /// served the `@@` match — `ts_rank` re-parsed and re-stemmed the
    /// full document text PER MATCHED ROW (~305 of 306 ms at 8k fleet
    /// rows in the P3 perf audit; ~4 s extrapolated at 100k rows).
    ///
    /// v57 adds `tsv tsvector GENERATED ALWAYS AS (...) STORED`,
    /// GIN-indexes the COLUMN (`memories_tsv_gin`), and the query
    /// shapes read `tsv` for both match and rank, so the tsvector is
    /// computed once per WRITE instead of once per matched row per
    /// read. The now-unreferenced expression index is dropped (pure
    /// write amplification otherwise); fresh bootstraps no longer
    /// create it (`src/store/postgres_schema.sql` carries the column
    /// inline; this arm attaches the index per the #797 convention —
    /// indexes on ALTER-added columns live in the migration arm, which
    /// fresh installs also execute because they enter the ladder at
    /// version 0).
    ///
    /// **Operational note (fleet apply):** `ADD COLUMN ... GENERATED
    /// ALWAYS AS ... STORED` takes an ACCESS EXCLUSIVE lock and
    /// rewrites the table to backfill the column. At the fleet's ~8k
    /// rows this is sub-second; plan a maintenance window before
    /// running it against multi-million-row deployments.
    ///
    /// SQLite twin is a version-stamp no-op (FTS5 already materialises
    /// the index text in the `memories_fts` virtual table — there is
    /// nothing to precompute), the inverse of the v55 arm.
    async fn migrate_v57(&self) -> StoreResult<()> {
        let mut tx = self
            .pool
            .begin()
            .await
            .map_err(|e| to_store_err("begin v57 tx", e))?;

        sqlx::query(
            "ALTER TABLE memories ADD COLUMN IF NOT EXISTS tsv tsvector \
             GENERATED ALWAYS AS (to_tsvector('english', \
             coalesce(title, '') || ' ' || coalesce(content, ''))) STORED",
        )
        .execute(&mut *tx)
        .await
        .map_err(|e| to_store_err("v57 add tsv generated column", e))?;

        sqlx::query("CREATE INDEX IF NOT EXISTS memories_tsv_gin ON memories USING gin (tsv)")
            .execute(&mut *tx)
            .await
            .map_err(|e| to_store_err("v57 create memories_tsv_gin", e))?;

        // The legacy EXPRESSION index served only the `@@` match and no
        // query references the expression any more — keeping it would
        // be pure write amplification on every memories INSERT/UPDATE.
        sqlx::query("DROP INDEX IF EXISTS memories_content_fts")
            .execute(&mut *tx)
            .await
            .map_err(|e| to_store_err("v57 drop memories_content_fts", e))?;

        record_schema_version(&mut tx, CURRENT_SCHEMA_VERSION).await?;

        tx.commit()
            .await
            .map_err(|e| to_store_err("commit v57 migration", e))?;

        tracing::info!(
            target: TRACE_TARGET,
            "schema migration v57 applied (#1579 B2: stored generated tsv column + memories_tsv_gin; dropped expression index memories_content_fts)"
        );
        Ok(())
    }

    // ─────────────────────────────────────────────────────────────────
    // v0.7.0 Provenance Gap parity — postgres SAL methods (issue #894).
    //
    // The six methods below bring `PostgresStore` to parity with the
    // sqlite-side `storage::` free functions for the Gap-1/2/3/5/6/7
    // provenance closeouts. Inherent methods (not on the
    // [`MemoryStore`] trait) so call-sites that hold an
    // `Arc<PostgresStore>` can drive them today; the trait can be
    // widened in a follow-up once both adapters stabilise.
    //
    // Sqlite reference impls:
    //   * `storage::update_with_expected_version` (Gap 1, #884)
    //   * `storage::update_with_archive_on_supersede` (Gap 5, #888)
    //   * `storage::search_with_source_uri` (Gap 6, #889)
    //   * `storage::list_by_source_uri` (Gap 6, #889)
    //   * `observations::record_recall` + `observations::gc::prune`
    //     (Gap 3, #886)
    // ─────────────────────────────────────────────────────────────────

    /// #1412/#1628 — owner pre-fetch for the caller-owns mutation gate.
    /// One declaration site (pm-v3.1) for the three gate consumers.
    const SQL_SELECT_OWNER_AGENT_ID_BY_ID: &'static str =
        "SELECT metadata->>'agent_id' FROM memories WHERE id = $1";

    /// #1412 caller-owns mutation gate shared by the tenant-facing
    /// write paths: the trait `update`, the trait `delete`, and the
    /// inherent `update_with_expected_version` (#1628). Threat model:
    /// cross-tenant write hijack on postgres-backed daemons. Admin
    /// paths skip via `ctx.bypass_visibility`; tenant-facing handlers
    /// MUST NOT pass a bypass context.
    ///
    /// `action` names the refused operation in the `PermissionDenied`
    /// envelope; `unstamped_reason` is the wire-pinned refusal text for
    /// legacy rows carrying no `metadata.agent_id` stamp (the verb
    /// differs between the write and delete gates —
    /// [`REASON_UNSTAMPED_TENANT_WRITE`] /
    /// [`REASON_UNSTAMPED_TENANT_DELETE`]). Hoisted per the pm-v3.1
    /// hardcoded-literal gate when #1628 added the third copy of the
    /// previously-inlined gate.
    async fn assert_caller_owns_for_mutation(
        &self,
        ctx: &CallerContext,
        id: &str,
        action: &str,
        unstamped_reason: &str,
    ) -> StoreResult<()> {
        if ctx.bypass_visibility {
            return Ok(());
        }
        let owner: Option<Option<String>> =
            sqlx::query_scalar(Self::SQL_SELECT_OWNER_AGENT_ID_BY_ID)
                .bind(id)
                .fetch_optional(&self.pool)
                .await
                .map_err(|e| to_store_err(&format!("{action}: pre-fetch owner"), e))?;
        match owner {
            None => Err(StoreError::NotFound { id: id.to_string() }),
            Some(None) => {
                // Row exists but has no agent_id stamp (legacy / migrated
                // pre-v0.6.3 row). Block tenant mutations — the conservative
                // posture lets the operator clean up via admin path.
                Err(StoreError::PermissionDenied {
                    action: action.to_string(),
                    target: id.to_string(),
                    reason: unstamped_reason.to_string(),
                })
            }
            Some(Some(existing_owner)) if existing_owner != ctx.effective_principal() => {
                Err(StoreError::PermissionDenied {
                    action: action.to_string(),
                    target: id.to_string(),
                    reason: format!(
                        "caller {:?} does not own memory (owner: {existing_owner:?})",
                        ctx.effective_principal()
                    ),
                })
            }
            Some(Some(_)) => Ok(()), // owner matches; proceed
        }
    }

    /// v0.7.0 Provenance Gap 1 (issue #884) — optimistic-concurrency
    /// aware update. Postgres twin of
    /// [`crate::storage::update_with_expected_version`].
    ///
    /// When `expected_version` is `Some(v)`, the update fails with a
    /// typed [`crate::storage::VersionConflict`] error if the stored
    /// row's `version` is not equal to `v`. When `None`, the legacy
    /// last-write-wins behaviour is preserved (still bumps `version`
    /// on success). On a successful mutation the row's `version` is
    /// monotonically incremented; the new value is observable on the
    /// subsequent read.
    ///
    /// Atomicity: the version gate is asserted inside the UPDATE
    /// WHERE clause AND re-checked on a 0-rows-affected outcome so
    /// a racing writer that slipped in between client read + server
    /// update still fails CONFLICT.
    ///
    /// # Errors
    ///
    /// * [`crate::storage::VersionConflict`] — when `expected_version`
    ///   is `Some` and the stored value has drifted (surfaced as
    ///   `StoreError::IntegrityFailed` whose detail starts with
    ///   `VersionConflict:`).
    /// * `StoreError::NotFound` — when no live memory matches `id`.
    /// * `StoreError::PermissionDenied` — when `ctx` does not own the
    ///   row (#1628; same gate as [`MemoryStore::update`]).
    /// * `StoreError::BackendUnavailable` — on SQL failure.
    pub async fn update_with_expected_version(
        &self,
        ctx: &CallerContext,
        id: &str,
        patch: UpdatePatch,
        expected_version: Option<i64>,
    ) -> StoreResult<i64> {
        // #1641 — bounded gate-CAS retry. The governance pre-write
        // gate evaluates a pre-read snapshot; the UPDATE re-asserts
        // the snapshot's version atomically (see the $11 bind). For
        // last-write-wins callers (expected_version=None) a lost race
        // re-reads + RE-GATES instead of erroring, preserving their
        // semantics while guaranteeing the gate evaluated the row
        // that was actually replaced. Explicit If-Match callers keep
        // exactly-one-winner semantics (no retry).
        const MAX_GATE_RETRIES: usize = 3;
        let mut attempt = 0;
        loop {
            attempt += 1;
            match self
                .update_with_expected_version_once(ctx, id, patch.clone(), expected_version)
                .await?
            {
                Some(new_version) => return Ok(new_version),
                None => {
                    // 0 rows: row vanished or version drifted.
                    let observed: Option<(i64,)> =
                        sqlx::query_as("SELECT version FROM memories WHERE id = $1")
                            .bind(id)
                            .fetch_optional(&self.pool)
                            .await
                            .map_err(|e| to_store_err("re-read version on conflict", e))?;
                    let Some((cur,)) = observed else {
                        return Err(StoreError::NotFound { id: id.to_string() });
                    };
                    if let Some(exp) = expected_version {
                        return Err(StoreError::IntegrityFailed {
                            detail: format!(
                                "VersionConflict: memory {id} expected_version={exp} but stored version={cur}"
                            ),
                        });
                    }
                    if attempt >= MAX_GATE_RETRIES {
                        return Err(StoreError::IntegrityFailed {
                            detail: format!(
                                "VersionConflict: memory {id} mutated concurrently on every                                  gate-CAS attempt ({MAX_GATE_RETRIES}); last stored version={cur}"
                            ),
                        });
                    }
                    // loop: re-read + re-gate on the fresh row.
                }
            }
        }
    }

    /// #1641 — single gate-CAS attempt. Returns `Ok(Some(new_version))`
    /// on success, `Ok(None)` when the guarded UPDATE matched 0 rows
    /// (version drifted / row vanished — the caller decides retry vs
    /// typed conflict).
    async fn update_with_expected_version_once(
        &self,
        ctx: &CallerContext,
        id: &str,
        patch: UpdatePatch,
        expected_version: Option<i64>,
    ) -> StoreResult<Option<i64>> {
        // #1628 — caller-owns write gate, mirroring the trait `update`
        // (#1412). This method gained its first production caller (the
        // HTTP `PUT /memories/{id}` If-Match branch), so it must apply
        // the SAME tenant-isolation gate; admin paths skip via
        // `ctx.bypass_visibility`.
        self.assert_caller_owns_for_mutation(ctx, id, "update", REASON_UNSTAMPED_TENANT_WRITE)
            .await?;
        // Pre-read the current version so a CONFLICT carries the
        // observed-current value in the typed error. The UPDATE
        // re-asserts the gate atomically below.
        // #1451 (SEC, HIGH) — fetch the governance-relevant columns
        // alongside `version` so the pre-write hook can evaluate the
        // POST-MERGE row before the UPDATE (parity with the SQLite
        // backend and the insert/supersede PG paths).
        let current_row: Option<(i64, String, String, String, String, serde_json::Value)> =
            sqlx::query_as(
                "SELECT version, namespace, tier, title, memory_kind, metadata \
                 FROM memories WHERE id = $1",
            )
            .bind(id)
            .fetch_optional(&self.pool)
            .await
            .map_err(|e| to_store_err("read memories row for update gate", e))?;
        let Some((current, cur_ns, cur_tier, cur_title, cur_kind, cur_meta)) = current_row else {
            return Err(StoreError::NotFound { id: id.to_string() });
        };

        // Pre-check (cheap fast-path); the atomic re-check below is
        // the load-bearing guard.
        if let Some(expected) = expected_version
            && expected != current
        {
            return Err(StoreError::IntegrityFailed {
                detail: format!(
                    "VersionConflict: memory {id} expected_version={expected} but stored version={current}"
                ),
            });
        }

        // #1451 — consult GOVERNANCE_PRE_WRITE on the post-merge row.
        // Mirror the SQLite tier-downgrade protection so the gate sees
        // the tier that will actually be written (Long never downgrades;
        // Mid never downgrades to Short).
        let existing_tier = Tier::from_str(&cur_tier).unwrap_or(Tier::Long);
        let effective_tier = match (patch.tier.as_ref(), existing_tier) {
            (Some(_), Tier::Long) => Tier::Long,
            (Some(Tier::Short), Tier::Mid) => Tier::Mid,
            (Some(req), _) => req.clone(),
            (None, existing) => existing,
        };
        let governed = Memory {
            namespace: patch.namespace.clone().unwrap_or(cur_ns),
            tier: effective_tier,
            title: patch.title.clone().unwrap_or(cur_title),
            memory_kind: crate::models::MemoryKind::from_str(&cur_kind).unwrap_or_default(),
            metadata: patch.metadata.clone().unwrap_or(cur_meta),
            ..Memory::default()
        };
        consult_governance_pre_write_pg(&governed)?;

        let new_version = current + 1;
        // v0.7.0 Provenance Gap 2 (#906) — source_uri ($10) follows
        // COALESCE semantics so a patch that omits source_uri leaves
        // the stored value alone. The expected_version gate is shifted
        // to $11.
        let rows_affected = sqlx::query(
            "UPDATE memories SET
                title = COALESCE($2, title),
                content = COALESCE($3, content),
                tier = CASE
                    WHEN $4::TEXT IS NULL THEN tier
                    WHEN tier_rank($4::TEXT) >= tier_rank(tier) THEN $4::TEXT
                    ELSE tier
                END,
                namespace = COALESCE($5, namespace),
                tags = COALESCE($6, tags),
                priority = COALESCE($7, priority),
                confidence = COALESCE($8, confidence),
                metadata = CASE
                    WHEN $9::JSONB IS NULL THEN metadata
                    WHEN metadata ? 'agent_id' THEN jsonb_set(
                        $9::JSONB, '{agent_id}', metadata -> 'agent_id'
                    )
                    ELSE $9::JSONB
                END,
                source_uri = COALESCE($10, source_uri),
                -- #1628/#1626 — If-Match PUTs route through this method
                -- on postgres, so it must mirror the trait `update`'s
                -- expires_at semantics including the #1626 tier→long
                -- coupling: when the patch tier IS long the clear wins
                -- over an explicitly-supplied $12; when the patch tier
                -- is NOT long an explicit $12 wins and an absent $12
                -- leaves the stored value untouched.
                expires_at = CASE
                    WHEN $4::TEXT = 'long' THEN NULL
                    ELSE COALESCE($12, expires_at)
                END,
                updated_at = NOW(),
                version = version + 1
             WHERE id = $1
               AND ($11::BIGINT IS NULL OR version = $11::BIGINT)",
        )
        .bind(id)
        .bind(patch.title)
        .bind(patch.content)
        .bind(patch.tier.as_ref().map(Tier::as_str))
        .bind(patch.namespace)
        .bind(
            patch
                .tags
                .map(serde_json::to_value)
                .transpose()
                .map_err(|e| StoreError::IntegrityFailed {
                    detail: format!("serialize tags patch: {e}"),
                })?,
        )
        .bind(patch.priority)
        .bind(patch.confidence)
        .bind(patch.metadata)
        .bind(patch.source_uri)
        // #1641 — $11 ALWAYS carries a version guard: the caller's
        // expected_version when supplied, else the pre-read `current`.
        // The governance gate above evaluated the pre-read row; an
        // unguarded UPDATE could land on a row that mutated in the
        // SELECT→UPDATE window (gate evaluated stale state). With
        // #1632 every mutation bumps `version`, so version-CAS is a
        // complete change detector for governance-relevant fields.
        .bind(expected_version.unwrap_or(current))
        // #1628 — expires_at COALESCE slot ($12); see the SET-clause
        // comment above for the #1626 tier→long interplay.
        .bind(parse_rfc3339_opt(patch.expires_at.as_deref()))
        .execute(&self.pool)
        .await
        .map_err(|e| to_store_err("update_with_expected_version", e))?
        .rows_affected();

        if rows_affected == 0 {
            // #1641 — the caller (the retry wrapper) owns the
            // drift-vs-vanished disposition.
            return Ok(None);
        }
        Ok(Some(new_version))
    }

    /// v0.7.0 Provenance Gap 5 (issue #888) — append-and-archive write
    /// path. Postgres twin of
    /// [`crate::storage::update_with_archive_on_supersede`].
    ///
    /// Used by the MCP `memory_update` tool when the caller passes
    /// `edit_source` of `llm` or `hook`. Atomic: every step runs
    /// inside a single `sqlx::Transaction` so a failure mid-way
    /// rolls every step back.
    ///
    /// Sequence (mirrors mem9's split-write-path pattern):
    /// 1. Honor the optimistic-concurrency gate (`expected_version`).
    ///    Conflict surfaces as `IntegrityFailed` carrying the
    ///    typed `VersionConflict` message before any mutation lands.
    /// 2. Archive the OLD row with `archive_reason='superseded'`.
    /// 3. Insert a NEW memory row carrying the patched fields plus
    ///    `metadata.superseded_id` forward pointer and the
    ///    `edit_source` provenance tag.
    /// 4. The supersede lineage is encoded via 2 mechanisms (not 3):
    ///    `archived_memories.archive_reason='superseded'` on OLD +
    ///    `new_memory.metadata.superseded_id` forward pointer on NEW.
    ///    No `memory_links` `supersedes` edge is written — the FK
    ///    target would point at a row that has left the live
    ///    `memories` table. See #895 for the archive-cross-ref
    ///    follow-on.
    ///
    /// Returns `(archived_id, new_id)` so callers (HTTP / MCP
    /// surfaces) can surface both in the wire response without a
    /// second SELECT.
    ///
    /// # Errors
    ///
    /// * `IntegrityFailed` carrying a `VersionConflict` message — when
    ///   `expected_version` is `Some` and the stored version drifted.
    /// * `NotFound` — when no live memory matches `id`.
    /// * `BackendUnavailable` — on SQL failure.
    pub async fn update_with_archive_on_supersede(
        &self,
        id: &str,
        patch: UpdatePatch,
        expected_version: Option<i64>,
        edit_source: crate::models::EditSource,
    ) -> StoreResult<(String, String)> {
        let mut tx = self
            .pool
            .begin()
            .await
            .map_err(|e| to_store_err("begin supersede tx", e))?;

        // Pre-read the existing row so we can compose the NEW row from
        // the OLD values. SELECT FOR UPDATE pins the row across the
        // archive + insert so a concurrent writer can't race past.
        let existing_row = sqlx::query("SELECT * FROM memories WHERE id = $1 FOR UPDATE")
            .bind(id)
            .fetch_optional(&mut *tx)
            .await
            .map_err(|e| to_store_err("select existing for supersede", e))?;
        let Some(existing_pg) = existing_row else {
            return Err(StoreError::NotFound { id: id.to_string() });
        };

        let existing = Self::row_to_memory(&existing_pg)?;

        // Optimistic-concurrency gate against the OLD row.
        if let Some(expected) = expected_version
            && expected != existing.version
        {
            return Err(StoreError::IntegrityFailed {
                detail: format!(
                    "VersionConflict: memory {id} expected_version={expected} but stored version={}",
                    existing.version
                ),
            });
        }

        // Compose the NEW row by overlaying the patch on the OLD row.
        let new_id = uuid::Uuid::new_v4().to_string();

        // Tier monotonicity preserved (long ≥ mid ≥ short).
        let new_tier = match (patch.tier.as_ref(), &existing.tier) {
            (Some(requested), existing_tier) => match (existing_tier, requested) {
                (Tier::Long, _) => Tier::Long,
                (Tier::Mid, Tier::Short) => Tier::Mid,
                (_, r) => r.clone(),
            },
            (None, existing_tier) => existing_tier.clone(),
        };

        let new_title = patch
            .title
            .as_deref()
            .unwrap_or(existing.title.as_str())
            .to_string();
        let new_content = patch
            .content
            .as_deref()
            .unwrap_or(existing.content.as_str())
            .to_string();
        let new_namespace = patch
            .namespace
            .as_deref()
            .unwrap_or(existing.namespace.as_str())
            .to_string();
        let new_tags = patch.tags.clone().unwrap_or_else(|| existing.tags.clone());
        let new_priority = patch.priority.unwrap_or(existing.priority);
        let new_confidence = patch.confidence.unwrap_or(existing.confidence);
        // v0.7.0 Provenance Gap 2 (#906) — caller-supplied source_uri
        // wins; otherwise inherit from the OLD row.
        let new_source_uri = patch
            .source_uri
            .clone()
            .or_else(|| existing.source_uri.clone());
        // #1627 — expires_at carry, mirroring the sqlite twin's
        // `new_expires` composition (src/storage/mod.rs:1656-1659): an
        // explicit empty/"null" patch clears it, an explicit value
        // rewrites it, and an absent patch inherits the OLD row's
        // expiry instead of silently dropping it.
        let new_expires = match patch.expires_at.as_deref() {
            Some("" | "null") => None,
            Some(v) => Some(v.to_string()),
            None => existing.expires_at.clone(),
        };
        // Stamp edit_source + superseded_id into the new row's metadata.
        let mut new_metadata = patch
            .metadata
            .clone()
            .unwrap_or_else(|| existing.metadata.clone());
        if let serde_json::Value::Object(ref mut m) = new_metadata {
            m.insert(
                "edit_source".to_string(),
                serde_json::Value::String(edit_source.as_str().to_string()),
            );
            m.insert(
                field_names::SUPERSEDED_ID.to_string(),
                serde_json::Value::String(existing.id.clone()),
            );
        }

        // FX-C5 — substrate governance pre-write hook parity. The
        // supersede path mints a NEW live row via a raw INSERT inside
        // this transaction that bypasses `PostgresStore::store(..)`
        // (which is where ARCH-1 wired in the
        // `consult_governance_pre_write_pg` adapter at line 7001).
        // Without this call the substrate hook is unaware that a
        // supersede was about to land — multi-tenant + supersession
        // workflow could bypass operator-signed governance. Compose
        // the candidate memory the way the INSERT below will persist
        // it and fire the hook BEFORE the archive step destroys the
        // OLD live row. A refusal returns `PermissionDenied` and the
        // tx ROLLBACK in the caller leaves the substrate clean.
        let now_dt = Utc::now();
        let now_rfc = now_dt.to_rfc3339();
        let candidate = Memory {
            id: new_id.clone(),
            tier: new_tier.clone(),
            namespace: new_namespace.clone(),
            title: new_title.clone(),
            content: new_content.clone(),
            tags: new_tags.clone(),
            priority: new_priority,
            confidence: new_confidence,
            source: existing.source.clone(),
            access_count: 0,
            created_at: now_rfc.clone(),
            updated_at: now_rfc,
            last_accessed_at: None,
            // #1627 — patch-or-inherit expiry (sqlite twin parity).
            expires_at: new_expires.clone(),
            metadata: new_metadata.clone(),
            reflection_depth: existing.reflection_depth,
            memory_kind: existing.memory_kind.clone(),
            entity_id: existing.entity_id.clone(),
            persona_version: existing.persona_version,
            citations: existing.citations.clone(),
            source_uri: new_source_uri.clone(),
            source_span: existing.source_span,
            confidence_source: existing.confidence_source.clone(),
            confidence_signals: existing.confidence_signals.clone(),
            confidence_decayed_at: existing.confidence_decayed_at.clone(),
            version: crate::models::default_memory_version(),
        };
        consult_governance_pre_write_pg(&candidate)?;

        // Step 1: archive the OLD row with archive_reason='superseded'.
        // #1025 (CRITICAL, 2026-05-21) — full v0.7.0 column carry.
        let archive_rows = sqlx::query(
            "INSERT INTO archived_memories
                (id, tier, namespace, title, content, tags, priority, confidence,
                 source, access_count, created_at, updated_at, last_accessed_at,
                 expires_at, archived_at, archive_reason, metadata,
                 embedding, embedding_dim, original_tier, original_expires_at,
                 reflection_depth, atomised_into, atom_of, memory_kind,
                 entity_id, persona_version, citations, source_uri, source_span,
                 confidence_source, confidence_signals, confidence_decayed_at,
                 mentioned_entity_id, version)
             SELECT id, tier, namespace, title, content, tags, priority, confidence,
                    source, access_count, created_at, updated_at, last_accessed_at,
                    expires_at, NOW(), 'superseded', metadata,
                    embedding, embedding_dim, tier, expires_at,
                    reflection_depth, atomised_into, atom_of, memory_kind,
                    entity_id, persona_version, citations, source_uri, source_span,
                    confidence_source, confidence_signals, confidence_decayed_at,
                    mentioned_entity_id, version
             FROM memories WHERE id = $1
             ON CONFLICT (id) DO NOTHING",
        )
        .bind(id)
        .execute(&mut *tx)
        .await
        .map_err(|e| to_store_err("archive on supersede", e))?
        .rows_affected();
        if archive_rows == 0 {
            // Row vanished or the ON CONFLICT path took over — surface a
            // typed not-found instead of silently dropping the supersede.
            tx.rollback()
                .await
                .map_err(|e| to_store_err("rollback supersede", e))?;
            return Err(StoreError::NotFound { id: id.to_string() });
        }

        // Step 2: DELETE the OLD row from the live `memories` table so
        // the (title, namespace) UNIQUE index doesn't collide with the
        // new INSERT.
        sqlx::query(SQL_DELETE_MEMORY_BY_ID)
            .bind(id)
            .execute(&mut *tx)
            .await
            .map_err(|e| to_store_err("delete old on supersede", e))?;

        // Step 3: insert the NEW row carrying the patched content.
        // version starts at 1 (fresh row, not a continuation).
        // v0.7.0 Provenance Gap 2 (#906) — source_uri is carried
        // onto the new row via patch-or-inherit composition above.
        // #1627 — persist the FULL candidate shape (the sqlite twin
        // routes through `storage::insert`, which writes every
        // Memory-struct column). Pre-#1627 this INSERT listed only 15
        // columns, so memory_kind / reflection_depth / citations /
        // confidence provenance / entity_id / persona_version /
        // expires_at / mentioned_entity_id were silently reset to
        // their SQL DEFAULTs on every supersede.
        let citations_json = serde_json::to_string(&candidate.citations).map_err(|e| {
            StoreError::IntegrityFailed {
                detail: serialize_err("citations", e),
            }
        })?;
        let source_span_json = match candidate.source_span {
            Some(span) => {
                Some(
                    serde_json::to_string(&span).map_err(|e| StoreError::IntegrityFailed {
                        detail: serialize_err(COL_SOURCE_SPAN, e),
                    })?,
                )
            }
            None => None,
        };
        let confidence_signals_json = match &candidate.confidence_signals {
            Some(s) => Some(
                serde_json::to_string(s).map_err(|e| StoreError::IntegrityFailed {
                    detail: serialize_err(COL_CONFIDENCE_SIGNALS, e),
                })?,
            ),
            None => None,
        };
        let mentioned_entity_id = crate::storage::extract_mentioned_entity_id(&candidate);
        // Tier-default expiry backfill (#1466 parity with the sqlite
        // `storage::insert` chokepoint the twin routes through).
        let new_expires_dt = parse_rfc3339_opt(candidate.effective_expires_at().as_deref());
        sqlx::query(
            "INSERT INTO memories
                (id, tier, namespace, title, content, tags, priority, confidence,
                 source, access_count, created_at, updated_at, last_accessed_at,
                 expires_at, metadata, reflection_depth, memory_kind,
                 entity_id, persona_version, citations, source_uri, source_span,
                 confidence_source, confidence_signals, confidence_decayed_at,
                 mentioned_entity_id, version)
             VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9, 0, NOW(), NOW(), NULL,
                     $10, $11, $12, $13,
                     $14, $15, $16, $17, $18,
                     $19, $20, $21,
                     $22, 1)",
        )
        .bind(&new_id)
        .bind(new_tier.as_str())
        .bind(&new_namespace)
        .bind(&new_title)
        .bind(&new_content)
        .bind(
            serde_json::to_value(&new_tags).map_err(|e| StoreError::IntegrityFailed {
                detail: serialize_err("tags", e),
            })?,
        )
        .bind(new_priority)
        .bind(new_confidence)
        .bind(&existing.source)
        .bind(new_expires_dt)
        .bind(&new_metadata)
        .bind(candidate.reflection_depth)
        .bind(candidate.memory_kind.as_str())
        .bind(candidate.entity_id.as_deref())
        .bind(candidate.persona_version)
        .bind(&citations_json)
        .bind(&new_source_uri)
        .bind(source_span_json.as_deref())
        .bind(candidate.confidence_source.as_str())
        .bind(confidence_signals_json.as_deref())
        .bind(candidate.confidence_decayed_at.as_deref())
        .bind(mentioned_entity_id.as_deref())
        .execute(&mut *tx)
        .await
        .map_err(|e| to_store_err("insert new on supersede", e))?;

        tx.commit()
            .await
            .map_err(|e| to_store_err("commit supersede tx", e))?;

        Ok((existing.id, new_id))
    }

    /// v0.7.0 Provenance Gap 6 (issue #889) — keyword search with
    /// optional reciprocal `source_uri` filter. Postgres twin of
    /// [`crate::storage::search_with_source_uri`].
    ///
    /// When `source_uri` is `Some(uri)`, the full-text search is
    /// post-filtered to memories whose `source_uri` column equals the
    /// supplied value verbatim. The partial `idx_memories_source_uri`
    /// index (created at v37) covers the lookup, keeping it O(log N)
    /// over the URI-keyed subspace.
    ///
    /// Returns up to `limit` matches ordered descending by a blended
    /// score (text-rank + priority + recency).
    pub async fn search_with_source_uri(
        &self,
        query: &str,
        filter: &Filter,
        source_uri: Option<&str>,
    ) -> StoreResult<Vec<Memory>> {
        let limit: i64 = filter
            .limit
            .clamp(1, crate::storage::LIST_MAX_LIMIT)
            .try_into()
            .unwrap_or(LIST_FALLBACK_LIMIT_I64);
        // #1579 B2 — rank + match read the stored generated `tsv`
        // column (schema v57) instead of recomputing
        // to_tsvector(title||' '||content) per matched row.
        let rows = sqlx::query(
            "SELECT m.*,
                    ts_rank(m.tsv, plainto_tsquery('english', $1)) AS rank
             FROM memories m
             WHERE m.tsv @@ plainto_tsquery('english', $1)
               AND ($2::text IS NULL OR m.namespace = $2)
               AND ($3::text IS NULL OR m.tier = $3)
               AND (m.expires_at IS NULL OR m.expires_at > NOW())
               AND ($4::timestamptz IS NULL OR m.created_at >= $4)
               AND ($5::timestamptz IS NULL OR m.created_at <= $5)
               AND ($6::text IS NULL OR m.source_uri = $6)
             ORDER BY rank DESC,
                      m.priority DESC,
                      m.updated_at DESC
             LIMIT $7",
        )
        .bind(query)
        .bind(filter.namespace.as_ref())
        .bind(filter.tier.as_ref().map(Tier::as_str))
        .bind(filter.since)
        .bind(filter.until)
        .bind(source_uri)
        .bind(limit)
        .fetch_all(&self.pool)
        .await
        .map_err(|e| to_store_err("search_with_source_uri", e))?;

        rows.iter().map(Self::row_to_memory).collect()
    }

    /// v0.7.0 Provenance Gap 6 (issue #889) — list every memory
    /// carrying the supplied `source_uri`. Postgres twin of
    /// [`crate::storage::list_by_source_uri`].
    ///
    /// Bypasses the FTS layer so callers that want the full reciprocal
    /// set ("every memory from this document") don't need to type a
    /// query. Hits the partial `idx_memories_source_uri` index
    /// directly. Pure read.
    pub async fn list_by_source_uri(
        &self,
        source_uri: &str,
        namespace: Option<&str>,
        limit: Option<usize>,
    ) -> StoreResult<Vec<Memory>> {
        let cap_usize = limit
            .unwrap_or(crate::storage::LIST_DEFAULT_CAP)
            .min(crate::storage::LIST_MAX_LIMIT);
        let cap: i64 = i64::try_from(cap_usize).unwrap_or(DEFAULT_LIST_CAP_I64);
        let rows = sqlx::query(
            "SELECT m.* FROM memories m
              WHERE m.source_uri = $1
                AND ($2::text IS NULL OR m.namespace = $2)
              ORDER BY m.created_at ASC
              LIMIT $3",
        )
        .bind(source_uri)
        .bind(namespace)
        .bind(cap)
        .fetch_all(&self.pool)
        .await
        .map_err(|e| to_store_err("list_by_source_uri", e))?;

        rows.iter().map(Self::row_to_memory).collect()
    }

    /// v0.7.0 Gap 3 (issue #886) — insert one or more
    /// `recall_observations` rows under a single `recall_id`. Postgres
    /// twin of [`crate::observations::record_recall`].
    ///
    /// Idempotent via `ON CONFLICT (recall_id, memory_id) DO NOTHING`
    /// — replaying the same recall is a no-op rather than a
    /// constraint violation.
    ///
    /// `candidates` is a slice of `(memory_id, retriever, rank, score)`
    /// tuples. Returns the number of rows actually inserted (excludes
    /// ON CONFLICT no-ops).
    pub async fn recall_observation_insert(
        &self,
        recall_id: &str,
        candidates: &[(String, String, i64, f64)],
    ) -> StoreResult<usize> {
        if candidates.is_empty() {
            return Ok(0);
        }
        let mut tx = self
            .pool
            .begin()
            .await
            .map_err(|e| to_store_err("begin recall_observation tx", e))?;
        let mut written: usize = 0;
        for (memory_id, retriever, rank, score) in candidates {
            let n = sqlx::query(
                "INSERT INTO recall_observations
                    (recall_id, memory_id, retriever, rank, score)
                 VALUES ($1, $2, $3, $4, $5)
                 ON CONFLICT (recall_id, memory_id) DO NOTHING",
            )
            .bind(recall_id)
            .bind(memory_id)
            .bind(retriever)
            .bind(rank)
            .bind(score)
            .execute(&mut *tx)
            .await
            .map_err(|e| to_store_err("insert recall_observation", e))?
            .rows_affected();
            written += usize::try_from(n).unwrap_or(0);
        }
        tx.commit()
            .await
            .map_err(|e| to_store_err("commit recall_observation tx", e))?;
        Ok(written)
    }

    /// v0.7.0 Gap 3 (issue #886) — TTL-based prune of the
    /// `recall_observations` ledger. Postgres twin of
    /// [`crate::observations::gc::prune`].
    ///
    /// Deletes every row whose `observed_at` is older than `ttl_days`
    /// days. Returns the count of rows pruned. Safe to invoke
    /// concurrently with `recall_observation_insert`.
    pub async fn recall_observation_gc(&self, ttl_days: i64) -> StoreResult<usize> {
        let cutoff = chrono::Utc::now() - chrono::Duration::days(ttl_days.max(1));
        let n = sqlx::query("DELETE FROM recall_observations WHERE observed_at < $1")
            .bind(cutoff)
            .execute(&self.pool)
            .await
            .map_err(|e| to_store_err("recall_observation_gc", e))?
            .rows_affected();
        Ok(usize::try_from(n).unwrap_or(0))
    }

    /// v0.7.0 issue #860 — Postgres twin of
    /// [`crate::storage::get_links`] expanded to surface the four
    /// temporal-validity + attestation columns
    /// (`valid_from`, `valid_until`, `observed_by`, `attest_level`)
    /// the `memory_get_links` MCP tool's docstring promises.
    ///
    /// Returns every link row where `id` is either source OR target,
    /// projecting the full row shape so the read path matches the
    /// SQLite contract byte-for-byte.
    pub async fn get_links(&self, id: &str) -> StoreResult<Vec<MemoryLink>> {
        let rows = sqlx::query(
            "SELECT source_id, target_id, relation, created_at,
                    valid_from, valid_until, observed_by, attest_level
             FROM memory_links
             WHERE source_id = $1 OR target_id = $1
             ORDER BY source_id, target_id, relation",
        )
        .bind(id)
        .fetch_all(&self.pool)
        .await
        .map_err(|e| to_store_err("get_links", e))?;

        rows.iter()
            .map(|r| {
                let created_at: DateTime<Utc> = r
                    .try_get(field_names::CREATED_AT)
                    .map_err(|e| to_store_err(READ_CREATED_AT, e))?;
                let valid_from: Option<DateTime<Utc>> = r
                    .try_get(field_names::VALID_FROM)
                    .map_err(|e| to_store_err(READ_VALID_FROM, e))?;
                let valid_until: Option<DateTime<Utc>> = r
                    .try_get(field_names::VALID_UNTIL)
                    .map_err(|e| to_store_err(READ_VALID_UNTIL, e))?;
                let observed_by: Option<String> = r
                    .try_get(field_names::OBSERVED_BY)
                    .map_err(|e| to_store_err(READ_OBSERVED_BY, e))?;
                let attest_level: Option<String> = r
                    .try_get(field_names::ATTEST_LEVEL)
                    .map_err(|e| to_store_err(READ_ATTEST_LEVEL, e))?;
                let relation_str: String = r
                    .try_get("relation")
                    .map_err(|e| to_store_err(READ_RELATION, e))?;
                Ok(MemoryLink {
                    source_id: r
                        .try_get("source_id")
                        .map_err(|e| to_store_err(READ_SOURCE_ID, e))?,
                    target_id: r
                        .try_get("target_id")
                        .map_err(|e| to_store_err(READ_TARGET_ID, e))?,
                    relation: crate::models::MemoryLinkRelation::from_str(&relation_str)
                        .unwrap_or_default(),
                    created_at: created_at.to_rfc3339(),
                    // `signature` is intentionally NOT surfaced through
                    // the get_links read path — that bytes-on-the-wire
                    // surface is the verifier's concern
                    // (`LinkVerifyRecord`), and exposing it here would
                    // force the JSON response to carry a base64 blob
                    // every existing caller would have to ignore.
                    signature: None,
                    valid_from: valid_from.map(|t| t.to_rfc3339()),
                    valid_until: valid_until.map(|t| t.to_rfc3339()),
                    observed_by,
                    attest_level,
                })
            })
            .collect()
    }

    // ─────────────────────────────────────────────────────────────────
    // AGE Cypher templates for Gap-5 / Gap-7 (issue #894 PG+AGE parity).
    //
    // These constants bind the canonical Cypher snippets a future AGE
    // runner will switch on when the operator network constraint lifts
    // (Track C/D: 192.168.50.100 ↔ 192.168.1.50 routing). They are
    // intentionally NOT executed by this build — the v0.7.0 PG path's
    // `kg_backend` probes for AGE at connect time and falls back to
    // the recursive-CTE path on `KgBackend::Cte` (the current default
    // on every PG instance we run against).
    //
    // When AGE is enrolled, the dispatch site:
    //   1. Pulls the template constant
    //   2. Substitutes `$param` placeholders via the AGE Cypher
    //      parameter-binding contract
    //   3. Executes via `SELECT * FROM cypher('memory_graph', $$ ... $$,
    //      $1) AS (col agtype)`
    //
    // Until then, the constants serve as the contract documentation
    // the AGE arm will commit to.
    // ─────────────────────────────────────────────────────────────────

    /// v0.7.0 Provenance Gap 5 (#888) — AGE Cypher template for the
    /// supersede edge. Bound but not executed pending AGE enrolment.
    /// Mirrors the metadata-pointer encoding the SQL path uses (#895
    /// is the follow-on for the FK-safe archive cross-ref).
    pub const AGE_CYPHER_SUPERSEDE_EDGE: &'static str = "\
        MERGE (a:Memory {id: $new_id})-[:SUPERSEDES {at: $ts, edit_source: $src}]->\
        (b:Memory {id: $archived_id})";

    /// v0.7.0 Provenance Gap 7 (#890) — AGE Cypher template for the
    /// `latest_link_attest_level` decoration: max of attest_level over
    /// every outbound link on a memory. Bound but not executed pending
    /// AGE enrolment.
    pub const AGE_CYPHER_LATEST_LINK_ATTEST_LEVEL: &'static str = "\
        MATCH (m:Memory {id: $id})-[r]->() \
        RETURN max(coalesce(r.attest_level, 'unsigned'))";

    /// v29 connect-time no-op pass.
    ///
    /// The actual `vector(N)` column conversion is destructive (rows
    /// have their embedding NULLed, HNSW indexes are dropped + recreated)
    /// and therefore MUST be operator-initiated rather than firing
    /// implicitly on daemon startup. The connect-time pass here just
    /// records that we've reached v29 once the bookkeeping is in place;
    /// the explicit conversion lives at
    /// [`Self::migrate_embedding_dim`].
    async fn migrate_v29_stamp(&self) -> StoreResult<()> {
        let mut tx = self
            .pool
            .begin()
            .await
            .map_err(|e| to_store_err("begin v29 stamp tx", e))?;

        record_schema_version(&mut tx, 29).await?;

        tx.commit()
            .await
            .map_err(|e| to_store_err("commit v29 stamp", e))?;

        tracing::info!(
            target: TRACE_TARGET,
            "schema migration v29 stamped (operator-initiated vector(N) conversion available via ai-memory schema-init --embedding-dim)"
        );
        Ok(())
    }

    /// Read the current dimension of `memories.embedding`. Returns
    /// `None` when the column is missing (which should not happen
    /// post-bootstrap) or the type isn't `vector(N)`.
    ///
    /// pgvector encodes the declared dim in `pg_attribute.atttypmod`;
    /// the value matches what `format_type(atttypid, atttypmod)` would
    /// surface as `vector(N)`.
    ///
    /// # Errors
    ///
    /// Returns `StoreError::BackendUnavailable` if the catalog probe
    /// fails (connection issue, etc.).
    pub async fn current_embedding_dim(&self) -> StoreResult<Option<i32>> {
        let row: Option<(i32,)> = sqlx::query_as(
            "SELECT atttypmod FROM pg_attribute a
             JOIN pg_class c ON c.oid = a.attrelid
             JOIN pg_namespace n ON c.relnamespace = n.oid
             WHERE c.relname = 'memories' AND a.attname = 'embedding'
             AND n.nspname = 'public'",
        )
        .fetch_optional(&self.pool)
        .await
        .map_err(|e| to_store_err("read memories.embedding atttypmod", e))?;
        Ok(row.map(|(t,)| t))
    }

    /// Operator-initiated `vector(N)` conversion. Destructive on the
    /// embedding column: rows have their `embedding` NULLed (vectors
    /// cannot be reprojected dim-to-dim), the HNSW indexes on both
    /// `memories.embedding` and `archived_memories.embedding` are
    /// dropped and recreated, and the column is `ALTER COLUMN ... TYPE
    /// vector(<target_dim>)`'d. The caller is responsible for
    /// re-running embeddings after the conversion.
    ///
    /// Idempotent: when the column is already `vector(target_dim)` the
    /// call is a no-op and returns `Ok(false)` (no change). On a real
    /// conversion it returns `Ok(true)`.
    ///
    /// The whole operation runs in a single transaction so a mid-way
    /// failure leaves the schema untouched.
    ///
    /// # Errors
    ///
    /// - `StoreError::InvalidInput` when `target_dim` is not one of the
    ///   supported values (`SUPPORTED_EMBEDDING_DIMS`).
    /// - `StoreError::BackendUnavailable` on any SQL failure during
    ///   the conversion.
    pub async fn migrate_embedding_dim(&self, target_dim: u32) -> StoreResult<bool> {
        let target_i32 = i32::try_from(target_dim).map_err(|_| StoreError::InvalidInput {
            detail: format!("target_dim {target_dim} out of i32 range"),
        })?;
        if !SUPPORTED_EMBEDDING_DIMS.contains(&target_i32) {
            return Err(StoreError::InvalidInput {
                detail: format!(
                    "unsupported target embedding dim {target_dim}: expected one of {SUPPORTED_EMBEDDING_DIMS:?}"
                ),
            });
        }

        let current = self.current_embedding_dim().await?;
        if let Some(cur) = current
            && cur == target_i32
        {
            tracing::info!(
                target: TRACE_TARGET,
                dim = target_i32,
                "v29 embedding-dim migration: column already vector({target_i32}); no-op"
            );
            return Ok(false);
        }

        tracing::warn!(
            target: TRACE_TARGET,
            current = ?current,
            target = target_i32,
            "v29 embedding-dim migration: converting memories.embedding + archived_memories.embedding; existing embeddings will be NULLed — operators MUST re-run embeddings after this conversion completes"
        );

        let mut tx = self
            .pool
            .begin()
            .await
            .map_err(|e| to_store_err("begin v29 conversion tx", e))?;

        // Drop the HNSW indexes that pin the column type. ALTER COLUMN
        // TYPE on a vector column fails while the HNSW index references
        // it; we drop here and recreate below. The named index from
        // postgres_schema.sql is `memories_embedding_hnsw`; the archive
        // table doesn't carry an HNSW index in the baseline schema but
        // we issue `IF EXISTS` to tolerate operator-added indexes too.
        sqlx::query("DROP INDEX IF EXISTS memories_embedding_hnsw")
            .execute(&mut *tx)
            .await
            .map_err(|e| to_store_err("drop memories_embedding_hnsw", e))?;
        sqlx::query("DROP INDEX IF EXISTS archived_memories_embedding_hnsw")
            .execute(&mut *tx)
            .await
            .map_err(|e| to_store_err("drop archived_memories_embedding_hnsw", e))?;

        // NULL existing embeddings. Cross-dim reprojection isn't
        // mathematically meaningful (a 384-d vector and a 768-d vector
        // from two different models live in different spaces); the
        // operator MUST re-embed after the migration. We don't TRUNCATE
        // because the memory rows themselves remain valid — only the
        // vector column is invalidated.
        sqlx::query("UPDATE memories SET embedding = NULL WHERE embedding IS NOT NULL")
            .execute(&mut *tx)
            .await
            .map_err(|e| to_store_err("null memories.embedding", e))?;
        sqlx::query("UPDATE archived_memories SET embedding = NULL WHERE embedding IS NOT NULL")
            .execute(&mut *tx)
            .await
            .map_err(|e| to_store_err("null archived_memories.embedding", e))?;

        // Alter the column types. pgvector's type allows ALTER COLUMN
        // TYPE between two `vector(N)` declarations even when rows are
        // present (because we just NULLed them above). The `USING NULL`
        // cast is required when there might be non-NULL rows; we add
        // it defensively even though the UPDATE above ensures none.
        let alter_memories = format!(
            "ALTER TABLE memories ALTER COLUMN embedding TYPE vector({target_dim}) USING NULL"
        );
        sqlx::query(&alter_memories)
            .execute(&mut *tx)
            .await
            .map_err(|e| to_store_err("alter memories.embedding type", e))?;

        let alter_archived = format!(
            "ALTER TABLE archived_memories ALTER COLUMN embedding TYPE vector({target_dim}) USING NULL"
        );
        sqlx::query(&alter_archived)
            .execute(&mut *tx)
            .await
            .map_err(|e| to_store_err("alter archived_memories.embedding type", e))?;

        // Recreate the HNSW index on the live table. The archived
        // table is intentionally NOT given an HNSW index (matches the
        // baseline schema — archive recall is rare and a covering
        // index would bloat write-time cost).
        sqlx::query(
            "CREATE INDEX IF NOT EXISTS memories_embedding_hnsw ON memories
             USING hnsw (embedding vector_cosine_ops)",
        )
        .execute(&mut *tx)
        .await
        .map_err(|e| to_store_err("recreate memories_embedding_hnsw", e))?;

        record_schema_version(&mut tx, 29).await?;

        tx.commit()
            .await
            .map_err(|e| to_store_err("commit v29 conversion", e))?;

        tracing::warn!(
            target: TRACE_TARGET,
            target_dim = target_i32,
            "v29 embedding-dim migration committed; re-run embeddings (e.g. via memory_store with the matching embedder configured)"
        );

        Ok(true)
    }

    /// v0.7.0 H2 — Add `attest_level` TEXT column to `memory_links`.
    /// Mirrors SQLite migration 0017_v07_link_attest_level.sql.
    /// Idempotent: ALTER TABLE … IF NOT EXISTS guarded by an
    /// information_schema lookup, plus an idempotent backfill.
    async fn migrate_v23(&self) -> StoreResult<()> {
        let mut tx = self
            .pool
            .begin()
            .await
            .map_err(|e| to_store_err("begin v23 tx", e))?;

        let has_attest_level: bool = sqlx::query_scalar(
            "SELECT EXISTS(
                SELECT 1 FROM information_schema.columns
                WHERE table_name='memory_links' AND column_name='attest_level'
            )",
        )
        .fetch_one(&mut *tx)
        .await
        .map_err(|e| to_store_err("check attest_level column", e))?;

        if !has_attest_level {
            sqlx::query("ALTER TABLE memory_links ADD COLUMN attest_level TEXT")
                .execute(&mut *tx)
                .await
                .map_err(|e| to_store_err("add attest_level column", e))?;
        }

        // Backfill rows written before the column existed.
        sqlx::query("UPDATE memory_links SET attest_level = 'unsigned' WHERE attest_level IS NULL")
            .execute(&mut *tx)
            .await
            .map_err(|e| to_store_err("backfill attest_level", e))?;

        sqlx::query(
            "CREATE INDEX IF NOT EXISTS idx_memory_links_attest_level
             ON memory_links (attest_level, created_at)",
        )
        .execute(&mut *tx)
        .await
        .map_err(|e| to_store_err("create idx_memory_links_attest_level", e))?;

        record_schema_version(&mut tx, 23).await?;

        tx.commit()
            .await
            .map_err(|e| to_store_err("commit v23 migration", e))?;

        tracing::info!(target: TRACE_TARGET, "schema migration v23 applied");
        Ok(())
    }

    /// v0.7.0 v24 — `memory_transcript_links` join table (I2) and the
    /// F6 SAL knowledge-graph SQL surfaces (`kg_query_view`,
    /// `kg_timeline_view`, `kg_find_paths()`).
    ///
    /// Mirrors `migrations/sqlite/0018_v07_transcript_links.sql` plus
    /// the Postgres-only F6 view set. The view bodies live in
    /// `postgres_schema.sql` (which is re-run on every connect, so they
    /// are always present on a fresh init); this migration also stamps
    /// the bookkeeping row and re-runs the DDL defensively in case an
    /// operator dropped a view between connects.
    async fn migrate_v24(&self) -> StoreResult<()> {
        let mut tx = self
            .pool
            .begin()
            .await
            .map_err(|e| to_store_err("begin v24 tx", e))?;

        // I2 — memory_transcript_links join table. ON DELETE CASCADE on
        // both foreign keys keeps the join free of dangling rows when
        // memories are deleted or I3's archive→prune lifecycle removes
        // transcripts. Mirrors SQLite migration 0018_v07_transcript_links.
        sqlx::query(
            "CREATE TABLE IF NOT EXISTS memory_transcript_links (
                memory_id     TEXT NOT NULL REFERENCES memories(id)           ON DELETE CASCADE,
                transcript_id TEXT NOT NULL REFERENCES memory_transcripts(id) ON DELETE CASCADE,
                span_start    BIGINT,
                span_end      BIGINT,
                PRIMARY KEY (memory_id, transcript_id)
            )",
        )
        .execute(&mut *tx)
        .await
        .map_err(|e| to_store_err("create memory_transcript_links table", e))?;

        sqlx::query(
            "CREATE INDEX IF NOT EXISTS idx_mtl_transcript
             ON memory_transcript_links (transcript_id)",
        )
        .execute(&mut *tx)
        .await
        .map_err(|e| to_store_err("create idx_mtl_transcript", e))?;

        sqlx::query(
            "CREATE INDEX IF NOT EXISTS idx_mtl_memory
             ON memory_transcript_links (memory_id)",
        )
        .execute(&mut *tx)
        .await
        .map_err(|e| to_store_err("create idx_mtl_memory", e))?;

        // Re-create the views in case operators dropped them between
        // connects. Bodies match postgres_schema.sql verbatim — kept
        // here as an inline copy so the migration is self-contained.
        // v0.7.0 #1086 (SR-2 #4, MEDIUM) — array-based cycle
        // detection. Pre-#1086 the cycle predicate used
        // `position('->' || ml.target_id IN t.path) = 0` against a
        // concatenated string `path`, which false-positives whenever
        // one id is a substring of another at the `->` boundary
        // (e.g. ids `foo` and `foo-bar`). Switch to a TEXT[] node
        // accumulator + `NOT (ml.target_id = ANY(t.nodes))`, matching
        // the correct pattern already in use by `kg_find_paths`.
        // `path` is preserved on the wire (as `array_to_string(nodes,
        // '->')`) for byte-stable downstream consumers.
        sqlx::query(
            "CREATE OR REPLACE VIEW kg_query_view AS
             WITH RECURSIVE traversal(source_id, target_id, relation, depth, nodes) AS (
                 SELECT ml.source_id, ml.target_id, ml.relation, 1,
                        ARRAY[ml.source_id, ml.target_id]::TEXT[]
                 FROM memory_links ml
                 UNION ALL
                 SELECT t.source_id, ml.target_id, ml.relation, t.depth + 1,
                        t.nodes || ml.target_id
                 FROM memory_links ml
                 JOIN traversal t ON ml.source_id = t.target_id
                 WHERE t.depth < 5
                   AND NOT (ml.target_id = ANY(t.nodes))
             )
             SELECT source_id, target_id, relation, depth,
                    array_to_string(nodes, '->') AS path
             FROM traversal",
        )
        .execute(&mut *tx)
        .await
        .map_err(|e| to_store_err("create kg_query_view", e))?;

        sqlx::query(
            "CREATE OR REPLACE VIEW kg_timeline_view AS
             SELECT ml.source_id, ml.target_id, ml.relation,
                    ml.valid_from, ml.valid_until, ml.observed_by,
                    encode(ml.signature, 'hex') AS signature_hex
             FROM memory_links ml
             WHERE ml.valid_from IS NOT NULL
             ORDER BY ml.valid_from DESC, ml.created_at DESC",
        )
        .execute(&mut *tx)
        .await
        .map_err(|e| to_store_err("create kg_timeline_view", e))?;

        sqlx::query(
            "CREATE OR REPLACE FUNCTION kg_find_paths(start_id TEXT, max_depth INTEGER)
             RETURNS TABLE (path_id INTEGER, length INTEGER, nodes TEXT[], relations TEXT[])
             LANGUAGE SQL STABLE PARALLEL SAFE AS $$
                 WITH RECURSIVE walk(current_id, depth, nodes, relations) AS (
                     SELECT start_id, 0, ARRAY[start_id], ARRAY[]::TEXT[]
                     UNION ALL
                     SELECT edges.next_id,
                            w.depth + 1,
                            w.nodes || edges.next_id,
                            w.relations || edges.relation
                     FROM walk w
                     JOIN (
                         SELECT source_id AS from_id, target_id AS next_id, relation FROM memory_links
                         UNION
                         SELECT target_id AS from_id, source_id AS next_id, relation FROM memory_links
                     ) edges ON edges.from_id = w.current_id
                     WHERE w.depth < LEAST(max_depth, 7)
                       AND NOT (edges.next_id = ANY(w.nodes))
                 )
                 SELECT
                     ROW_NUMBER() OVER (ORDER BY depth ASC, nodes ASC)::INTEGER AS path_id,
                     depth                                                      AS length,
                     nodes,
                     relations
                 FROM walk
                 WHERE depth >= 1
             $$",
        )
        .execute(&mut *tx)
        .await
        .map_err(|e| to_store_err("create kg_find_paths", e))?;

        record_schema_version(&mut tx, 24).await?;

        tx.commit()
            .await
            .map_err(|e| to_store_err("commit v24 migration", e))?;

        tracing::info!(target: TRACE_TARGET, "schema migration v24 applied");
        Ok(())
    }

    // ───────────────────────────────────────────────────────────────────
    // v0.7.0 schema parity — Wave 2 ports of SQLite migrations 0012-0022
    // (schema versions 17-28) onto the Postgres adapter. Each function
    // is independently idempotent: it re-issues IF NOT EXISTS DDL plus
    // explicit `information_schema.columns` checks for ALTER TABLE
    // additions Postgres lacks an `IF NOT EXISTS` clause for. The
    // bootstrap script (`postgres_schema.sql`) already creates the
    // current shape on a fresh init; these handlers exist for in-place
    // upgrades from v15-stamped or v23-stamped pre-existing deployments.
    // Mirrors the SQLite-side ladder in `crate::storage::migrations::migrate`.
    // ───────────────────────────────────────────────────────────────────

    /// v17 — Governance inheritance backfill.
    ///
    /// Mirrors `migrations/sqlite/0012_governance_inherit.sql`. Adds the
    /// `inherit` field (default `true`) to existing
    /// `metadata.governance` policy objects so the field is physically
    /// present on legacy rows. The Rust deserializer already defaults
    /// missing fields to `true`, so this only changes how the JSON
    /// looks at SQL inspection time, not the semantic resolution.
    /// Idempotent: only updates rows whose `inherit` is currently NULL.
    async fn migrate_v17(&self) -> StoreResult<()> {
        let mut tx = self
            .pool
            .begin()
            .await
            .map_err(|e| to_store_err("begin v17 tx", e))?;

        // Postgres jsonb_set sets inherit=true on `metadata.governance`
        // objects that don't yet carry the field. The WHERE clause
        // restricts the rewrite to JSON objects with a non-null
        // governance object whose `inherit` is missing — same shape as
        // the SQLite UPDATE in 0012_governance_inherit.sql.
        sqlx::query(
            "UPDATE memories
             SET metadata = jsonb_set(
                 metadata,
                 '{governance,inherit}',
                 'true'::jsonb,
                 true
             )
             WHERE jsonb_typeof(metadata -> 'governance') = 'object'
               AND NOT (metadata -> 'governance' ? 'inherit')",
        )
        .execute(&mut *tx)
        .await
        .map_err(|e| to_store_err("backfill governance.inherit", e))?;

        record_schema_version(&mut tx, 17).await?;

        tx.commit()
            .await
            .map_err(|e| to_store_err("commit v17 migration", e))?;

        tracing::info!(target: TRACE_TARGET, "schema migration v17 applied");
        Ok(())
    }

    /// v18 — Data-integrity hardening (`embedding_dim` columns + archive
    /// lossless metadata).
    ///
    /// Mirrors `migrations/sqlite/0011_v0631_data_integrity.sql` and the
    /// inline column adds in `db.rs::migrate` v18 block. Adds:
    ///   - `memories.embedding_dim`
    ///   - `archived_memories.embedding`, `embedding_dim`,
    ///     `original_tier`, `original_expires_at`
    /// plus the partial `embedding_dim` indexes on memories.
    ///
    /// Backfill: legacy rows have `embedding_dim` NULL; we leave them
    /// NULL because Postgres `vector` type does not expose an octet
    /// length matching SQLite's `length(embedding)/4` heuristic — the
    /// in-app daemon writes the dim alongside the vector going forward.
    /// `archived_memories.original_tier` is backfilled to `'long'` to
    /// match the SQLite path's defensive default.
    async fn migrate_v18(&self) -> StoreResult<()> {
        let mut tx = self
            .pool
            .begin()
            .await
            .map_err(|e| to_store_err("begin v18 tx", e))?;

        // Read the current dim of `memories.embedding` so we add the
        // archive-side column at the same dim. The bootstrap schema
        // has already run by the time we reach here, so this column
        // exists with whatever dim the operator chose at connect time.
        // Falls back to DEFAULT_EMBEDDING_DIM if the probe comes back
        // empty (defensive — should never happen in practice).
        let existing_dim: Option<(i32,)> = sqlx::query_as(
            "SELECT atttypmod FROM pg_attribute a
             JOIN pg_class c ON c.oid = a.attrelid
             JOIN pg_namespace n ON c.relnamespace = n.oid
             WHERE c.relname = 'memories' AND a.attname = 'embedding'
             AND n.nspname = 'public'",
        )
        .fetch_optional(&mut *tx)
        .await
        .map_err(|e| to_store_err("read memories.embedding dim in v18", e))?;
        let dim_for_archive = existing_dim.map_or(DEFAULT_EMBEDDING_DIM, |(d,)| {
            u32::try_from(d).unwrap_or(DEFAULT_EMBEDDING_DIM)
        });
        let archive_embedding_ddl =
            format!("ALTER TABLE archived_memories ADD COLUMN embedding vector({dim_for_archive})");

        for (table, column, ddl) in [
            (
                "memories",
                "embedding_dim",
                "ALTER TABLE memories ADD COLUMN embedding_dim INTEGER".to_string(),
            ),
            (TABLE_ARCHIVED_MEMORIES, "embedding", archive_embedding_ddl),
            (
                TABLE_ARCHIVED_MEMORIES,
                "embedding_dim",
                "ALTER TABLE archived_memories ADD COLUMN embedding_dim INTEGER".to_string(),
            ),
            (
                TABLE_ARCHIVED_MEMORIES,
                "original_tier",
                "ALTER TABLE archived_memories ADD COLUMN original_tier TEXT".to_string(),
            ),
            (
                TABLE_ARCHIVED_MEMORIES,
                "original_expires_at",
                "ALTER TABLE archived_memories ADD COLUMN original_expires_at TIMESTAMPTZ"
                    .to_string(),
            ),
        ] {
            add_column_if_missing(&mut tx, table, column, &ddl).await?;
        }

        // G5 backfill — pre-existing archive rows have lost original
        // tier/expiry; default original_tier to 'long' so restore_archived
        // doesn't immediately re-delete on first restore. NULL stays NULL
        // for original_expires_at (permanent until re-tiered).
        sqlx::query(
            "UPDATE archived_memories
             SET original_tier = 'long'
             WHERE original_tier IS NULL",
        )
        .execute(&mut *tx)
        .await
        .map_err(|e| to_store_err("backfill original_tier", e))?;

        // Partial indexes — match SQLite's idx_memories_embedding_dim and
        // idx_memories_ns_dim. The bootstrap creates these too; re-running
        // here is a no-op against a fresh init.
        sqlx::query(
            "CREATE INDEX IF NOT EXISTS idx_memories_embedding_dim
             ON memories (embedding_dim)
             WHERE embedding_dim IS NOT NULL",
        )
        .execute(&mut *tx)
        .await
        .map_err(|e| to_store_err("create idx_memories_embedding_dim", e))?;

        sqlx::query(
            "CREATE INDEX IF NOT EXISTS idx_memories_ns_dim
             ON memories (namespace, embedding_dim)
             WHERE embedding_dim IS NOT NULL",
        )
        .execute(&mut *tx)
        .await
        .map_err(|e| to_store_err("create idx_memories_ns_dim", e))?;

        record_schema_version(&mut tx, 18).await?;

        tx.commit()
            .await
            .map_err(|e| to_store_err("commit v18 migration", e))?;

        tracing::info!(target: TRACE_TARGET, "schema migration v18 applied");
        Ok(())
    }

    /// v19 — Webhook `event_types` JSON array on subscriptions.
    ///
    /// Mirrors `migrations/sqlite/0013_webhook_event_types.sql`. Adds a
    /// JSONB column for the structured event-type opt-in surface; the
    /// legacy `events` text column stays as the canonical match key at
    /// dispatch time. The supporting index keeps list_subscriptions
    /// O(log n) when callers want to scope by event.
    async fn migrate_v19(&self) -> StoreResult<()> {
        let mut tx = self
            .pool
            .begin()
            .await
            .map_err(|e| to_store_err("begin v19 tx", e))?;

        add_column_if_missing(
            &mut tx,
            field_names::SUBSCRIPTIONS,
            field_names::EVENT_TYPES,
            "ALTER TABLE subscriptions ADD COLUMN event_types JSONB",
        )
        .await?;

        sqlx::query(
            "CREATE INDEX IF NOT EXISTS idx_subscriptions_event_types
             ON subscriptions (event_types)",
        )
        .execute(&mut *tx)
        .await
        .map_err(|e| to_store_err("create idx_subscriptions_event_types", e))?;

        record_schema_version(&mut tx, 19).await?;

        tx.commit()
            .await
            .map_err(|e| to_store_err("commit v19 migration", e))?;

        tracing::info!(target: TRACE_TARGET, "schema migration v19 applied");
        Ok(())
    }

    /// v20 — Capability-expansion `audit_log` table.
    ///
    /// Mirrors `migrations/sqlite/0014_v064_audit_log.sql`. Idempotent
    /// CREATE TABLE IF NOT EXISTS + indexes. The Postgres column type
    /// for `granted` is BOOLEAN where SQLite uses INTEGER 0/1; both
    /// surface as Rust `bool` so callers stay backend-agnostic.
    async fn migrate_v20(&self) -> StoreResult<()> {
        let mut tx = self
            .pool
            .begin()
            .await
            .map_err(|e| to_store_err("begin v20 tx", e))?;

        sqlx::query(
            "CREATE TABLE IF NOT EXISTS audit_log (
                id                 TEXT PRIMARY KEY,
                agent_id           TEXT,
                event_type         TEXT NOT NULL,
                requested_family   TEXT,
                granted            BOOLEAN NOT NULL,
                attestation_tier   TEXT,
                timestamp          TIMESTAMPTZ NOT NULL
            )",
        )
        .execute(&mut *tx)
        .await
        .map_err(|e| to_store_err("create audit_log table", e))?;

        for (name, ddl) in [
            (
                "idx_audit_log_agent_id",
                "CREATE INDEX IF NOT EXISTS idx_audit_log_agent_id ON audit_log (agent_id)",
            ),
            (
                "idx_audit_log_timestamp",
                "CREATE INDEX IF NOT EXISTS idx_audit_log_timestamp ON audit_log (timestamp)",
            ),
            (
                "idx_audit_log_event_type",
                "CREATE INDEX IF NOT EXISTS idx_audit_log_event_type ON audit_log (event_type)",
            ),
        ] {
            sqlx::query(ddl)
                .execute(&mut *tx)
                .await
                .map_err(|e| to_store_err(&format!("create {name}"), e))?;
        }

        record_schema_version(&mut tx, 20).await?;

        tx.commit()
            .await
            .map_err(|e| to_store_err("commit v20 migration", e))?;

        tracing::info!(target: TRACE_TARGET, "schema migration v20 applied");
        Ok(())
    }

    /// v21 — `pending_actions` timeout sweeper columns + sweep index.
    ///
    /// Mirrors `migrations/sqlite/0015_v07_pending_action_timeouts.sql`
    /// and the inline column adds in `db.rs::migrate` v21 block. Adds:
    ///   - `pending_actions.default_timeout_seconds` (per-row TTL)
    ///   - `pending_actions.expired_at` (RFC3339 stamp on transition)
    /// plus the composite `(status, requested_at)` sweep index.
    async fn migrate_v21(&self) -> StoreResult<()> {
        let mut tx = self
            .pool
            .begin()
            .await
            .map_err(|e| to_store_err("begin v21 tx", e))?;

        add_column_if_missing(
            &mut tx,
            "pending_actions",
            field_names::DEFAULT_TIMEOUT_SECONDS,
            "ALTER TABLE pending_actions ADD COLUMN default_timeout_seconds BIGINT",
        )
        .await?;

        add_column_if_missing(
            &mut tx,
            "pending_actions",
            field_names::EXPIRED_AT,
            "ALTER TABLE pending_actions ADD COLUMN expired_at TIMESTAMPTZ",
        )
        .await?;

        sqlx::query(
            "CREATE INDEX IF NOT EXISTS pending_actions_status_requested_idx
             ON pending_actions (status, requested_at)",
        )
        .execute(&mut *tx)
        .await
        .map_err(|e| to_store_err("create pending_actions_status_requested_idx", e))?;

        record_schema_version(&mut tx, 21).await?;

        tx.commit()
            .await
            .map_err(|e| to_store_err("commit v21 migration", e))?;

        tracing::info!(target: TRACE_TARGET, "schema migration v21 applied");
        Ok(())
    }

    /// v22 — `memory_transcripts` substrate (attested-cortex epic, I1).
    ///
    /// Mirrors `migrations/sqlite/0016_v07_transcripts.sql`. Compressed
    /// (zstd-3) blob storage of conversation transcripts. The Rust
    /// transcripts.rs read/write path currently binds to SQLite; the
    /// table is provisioned here for parity so a Postgres bootstrap is
    /// one wiring change away from full SAL coverage.
    async fn migrate_v22(&self) -> StoreResult<()> {
        let mut tx = self
            .pool
            .begin()
            .await
            .map_err(|e| to_store_err("begin v22 tx", e))?;

        sqlx::query(
            "CREATE TABLE IF NOT EXISTS memory_transcripts (
                id               TEXT PRIMARY KEY,
                namespace        TEXT NOT NULL,
                created_at       TIMESTAMPTZ NOT NULL,
                expires_at       TIMESTAMPTZ,
                compressed_size  BIGINT NOT NULL,
                original_size    BIGINT NOT NULL,
                zstd_level       INTEGER NOT NULL DEFAULT 3,
                content_blob     BYTEA NOT NULL
            )",
        )
        .execute(&mut *tx)
        .await
        .map_err(|e| to_store_err("create memory_transcripts table", e))?;

        sqlx::query(
            "CREATE INDEX IF NOT EXISTS idx_memory_transcripts_namespace_created
             ON memory_transcripts (namespace, created_at)",
        )
        .execute(&mut *tx)
        .await
        .map_err(|e| to_store_err("create idx_memory_transcripts_namespace_created", e))?;

        record_schema_version(&mut tx, 22).await?;

        tx.commit()
            .await
            .map_err(|e| to_store_err("commit v22 migration", e))?;

        tracing::info!(target: TRACE_TARGET, "schema migration v22 applied");
        Ok(())
    }

    /// v25 — Per-namespace transcript TTL with archive→prune lifecycle (I3).
    ///
    /// Mirrors `migrations/sqlite/0019_v07_transcript_lifecycle.sql` and
    /// the inline ADD COLUMN in `db.rs::migrate` v25 block. Adds
    /// `memory_transcripts.archived_at` plus the supporting partial
    /// index on archived rows so the prune-phase scan stays
    /// O(archived) rather than O(total transcripts).
    async fn migrate_v25(&self) -> StoreResult<()> {
        let mut tx = self
            .pool
            .begin()
            .await
            .map_err(|e| to_store_err("begin v25 tx", e))?;

        add_column_if_missing(
            &mut tx,
            "memory_transcripts",
            field_names::ARCHIVED_AT,
            "ALTER TABLE memory_transcripts ADD COLUMN archived_at TIMESTAMPTZ",
        )
        .await?;

        sqlx::query(
            "CREATE INDEX IF NOT EXISTS idx_memory_transcripts_archived_at
             ON memory_transcripts (archived_at)
             WHERE archived_at IS NOT NULL",
        )
        .execute(&mut *tx)
        .await
        .map_err(|e| to_store_err("create idx_memory_transcripts_archived_at", e))?;

        record_schema_version(&mut tx, 25).await?;

        tx.commit()
            .await
            .map_err(|e| to_store_err("commit v25 migration", e))?;

        tracing::info!(target: TRACE_TARGET, "schema migration v25 applied");
        Ok(())
    }

    /// v26 — `signed_events` append-only audit table (H5).
    ///
    /// Mirrors `migrations/sqlite/0020_v07_signed_events.sql`. The
    /// append-only invariant is enforced at the Rust API surface (one
    /// writer, no UPDATE/DELETE call sites) — no SQL-layer triggers
    /// here because they would also fire against operator-driven
    /// retention pruning, defeating the documented escape hatch.
    async fn migrate_v26(&self) -> StoreResult<()> {
        let mut tx = self
            .pool
            .begin()
            .await
            .map_err(|e| to_store_err("begin v26 tx", e))?;

        sqlx::query(
            "CREATE TABLE IF NOT EXISTS signed_events (
                id           TEXT PRIMARY KEY,
                agent_id     TEXT NOT NULL,
                event_type   TEXT NOT NULL,
                payload_hash BYTEA NOT NULL,
                signature    BYTEA,
                attest_level TEXT NOT NULL DEFAULT 'unsigned',
                timestamp    TIMESTAMPTZ NOT NULL
            )",
        )
        .execute(&mut *tx)
        .await
        .map_err(|e| to_store_err("create signed_events table", e))?;

        for (name, ddl) in [
            (
                "idx_signed_events_agent",
                "CREATE INDEX IF NOT EXISTS idx_signed_events_agent ON signed_events (agent_id)",
            ),
            (
                "idx_signed_events_type",
                "CREATE INDEX IF NOT EXISTS idx_signed_events_type ON signed_events (event_type)",
            ),
            (
                "idx_signed_events_timestamp",
                "CREATE INDEX IF NOT EXISTS idx_signed_events_timestamp ON signed_events (timestamp)",
            ),
        ] {
            sqlx::query(ddl)
                .execute(&mut *tx)
                .await
                .map_err(|e| to_store_err(&format!("create {name}"), e))?;
        }

        record_schema_version(&mut tx, 26).await?;

        tx.commit()
            .await
            .map_err(|e| to_store_err("commit v26 migration", e))?;

        tracing::info!(target: TRACE_TARGET, "schema migration v26 applied");
        Ok(())
    }

    /// v27 — A2A correlation IDs + DLQ.
    ///
    /// Mirrors `migrations/sqlite/0021_v07_a2a_correlation.sql`. Brings
    /// up `subscription_events` (per-delivery audit log keyed on
    /// UUIDv7 correlation_id) and `subscription_dlq` (failures past
    /// the three-attempt retry ladder). On Postgres these tables use
    /// BIGSERIAL primary keys; the Rust callers see monotonically-
    /// increasing i64 values matching SQLite's autoincrement.
    async fn migrate_v27(&self) -> StoreResult<()> {
        let mut tx = self
            .pool
            .begin()
            .await
            .map_err(|e| to_store_err("begin v27 tx", e))?;

        sqlx::query(
            "CREATE TABLE IF NOT EXISTS subscription_events (
                id              BIGSERIAL PRIMARY KEY,
                subscription_id TEXT NOT NULL,
                correlation_id  TEXT NOT NULL DEFAULT '',
                event_type      TEXT NOT NULL,
                payload         JSONB NOT NULL,
                delivered_at    TIMESTAMPTZ NOT NULL,
                delivery_status TEXT NOT NULL DEFAULT 'pending'
            )",
        )
        .execute(&mut *tx)
        .await
        .map_err(|e| to_store_err("create subscription_events table", e))?;

        // Defensive ALTER TABLE for deployments that hand-rolled a
        // `subscription_events` table before K6 (mirrors the inline
        // column add in crate::storage::migrations::migrate v27 block).
        add_column_if_missing(
            &mut tx,
            "subscription_events",
            "correlation_id",
            "ALTER TABLE subscription_events ADD COLUMN correlation_id TEXT NOT NULL DEFAULT ''",
        )
        .await?;

        sqlx::query(
            "CREATE INDEX IF NOT EXISTS idx_subscription_events_correlation
             ON subscription_events (correlation_id)",
        )
        .execute(&mut *tx)
        .await
        .map_err(|e| to_store_err("create idx_subscription_events_correlation", e))?;

        sqlx::query(
            "CREATE INDEX IF NOT EXISTS idx_subscription_events_subscription
             ON subscription_events (subscription_id, delivered_at)",
        )
        .execute(&mut *tx)
        .await
        .map_err(|e| to_store_err("create idx_subscription_events_subscription", e))?;

        sqlx::query(
            "CREATE TABLE IF NOT EXISTS subscription_dlq (
                id               BIGSERIAL PRIMARY KEY,
                subscription_id  TEXT NOT NULL,
                correlation_id   TEXT NOT NULL,
                event_type       TEXT NOT NULL,
                payload          JSONB NOT NULL,
                retry_count      INTEGER NOT NULL,
                last_error       TEXT NOT NULL,
                first_failed_at  TIMESTAMPTZ NOT NULL,
                last_failed_at   TIMESTAMPTZ NOT NULL
            )",
        )
        .execute(&mut *tx)
        .await
        .map_err(|e| to_store_err("create subscription_dlq table", e))?;

        sqlx::query(
            "CREATE INDEX IF NOT EXISTS idx_subscription_dlq_subscription
             ON subscription_dlq (subscription_id, last_failed_at)",
        )
        .execute(&mut *tx)
        .await
        .map_err(|e| to_store_err("create idx_subscription_dlq_subscription", e))?;

        sqlx::query(
            "CREATE INDEX IF NOT EXISTS idx_subscription_dlq_correlation
             ON subscription_dlq (correlation_id)",
        )
        .execute(&mut *tx)
        .await
        .map_err(|e| to_store_err("create idx_subscription_dlq_correlation", e))?;

        record_schema_version(&mut tx, 27).await?;

        tx.commit()
            .await
            .map_err(|e| to_store_err("commit v27 migration", e))?;

        tracing::info!(target: TRACE_TARGET, "schema migration v27 applied");
        Ok(())
    }

    /// v28 — Per-agent quotas (`agent_quotas`).
    ///
    /// Mirrors `migrations/sqlite/0022_v07_agent_quotas.sql`. Idempotent
    /// CREATE TABLE IF NOT EXISTS + index. Compiled defaults match the
    /// SQLite path: 1000 memories/day, 100 MiB storage cap, 5000
    /// links/day. Daily counters reset at UTC midnight via the K8
    /// sweep loop (currently SQLite-bound; SAL wiring in a future wave).
    async fn migrate_v28(&self) -> StoreResult<()> {
        let mut tx = self
            .pool
            .begin()
            .await
            .map_err(|e| to_store_err("begin v28 tx", e))?;

        sqlx::query(&format!(
            "CREATE TABLE IF NOT EXISTS agent_quotas (
                agent_id                TEXT PRIMARY KEY,
                max_memories_per_day    BIGINT  NOT NULL DEFAULT {memories},
                max_storage_bytes       BIGINT  NOT NULL DEFAULT {storage},
                max_links_per_day       BIGINT  NOT NULL DEFAULT {links},
                current_memories_today  BIGINT  NOT NULL DEFAULT 0,
                current_storage_bytes   BIGINT  NOT NULL DEFAULT 0,
                current_links_today     BIGINT  NOT NULL DEFAULT 0,
                day_started_at          TIMESTAMPTZ NOT NULL,
                created_at              TIMESTAMPTZ NOT NULL,
                updated_at              TIMESTAMPTZ NOT NULL
            )",
            memories = crate::quotas::DEFAULT_MAX_MEMORIES_PER_DAY,
            storage = crate::quotas::DEFAULT_MAX_STORAGE_BYTES,
            links = crate::quotas::DEFAULT_MAX_LINKS_PER_DAY,
        ))
        .execute(&mut *tx)
        .await
        .map_err(|e| to_store_err("create agent_quotas table", e))?;

        sqlx::query(
            "CREATE INDEX IF NOT EXISTS idx_agent_quotas_agent_id
             ON agent_quotas (agent_id)",
        )
        .execute(&mut *tx)
        .await
        .map_err(|e| to_store_err("create idx_agent_quotas_agent_id", e))?;

        record_schema_version(&mut tx, 28).await?;

        tx.commit()
            .await
            .map_err(|e| to_store_err("commit v28 migration", e))?;

        tracing::info!(target: TRACE_TARGET, "schema migration v28 applied");
        Ok(())
    }

    /// v0.6.3 Stream B — Temporal-Validity KG schema additions.
    /// Idempotent: safe to run twice. Mirrors src/db.rs migrate v15 block.
    async fn migrate_v15(&self) -> StoreResult<()> {
        let mut tx = self
            .pool
            .begin()
            .await
            .map_err(|e| to_store_err("begin transaction", e))?;

        // Add temporal columns to memory_links if they do not exist.
        let has_valid_from: bool = sqlx::query_scalar(
            "SELECT EXISTS(
                SELECT 1 FROM information_schema.columns
                WHERE table_name='memory_links' AND column_name='valid_from'
            )",
        )
        .fetch_one(&mut *tx)
        .await
        .map_err(|e| to_store_err("check valid_from column", e))?;

        if !has_valid_from {
            sqlx::query("ALTER TABLE memory_links ADD COLUMN valid_from TIMESTAMPTZ")
                .execute(&mut *tx)
                .await
                .map_err(|e| to_store_err("add valid_from column", e))?;
        }

        let has_valid_until: bool = sqlx::query_scalar(
            "SELECT EXISTS(
                SELECT 1 FROM information_schema.columns
                WHERE table_name='memory_links' AND column_name='valid_until'
            )",
        )
        .fetch_one(&mut *tx)
        .await
        .map_err(|e| to_store_err("check valid_until column", e))?;

        if !has_valid_until {
            sqlx::query("ALTER TABLE memory_links ADD COLUMN valid_until TIMESTAMPTZ")
                .execute(&mut *tx)
                .await
                .map_err(|e| to_store_err("add valid_until column", e))?;
        }

        let has_observed_by: bool = sqlx::query_scalar(
            "SELECT EXISTS(
                SELECT 1 FROM information_schema.columns
                WHERE table_name='memory_links' AND column_name='observed_by'
            )",
        )
        .fetch_one(&mut *tx)
        .await
        .map_err(|e| to_store_err("check observed_by column", e))?;

        if !has_observed_by {
            sqlx::query("ALTER TABLE memory_links ADD COLUMN observed_by TEXT")
                .execute(&mut *tx)
                .await
                .map_err(|e| to_store_err("add observed_by column", e))?;
        }

        let has_signature: bool = sqlx::query_scalar(
            "SELECT EXISTS(
                SELECT 1 FROM information_schema.columns
                WHERE table_name='memory_links' AND column_name='signature'
            )",
        )
        .fetch_one(&mut *tx)
        .await
        .map_err(|e| to_store_err("check signature column", e))?;

        if !has_signature {
            sqlx::query("ALTER TABLE memory_links ADD COLUMN signature BYTEA")
                .execute(&mut *tx)
                .await
                .map_err(|e| to_store_err("add signature column", e))?;
        }

        // Backfill valid_from from source memory's created_at (idempotent).
        sqlx::query(
            "UPDATE memory_links
             SET valid_from = (SELECT created_at FROM memories WHERE id = memory_links.source_id)
             WHERE valid_from IS NULL",
        )
        .execute(&mut *tx)
        .await
        .map_err(|e| to_store_err("backfill valid_from", e))?;

        // Create temporal indexes (idempotent via IF NOT EXISTS).
        sqlx::query(
            "CREATE INDEX IF NOT EXISTS idx_links_temporal_src
             ON memory_links (source_id, valid_from, valid_until)",
        )
        .execute(&mut *tx)
        .await
        .map_err(|e| to_store_err("create idx_links_temporal_src", e))?;

        sqlx::query(
            "CREATE INDEX IF NOT EXISTS idx_links_temporal_tgt
             ON memory_links (target_id, valid_from, valid_until)",
        )
        .execute(&mut *tx)
        .await
        .map_err(|e| to_store_err("create idx_links_temporal_tgt", e))?;

        sqlx::query(
            "CREATE INDEX IF NOT EXISTS idx_links_relation
             ON memory_links (relation, valid_from)",
        )
        .execute(&mut *tx)
        .await
        .map_err(|e| to_store_err("create idx_links_relation", e))?;

        // Create entity_aliases table (idempotent via IF NOT EXISTS).
        sqlx::query(
            "CREATE TABLE IF NOT EXISTS entity_aliases (
                entity_id  TEXT NOT NULL,
                alias      TEXT NOT NULL,
                created_at TIMESTAMPTZ NOT NULL DEFAULT NOW(),
                PRIMARY KEY (entity_id, alias)
            )",
        )
        .execute(&mut *tx)
        .await
        .map_err(|e| to_store_err("create entity_aliases table", e))?;

        sqlx::query(
            "CREATE INDEX IF NOT EXISTS idx_entity_aliases_alias
             ON entity_aliases (alias)",
        )
        .execute(&mut *tx)
        .await
        .map_err(|e| to_store_err("create idx_entity_aliases_alias", e))?;

        // Record the migration in schema_version.
        record_schema_version(&mut tx, 15).await?;

        tx.commit()
            .await
            .map_err(|e| to_store_err("commit migration transaction", e))?;

        tracing::info!(
            target: TRACE_TARGET,
            version = 15,
            "schema migration v15 applied"
        );

        Ok(())
    }

    /// Outbound knowledge-graph traversal — v0.7 Track J dispatcher.
    ///
    /// Routes on the [`KgBackend`] resolved at [`Self::connect`] time
    /// (J1 substrate). When AGE is installed the traversal runs as a
    /// Cypher `MATCH ... -[:related_to*1..N]-> ...` query through the
    /// `memory_graph` projection; otherwise we fall back to a recursive
    /// CTE over the `memory_links` table that mirrors the SQLite shape.
    ///
    /// Both branches return rows in the same [`KgQueryRow`] shape so
    /// the upper-layer `memory_kg_query` handler can stay backend-blind.
    ///
    /// `max_depth` is clamped at [`KG_QUERY_MAX_SUPPORTED_DEPTH`] to
    /// match the SQLite implementation's published budget; passing a
    /// larger value yields an explicit error rather than a silent
    /// truncation, so callers learn they hit the ceiling.
    ///
    /// # Errors
    ///
    /// Returns `StoreError::InvalidInput` when `max_depth` is zero or
    /// exceeds the supported ceiling, and `StoreError::BackendUnavailable`
    /// when the underlying SQL or Cypher query fails.
    pub async fn kg_query(
        &self,
        source_id: &str,
        max_depth: usize,
    ) -> StoreResult<Vec<KgQueryRow>> {
        // v0.7.0 Wave-3 Continuation 5 — see `kg_query_with_history`
        // for the AGE-vs-CTE rationale. This entry point hides the
        // `include_invalidated` knob (defaults to false / "current
        // view") for callers that don't care about the historical
        // posture; S82 + parity tests use this wider-scoped variant.
        self.kg_query_with_history(source_id, max_depth, false)
            .await
    }

    /// Outbound traversal with explicit historical-view toggle.
    /// `include_invalidated=true` lifts the
    /// `valid_until IS NULL OR valid_until > NOW()` filter so callers
    /// can read the full historical edge graph (S45's `as_of=past`
    /// semantics through `memory_kg_query`).
    pub async fn kg_query_with_history(
        &self,
        source_id: &str,
        max_depth: usize,
        include_invalidated: bool,
    ) -> StoreResult<Vec<KgQueryRow>> {
        // v0.7.0 S6-M3 — AGE Cypher dispatcher. Routes on the
        // `kg_backend` resolved at `connect()` time (J1 substrate
        // probe). The AGE path delivers the ~30% speed-up advertised
        // in ROADMAP §7.4.4; the CTE path is the universal fallback
        // for vanilla Postgres deployments. Dual-path test discipline
        // (#648) requires identical KgQueryRow outputs from both
        // branches — `tests/postgres_kg_age_cte_parity.rs` pins that
        // contract.
        //
        // `include_invalidated=true` lifts the historical filter; the
        // Cypher branch doesn't expose that switch yet (#681) so we
        // fall back to the CTE for historical queries even when AGE
        // is available. AGE's coverage is the "current view" hot
        // path — historical traversal is a smaller niche and lives on
        // the CTE.
        // v0.7.0 fold-A2A1.3 (#700) — runtime AGE→CTE graceful
        // fallback. Boot-time `detect_kg_backend` is already graceful
        // for the missing-extension case, but a `LOAD 'age'` /
        // `cypher()` call can still fail at request time (DROP
        // EXTENSION between boot and now, projection missing, role
        // permissions on `ag_catalog`, transient pool error). Rather
        // than propagate `BackendUnavailable` to the four KG MCP
        // handlers — which historically materialised as a hard 503 on
        // `kg_query` / `kg_timeline` / `kg_invalidate` /
        // `find_paths` — we catch the AGE-side failure, log a
        // structured warning, and re-issue via the relational CTE so
        // operators see a degraded but functional KG surface. Each
        // request retries AGE first; we don't latch the backend
        // permanently in case the operator restores AGE behind us.
        match self.kg_backend {
            KgBackend::Age if !include_invalidated => {
                match self.kg_query_cypher(source_id, max_depth).await {
                    Ok(rows) => Ok(rows),
                    Err(err) if is_age_runtime_failure(&err) => {
                        warn_age_fallback("kg_query", source_id, &err);
                        self.kg_query_cte_filtered(source_id, max_depth, include_invalidated)
                            .await
                    }
                    Err(err) => Err(err),
                }
            }
            _ => {
                self.kg_query_cte_filtered(source_id, max_depth, include_invalidated)
                    .await
            }
        }
    }

    /// Cypher (Apache AGE) implementation of `kg_query`.
    ///
    /// Wraps a `MATCH (a)-[:related_to*1..N]->(b)` traversal in the
    /// `cypher('memory_graph', ...)` set-returning function. Parameter
    /// passing uses AGE's `$vars` syntax through a JSON-encoded second
    /// argument so the start id is bound — never interpolated — to
    /// keep the surface free of injection hazards.
    ///
    /// The graph projection (`memory_graph`) and the `:related_to`
    /// edge label are conventions established by the J1 schema-prep
    /// scripts. When the projection is absent the underlying call
    /// surfaces as `BackendUnavailable` so the test harness can
    /// distinguish "AGE present, graph missing" from a real bug.
    ///
    /// # Errors
    ///
    /// Returns `StoreError::InvalidInput` for an out-of-range
    /// `max_depth`, and `StoreError::BackendUnavailable` for any sqlx
    /// or AGE error.
    pub async fn kg_query_cypher(
        &self,
        source_id: &str,
        max_depth: usize,
    ) -> StoreResult<Vec<KgQueryRow>> {
        validate_depth(max_depth)?;

        // AGE requires `ag_catalog` on the search path and the extension
        // loaded into the session. Both are session-local — sqlx hands
        // each query a fresh connection from the pool so we issue them
        // as part of the same transaction to keep them in scope.
        let mut tx = self
            .pool
            .begin()
            .await
            .map_err(|e| to_store_err(CTX_BEGIN_AGE_TX, e))?;

        // #1640 — tolerated LOAD (see load_age_tolerated): a role-level
        // LOAD refusal must not fail the query on fleets where
        // shared_preload_libraries provides the library.
        load_age_tolerated(&mut tx).await?;
        // #925 (2026-05-20): use `SET LOCAL` so the search_path
        // mutation is transaction-scoped and auto-reverts at
        // COMMIT/ROLLBACK. Pre-fix the bare `SET search_path`
        // persisted across the transaction boundary; sqlx's pool
        // reset doesn't fire until the NEXT checkout, so a subsequent
        // regular `INSERT INTO memories` on the same pooled
        // connection inherited `ag_catalog` as the first search_path
        // entry and the row landed under `ag_catalog.memories`
        // instead of the operator-requested per-IronClaw schema
        // (e.g. `ic_alice`). That broke the per-daemon data
        // isolation the lan-parity test mesh depends on. The other
        // three AGE entry points (sibling sites below) follow the
        // same `SET LOCAL` pattern.
        sqlx::query(SQL_SET_AGE_SEARCH_PATH)
            .execute(&mut *tx)
            .await
            .map_err(|e| to_store_err(CTX_SET_SEARCH_PATH, e))?;

        // Build the Cypher body. `max_depth` is interpolated into the
        // variable-length pattern (Cypher does NOT accept a parameter
        // there); we already clamped it via `validate_depth` so the
        // value is a small bounded integer with no injection surface.
        // The start id + the as-of cut-off are parameterised through
        // AGE's `$vars` JSON.
        let cypher = build_kg_query_current_view_cypher(max_depth);

        // #1689 — current-view traversal MUST exclude invalidated edges.
        // `kg_invalidate_cypher` SETs `r.valid_until` (it does NOT delete
        // the edge), so without this filter a current-view query returns
        // edges that were already invalidated — the same defect the CTE
        // path carried. The cut-off is the relational-mirror's RFC3339
        // form (`to_rfc3339`, `+00:00` offset) so the agtype string
        // comparison matches the dual-written value byte-for-byte.
        // Defense in depth: if a given AGE build rejects the
        // `relationships()`/`ALL()` predicate, the dispatcher's
        // `is_age_runtime_failure` arm in `kg_query_with_history` falls
        // back to the already-correct `kg_query_cte_filtered`.
        let now_stamp = Utc::now().to_rfc3339();

        // v0.7.0 Wave-3 Continuation 5 — AGE rejects `$1::agtype` (the
        // third arg to `cypher()` must be a bare Param node, not a
        // FuncExpr cast). Inline the params object as a literal
        // agtype constant; `source_id` is UUID-validated upstream so
        // this is safe. The dollar-quoted string body uses `$$`; the
        // params literal lives outside it.
        let params_lit = age_params_literal(&[("start_id", source_id), ("now", &now_stamp)]);
        let sql = format!(
            "SELECT target_id, relation, depth, path FROM cypher('memory_graph', $$ {cypher} $$, \
             {params_lit}) AS (target_id agtype, relation agtype, depth agtype, path agtype)"
        );

        // #1482 — the cypher text is per-call-unique (inlined ids +
        // depth), so caching it as a named prepared statement only
        // pollutes the bounded per-connection LRU and evicts genuinely
        // reusable hot statements. Run it via the unnamed statement.
        let rows = sqlx::query(&sql)
            .persistent(false)
            .fetch_all(&mut *tx)
            .await
            .map_err(|e| to_store_err("cypher kg_query", e))?;

        tx.commit()
            .await
            .map_err(|e| to_store_err(CTX_COMMIT_AGE_TX, e))?;

        rows.iter()
            .map(|r| {
                // AGE returns `agtype`. sqlx has no first-class agtype
                // decoder; we read each cell as String and trim AGE's
                // quoting (`"id"` -> `id`, `2` stays `2`). This keeps
                // the dependency surface minimal — pulling a dedicated
                // agtype crate would balloon CI for one type tag.
                let target_id: String = r
                    .try_get::<String, _>("target_id")
                    .map_err(|e| to_store_err(READ_TARGET_ID, e))?;
                let relation: String = r
                    .try_get::<String, _>("relation")
                    .map_err(|e| to_store_err(READ_RELATION, e))?;
                let depth_raw: String = r
                    .try_get::<String, _>("depth")
                    .map_err(|e| to_store_err("read depth", e))?;
                let path: String = r
                    .try_get::<String, _>("path")
                    .map_err(|e| to_store_err("read path", e))?;
                let depth: usize = strip_agtype_quotes(&depth_raw).parse().map_err(|_| {
                    StoreError::IntegrityFailed {
                        detail: format!("non-numeric AGE depth: {depth_raw}"),
                    }
                })?;
                Ok(KgQueryRow {
                    target_id: strip_agtype_quotes(&target_id).to_string(),
                    relation: strip_agtype_quotes(&relation).to_string(),
                    depth,
                    path: strip_agtype_quotes(&path).to_string(),
                })
            })
            .collect()
    }

    /// Recursive-CTE fallback for `kg_query` on Postgres.
    ///
    /// Mirrors the SQLite recursive-CTE in `db::kg_query` so deployments
    /// running vanilla Postgres (no AGE extension) still get the same
    /// traversal semantics. Returns the shared [`KgQueryRow`] shape —
    /// the dispatcher in [`Self::kg_query`] doesn't have to care which
    /// branch ran.
    ///
    /// # Errors
    ///
    /// `StoreError::InvalidInput` for an out-of-range `max_depth`;
    /// `StoreError::BackendUnavailable` for any sqlx error.
    pub async fn kg_query_cte(
        &self,
        source_id: &str,
        max_depth: usize,
    ) -> StoreResult<Vec<KgQueryRow>> {
        // Default current-view posture mirrors `db::kg_query` —
        // invalidated edges hidden. Callers that need the historical
        // view go through `kg_query_with_history` /
        // `kg_query_cte_filtered`.
        self.kg_query_cte_filtered(source_id, max_depth, false)
            .await
    }

    /// Recursive-CTE traversal with explicit historical-view toggle.
    /// `include_invalidated=true` lifts the
    /// `valid_until IS NULL OR valid_until > NOW()` filter on both
    /// the CTE seed AND step rows.
    pub async fn kg_query_cte_filtered(
        &self,
        source_id: &str,
        max_depth: usize,
        include_invalidated: bool,
    ) -> StoreResult<Vec<KgQueryRow>> {
        validate_depth(max_depth)?;

        let depth_cap = i32::try_from(max_depth).unwrap_or(i32::MAX);
        // v0.7.0 Wave-3 Continuation 5 — filter out invalidated edges
        // (`valid_until` set in the past) so `as_of=now` queries
        // only see currently-valid edges. The filter clause is
        // dropped in via format! when include_invalidated is false;
        // the historical view (`include_invalidated=true`) issues
        // the same SQL with `TRUE` in place of the predicate so the
        // query plan stays uniform across views.
        let valid_filter = if include_invalidated {
            "TRUE"
        } else {
            "(ml.valid_until IS NULL OR ml.valid_until > NOW())"
        };
        // v0.7.0 #1086 (SR-2 #4, MEDIUM) — array-based cycle
        // detection in the runtime kg_query CTE. Mirrors the view
        // fix; closes the substring false-positive when one id is a
        // substring of another at the `->` boundary.
        let sql = format!(
            "WITH RECURSIVE traversal(target_id, relation, depth, nodes) AS (
                SELECT ml.target_id, ml.relation, 1,
                       ARRAY[ml.source_id, ml.target_id]::TEXT[]
                FROM memory_links ml
                WHERE ml.source_id = $1
                  AND {valid_filter}
                UNION ALL
                SELECT ml.target_id, ml.relation, t.depth + 1,
                       t.nodes || ml.target_id
                FROM memory_links ml
                JOIN traversal t ON ml.source_id = t.target_id
                WHERE t.depth < $2
                  AND NOT (ml.target_id = ANY(t.nodes))
                  AND {valid_filter}
            )
            SELECT target_id, relation, depth,
                   array_to_string(nodes, '->') AS path
            FROM traversal
            ORDER BY depth ASC, target_id ASC"
        );

        let rows = sqlx::query(&sql)
            .bind(source_id)
            .bind(depth_cap)
            .fetch_all(&self.pool)
            .await
            .map_err(|e| to_store_err("cte kg_query", e))?;

        rows.iter()
            .map(|r| {
                let target_id: String = r
                    .try_get::<String, _>("target_id")
                    .map_err(|e| to_store_err(READ_TARGET_ID, e))?;
                let relation: String = r
                    .try_get::<String, _>("relation")
                    .map_err(|e| to_store_err(READ_RELATION, e))?;
                let depth_i: i32 = r
                    .try_get::<i32, _>("depth")
                    .map_err(|e| to_store_err("read depth", e))?;
                let path: String = r
                    .try_get::<String, _>("path")
                    .map_err(|e| to_store_err("read path", e))?;
                Ok(KgQueryRow {
                    target_id,
                    relation,
                    depth: usize::try_from(depth_i).unwrap_or(0),
                    path,
                })
            })
            .collect()
    }

    /// Ordered fact timeline for an entity — v0.7 Track J dispatcher.
    ///
    /// Routes on the [`KgBackend`] resolved at [`Self::connect`] time
    /// (J1 substrate). When AGE is installed the timeline is assembled
    /// via a Cypher `MATCH (a)-[r]->(b)` over the `memory_graph`
    /// projection, ordered by `r.valid_from ASC`; otherwise we fall
    /// back to a plain SQL scan over `memory_links` joined to
    /// `memories` that mirrors the SQLite shape in `db::kg_timeline`.
    ///
    /// Both branches return rows in the same [`KgTimelineRow`] shape
    /// so the upper-layer `memory_kg_timeline` handler can stay
    /// backend-blind, mirroring J2's pattern for `kg_query`.
    ///
    /// `since` and `until` are RFC3339 timestamps (inclusive) that
    /// filter on `valid_from`; `limit` is clamped to
    /// `[1, KG_TIMELINE_MAX_LIMIT_SAL]` and defaults to
    /// [`KG_TIMELINE_DEFAULT_LIMIT_SAL`] when omitted.
    ///
    /// Rows with NULL `valid_from` are excluded — a link without a
    /// valid-from anchor cannot be ordered on the timeline. This
    /// matches the SQLite contract documented on `db::kg_timeline`.
    ///
    /// # Errors
    ///
    /// Returns `StoreError::InvalidInput` for malformed timestamp
    /// inputs; `StoreError::BackendUnavailable` for any sqlx or AGE
    /// error.
    pub async fn kg_timeline(
        &self,
        source_id: &str,
        since: Option<&str>,
        until: Option<&str>,
        limit: Option<usize>,
    ) -> StoreResult<Vec<KgTimelineRow>> {
        // v0.7.0 S6-M3 — AGE Cypher dispatcher. Routes on the
        // resolved `kg_backend` so the AGE-installed deployments get
        // the property-graph-path speedup while vanilla Postgres
        // deployments keep the relational CTE. The dual-path
        // discipline (#648) holds for the timeline shape too —
        // `tests/postgres_kg_age_cte_parity.rs` exercises both.
        // v0.7.0 fold-A2A1.3 (#700) — runtime AGE→CTE graceful
        // fallback; see `kg_query_with_history` for rationale. Same
        // pattern applied to the timeline dispatcher so an
        // AGE-side cypher failure degrades to the relational walk
        // instead of surfacing as a 503 to the `memory_kg_timeline`
        // MCP handler.
        match self.kg_backend {
            KgBackend::Age => {
                match self
                    .kg_timeline_cypher(source_id, since, until, limit)
                    .await
                {
                    Ok(rows) => Ok(rows),
                    Err(err) if is_age_runtime_failure(&err) => {
                        warn_age_fallback("kg_timeline", source_id, &err);
                        self.kg_timeline_cte(source_id, since, until, limit).await
                    }
                    Err(err) => Err(err),
                }
            }
            KgBackend::Cte => self.kg_timeline_cte(source_id, since, until, limit).await,
        }
    }

    /// Cypher (Apache AGE) implementation of `kg_timeline`.
    ///
    /// Wraps a `MATCH (a)-[r:related_to]->(b)` traversal in the
    /// `cypher('memory_graph', ...)` set-returning function, ordered
    /// by `r.valid_from ASC` and tie-broken by `r.created_at ASC` to
    /// match the SQLite implementation. The since/until filters are
    /// applied through Cypher's `WHERE` predicate; the start id is
    /// passed as an AGE `$vars` JSON parameter so the user-supplied
    /// value is never interpolated into the query body.
    ///
    /// Title and namespace are pulled by joining the AGE result back
    /// to the source-of-truth `memories` table — keeping the column
    /// snapshots in sync with the relational store and avoiding
    /// drift if the property-graph projection lags behind.
    ///
    /// # Errors
    ///
    /// `StoreError::BackendUnavailable` for any sqlx or AGE error.
    pub async fn kg_timeline_cypher(
        &self,
        source_id: &str,
        since: Option<&str>,
        until: Option<&str>,
        limit: Option<usize>,
    ) -> StoreResult<Vec<KgTimelineRow>> {
        let cap = clamp_timeline_limit(limit);

        // AGE requires `ag_catalog` on the search path and the
        // extension loaded into the session. Both are session-local
        // — sqlx hands each query a fresh connection from the pool
        // so we issue them as part of the same transaction to keep
        // them in scope. Same shape as `kg_query_cypher`.
        let mut tx = self
            .pool
            .begin()
            .await
            .map_err(|e| to_store_err(CTX_BEGIN_AGE_TX, e))?;

        // #1640 — tolerated LOAD (see load_age_tolerated): a role-level
        // LOAD refusal must not fail the query on fleets where
        // shared_preload_libraries provides the library.
        load_age_tolerated(&mut tx).await?;
        sqlx::query(SQL_SET_AGE_SEARCH_PATH)
            .execute(&mut *tx)
            .await
            .map_err(|e| to_store_err(CTX_SET_SEARCH_PATH, e))?;

        // Build the WHERE predicate dynamically. `since`/`until` are
        // pre-validated RFC3339 strings at the upper layer (the MCP
        // handler runs `validate_expires_at_format`), but we still
        // pass them through as bound `$since`/`$until` AGE vars so
        // they're never interpolated into the Cypher body.
        let mut where_clauses: Vec<&str> = vec!["a.id = $start_id", "r.valid_from IS NOT NULL"];
        if since.is_some() {
            where_clauses.push("r.valid_from >= $since");
        }
        if until.is_some() {
            where_clauses.push("r.valid_from <= $until");
        }
        let where_sql = where_clauses.join(" AND ");

        let cypher = format!(
            "MATCH (a)-[r:related_to]->(b) \
             WHERE {where_sql} \
             RETURN b.id AS target_id, \
                    r.relation AS relation, \
                    r.valid_from AS valid_from, \
                    r.valid_until AS valid_until, \
                    r.observed_by AS observed_by \
             ORDER BY r.valid_from ASC, r.created_at ASC \
             LIMIT {cap}"
        );

        // Inline the params dict as an AGE literal — see
        // `age_params_literal` for the rationale (AGE rejects
        // `$1::agtype` as a FuncExpr).
        let mut pairs: Vec<(&str, &str)> = vec![("start_id", source_id)];
        if let Some(s) = since {
            pairs.push(("since", s));
        }
        if let Some(u) = until {
            pairs.push(("until", u));
        }
        let params_lit = age_params_literal(&pairs);
        let sql = format!(
            "SELECT target_id, relation, valid_from, valid_until, observed_by \
             FROM cypher('memory_graph', $$ {cypher} $$, {params_lit}) AS \
             (target_id agtype, relation agtype, valid_from agtype, \
              valid_until agtype, observed_by agtype)"
        );

        // #1482 — per-call-unique cypher text (inlined id + since/until
        // + cap); run unnamed so it never enters the prepared-statement
        // cache and evicts reusable hot statements.
        let rows = sqlx::query(&sql)
            .persistent(false)
            .fetch_all(&mut *tx)
            .await
            .map_err(|e| to_store_err("cypher kg_timeline", e))?;

        // Decode the agtype payloads into raw Rust strings/options
        // first; we'll backfill `title` + `target_namespace` from
        // the `memories` table inside the same transaction. Pulling
        // the display fields from the relational store avoids a
        // class of drift bugs where the AGE projection lags behind
        // a `memories` rename.
        let mut decoded: Vec<KgTimelineRow> = Vec::with_capacity(rows.len());
        for r in &rows {
            let target_id_raw: String = r
                .try_get::<String, _>("target_id")
                .map_err(|e| to_store_err(READ_TARGET_ID, e))?;
            let relation_raw: String = r
                .try_get::<String, _>("relation")
                .map_err(|e| to_store_err(READ_RELATION, e))?;
            let valid_from_raw: String = r
                .try_get::<String, _>(field_names::VALID_FROM)
                .map_err(|e| to_store_err(READ_VALID_FROM, e))?;
            let valid_until_raw: String = r
                .try_get::<String, _>(field_names::VALID_UNTIL)
                .map_err(|e| to_store_err(READ_VALID_UNTIL, e))?;
            let observed_by_raw: String = r
                .try_get::<String, _>(field_names::OBSERVED_BY)
                .map_err(|e| to_store_err(READ_OBSERVED_BY, e))?;

            decoded.push(KgTimelineRow {
                target_id: strip_agtype_quotes(&target_id_raw).to_string(),
                relation: strip_agtype_quotes(&relation_raw).to_string(),
                valid_from: strip_agtype_quotes(&valid_from_raw).to_string(),
                valid_until: agtype_optional_string(&valid_until_raw),
                observed_by: agtype_optional_string(&observed_by_raw),
                // Filled in below by the `memories` join.
                title: String::new(),
                target_namespace: String::new(),
            });
        }

        // Backfill title + namespace in a single round-trip by
        // pulling the unique target ids and joining server-side.
        // Empty result set short-circuits without hitting Postgres.
        if !decoded.is_empty() {
            let ids: Vec<String> = {
                let mut seen: std::collections::BTreeSet<String> =
                    std::collections::BTreeSet::new();
                for row in &decoded {
                    seen.insert(row.target_id.clone());
                }
                seen.into_iter().collect()
            };

            let display_rows =
                sqlx::query("SELECT id, title, namespace FROM memories WHERE id = ANY($1)")
                    .bind(&ids)
                    .fetch_all(&mut *tx)
                    .await
                    .map_err(|e| to_store_err("fetch timeline display fields", e))?;

            let mut display: std::collections::HashMap<String, (String, String)> =
                std::collections::HashMap::with_capacity(display_rows.len());
            for r in &display_rows {
                let id: String = r
                    .try_get::<String, _>("id")
                    .map_err(|e| to_store_err("read id", e))?;
                let title: String = r
                    .try_get::<String, _>("title")
                    .map_err(|e| to_store_err(READ_TITLE, e))?;
                let namespace: String = r
                    .try_get::<String, _>("namespace")
                    .map_err(|e| to_store_err(READ_NAMESPACE, e))?;
                display.insert(id, (title, namespace));
            }

            for row in &mut decoded {
                if let Some((title, ns)) = display.get(&row.target_id) {
                    row.title.clone_from(title);
                    row.target_namespace.clone_from(ns);
                }
            }
        }

        tx.commit()
            .await
            .map_err(|e| to_store_err(CTX_COMMIT_AGE_TX, e))?;

        Ok(decoded)
    }

    /// SQL fallback for `kg_timeline` on Postgres.
    ///
    /// Mirrors the SQLite query in `db::kg_timeline` so deployments
    /// running vanilla Postgres (no AGE extension) still get the
    /// same temporal ordering and filter semantics. Returns the
    /// shared [`KgTimelineRow`] shape so the dispatcher in
    /// [`Self::kg_timeline`] doesn't have to care which branch ran.
    ///
    /// # Errors
    ///
    /// `StoreError::BackendUnavailable` for any sqlx error.
    pub async fn kg_timeline_cte(
        &self,
        source_id: &str,
        since: Option<&str>,
        until: Option<&str>,
        limit: Option<usize>,
    ) -> StoreResult<Vec<KgTimelineRow>> {
        let cap = clamp_timeline_limit(limit);
        let cap_i64 = i64::try_from(cap).unwrap_or(i64::MAX);

        // Compose the predicate dynamically for `since` / `until`.
        // Bind values are appended in the same order so the `$N`
        // placeholders line up. We rely on TIMESTAMPTZ casting to
        // parse the RFC3339 inputs; malformed values surface as a
        // `BackendUnavailable` from sqlx (the upper-layer handler
        // pre-validates so this is a defense-in-depth path).
        let mut sql = String::from(
            "SELECT ml.target_id, ml.relation, ml.valid_from, ml.valid_until,
                    ml.observed_by, m.title, m.namespace, ml.created_at
             FROM memory_links ml
             JOIN memories m ON m.id = ml.target_id
             WHERE ml.source_id = $1
               AND ml.valid_from IS NOT NULL",
        );
        let mut next_placeholder = 2usize;
        if since.is_some() {
            sql.push_str(&format!(
                " AND ml.valid_from >= ${next_placeholder}::TIMESTAMPTZ"
            ));
            next_placeholder += 1;
        }
        if until.is_some() {
            sql.push_str(&format!(
                " AND ml.valid_from <= ${next_placeholder}::TIMESTAMPTZ"
            ));
            next_placeholder += 1;
        }
        sql.push_str(&format!(
            " ORDER BY ml.valid_from ASC, ml.created_at ASC LIMIT ${next_placeholder}"
        ));

        let mut q = sqlx::query(&sql).bind(source_id);
        if let Some(s) = since {
            q = q.bind(s);
        }
        if let Some(u) = until {
            q = q.bind(u);
        }
        q = q.bind(cap_i64);

        let rows = q
            .fetch_all(&self.pool)
            .await
            .map_err(|e| to_store_err("cte kg_timeline", e))?;

        rows.iter()
            .map(|r| {
                let target_id: String = r
                    .try_get::<String, _>("target_id")
                    .map_err(|e| to_store_err(READ_TARGET_ID, e))?;
                let relation: String = r
                    .try_get::<String, _>("relation")
                    .map_err(|e| to_store_err(READ_RELATION, e))?;
                let valid_from: DateTime<Utc> = r
                    .try_get::<DateTime<Utc>, _>(field_names::VALID_FROM)
                    .map_err(|e| to_store_err(READ_VALID_FROM, e))?;
                let valid_until: Option<DateTime<Utc>> = r
                    .try_get::<Option<DateTime<Utc>>, _>(field_names::VALID_UNTIL)
                    .map_err(|e| to_store_err(READ_VALID_UNTIL, e))?;
                let observed_by: Option<String> = r
                    .try_get::<Option<String>, _>(field_names::OBSERVED_BY)
                    .map_err(|e| to_store_err(READ_OBSERVED_BY, e))?;
                let title: String = r
                    .try_get::<String, _>("title")
                    .map_err(|e| to_store_err(READ_TITLE, e))?;
                let target_namespace: String = r
                    .try_get::<String, _>("namespace")
                    .map_err(|e| to_store_err(READ_NAMESPACE, e))?;
                Ok(KgTimelineRow {
                    target_id,
                    relation,
                    valid_from: valid_from.to_rfc3339(),
                    valid_until: valid_until.map(|t| t.to_rfc3339()),
                    observed_by,
                    title,
                    target_namespace,
                })
            })
            .collect()
    }

    /// Mark a KG link as superseded — v0.7 Track J dispatcher.
    ///
    /// Routes on the [`KgBackend`] resolved at [`Self::connect`] time
    /// (J1 substrate). When AGE is installed the supersession runs as
    /// a Cypher `MATCH (a)-[r:related_to]->(b) ... SET r.valid_until`
    /// over the `memory_graph` projection; otherwise we fall back to a
    /// plain `UPDATE memory_links` that mirrors the SQLite shape in
    /// `db::invalidate_link`.
    ///
    /// Both branches return rows in the same [`KgInvalidateRow`] shape
    /// so the upper-layer `memory_kg_invalidate` handler can stay
    /// backend-blind, mirroring J2/J3's pattern for `kg_query` and
    /// `kg_timeline`.
    ///
    /// `valid_until` defaults to the current wall-clock time in
    /// RFC3339 form when `None`. Idempotent: calling repeatedly
    /// overwrites the prior `valid_until` (the prior value is returned
    /// in `previous_valid_until` so callers can detect the overwrite).
    /// When the `(source_id, target_id, relation)` triple does not
    /// match an existing link the returned row carries `found = false`
    /// so the SAL shape distinguishes "no-op" from "applied" the same
    /// way the SQLite path does (via `Option::None`).
    ///
    /// G14 audit-edge emission lives in the upper-layer handler —
    /// keeping it there means both backends share a single
    /// invalidation-event call site rather than duplicating webhook
    /// dispatch into the SAL layer.
    ///
    /// # Errors
    ///
    /// Returns `StoreError::BackendUnavailable` for any sqlx or AGE
    /// error.
    pub async fn kg_invalidate(
        &self,
        source_id: &str,
        target_id: &str,
        relation: &str,
        valid_until: Option<&str>,
    ) -> StoreResult<KgInvalidateRow> {
        // v0.7.0 S6-M3 — AGE Cypher dispatcher. Same dual-path
        // discipline as `kg_query` / `kg_timeline`. When AGE is
        // available we set the `valid_until` property through Cypher
        // so the property-graph projection stays in sync with
        // `memory_links`; otherwise we update the relational table
        // directly.
        // v0.7.0 fold-A2A1.3 (#700) — runtime AGE→CTE graceful
        // fallback for the invalidation path. The CTE branch also
        // performs an idempotent UPDATE so a re-issue against the
        // relational table after an AGE-side failure is safe — and
        // `kg_invalidate_cypher` mirrors its SET back into
        // `memory_links` so the CTE branch returns the same
        // `previous_valid_until` shape on a retry.
        match self.kg_backend {
            KgBackend::Age => {
                match self
                    .kg_invalidate_cypher(source_id, target_id, relation, valid_until)
                    .await
                {
                    Ok(row) => Ok(row),
                    Err(err) if is_age_runtime_failure(&err) => {
                        warn_age_fallback(
                            crate::governance::action_labels::KG_INVALIDATE,
                            source_id,
                            &err,
                        );
                        self.kg_invalidate_cte(source_id, target_id, relation, valid_until)
                            .await
                    }
                    Err(err) => Err(err),
                }
            }
            KgBackend::Cte => {
                self.kg_invalidate_cte(source_id, target_id, relation, valid_until)
                    .await
            }
        }
    }

    /// Cypher (Apache AGE) implementation of `kg_invalidate`.
    ///
    /// Wraps a `MATCH (a)-[r:related_to]->(b) ... SET r.valid_until`
    /// over the `memory_graph` projection in the
    /// `cypher('memory_graph', ...)` set-returning function. Parameter
    /// passing uses AGE's `$vars` syntax through a JSON-encoded second
    /// argument so the source/target ids and the timestamp are bound
    /// — never interpolated — into the Cypher body.
    ///
    /// Two-step traversal: a `MATCH ... RETURN r.valid_until` first
    /// captures the prior value (so the dispatcher can populate
    /// `previous_valid_until`), then the same triple is matched again
    /// with `SET r.valid_until = $now RETURN count(r)`. Both run
    /// inside a single AGE transaction so a parallel writer can't
    /// interleave between the read and the SET. The two-step shape
    /// mirrors the SQLite path in `db::invalidate_link` which also
    /// SELECTs the prior row before UPDATEing it.
    ///
    /// AGE's `cypher()` SRF returns no rows when the MATCH misses —
    /// we map that to `found = false` so the upper-layer wire shape
    /// matches the CTE branch exactly.
    ///
    /// # Errors
    ///
    /// Returns `StoreError::BackendUnavailable` for any sqlx or AGE
    /// error.
    pub async fn kg_invalidate_cypher(
        &self,
        source_id: &str,
        target_id: &str,
        relation: &str,
        valid_until: Option<&str>,
    ) -> StoreResult<KgInvalidateRow> {
        let stamp = valid_until.map_or_else(|| Utc::now().to_rfc3339(), str::to_string);

        // AGE requires `ag_catalog` on the search path and the
        // extension loaded into the session. Both are session-local
        // — sqlx hands each query a fresh connection from the pool
        // so we issue them as part of the same transaction to keep
        // them in scope. Same shape as `kg_query_cypher` and
        // `kg_timeline_cypher`.
        let mut tx = self
            .pool
            .begin()
            .await
            .map_err(|e| to_store_err(CTX_BEGIN_AGE_TX, e))?;

        // #1640 — tolerated LOAD (see load_age_tolerated): a role-level
        // LOAD refusal must not fail the query on fleets where
        // shared_preload_libraries provides the library.
        load_age_tolerated(&mut tx).await?;
        sqlx::query(SQL_SET_AGE_SEARCH_PATH)
            .execute(&mut *tx)
            .await
            .map_err(|e| to_store_err(CTX_SET_SEARCH_PATH, e))?;

        // Step 1: capture the prior `valid_until` so the wire-shape
        // can surface it. We bind the ids + relation through AGE's
        // `$vars` JSON so user input is never interpolated.
        let read_cypher = "MATCH (a)-[r:related_to]->(b) \
             WHERE a.id = $src AND b.id = $dst AND r.relation = $rel \
             RETURN r.valid_until AS prior";
        // Inline the params dict — see `age_params_literal`.
        let read_params_lit =
            age_params_literal(&[("src", source_id), ("dst", target_id), ("rel", relation)]);
        let read_sql = format!(
            "SELECT prior FROM cypher('memory_graph', $$ {read_cypher} $$, {read_params_lit}) AS \
             (prior agtype)"
        );
        let prior_rows = sqlx::query(&read_sql)
            .fetch_all(&mut *tx)
            .await
            .map_err(|e| to_store_err("cypher kg_invalidate read", e))?;

        if prior_rows.is_empty() {
            // No matching edge — mirror the SQLite path's `Ok(None)`
            // contract by surfacing `found = false`. The transaction
            // still commits so the LOAD/SET search_path pair don't
            // leak across pool checkouts.
            tx.commit()
                .await
                .map_err(|e| to_store_err(CTX_COMMIT_AGE_TX, e))?;
            return Ok(KgInvalidateRow {
                found: false,
                valid_until: String::new(),
                previous_valid_until: None,
            });
        }

        let prior_raw: String = prior_rows[0]
            .try_get::<String, _>("prior")
            .map_err(|e| to_store_err("read prior valid_until", e))?;
        let previous_valid_until = agtype_optional_string(&prior_raw);

        // Step 2: SET r.valid_until = $now and count the affected
        // edge. We rely on AGE's identity to atomically rewrite the
        // edge property — Cypher's SET semantics replace the property
        // value (no append). count(r) returns the number of edges
        // that matched the WHERE; for a unique (src, dst, rel) triple
        // this is 1, but we don't assume — duplicate edges would show
        // up here and the dispatcher's contract is the same either
        // way (the prior value already came from row[0]).
        let write_cypher = "MATCH (a)-[r:related_to]->(b) \
             WHERE a.id = $src AND b.id = $dst AND r.relation = $rel \
             SET r.valid_until = $now \
             RETURN count(r) AS affected";
        let write_params_lit = age_params_literal(&[
            ("src", source_id),
            ("dst", target_id),
            ("rel", relation),
            ("now", &stamp),
        ]);
        let write_sql = format!(
            "SELECT affected FROM cypher('memory_graph', $$ {write_cypher} $$, {write_params_lit}) AS \
             (affected agtype)"
        );
        let _ = sqlx::query(&write_sql)
            .fetch_all(&mut *tx)
            .await
            .map_err(|e| to_store_err("cypher kg_invalidate set", e))?;

        // Mirror the SET into the relational `memory_links` row so the
        // CTE-side reads and the AGE-side reads stay aligned. The AGE
        // projection lags behind a relational `UPDATE` in deployments
        // that lack a sync trigger; doing both writes here is the same
        // dual-write contract J2/J3 already rely on for the read path.
        sqlx::query(
            "UPDATE memory_links SET valid_until = $4 \
             WHERE source_id = $1 AND target_id = $2 AND relation = $3",
        )
        .bind(source_id)
        .bind(target_id)
        .bind(relation)
        .bind(&stamp)
        .execute(&mut *tx)
        .await
        .map_err(|e| to_store_err("cypher kg_invalidate mirror", e))?;

        tx.commit()
            .await
            .map_err(|e| to_store_err(CTX_COMMIT_AGE_TX, e))?;

        Ok(KgInvalidateRow {
            found: true,
            valid_until: stamp,
            previous_valid_until,
        })
    }

    /// SQL fallback for `kg_invalidate` on Postgres.
    ///
    /// Mirrors the SQLite query in `db::invalidate_link` so deployments
    /// running vanilla Postgres (no AGE extension) get the same
    /// supersession semantics. Uses `UPDATE ... RETURNING` to atomically
    /// read the prior `valid_until` and write the new value in one
    /// round-trip — the SQLite path has to issue a SELECT then an
    /// UPDATE because rusqlite's RETURNING is gated on a feature flag,
    /// but Postgres has it natively. Returns the shared
    /// [`KgInvalidateRow`] shape so the dispatcher in
    /// [`Self::kg_invalidate`] doesn't have to care which branch ran.
    ///
    /// # Errors
    ///
    /// `StoreError::BackendUnavailable` for any sqlx error.
    pub async fn kg_invalidate_cte(
        &self,
        source_id: &str,
        target_id: &str,
        relation: &str,
        valid_until: Option<&str>,
    ) -> StoreResult<KgInvalidateRow> {
        let stamp = valid_until.map_or_else(|| Utc::now().to_rfc3339(), str::to_string);

        // `UPDATE ... RETURNING` captures the prior `valid_until` and
        // writes the new one in a single round-trip. The OLD-row
        // semantics come from a CTE: Postgres' `RETURNING` clause sees
        // the NEW row, so we wrap the UPDATE in a CTE and read the
        // prior value through a separate `SELECT` joined on the same
        // (source, target, relation) triple.
        let sql = "WITH prev AS (
                SELECT valid_until AS prior
                FROM memory_links
                WHERE source_id = $1 AND target_id = $2 AND relation = $3
                FOR UPDATE
            ),
            upd AS (
                UPDATE memory_links
                SET valid_until = $4::TIMESTAMPTZ
                WHERE source_id = $1 AND target_id = $2 AND relation = $3
                RETURNING valid_until AS now_until
            )
            SELECT prev.prior, upd.now_until
            FROM prev FULL OUTER JOIN upd ON TRUE";

        let rows = sqlx::query(sql)
            .bind(source_id)
            .bind(target_id)
            .bind(relation)
            .bind(&stamp)
            .fetch_all(&self.pool)
            .await
            .map_err(|e| to_store_err("cte kg_invalidate", e))?;

        if rows.is_empty() {
            return Ok(KgInvalidateRow {
                found: false,
                valid_until: String::new(),
                previous_valid_until: None,
            });
        }

        // The FULL OUTER JOIN yields one row when the triple matched
        // (both `prior` and `now_until` populated) and zero rows when
        // it missed. We've handled the empty case above; pull the
        // first row for the matched case.
        let row = &rows[0];
        let prior: Option<DateTime<Utc>> = row
            .try_get::<Option<DateTime<Utc>>, _>("prior")
            .map_err(|e| to_store_err("read prior valid_until", e))?;
        let now_until: Option<DateTime<Utc>> = row
            .try_get::<Option<DateTime<Utc>>, _>("now_until")
            .map_err(|e| to_store_err("read new valid_until", e))?;

        // `now_until` is `None` only when the UPDATE matched zero rows
        // — i.e. the link did not exist. The `WITH prev AS (...)` CTE
        // would also produce zero rows in that case, so `rows` would
        // be empty. Defensive double-check: if we got here with `None`
        // the triple didn't match.
        if now_until.is_none() {
            return Ok(KgInvalidateRow {
                found: false,
                valid_until: String::new(),
                previous_valid_until: None,
            });
        }

        Ok(KgInvalidateRow {
            found: true,
            valid_until: stamp,
            previous_valid_until: prior.map(|t| t.to_rfc3339()),
        })
    }

    /// v0.7 J7 — enumerate up to N paths between two memories.
    ///
    /// Routes on the [`KgBackend`] resolved at [`Self::connect`] time
    /// (J1 substrate). When AGE is installed the enumeration runs as a
    /// Cypher `MATCH p = (s)-[*..N]-(t) RETURN p LIMIT M` query through
    /// the `memory_graph` projection; otherwise we fall back to a
    /// recursive CTE over the `memory_links` table that mirrors the
    /// SQLite shape in `db::find_paths`.
    ///
    /// Both branches return rows in the same `Vec<Vec<String>>` shape
    /// so the upper-layer `memory_find_paths` handler stays
    /// backend-blind.
    ///
    /// # Errors
    ///
    /// Returns `StoreError::InvalidInput` for `max_depth == 0` or above
    /// the supported ceiling, and `StoreError::BackendUnavailable` for
    /// any underlying SQL or Cypher error.
    pub async fn find_paths(
        &self,
        source_id: &str,
        target_id: &str,
        max_depth: Option<usize>,
        max_results: Option<usize>,
    ) -> StoreResult<Vec<Vec<String>>> {
        // v0.7.0 fold-A2A1.3 (#700) — runtime AGE→CTE graceful
        // fallback for `find_paths`. Same shape as the other three
        // dispatchers; the CTE enumeration produces the same
        // `Vec<Vec<String>>` shape so the upper-layer handler stays
        // backend-blind.
        match self.kg_backend {
            KgBackend::Age => {
                match self
                    .find_paths_cypher(source_id, target_id, max_depth, max_results)
                    .await
                {
                    Ok(paths) => Ok(paths),
                    Err(err) if is_age_runtime_failure(&err) => {
                        warn_age_fallback_pair("find_paths", source_id, target_id, &err);
                        self.find_paths_cte(source_id, target_id, max_depth, max_results)
                            .await
                    }
                    Err(err) => Err(err),
                }
            }
            KgBackend::Cte => {
                self.find_paths_cte(source_id, target_id, max_depth, max_results)
                    .await
            }
        }
    }

    /// Recursive-CTE fallback for `find_paths` on Postgres.
    ///
    /// Mirrors the SQLite recursive-CTE in `db::find_paths` so vanilla
    /// Postgres deployments (no AGE extension) get the same enumeration
    /// semantics. The walk is undirected: edges are unioned with their
    /// reverse so paths can traverse `memory_links` against the
    /// declared direction. Cycle prevention uses a TEXT-array prefix
    /// of visited ids.
    ///
    /// # Errors
    ///
    /// `StoreError::InvalidInput` for an out-of-range `max_depth`;
    /// `StoreError::BackendUnavailable` for any sqlx error.
    pub async fn find_paths_cte(
        &self,
        source_id: &str,
        target_id: &str,
        max_depth: Option<usize>,
        max_results: Option<usize>,
    ) -> StoreResult<Vec<Vec<String>>> {
        let depth = max_depth.unwrap_or(FIND_PATHS_DEFAULT_DEPTH_SAL);
        validate_find_paths_depth(depth)?;
        let cap = max_results
            .unwrap_or(FIND_PATHS_DEFAULT_LIMIT_SAL)
            .clamp(1, FIND_PATHS_MAX_LIMIT_SAL);

        if source_id == target_id {
            return Ok(vec![vec![source_id.to_string()]]);
        }

        let depth_i32 = i32::try_from(depth).unwrap_or(i32::MAX);
        let cap_i64 = i64::try_from(cap).unwrap_or(i64::MAX);

        // The CTE walks symmetric edges via a UNION over the original
        // and reverse direction. The visited-id prefix is carried as
        // TEXT[] so we can both check membership (= ANY) and append
        // (array_append). Rows whose `current_id` matches the target
        // and whose depth is at least 1 are reported as completed
        // paths; ordering by depth then path keeps the shortest paths
        // first so the LIMIT cap drops the longest tail.
        let sql = "WITH RECURSIVE traversal(current_id, depth, path) AS (
                SELECT $1::TEXT, 0, ARRAY[$1::TEXT]
                UNION ALL
                SELECT edges.next_id, t.depth + 1, t.path || edges.next_id
                FROM traversal t
                JOIN (
                    -- #1689 — exclude invalidated edges from traversal so a
                    -- retracted link no longer influences path-finding, matching
                    -- the sqlite find_paths current-view default and pg
                    -- kg_query_cte_filtered. Both UNION arms get the filter.
                    SELECT source_id AS from_id, target_id AS next_id FROM memory_links
                    WHERE valid_until IS NULL OR valid_until > NOW()
                    UNION
                    SELECT target_id AS from_id, source_id AS next_id FROM memory_links
                    WHERE valid_until IS NULL OR valid_until > NOW()
                ) edges ON edges.from_id = t.current_id
                WHERE t.depth < $3
                  AND NOT (edges.next_id = ANY(t.path))
            )
            SELECT path
            FROM traversal
            WHERE current_id = $2 AND depth >= 1
            ORDER BY depth ASC, path ASC
            LIMIT $4";

        let rows = sqlx::query(sql)
            .bind(source_id)
            .bind(target_id)
            .bind(depth_i32)
            .bind(cap_i64)
            .fetch_all(&self.pool)
            .await
            .map_err(|e| to_store_err("cte find_paths", e))?;

        rows.iter()
            .map(|r| {
                let path: Vec<String> = r
                    .try_get::<Vec<String>, _>("path")
                    .map_err(|e| to_store_err("read path", e))?;
                Ok(path)
            })
            .collect()
    }

    /// Cypher (Apache AGE) implementation of `find_paths`.
    ///
    /// Wraps a `MATCH p = (s)-[*..N]-(t) RETURN [n IN nodes(p) | n.id]`
    /// traversal in the `cypher('memory_graph', ...)` set-returning
    /// function, ordered by `length(p)` so shorter paths land first.
    /// Source / target ids are bound through AGE's `$vars` JSON so
    /// user input is never interpolated into the Cypher body. The
    /// variable-length pattern's upper bound IS interpolated — Cypher
    /// does not accept a parameter there — but `validate_find_paths_depth`
    /// already clamps it to a small bounded integer with no injection
    /// surface.
    ///
    /// # Errors
    ///
    /// Returns `StoreError::InvalidInput` for an out-of-range
    /// `max_depth`; `StoreError::BackendUnavailable` for any sqlx or
    /// AGE error.
    pub async fn find_paths_cypher(
        &self,
        source_id: &str,
        target_id: &str,
        max_depth: Option<usize>,
        max_results: Option<usize>,
    ) -> StoreResult<Vec<Vec<String>>> {
        let depth = max_depth.unwrap_or(FIND_PATHS_DEFAULT_DEPTH_SAL);
        validate_find_paths_depth(depth)?;
        let cap = max_results
            .unwrap_or(FIND_PATHS_DEFAULT_LIMIT_SAL)
            .clamp(1, FIND_PATHS_MAX_LIMIT_SAL);

        if source_id == target_id {
            return Ok(vec![vec![source_id.to_string()]]);
        }

        // AGE requires `ag_catalog` on the search path and the extension
        // loaded into the session. Same shape as `kg_query_cypher`.
        let mut tx = self
            .pool
            .begin()
            .await
            .map_err(|e| to_store_err(CTX_BEGIN_AGE_TX, e))?;

        // #1640 — tolerated LOAD (see load_age_tolerated): a role-level
        // LOAD refusal must not fail the query on fleets where
        // shared_preload_libraries provides the library.
        load_age_tolerated(&mut tx).await?;
        sqlx::query(SQL_SET_AGE_SEARCH_PATH)
            .execute(&mut *tx)
            .await
            .map_err(|e| to_store_err(CTX_SET_SEARCH_PATH, e))?;

        // v0.7.0 ship-hardening (2026-05-19): the prior shape
        // `RETURN reduce(s = a.id, n IN nodes(p)[1..] | s + '->' +
        // n.id) AS path` is REJECTED at parse time by AGE 1.6.0 with
        // `syntax error at or near "|"`. AGE 1.5.0 accepted reduce
        // bodies containing `|`; AGE 1.6.0's grammar narrowed the
        // `|` recovery point and now treats it as the list-comprehension
        // pipe separator only — making `reduce(... | ...)` ambiguous
        // with `[var IN list | expr]` and rejected entirely. Direct
        // psql PREPARE/EXECUTE confirms: the reduce form errors, the
        // list-comp form errors with "could not find properties for n"
        // (same grammar narrowing), and the alternative `UNWIND + collect`
        // form silently returns an empty path. The ONLY portable shape
        // that survives both AGE 1.5 and 1.6 is `RETURN nodes(p)` which
        // returns the vertex list directly; the Rust-side decode then
        // strips AGE's text-format `::vertex` type tags and pulls each
        // `properties.id` to reconstruct the path.
        //
        // The variable-length pattern stays `-[*1..N]-` (un-arrowed,
        // explicit lower bound) per the symmetric-closure contract
        // from the CTE branch — matching either declared edge
        // direction. AGE 1.6.0 accepts this shape; the `convert_cypher_to_subquery`
        // pattern walker round-trips it correctly.
        // v0.7.0 ship-hardening (2026-05-19): use 2-arg `cypher()` with
        // IDs inlined into the cypher body instead of a 3-arg form with
        // a params dict. Empirical findings via PREPARE/EXECUTE + raw
        // SQL in psql + sqlx round-trips:
        //
        //   * 3-arg `cypher(graph, body, params)` with `params` bound
        //     via sqlx's `Agtype` binary wrapper → cypher executes
        //     without error but matches 0 rows (the `$start_id` /
        //     `$target_id` variable substitution doesn't happen — the
        //     binary protocol's agtype encoding does not surface the
        //     params dict's keys to AGE's cypher analyzer).
        //   * 3-arg `cypher(graph, body, '{"…"}'::agtype)` with an
        //     INLINE agtype literal → AGE 1.5/1.6 rejects: "third
        //     argument of cypher function must be a parameter" (the
        //     `Const` node it sees isn't accepted).
        //   * 2-arg `cypher(graph, body)` with the IDs inlined into
        //     the cypher TEXT (WHERE a.id = 'literal') → works on
        //     both AGE 1.5 and 1.6, returns matched paths correctly.
        //
        // We take the 2-arg path. Source and target IDs are
        // UUID-validated upstream (`validate_memory_id`) so the
        // inlined values are safe from SQL injection; the
        // defense-in-depth `assert_age_id_safe()` check below rejects
        // any residual id that doesn't match `[A-Za-z0-9_-]+` before
        // it reaches the format string. The `reduce(... | ...)`
        // string-join shape from earlier was ALSO broken on AGE
        // 1.6 (the `|` separator became unparseable in reduce
        // bodies); the new cypher uses `RETURN nodes(p)` and the
        // Rust-side decode pulls each vertex's `properties.id` to
        // reconstruct the chain.
        assert_age_id_safe(source_id).map_err(|detail| StoreError::InvalidInput { detail })?;
        assert_age_id_safe(target_id).map_err(|detail| StoreError::InvalidInput { detail })?;

        // #1689 — current-view path-finding MUST exclude invalidated edges,
        // matching sqlite `db::find_paths`, `find_paths_cte` (both UNION arms),
        // and `kg_query_cypher`. `kg_invalidate_cypher` SETs `r.valid_until`
        // on the edge (it does NOT delete it), so the
        // `ALL(e IN relationships(p) ...)` guard drops any path that traverses
        // an invalidated edge. The `IS NULL OR` arm is load-bearing: this
        // traversal matches UNTYPED edges, and relations that never carry an
        // invalidation (e.g. `supersedes`, or a never-retracted `related_to`)
        // have NO `valid_until` property — `IS NULL` keeps them, so the filter
        // can never silently drop uninvalidated paths. The cut-off is inlined
        // as an RFC3339 `+00:00` literal (find_paths uses the 2-arg `cypher()`
        // form — see the param-binding note above — so it cannot bind `$now`);
        // `to_rfc3339()` output contains no single quote, so no injection
        // surface. Defense in depth: if an AGE build rejects the
        // `relationships()`/`ALL()` predicate, the `find_paths` dispatcher's
        // `is_age_runtime_failure` arm falls back to the correct
        // `find_paths_cte`.
        let now_stamp = Utc::now().to_rfc3339();
        let sql = format!(
            "SELECT path FROM cypher('memory_graph', $$ {} $$) AS (path agtype)",
            build_find_paths_current_view_cypher(source_id, target_id, depth, cap, &now_stamp)
        );
        // #1482 — per-call-unique cypher text (inlined source/target
        // ids + depth + cap); run unnamed so it never enters the
        // prepared-statement cache and evicts reusable hot statements.
        let rows = sqlx::query(&sql)
            .persistent(false)
            .fetch_all(&mut *tx)
            .await
            .map_err(|e| to_store_err("cypher find_paths", e))?;

        tx.commit()
            .await
            .map_err(|e| to_store_err(CTX_COMMIT_AGE_TX, e))?;

        // AGE returns each `path` cell as a JSON-encoded string
        // (agtype string) of the shape `"id1->id2->…"` — `reduce`
        // walks a `nodes(p)[1..]` slice and appends `'->' + n.id` per
        // step starting from `a.id`. Decode through the [`Agtype`]
        // wrapper so sqlx's binary-protocol path strips the version
        // byte; the resulting payload is a JSON string literal that
        // we parse and then split on `->` to recover the path.
        rows.iter()
            .map(|r| {
                let raw: Agtype = r
                    .try_get::<Agtype, _>("path")
                    .map_err(|e| to_store_err("read path", e))?;
                // AGE serialises strings as JSON-quoted strings (e.g.
                // `"abc"`); parse as JSON to strip the
                // quotes and decode any escapes the encoder applied.
                // `raw.0` is AGE's text format for a vertex list:
                //   `[{"id":..., "label":"Memory",
                //      "properties":{"id":"uuid1"}}::vertex,
                //     {"id":..., "properties":{"id":"uuid2"}}::vertex, ...]`
                // The `::vertex` (and `::edge`, `::path`) suffixes are
                // AGE's text-format type tags and are NOT valid JSON.
                // Strip them, parse as JSON, then pull each
                // `properties.id` to reconstruct the chain.
                let json_payload = raw
                    .0
                    .replace("::vertex", "")
                    .replace("::edge", "")
                    .replace("::path", "");
                // QC Obs #8 (2026-05-20): cap echoed payload at 200
                // chars in error messages so an unbounded malformed
                // response doesn't blow up the log / response body.
                let payload_preview = |s: &str| -> String {
                    if s.len() <= 200 {
                        s.to_string()
                    } else {
                        format!("{}…<{}b truncated>", &s[..200], s.len() - 200)
                    }
                };
                let arr: serde_json::Value = serde_json::from_str(&json_payload).map_err(|e| {
                    StoreError::IntegrityFailed {
                        detail: format!(
                            "non-JSON AGE path payload: {}: {e}",
                            payload_preview(&raw.0)
                        ),
                    }
                })?;
                let nodes = arr.as_array().ok_or_else(|| StoreError::IntegrityFailed {
                    detail: format!("AGE path is not an array: {}", payload_preview(&raw.0)),
                })?;
                let ids: Vec<String> = nodes
                    .iter()
                    .filter_map(|v| {
                        v.get(field_names::PROPERTIES)
                            .and_then(|p| p.get("id"))
                            .and_then(|i| i.as_str())
                            .map(String::from)
                    })
                    .collect();
                if ids.is_empty() {
                    return Err(StoreError::IntegrityFailed {
                        detail: format!(
                            "AGE path has no extractable ids: {}",
                            payload_preview(&raw.0)
                        ),
                    });
                }
                Ok(ids)
            })
            .collect()
    }

    /// Common implementation for [`PostgresStore::link`] +
    /// [`PostgresStore::link_signed`]. Mirrors SQLite's
    /// `db::create_link_signed` byte-for-byte: when `keypair` carries a
    /// usable private key, the canonical-CBOR-signed bytes land in
    /// `memory_links.signature` with `attest_level = "self_signed"` and
    /// `observed_by = kp.agent_id`; otherwise the row is unsigned.
    ///
    /// Idempotent on the `(source_id, target_id, relation)` unique key
    /// — duplicate writes collapse via `ON CONFLICT … DO NOTHING` so a
    /// migrate replay doesn't error on already-shipped links.
    ///
    /// Returns the resolved attestation level so the trait surfaces
    /// (`link_signed`) can pass it back to upper layers without
    /// re-querying.
    /// #1568 (H1 residual) — postgres twin of the sqlite pre-link
    /// gates (`db::create_link_signed` → `db::validate_link_pre_create`).
    /// Pre-fix the postgres SAL link path performed FK pre-flight only,
    /// so a postgres-backed daemon accepted link writes ungoverned.
    ///
    /// Pass 1 (reflects_on cycle gate): pre-fetches the bounded
    /// `reflects_on` subgraph reachable forward from the proposed
    /// target via a recursive CTE, then runs the SHARED
    /// backend-agnostic walker
    /// ([`crate::kg::cycle_check::would_create_reflection_cycle_with`])
    /// over the in-memory adjacency — identical BFS semantics (visited
    /// set, fail-CLOSED on depth-ceiling truncation) to the sqlite
    /// path, with the same namespace-scoped
    /// `effective_max_reflection_depth` cap. The CTE is bounded at
    /// [`crate::kg::cycle_check::walk_bound`], which by construction
    /// covers every node the walker can explore, so the prefetch
    /// cannot under-feed the walk.
    ///
    /// Pass 2 (K9 governance gate): the SHARED
    /// [`crate::storage::evaluate_link_permission`] free fn — the same
    /// `Permissions::evaluate` pipeline `validate_link_pre_create`
    /// consults on sqlite, with Ask treated as Deny at the storage
    /// layer.
    ///
    /// Wire shapes: cycle → [`StoreError::LinkRefused`] (HTTP 409 via
    /// `store_err_to_response`, body message byte-identical to
    /// sqlite's `StorageError::LinkReflectionCycle` Display); deny →
    /// [`StoreError::PermissionDenied`] (HTTP 403, reason carries the
    /// canonical `LINK_PERMISSION_DENIED_ERR_PREFIX`). The federation
    /// inbound path (`apply_remote_link`) is intentionally NOT routed
    /// through this gate — it mirrors sqlite's `create_link_inbound`
    /// peer-attested posture, tracked separately.
    async fn validate_link_pre_create_pg(
        &self,
        link: &MemoryLink,
        keypair: Option<&crate::identity::keypair::AgentKeypair>,
    ) -> StoreResult<()> {
        // Same identity fallback as sqlite's `create_link_signed`: the
        // signing keypair's claim when present (the writer is by
        // definition the actor), else "system".
        let agent_id_for_eval = keypair.map_or("system", |kp| kp.agent_id.as_str());

        // The source memory's namespace scopes both gates (matches the
        // sqlite/MCP choice). A missing source falls back to the
        // default namespace — the FK pre-flight in `link_internal`
        // surfaces the missing-memory error after this returns.
        let link_ns: Option<String> =
            sqlx::query_scalar("SELECT namespace FROM memories WHERE id = $1")
                .bind(&link.source_id)
                .fetch_optional(&self.pool)
                .await
                .map_err(|e| to_store_err("resolve link source namespace", e))?;
        let link_ns = link_ns.unwrap_or_else(|| crate::DEFAULT_NAMESPACE.to_string());

        // Pass 1: cycle gate — only `reflects_on` participates in the
        // DAG invariant; the other relations may legally form cycles.
        if link.relation == crate::models::MemoryLinkRelation::ReflectsOn {
            let max_depth = super::MemoryStore::resolve_governance_policy(self, &link_ns)
                .await?
                .unwrap_or_default()
                .effective_max_reflection_depth();
            let bound = crate::kg::cycle_check::walk_bound(max_depth);

            let rows: Vec<(String, String)> = sqlx::query_as(
                "WITH RECURSIVE walk(source_id, target_id, depth) AS (
                     SELECT ml.source_id, ml.target_id, 1
                     FROM memory_links ml
                     WHERE ml.source_id = $1 AND ml.relation = $3
                   UNION
                     SELECT ml.source_id, ml.target_id, w.depth + 1
                     FROM memory_links ml
                     JOIN walk w ON ml.source_id = w.target_id
                     WHERE ml.relation = $3 AND w.depth < $2
                 )
                 SELECT source_id, target_id FROM walk",
            )
            .bind(&link.target_id)
            .bind(i64::from(bound))
            .bind(crate::models::MemoryLinkRelation::ReflectsOn.as_str())
            .fetch_all(&self.pool)
            .await
            .map_err(|e| to_store_err("cycle-check subgraph fetch", e))?;

            let mut adjacency: std::collections::HashMap<String, Vec<String>> =
                std::collections::HashMap::new();
            for (src, dst) in rows {
                adjacency.entry(src).or_default().push(dst);
            }
            let result = crate::kg::cycle_check::would_create_reflection_cycle_with::<
                std::convert::Infallible,
            >(&link.source_id, &link.target_id, max_depth, &mut |node| {
                Ok(adjacency.get(node).cloned().unwrap_or_default())
            })
            .unwrap_or_else(|never| match never {});
            if result.would_cycle {
                return Err(StoreError::LinkRefused {
                    // Reuse the sqlite typed envelope's Display so the
                    // wire body is byte-identical across backends.
                    detail: crate::storage::StorageError::LinkReflectionCycle {
                        source_id: link.source_id.clone(),
                        target_id: link.target_id.clone(),
                    }
                    .to_string(),
                });
            }
        }

        // Pass 2: K9 governance gate (shared free fn — see
        // `crate::storage::evaluate_link_permission`).
        crate::storage::evaluate_link_permission(
            &link_ns,
            &link.source_id,
            &link.target_id,
            link.relation.as_str(),
            agent_id_for_eval,
        )
        .map_err(|se| StoreError::PermissionDenied {
            action: "memory_link".to_string(),
            target: link_ns.clone(),
            reason: se.to_string(),
        })?;
        Ok(())
    }

    async fn link_internal(
        &self,
        link: &MemoryLink,
        keypair: Option<&crate::identity::keypair::AgentKeypair>,
    ) -> StoreResult<&'static str> {
        // #1568 (H1 residual) — run the same pre-link gates the sqlite
        // `db::create_link_signed` path runs (reflects_on cycle
        // invariant + K9 governance) BEFORE any FK pre-flight or write.
        self.validate_link_pre_create_pg(link, keypair).await?;

        // FK pre-flight — mirror SQLite's explicit existence check so
        // the error message names the missing memory rather than
        // surfacing a raw `pg_class` constraint violation. Both
        // adapters now agree on the wire-shape for this failure mode.
        let source_exists: bool =
            sqlx::query_scalar("SELECT EXISTS(SELECT 1 FROM memories WHERE id = $1)")
                .bind(&link.source_id)
                .fetch_one(&self.pool)
                .await
                .map_err(|e| to_store_err("check source memory", e))?;
        if !source_exists {
            return Err(StoreError::InvalidInput {
                detail: format!("source memory not found: {}", link.source_id),
            });
        }
        let target_exists: bool =
            sqlx::query_scalar("SELECT EXISTS(SELECT 1 FROM memories WHERE id = $1)")
                .bind(&link.target_id)
                .fetch_one(&self.pool)
                .await
                .map_err(|e| to_store_err("check target memory", e))?;
        if !target_exists {
            return Err(StoreError::InvalidInput {
                detail: format!("target memory not found: {}", link.target_id),
            });
        }

        // Resolve `created_at` / `valid_from`. Mirrors SQLite — both
        // columns get the current wall-clock when the caller did not
        // supply explicit values on the input record. Federation
        // replays (peer-attested links) carry their own stamps so we
        // honour them when present so signatures still verify.
        let now_utc = Utc::now();

        let created_at_dt = if link.created_at.is_empty() {
            now_utc
        } else {
            parse_rfc3339_required(&link.created_at)?
        };
        let valid_from_dt = match link.valid_from.as_deref() {
            Some(s) if !s.is_empty() => parse_rfc3339_required(s)?,
            _ => now_utc,
        };
        let valid_until_dt = match link.valid_until.as_deref() {
            Some(s) if !s.is_empty() => Some(parse_rfc3339_required(s)?),
            _ => None,
        };

        // v0.7.0.1 G3 — normalize the temporal-validity timestamps to
        // microsecond precision BEFORE we both sign over them and
        // commit them to PostgreSQL. PostgreSQL's `TIMESTAMPTZ` column
        // stores microseconds since epoch — sub-microsecond digits are
        // silently dropped at write time. If the canonical CBOR
        // payload commits to a nanosecond-precision RFC3339 string,
        // the verify path's `to_rfc3339()` of the read-back
        // `DateTime<Utc>` produces a microsecond-precision string,
        // changing the canonical CBOR bytes and invalidating the
        // signature (HALT R1b S52). Truncating both ends to the same
        // precision the column round-trips makes sign/verify byte-
        // stable across the storage layer. SQLite stores TIMESTAMPTZ
        // as RFC3339 TEXT and round-trips losslessly so the SQLite
        // path is unaffected — the truncation is a no-op when the
        // input is already microsecond-aligned.
        let valid_from_dt = truncate_to_microseconds(valid_from_dt);
        let valid_until_dt = valid_until_dt.map(truncate_to_microseconds);
        let valid_from_str = valid_from_dt.to_rfc3339();
        let valid_until_str = valid_until_dt.map(|t| t.to_rfc3339());

        // Branch on the keypair: signed vs. unsigned. The signed path
        // computes the canonical CBOR + Ed25519 signature BEFORE the
        // INSERT so a CBOR/sign failure surfaces as a clean error
        // rather than a half-written row. This is the same ordering
        // SQLite uses (see `db::create_link_signed`).
        let (signature, attest_level, observed_by_col): (
            Option<Vec<u8>>,
            &'static str,
            Option<String>,
        ) = match keypair {
            Some(kp) if kp.can_sign() => {
                let signable = crate::identity::sign::SignableLink {
                    src_id: &link.source_id,
                    dst_id: &link.target_id,
                    relation: link.relation.as_str(),
                    observed_by: Some(kp.agent_id.as_str()),
                    valid_from: Some(valid_from_str.as_str()),
                    valid_until: valid_until_str.as_deref(),
                };
                let sig = crate::identity::sign::sign(kp, &signable).map_err(|e| {
                    StoreError::IntegrityFailed {
                        detail: format!("sign link: {e}"),
                    }
                })?;
                (
                    Some(sig),
                    crate::models::AttestLevel::SelfSigned.as_str(),
                    Some(kp.agent_id.clone()),
                )
            }
            _ => (None, crate::models::AttestLevel::Unsigned.as_str(), None),
        };

        // v0.7.0.1 G4 — wrap the SQL `INSERT INTO memory_links` write
        // and the AGE `memory_graph` projection MERGE in a single
        // transaction so a successful link write never leaves a
        // stale AGE projection that would surface as `paths_found=0`
        // on `find_paths_cypher` (HALT v0.7.0 R1 S65). When the
        // adapter resolved the CTE backend at connect time the AGE
        // branch is a no-op — the recursive-CTE path reads from
        // `memory_links` directly.
        let mut tx = self
            .pool
            .begin()
            .await
            .map_err(|e| to_store_err("begin link tx", e))?;

        // ON CONFLICT … DO NOTHING gives idempotent migrate replays:
        // re-shipping a link the destination already holds collapses
        // to a no-op. The row's existing `signature` / `attest_level`
        // are preserved, so a self-signed write is never silently
        // demoted to unsigned by a subsequent unsigned replay.
        sqlx::query(
            "INSERT INTO memory_links
                 (source_id, target_id, relation, created_at, valid_from,
                  valid_until, signature, attest_level, observed_by)
             VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9)
             ON CONFLICT (source_id, target_id, relation) DO NOTHING",
        )
        .bind(&link.source_id)
        .bind(&link.target_id)
        .bind(link.relation.as_str())
        .bind(created_at_dt)
        .bind(valid_from_dt)
        .bind(valid_until_dt)
        .bind(signature)
        .bind(attest_level)
        .bind(observed_by_col)
        .execute(&mut *tx)
        .await
        .map_err(|e| to_store_err("insert memory_link", e))?;

        if matches!(self.kg_backend, KgBackend::Age) {
            // v0.7.0 fold-A2A1.3 (#700) extended to the link path
            // (#858 follow-up, 2026-05-18): AGE projection is
            // best-effort. The relational `memory_links` insert
            // above is the canonical source of truth — the AGE
            // graph projection is a query-acceleration mirror used
            // by the cypher-backed `find_paths_cypher` path, which
            // already falls back to the recursive CTE
            // (`is_age_runtime_failure` → `warn_age_fallback`) when
            // AGE is unavailable at query time.
            //
            // Pre-fix: any AGE runtime failure here (e.g. the test
            // postgres user lacking permission to `LOAD 'age'`)
            // propagated up as `BackendUnavailable` → HTTP 503,
            // even though the link row was successfully inserted
            // into `memory_links`. That broke every link-creating
            // postgres test (smoke + 5 handler_parity tests +
            // anything else that creates a link before reading via
            // cypher). The canonical link insert had already
            // committed at this point (well, it was queued in
            // `tx` — see below); the AGE projection failure should
            // degrade to a warning, not a 503.
            //
            // Treatment: catch the failure, log a structured warn
            // event with the same shape `warn_age_fallback` uses,
            // and continue to commit. Operators monitoring the
            // tracing stream see exactly which link skipped its
            // AGE projection.
            // #1542 — the WHOLE projection rides a SAVEPOINT. The
            // pre-#1542 warn-and-continue arm left the outer tx in the
            // ABORTED state after a projection error, so the commit
            // below silently became a ROLLBACK and the canonical
            // `memory_links` INSERT was lost while the handler
            // returned 201. Rolling back to the savepoint keeps the
            // outer tx healthy so the relational row truly commits —
            // making the warning below honest.
            sqlx::query("SAVEPOINT age_link_projection")
                .execute(&mut *tx)
                .await
                .map_err(|e| to_store_err("savepoint age_link_projection", e))?;
            match project_link_into_age(
                &mut tx,
                &link.source_id,
                &link.target_id,
                link.relation.as_str(),
            )
            .await
            {
                Ok(()) => {
                    sqlx::query("RELEASE SAVEPOINT age_link_projection")
                        .execute(&mut *tx)
                        .await
                        .map_err(|e| to_store_err("release savepoint age_link_projection", e))?;
                }
                Err(e) if is_age_runtime_failure(&e) => {
                    sqlx::query("ROLLBACK TO SAVEPOINT age_link_projection")
                        .execute(&mut *tx)
                        .await
                        .map_err(|e2| to_store_err("rollback savepoint age_link_projection", e2))?;
                    tracing::warn!(
                        target: TRACE_TARGET_KG,
                        source_id = %link.source_id,
                        target_id = %link.target_id,
                        relation = link.relation.as_str(),
                        err = %e,
                        "AGE projection skipped on link insert — \
                         relational memory_links row still committed. \
                         find_paths_cypher will degrade to CTE fallback for \
                         queries that traverse this edge."
                    );
                }
                Err(e) => return Err(e),
            }
        }

        tx.commit()
            .await
            .map_err(|e| to_store_err("commit link tx", e))?;

        Ok(attest_level)
    }

    fn row_to_memory(row: &sqlx::postgres::PgRow) -> StoreResult<Memory> {
        let created_at: DateTime<Utc> = row
            .try_get(field_names::CREATED_AT)
            .map_err(|e| to_store_err(READ_CREATED_AT, e))?;
        let updated_at: DateTime<Utc> = row
            .try_get(field_names::UPDATED_AT)
            .map_err(|e| to_store_err("read updated_at", e))?;
        let last_accessed_at: Option<DateTime<Utc>> = row
            .try_get(field_names::LAST_ACCESSED_AT)
            .map_err(|e| to_store_err("read last_accessed_at", e))?;
        let expires_at: Option<DateTime<Utc>> = row
            .try_get(field_names::EXPIRES_AT)
            .map_err(|e| to_store_err("read expires_at", e))?;

        let tier_str: String = row
            .try_get("tier")
            .map_err(|e| to_store_err("read tier", e))?;
        let tier = Tier::from_str(&tier_str).ok_or_else(|| StoreError::IntegrityFailed {
            detail: format!("invalid tier value: {tier_str}"),
        })?;

        // #1636 — pre-read the id so corrupt-provenance warns can name
        // the row (parity with the sqlite mapper's COR-3 hardening).
        let row_id: String = row.try_get("id").map_err(|e| to_store_err("read id", e))?;

        let tags_json: serde_json::Value = row
            .try_get("tags")
            .map_err(|e| to_store_err("read tags", e))?;
        let tags: Vec<String> = serde_json::from_value(tags_json).unwrap_or_default();

        let metadata: serde_json::Value = row
            .try_get("metadata")
            .map_err(|e| to_store_err("read metadata", e))?;

        // v0.7.0 Task 1/8 — read the v31 column; tolerate pre-v31 reads
        // (column missing on a freshly-restored backup, for instance) by
        // falling back to 0, which matches the SQL-side `DEFAULT 0`.
        let reflection_depth: i32 = row.try_get(field_names::REFLECTION_DEPTH).unwrap_or(0);
        // L1-1 — read the Postgres-side memory_kind column. Falls back to
        // Observation on pre-v30 rows and on any unrecognised value.
        let memory_kind: crate::models::MemoryKind = row
            .try_get::<String, _>(field_names::MEMORY_KIND)
            .ok()
            .and_then(|s| crate::models::MemoryKind::from_str(&s))
            .unwrap_or_default();

        Ok(Memory {
            id: row_id.clone(),
            tier,
            namespace: row
                .try_get("namespace")
                .map_err(|e| to_store_err(READ_NAMESPACE, e))?,
            title: row
                .try_get("title")
                .map_err(|e| to_store_err(READ_TITLE, e))?,
            content: row
                .try_get("content")
                .map_err(|e| to_store_err("read content", e))?,
            tags,
            priority: row
                .try_get("priority")
                .map_err(|e| to_store_err("read priority", e))?,
            confidence: row
                .try_get(field_names::CONFIDENCE)
                .map_err(|e| to_store_err("read confidence", e))?,
            source: row
                .try_get("source")
                .map_err(|e| to_store_err("read source", e))?,
            access_count: row
                .try_get(field_names::ACCESS_COUNT)
                .map_err(|e| to_store_err("read access_count", e))?,
            created_at: created_at.to_rfc3339(),
            updated_at: updated_at.to_rfc3339(),
            last_accessed_at: last_accessed_at.map(|t| t.to_rfc3339()),
            expires_at: expires_at.map(|t| t.to_rfc3339()),
            metadata,
            reflection_depth,
            memory_kind,
            // v0.7.0 QW-2 — pre-v36 rows lack these columns; tolerate the
            // missing-column error and fall back to NULL (matches SQLite
            // path behaviour for backups predating the persona migration).
            entity_id: row
                .try_get::<Option<String>, _>("entity_id")
                .unwrap_or(None),
            persona_version: row
                .try_get::<Option<i32>, _>(field_names::PERSONA_VERSION)
                .unwrap_or(None),
            // v0.7.0 Form 4 — Postgres v37 fact-provenance columns. The
            // SQL DEFAULT '[]' on `citations` keeps legacy rows visible
            // as the empty vec; pre-v37 backups missing the column hit
            // the `.unwrap_or_default()` fallthrough below.
            citations: match row.try_get::<String, _>("citations") {
                // Pre-v37 backup: column absent — silent empty is correct.
                Err(_) => Vec::new(),
                Ok(s) => serde_json::from_str(&s).unwrap_or_else(|e| {
                    // #1636 — corrupt CONTENT is observable (COR-3
                    // parity with the sqlite mapper), not silently
                    // defaulted.
                    tracing::warn!(memory_id = %row_id, "corrupt citations JSON in postgres row: {e}");
                    crate::metrics::record_corrupt_provenance("citations");
                    Vec::new()
                }),
            },
            source_uri: row
                .try_get::<Option<String>, _>(field_names::SOURCE_URI)
                .unwrap_or(None),
            source_span: row
                .try_get::<Option<String>, _>(COL_SOURCE_SPAN)
                .unwrap_or(None)
                .and_then(|s| match serde_json::from_str(&s) {
                    Ok(v) => Some(v),
                    Err(e) => {
                        // #1636 — COR-3 observability parity.
                        tracing::warn!(memory_id = %row_id, "corrupt source_span JSON in postgres row: {e}");
                        crate::metrics::record_corrupt_provenance(field_names::SOURCE_SPAN);
                        None
                    }
                }),
            // v0.7.0 Form 5 — Postgres v38 confidence-provenance columns.
            // Pre-v38 backups missing the column hit the `.ok()`
            // fallthrough; legacy rows resolve to `CallerProvided`
            // (the SQL DEFAULT on the v38 column).
            confidence_source: row
                .try_get::<String, _>(field_names::CONFIDENCE_SOURCE)
                .ok()
                .and_then(|s| crate::models::ConfidenceSource::from_str(&s))
                .unwrap_or_default(),
            confidence_signals: row
                .try_get::<Option<String>, _>(COL_CONFIDENCE_SIGNALS)
                .unwrap_or(None)
                .and_then(|s| match serde_json::from_str(&s) {
                    Ok(v) => Some(v),
                    Err(e) => {
                        // #1636 — COR-3 observability parity.
                        tracing::warn!(memory_id = %row_id, "corrupt confidence_signals JSON in postgres row: {e}");
                        crate::metrics::record_corrupt_provenance(COL_CONFIDENCE_SIGNALS);
                        None
                    }
                }),
            confidence_decayed_at: row
                .try_get::<Option<String>, _>(field_names::CONFIDENCE_DECAYED_AT)
                .unwrap_or(None),
            // v0.7.0 Provenance Gap 1 (#884) — read the v42 column.
            // Pre-v42 rows / backups missing the column fall back to
            // the SQL DEFAULT (1) via `default_memory_version()`.
            version: row
                .try_get::<i64, _>("version")
                .unwrap_or_else(|_| crate::models::default_memory_version()),
        })
    }

    /// v0.7.0 recursive-learning Task 4/8 (issue #655) — Postgres parity
    /// for [`crate::db::reflect`]. Inherent method (not on the
    /// [`MemoryStore`] trait) to keep the trait surface minimal per the
    /// Task 4 spec.
    ///
    /// Atomicity: the reflection memory insert + N `reflects_on` link
    /// inserts run inside a single `sqlx::Transaction`. Any link
    /// failure rolls back the entire write. Mirrors the
    /// `BEGIN IMMEDIATE` … `COMMIT` block on the SQLite path.
    ///
    /// Governance: walks the namespace ancestor chain via
    /// [`MemoryStore::resolve_governance_policy`], falls back to
    /// [`crate::models::GovernancePolicy::default`] when no policy is
    /// configured anywhere in the chain, then evaluates
    /// [`crate::models::GovernancePolicy::effective_max_reflection_depth`].
    ///
    /// Returns the [`crate::db::ReflectOutcome`] shape the SQLite path
    /// returns so test code can be backend-agnostic.
    ///
    /// # Errors
    ///
    /// Same [`crate::db::ReflectError`] variants as the SQLite path,
    /// emitted in the same order:
    /// 1. validation
    /// 2. source-not-found (no partial write)
    /// 3. depth-exceeded refusal
    /// 4. database errors during the atomic write
    pub async fn reflect(
        &self,
        ctx: &super::CallerContext,
        input: &crate::db::ReflectInput,
    ) -> std::result::Result<crate::db::ReflectOutcome, crate::db::ReflectError> {
        // Thin shim over [`reflect_with_hooks`] with an empty hook
        // bundle — keeps the public entry-point shape stable while
        // the v0.7.0 Task 6/8 pre_reflect / post_reflect surface
        // lands behind an opt-in second function.
        self.reflect_with_hooks(ctx, input, &crate::db::ReflectHooks::empty())
            .await
    }

    /// v0.7.0 recursive-learning Task 6/8 — Postgres twin of
    /// [`crate::db::reflect_with_hooks`]. Fires `pre_reflect` BEFORE
    /// the depth-cap check (a `Deny` propagates as
    /// [`crate::db::ReflectError::HookVeto`]; cap audit is NOT
    /// emitted on this path) and fires `post_reflect` AFTER the
    /// transaction commits (notify-class; return value ignored).
    ///
    /// # Errors
    ///
    /// Same variants as [`PostgresStore::reflect`] plus
    /// [`crate::db::ReflectError::HookVeto`] on `pre_reflect` veto.
    #[allow(clippy::too_many_lines)]
    pub async fn reflect_with_hooks(
        &self,
        ctx: &super::CallerContext,
        input: &crate::db::ReflectInput,
        hooks: &crate::db::ReflectHooks<'_>,
    ) -> std::result::Result<crate::db::ReflectOutcome, crate::db::ReflectError> {
        use crate::db::ReflectError;
        use crate::validate;

        // ─── 1. Validate inputs ─────────────────────────────────────
        validate::validate_title(&input.title)
            .map_err(|e| ReflectError::Validation(e.to_string()))?;
        validate::validate_content(&input.content)
            .map_err(|e| ReflectError::Validation(e.to_string()))?;
        validate::validate_tags(&input.tags)
            .map_err(|e| ReflectError::Validation(e.to_string()))?;
        validate::validate_priority(input.priority)
            .map_err(|e| ReflectError::Validation(e.to_string()))?;
        validate::validate_confidence(input.confidence)
            .map_err(|e| ReflectError::Validation(e.to_string()))?;
        validate::validate_source(&input.source)
            .map_err(|e| ReflectError::Validation(e.to_string()))?;
        validate::validate_agent_id(&input.agent_id)
            .map_err(|e| ReflectError::Validation(e.to_string()))?;
        if input.source_ids.is_empty() {
            return Err(ReflectError::Validation(
                "source_ids cannot be empty — a reflection must reflect on at least one source memory".into(),
            ));
        }
        let mut seen = std::collections::HashSet::new();
        for (i, id) in input.source_ids.iter().enumerate() {
            validate::validate_id(id)
                .map_err(|e| ReflectError::Validation(format!("source_ids[{i}]: {e}")))?;
            if !seen.insert(id.as_str()) {
                return Err(ReflectError::Validation(format!(
                    "source_ids[{i}]: duplicate id '{id}'"
                )));
            }
        }
        if let Some(ref ns) = input.namespace {
            validate::validate_namespace(ns)
                .map_err(|e| ReflectError::Validation(e.to_string()))?;
        }
        validate::validate_metadata(&input.metadata)
            .map_err(|e| ReflectError::Validation(e.to_string()))?;

        // ─── 2. Load each source memory ─────────────────────────────
        let mut sources = Vec::with_capacity(input.source_ids.len());
        for id in &input.source_ids {
            match super::MemoryStore::get(self, ctx, id).await {
                Ok(m) => sources.push(m),
                Err(StoreError::NotFound { .. }) => {
                    return Err(ReflectError::SourceNotFound(id.clone()));
                }
                Err(e) => return Err(ReflectError::Database(e.to_string())),
            }
        }

        // ─── 3. Compute new_depth ───────────────────────────────────
        let max_src_depth = sources
            .iter()
            .map(|m| m.reflection_depth)
            .max()
            .unwrap_or(0);
        let new_depth_i32 = max_src_depth.max(0).saturating_add(1);
        #[allow(clippy::cast_sign_loss)]
        let new_depth_u32: u32 = new_depth_i32 as u32;

        // ─── 4. Resolve target namespace + cap ──────────────────────
        let target_namespace = match input.namespace {
            Some(ref ns) => ns.clone(),
            None => sources[0].namespace.clone(),
        };
        let policy = super::MemoryStore::resolve_governance_policy(self, &target_namespace)
            .await
            .map_err(|e| ReflectError::Database(e.to_string()))?
            .unwrap_or_else(crate::models::GovernancePolicy::default);
        let cap = policy.effective_max_reflection_depth();

        // ─── 4.5 `pre_reflect` hook (v0.7.0 Task 6/8) ──────────────
        //
        // Fires BEFORE the cap check so a hook handler may VETO the
        // reflection. The veto path returns `ReflectError::HookVeto`
        // and does NOT emit the Task 5 depth-cap audit row.
        if let Some(pre) = hooks.pre_reflect.as_ref() {
            match (pre)(input) {
                crate::db::ReflectHookDecision::Allow => {}
                crate::db::ReflectHookDecision::Deny { reason, code } => {
                    return Err(ReflectError::HookVeto { reason, code });
                }
            }
        }

        // ─── 5. Refuse if proposed depth exceeds cap ────────────────
        //
        // Task 5/8 (v0.7.0): before propagating the refusal, append a
        // `reflection.depth_exceeded` row to `signed_events`. Mirrors
        // the SQLite parity path in `db::reflect`. Audit-write failure
        // is logged (best-effort); the refusal still propagates. Hook
        // vetoes (Task 6/8 `pre_reflect`) carry their own provenance
        // and are deliberately NOT emitted here.
        if new_depth_u32 > cap {
            // v0.7.0 L2-2 — surface cross-peer provenance in the audit
            // row when at least one source memory carries a
            // `reflection_origin.peer_origin` stamp (i.e. it was
            // imported via federation `sync_push`). Local cap is
            // enforced regardless of source origin (territorial
            // sovereignty); the peer claim only enriches the audit
            // record so a downstream auditor sees WHERE the depth
            // came from. Mirrors the SQLite parity path.
            let cross_peer_refusal =
                crate::federation::reflection_bookkeeping::enforce_local_cap_on_derived(
                    new_depth_u32,
                    cap,
                    &sources,
                );
            let peer_origin: Option<String> = if let Err(ref r) = cross_peer_refusal {
                if let Some(ref peer) = r.imported_peer {
                    tracing::warn!(
                        target: "federation::reflection_bookkeeping",
                        peer = %peer,
                        attempted = new_depth_u32,
                        local_cap = cap,
                        namespace = %target_namespace,
                        "L2-2 (pg): refusing derived reflection: {}",
                        r,
                    );
                }
                r.imported_peer.clone()
            } else {
                None
            };
            self.emit_reflection_depth_exceeded_audit(
                &input.agent_id,
                new_depth_u32,
                cap,
                &target_namespace,
                &input.source_ids,
                &input.title,
                peer_origin.as_deref(),
            )
            .await;
            return Err(ReflectError::DepthExceeded {
                attempted: new_depth_u32,
                cap,
                namespace: target_namespace,
            });
        }

        // ─── 6. Atomic insert + N links inside a single tx ──────────
        let now = Utc::now().to_rfc3339();
        let mut metadata = match input.metadata.clone() {
            serde_json::Value::Object(map) => map,
            _ => serde_json::Map::new(),
        };
        metadata.insert(
            "agent_id".to_string(),
            serde_json::Value::String(input.agent_id.clone()),
        );
        if !metadata.contains_key(field_names::REFLECTION_METADATA) {
            let reflection_meta = serde_json::json!({
                "reflected_on_source_ids": input.source_ids,
                (field_names::REFLECTION_DEPTH): new_depth_i32,
                "reflection_created_at": now,
            });
            metadata.insert(
                field_names::REFLECTION_METADATA.to_string(),
                reflection_meta,
            );
        }
        let metadata_value = serde_json::Value::Object(metadata);
        validate::validate_metadata(&metadata_value)
            .map_err(|e| ReflectError::Validation(e.to_string()))?;

        let new_id = uuid::Uuid::new_v4().to_string();
        let created_at_dt = chrono::DateTime::parse_from_rfc3339(&now)
            .map_err(|e| ReflectError::Database(format!("parse now: {e}")))?
            .with_timezone(&Utc);
        let tags_json = serde_json::to_value(&input.tags)
            .map_err(|e| ReflectError::Database(serialize_err("tags", e)))?;

        // FX-C5 — substrate governance pre-write hook parity. The
        // postgres reflect path mints a fresh memory via a raw INSERT
        // that bypasses `PostgresStore::store(..)` (which is where
        // ARCH-1 wired in the `consult_governance_pre_write_pg`
        // adapter at line 7001). Without this call, an operator's
        // signed governance rule could be bypassed by routing through
        // the reflect surface. Compose the candidate memory the way
        // the INSERT below will persist it and fire the hook BEFORE
        // the tx opens. A refusal returns
        // `ReflectError::HookVeto`-style via map of
        // `StoreError::PermissionDenied` so the surface stays typed.
        let candidate = Memory {
            id: new_id.clone(),
            tier: input.tier.clone(),
            namespace: target_namespace.clone(),
            title: input.title.clone(),
            content: input.content.clone(),
            tags: input.tags.clone(),
            priority: input.priority.clamp(1, 10),
            confidence: input.confidence.clamp(0.0, 1.0),
            source: input.source.clone(),
            access_count: 0,
            created_at: now.clone(),
            updated_at: now.clone(),
            last_accessed_at: None,
            expires_at: None,
            metadata: metadata_value.clone(),
            reflection_depth: new_depth_i32,
            memory_kind: crate::models::MemoryKind::Reflection,
            entity_id: None,
            persona_version: None,
            citations: Vec::new(),
            source_uri: None,
            source_span: None,
            confidence_source: crate::models::ConfidenceSource::CallerProvided,
            confidence_signals: None,
            confidence_decayed_at: None,
            version: crate::models::default_memory_version(),
        };
        if let Err(e) = consult_governance_pre_write_pg(&candidate) {
            // Map `StoreError::PermissionDenied` (the canonical refusal
            // shape on the postgres adapter) into `ReflectError`. The
            // operator-authored reason rides on the payload so callers
            // can surface it in the wire response. Use HTTP-style code
            // 403 to mirror the wire-level mapping the
            // `consult_governance_pre_write_pg` adapter produces on the
            // other postgres write paths (`GOVERNANCE_REFUSED`).
            let reason = match &e {
                StoreError::PermissionDenied { reason, .. } => reason.clone(),
                other => other.to_string(),
            };
            return Err(ReflectError::HookVeto { reason, code: 403 });
        }

        let mut tx = self
            .pool
            .begin()
            .await
            .map_err(|e| ReflectError::Database(format!("begin reflect tx: {e}")))?;

        // #1383 — extract the `mentioned_entity_id` denormalisation
        // from the candidate row (`metadata.entity_id` or `[entity:X]`
        // title marker, per `extract_mentioned_entity_id`). Pre-#1383
        // the postgres reflection insert dropped this column entirely
        // so `memory_persona_generate`'s `WHERE mentioned_entity_id = ?`
        // query returned zero reflections against the alice lan-parity
        // postgres-backed daemon — even when the caller correctly
        // passed `metadata.entity_id` through `memory_reflect`. SQLite
        // populates it at `src/storage/mod.rs:616`; this brings the
        // postgres adapter to parity.
        let mentioned_entity_id = crate::storage::extract_mentioned_entity_id(&candidate);

        // Insert the reflection memory inside the tx.
        let actual_id: String = sqlx::query(
            "INSERT INTO memories (
                id, tier, namespace, title, content, tags, priority, confidence,
                source, access_count, created_at, updated_at, last_accessed_at,
                expires_at, metadata, reflection_depth, memory_kind, mentioned_entity_id
            ) VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9, $10, $11, $12, NULL, NULL, $13, $14, $15, $16)
            ON CONFLICT (title, namespace) DO UPDATE SET
                content = EXCLUDED.content,
                tier = CASE
                    WHEN tier_rank(EXCLUDED.tier) >= tier_rank(memories.tier)
                        THEN EXCLUDED.tier
                    ELSE memories.tier
                END,
                tags = EXCLUDED.tags,
                priority = EXCLUDED.priority,
                confidence = EXCLUDED.confidence,
                updated_at = EXCLUDED.updated_at,
                metadata = CASE
                    WHEN memories.metadata ? 'agent_id'
                        THEN jsonb_set(
                            EXCLUDED.metadata,
                            '{agent_id}',
                            memories.metadata -> 'agent_id'
                        )
                    ELSE EXCLUDED.metadata
                END,
                reflection_depth = GREATEST(memories.reflection_depth, EXCLUDED.reflection_depth),
                memory_kind = CASE WHEN memories.memory_kind = 'reflection' THEN 'reflection'
                                   ELSE EXCLUDED.memory_kind END,
                -- #1383 — mirror the sqlite ON CONFLICT clause: preserve
                -- a previously-extracted attribution if EXCLUDED is NULL
                -- (e.g. a re-store that lost the metadata key by accident).
                mentioned_entity_id = COALESCE(EXCLUDED.mentioned_entity_id, memories.mentioned_entity_id)
            RETURNING id",
        )
        .bind(&new_id)
        .bind(input.tier.as_str())
        .bind(&target_namespace)
        .bind(&input.title)
        .bind(&input.content)
        .bind(&tags_json)
        .bind(input.priority.clamp(1, 10))
        .bind(input.confidence.clamp(0.0, 1.0))
        .bind(&input.source)
        .bind(0_i64)
        .bind(created_at_dt)
        .bind(created_at_dt)
        .bind(&metadata_value)
        .bind(new_depth_i32)
        .bind(crate::models::MemoryKind::Reflection.as_str())
        .bind(mentioned_entity_id.as_deref())
        .fetch_one(&mut *tx)
        .await
        .map_err(|e| ReflectError::Database(format!("insert reflection memory: {e}")))?
        .try_get::<String, _>("id")
        .map_err(|e| ReflectError::Database(format!("read returned id: {e}")))?;

        // Write each `reflects_on` link inside the same tx.
        for src_id in &input.source_ids {
            validate::validate_link(
                &actual_id,
                src_id,
                crate::models::MemoryLinkRelation::ReflectsOn.as_str(),
            )
            .map_err(|e| ReflectError::Validation(e.to_string()))?;
            // Inline a minimal `memory_links` INSERT — full
            // `link_internal` runs its own queries on the pool and
            // wouldn't share the tx. SQLite parity calls
            // `db::create_link` which uses the same connection; we
            // mirror that here with a `&mut tx` binding so a link
            // failure rolls back the memory insert.
            sqlx::query(
                "INSERT INTO memory_links \
                    (source_id, target_id, relation, created_at, valid_from, attest_level) \
                 VALUES ($1, $2, $3, $4, $4, 'unsigned') \
                 ON CONFLICT (source_id, target_id, relation) DO NOTHING",
            )
            .bind(&actual_id)
            .bind(src_id)
            .bind(crate::models::MemoryLinkRelation::ReflectsOn.as_str())
            .bind(created_at_dt)
            .execute(&mut *tx)
            .await
            .map_err(|e| ReflectError::Database(format!("insert reflects_on link: {e}")))?;
        }

        tx.commit()
            .await
            .map_err(|e| ReflectError::Database(format!("commit reflect tx: {e}")))?;

        let outcome = crate::db::ReflectOutcome {
            id: actual_id,
            reflection_depth: new_depth_i32,
            reflects_on: input.source_ids.clone(),
            namespace: target_namespace,
        };
        // ─── 7. `post_reflect` hook (v0.7.0 Task 6/8) ───────────────
        //
        // Fires AFTER the transaction commits so the hook handler can
        // see a fully durable reflection memory + its links. Notify-
        // class — the return value is ignored.
        if let Some(post) = hooks.post_reflect.as_ref() {
            (post)(&outcome);
        }
        Ok(outcome)
    }

    /// v0.7.0 recursive-learning Task 5/8 — append a
    /// `reflection.depth_exceeded` row to `signed_events` for an
    /// in-flight cap refusal on the Postgres backend.
    ///
    /// Mirrors the SQLite `db::emit_reflection_depth_exceeded_audit`
    /// helper byte-for-byte (the canonical-CBOR encoding lives in
    /// `db::canonical_cbor_reflection_depth_exceeded` and is shared
    /// across both substrates so the `payload_hash` round-trips).
    /// Best-effort: audit-write failure is logged but does NOT crater
    /// the refusal path.
    async fn emit_reflection_depth_exceeded_audit(
        &self,
        agent_id: &str,
        attempted: u32,
        cap: u32,
        namespace: &str,
        source_ids: &[String],
        proposed_title: &str,
        peer_origin: Option<&str>,
    ) {
        let created_at_dt = Utc::now();
        let created_at = created_at_dt.to_rfc3339();
        let cbor = match crate::db::canonical_cbor_reflection_depth_exceeded(
            agent_id,
            attempted,
            cap,
            namespace,
            source_ids,
            proposed_title,
            &created_at,
            peer_origin,
        ) {
            Ok(b) => b,
            Err(e) => {
                tracing::warn!(
                    target: crate::signed_events::SIGNED_EVENTS_TRACE_TARGET,
                    agent_id, attempted, cap, namespace,
                    "failed to encode canonical CBOR for reflection_depth_exceeded audit: {e}"
                );
                return;
            }
        };
        let id = uuid::Uuid::new_v4().to_string();
        let payload_hash = crate::signed_events::payload_hash(&cbor);
        // v0.7.0 L2-2 — distinguish the audit row's `event_type` so
        // operators can filter cross-peer refusals from local-only
        // refusals without re-decoding the CBOR payload. Mirrors the
        // SQLite parity path.
        let event_type = if peer_origin.is_some() {
            "reflection.depth_exceeded.cross_peer"
        } else {
            "reflection.depth_exceeded"
        };
        // v34 (#698 V-4 closeout) — compute the cross-row chain
        // (prev_hash, sequence) and INSERT all in one transaction so
        // the read MAX(sequence) → INSERT race is closed. The UNIQUE
        // INDEX on `sequence` makes the worst case a constraint
        // violation rather than a silent chain break.
        let insert_row = PgSignedEventInsert {
            id: &id,
            agent_id,
            event_type,
            payload_hash: &payload_hash,
            signature: None,
            attest_level: crate::models::AttestLevel::Unsigned.as_str(),
            timestamp: created_at_dt,
        };
        if let Err(e) = pg_append_signed_event_with_chain(&self.pool, insert_row).await {
            tracing::warn!(
                target: crate::signed_events::SIGNED_EVENTS_TRACE_TARGET,
                agent_id, attempted, cap, namespace,
                "failed to append reflection_depth_exceeded audit row: {e}"
            );
        }
    }
}

/// Caller-supplied fields for [`pg_append_signed_event_with_chain`].
/// Bundled in a struct rather than positional args so the helper
/// doesn't trip `clippy::too_many_arguments`.
struct PgSignedEventInsert<'a> {
    id: &'a str,
    agent_id: &'a str,
    event_type: &'a str,
    payload_hash: &'a [u8],
    signature: Option<&'a [u8]>,
    attest_level: &'a str,
    timestamp: chrono::DateTime<chrono::Utc>,
}

/// Postgres-side companion to
/// [`crate::signed_events::append_signed_event`]. Computes the
/// chain head (`MAX(sequence)` + canonical hash of that row) and
/// INSERTs the new row inside a single transaction. The
/// `SERIALIZABLE` isolation isn't required — the UNIQUE INDEX on
/// `sequence` enforces correctness under concurrent writers — but
/// we wrap in a transaction so the read+insert pair is atomic
/// against rollback.
///
/// # Errors
///
/// Returns the underlying `sqlx::Error` wrapped in `StoreError` on
/// failure.
async fn pg_append_signed_event_with_chain(
    pool: &PgPool,
    row: PgSignedEventInsert<'_>,
) -> Result<(), sqlx::Error> {
    let mut tx = pool.begin().await?;
    pg_append_signed_event_with_chain_in_tx(&mut tx, row).await?;
    tx.commit().await?;
    Ok(())
}

/// Transaction-scoped twin of [`pg_append_signed_event_with_chain`].
/// Computes the chain head and INSERTs the new `signed_events` row
/// against a caller-owned transaction so multi-row writes (e.g. the L4
/// `capture_turn_idempotent` path, #1416) can append the audit row in
/// the SAME transaction as the data rows — the chain never lags the
/// data, and a rollback discards both. The caller owns BEGIN/COMMIT.
async fn pg_append_signed_event_with_chain_in_tx(
    tx: &mut sqlx::Transaction<'_, sqlx::Postgres>,
    row: PgSignedEventInsert<'_>,
) -> Result<(), sqlx::Error> {
    let PgSignedEventInsert {
        id,
        agent_id,
        event_type,
        payload_hash,
        signature,
        attest_level,
        timestamp,
    } = row;
    use crate::signed_events::{ZERO_HASH, canonical_chain_bytes};
    use sha2::{Digest, Sha256};

    // Read the chain head.
    let head: Option<(
        String,
        String,
        String,
        Vec<u8>,
        Option<Vec<u8>>,
        String,
        chrono::DateTime<chrono::Utc>,
        Option<i64>,
    )> = sqlx::query_as(
        "SELECT id, agent_id, event_type, payload_hash, signature, attest_level, timestamp, \
                sequence \
         FROM signed_events \
         ORDER BY COALESCE(sequence, 0) DESC, ctid DESC \
         LIMIT 1",
    )
    .fetch_optional(&mut **tx)
    .await?;

    let (next_seq, prev_hash) = match head {
        None => (1_i64, ZERO_HASH.to_vec()),
        Some((h_id, h_agent, h_type, h_payload, h_sig, h_attest, h_ts, h_seq)) => {
            let seq = h_seq.unwrap_or(0);
            let event = crate::signed_events::SignedEvent {
                id: h_id,
                agent_id: h_agent,
                event_type: h_type,
                payload_hash: h_payload,
                signature: h_sig,
                attest_level: h_attest,
                timestamp: h_ts.to_rfc3339(),
                prev_hash: Vec::new(),
                sequence: seq,
            };
            let canon = canonical_chain_bytes(&event);
            let mut hasher = Sha256::new();
            hasher.update(&canon);
            let mut digest = [0u8; 32];
            digest.copy_from_slice(&hasher.finalize());
            (seq + 1, digest.to_vec())
        }
    };

    sqlx::query(
        "INSERT INTO signed_events \
            (id, agent_id, event_type, payload_hash, signature, attest_level, timestamp, \
             prev_hash, sequence) \
         VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9)",
    )
    .bind(id)
    .bind(agent_id)
    .bind(event_type)
    .bind(payload_hash)
    .bind(signature.map(<[u8]>::to_vec))
    .bind(attest_level)
    .bind(timestamp)
    .bind(&prev_hash)
    .bind(next_seq)
    .execute(&mut **tx)
    .await?;

    Ok(())
}

// ---------------------------------------------------------------------------
// #1558 batch 5 wave 2 — shared sqlx `row.try_get` context labels.
//
// The high-traffic column-read labels passed to `to_store_err` were
// previously spelled inline at 3-9 sites each. `&'static str` consts:
// zero allocation, byte-identical error detail. Labels used at fewer
// than 3 sites stay inline (below the no-hardcoded-literals ratchet
// threshold).
// ---------------------------------------------------------------------------
const READ_NAMESPACE: &str = "read namespace";
const READ_RELATION: &str = "read relation";
const READ_TARGET_ID: &str = "read target_id";
const READ_VALID_FROM: &str = "read valid_from";
const READ_VALID_UNTIL: &str = "read valid_until";
const READ_OBSERVED_BY: &str = "read observed_by";
const READ_CREATED_AT: &str = "read created_at";
const READ_TITLE: &str = "read title";
const READ_SOURCE_ID: &str = "read source_id";
const READ_ATTEST_LEVEL: &str = "read attest_level";
const READ_RETURNED_ID: &str = "read returned id";

/// #1558 batch 5 wave 2 — JSON-column field names shared by the
/// `serialize_err` encode sites and the `row.try_get` decode sites.
const COL_SOURCE_SPAN: &str = "source_span";
const COL_CONFIDENCE_SIGNALS: &str = "confidence_signals";

/// #1558 batch 5 wave 2 — canonical `"serialize {field}: {e}"` detail
/// string for the serde-to-column encode failures (`tags`, `citations`,
/// `source_span`, `confidence_signals`). Byte-identical to the prior
/// inline `format!` at every site.
fn serialize_err(field: &str, e: impl std::fmt::Display) -> String {
    format!("serialize {field}: {e}")
}

#[allow(clippy::needless_pass_by_value)]
fn to_store_err(what: &str, e: sqlx::Error) -> StoreError {
    StoreError::BackendUnavailable {
        backend: "postgres".to_string(),
        // #1585 (SEC) — the #1579 A3 redaction covered the parse-url
        // site only; this shared helper wraps `pool.acquire` / `begin`
        // / per-statement errors, and `sqlx::Error::Configuration`
        // (and some connect-time variants) can interpolate the raw
        // connection URL — credentials included — into its Display.
        // Scrub any embedded URL's password before the detail leaves
        // the adapter, mirroring the A3 parse-url site.
        detail: crate::logging::redact_urls_in_message(&format!("{what}: {e}")),
    }
}

/// ARCH-1 — Postgres-side adapter for the substrate
/// [`crate::storage::GOVERNANCE_PRE_WRITE`] hook.
///
/// Consults the process-wide pre-write hook installed by the daemon
/// `serve` bootstrap. On refusal, returns
/// [`StoreError::PermissionDenied`] with the operator-authored
/// `reason` so the SAL-trait-routed write surfaces as `403 FORBIDDEN`
/// via [`crate::handlers::postgres_gate::store_err_to_response`] — the
/// nearest typed variant that maps to the canonical
/// `GOVERNANCE_REFUSED` HTTP status. The `action` /
/// `target` fields carry enough context for operators reading the
/// scrubbed wire response to recognise the substrate gate.
///
/// The SQLite path uses the same hook from inside
/// `crate::storage::insert*`; this helper mirrors that contract for
/// the sqlx-native postgres write paths so multi-tenant
/// postgres-backed deployments cannot bypass operator-signed
/// governance.
fn consult_governance_pre_write_pg(memory: &Memory) -> StoreResult<()> {
    match crate::storage::consult_governance_pre_write(memory) {
        Ok(()) => Ok(()),
        Err(e) => {
            // The substrate helper wraps the refusal in
            // `anyhow::Error::new(GovernanceRefusal { reason })`.
            // Downcast to recover the operator-authored reason; if
            // the downcast somehow fails (cannot happen in practice
            // given the helper's contract), fall back to the
            // anyhow display string so the refusal still flows.
            let reason = e
                .downcast_ref::<crate::storage::GovernanceRefusal>()
                .map_or_else(|| e.to_string(), |r| r.reason.clone());
            Err(StoreError::PermissionDenied {
                action: "memory_write".to_string(),
                target: memory.namespace.clone(),
                reason,
            })
        }
    }
}

impl PostgresStore {
    /// FX-C5 — load a row from `archived_memories` shaped as a
    /// [`Memory`] so the substrate
    /// [`crate::storage::GOVERNANCE_PRE_WRITE`] hook can inspect the
    /// restore candidate BEFORE the live INSERT lands. The archived
    /// table shares the v0.7.0 column shape with `memories` (#1025)
    /// so the same [`PostgresStore::row_to_memory`] mapper applies;
    /// columns absent on legacy pre-#1025 archived rows fall through
    /// to the same defaults the mapper already applies. The
    /// `original_tier` column wins over the archive-time `tier` so
    /// the candidate hook sees the row at the tier it will land at
    /// post-restore (matches the SQL the caller is about to execute).
    async fn load_archived_as_memory_pg(
        executor: &mut sqlx::PgConnection,
        id: &str,
    ) -> StoreResult<Memory> {
        let row = sqlx::query(
            "SELECT id, COALESCE(original_tier, tier) AS tier, namespace, title, content,
                    tags, priority, confidence, source, access_count, created_at,
                    updated_at, last_accessed_at,
                    COALESCE(original_expires_at, expires_at) AS expires_at, metadata,
                    embedding, embedding_dim,
                    COALESCE(reflection_depth, 0) AS reflection_depth,
                    atomised_into, atom_of,
                    COALESCE(memory_kind, 'observation') AS memory_kind,
                    entity_id, persona_version,
                    COALESCE(citations, '[]') AS citations,
                    source_uri, source_span,
                    COALESCE(confidence_source, 'caller_provided') AS confidence_source,
                    confidence_signals, confidence_decayed_at,
                    mentioned_entity_id,
                    COALESCE(version, 1) AS version
             FROM archived_memories WHERE id = $1",
        )
        .bind(id)
        .fetch_optional(executor)
        .await
        .map_err(|e| to_store_err("load archived as memory", e))?;
        let row = row.ok_or_else(|| StoreError::NotFound { id: id.to_string() })?;
        Self::row_to_memory(&row)
    }
}

/// #1473 — sargable namespace equality predicate for `list()`. Emitted
/// when the caller supplies an explicit namespace; the bare `= $1`
/// equality is recognized as an `Index Cond` on `memories_namespace_idx`
/// even under sqlx's generic prepared-statement plan.
const NS_FILTER_SARGABLE: &str = "namespace = $1";

/// #1473 — OR-NULL optional namespace predicate for `list()`. Emitted
/// only when the caller passes NO namespace, where it is a no-op (an
/// unfiltered list has no index to exploit, so the OR-NULL form costs
/// nothing the equality form would save). Never use this form when a
/// namespace IS present — under the generic plan it degrades to a Seq
/// Scan (the #1473 defect).
const NS_FILTER_OPTIONAL: &str = "($1::text IS NULL OR namespace = $1)";

/// Exclusive upper bound for a byte-ordered prefix range: the smallest
/// string strictly greater than every string starting with `prefix`.
///
/// Increments the last byte that is `< 0xFF`, dropping any trailing
/// `0xFF` bytes. Returns `None` when no such bound exists (empty prefix,
/// or all-`0xFF`), in which case the caller uses an open-ended `>=`
/// lower bound only. Valid for the database's byte-ordered (C) collation.
fn prefix_upper_bound(prefix: &str) -> Option<String> {
    let mut bytes = prefix.as_bytes().to_vec();
    while let Some(&last) = bytes.last() {
        if last < 0xFF {
            *bytes.last_mut().unwrap() = last + 1;
            // Bytes before the incremented one stay valid UTF-8; the
            // incremented tail byte keeps any multi-byte sequence's lead
            // bytes intact for ASCII prefixes (our namespaces are ASCII).
            return String::from_utf8(bytes).ok();
        }
        bytes.pop();
    }
    None
}

/// v0.7.0 fold-A2A1.3 (#700) — AGE-side runtime failure classifier.
///
/// Decides whether a `StoreError` returned from one of the
/// `*_cypher` methods is an *AGE substrate* failure that should fall
/// through to the CTE branch, vs an upstream concern that the caller
/// must see (invalid input, integrity error, etc.).
///
/// We treat every `BackendUnavailable` from an AGE method as a
/// runtime AGE failure: the cypher path's call sites (`LOAD 'age'`,
/// `SET search_path`, the `cypher()` SRF) all funnel their errors
/// through [`to_store_err`] which maps to `BackendUnavailable`, so
/// any of these failing — extension dropped, projection missing,
/// connection killed mid-tx — counts. `InvalidInput`,
/// `IntegrityFailed`, `NotFound`, `Conflict`, `PermissionDenied`,
/// `UnsupportedCapability` and `Backend` all bubble up unchanged
/// because they reflect either caller bugs or non-AGE issues the
/// CTE branch can't paper over.
fn is_age_runtime_failure(err: &StoreError) -> bool {
    matches!(err, StoreError::BackendUnavailable { .. })
}

/// v0.7.0 fold-A2A1.3 (#700) — structured warning emitted when a
/// single-source KG operation falls back from AGE to the relational
/// CTE at runtime. Operators monitoring the daemon's `tracing`
/// stream see the per-request degradation event with enough
/// structured fields to grep for: which KG op fired, which source
/// id, and the underlying AGE error string.
///
/// The matching operator-side surface is documented in
/// `docs/kg-backend-fallback.md`.
fn warn_age_fallback(op: &str, source_id: &str, err: &StoreError) {
    tracing::warn!(
        target: TRACE_TARGET_KG,
        op = op,
        source_id = source_id,
        backend = "age",
        fallback = "cte",
        error = %err,
        "AGE backend unreachable; falling back to CTE for kg_{op}=<{source_id}>"
    );
}

/// v0.7.0 fold-A2A1.3 (#700) — variant of [`warn_age_fallback`] for
/// the two-id `find_paths` operation, where the structured event
/// needs both `source_id` and `target_id`.
fn warn_age_fallback_pair(op: &str, source_id: &str, target_id: &str, err: &StoreError) {
    tracing::warn!(
        target: TRACE_TARGET_KG,
        op = op,
        source_id = source_id,
        target_id = target_id,
        backend = "age",
        fallback = "cte",
        error = %err,
        "AGE backend unreachable; falling back to CTE for kg_{op}=<{source_id}->{target_id}>"
    );
}

/// Issue an `ALTER TABLE ... ADD COLUMN` only when the column is not
/// yet present. Postgres has no `ADD COLUMN IF NOT EXISTS` clause that
/// also tolerates an existing column with a different shape — the
/// `information_schema.columns` lookup is the safest probe and runs in
/// the same transaction so a concurrent re-applied migration is
/// serializable. Caller passes the full DDL string verbatim because
/// each ADD COLUMN may carry different defaults / nullability.
async fn add_column_if_missing(
    tx: &mut sqlx::Transaction<'_, sqlx::Postgres>,
    table: &str,
    column: &str,
    ddl: &str,
) -> StoreResult<()> {
    let exists: bool = sqlx::query_scalar(
        "SELECT EXISTS(
            SELECT 1 FROM information_schema.columns
            WHERE table_name = $1 AND column_name = $2
        )",
    )
    .bind(table)
    .bind(column)
    .fetch_one(&mut **tx)
    .await
    .map_err(|e| to_store_err(&format!("check {table}.{column} column"), e))?;

    if !exists {
        sqlx::query(ddl)
            .execute(&mut **tx)
            .await
            .map_err(|e| to_store_err(&format!("add {table}.{column} column"), e))?;
    }
    Ok(())
}

/// Stamp a successful schema migration into `schema_version`.
///
/// Each step calls this with its own version number; we use
/// `ON CONFLICT (version) DO NOTHING` so re-running the migration over
/// an already-stamped row is a clean no-op. The previous v15 path
/// `DELETE` + `INSERT`'d which would drop history of intermediate
/// versions; preserving every applied version is more useful for
/// post-mortem auditing.
async fn record_schema_version(
    tx: &mut sqlx::Transaction<'_, sqlx::Postgres>,
    version: i32,
) -> StoreResult<()> {
    sqlx::query(
        "INSERT INTO schema_version (version) VALUES ($1) ON CONFLICT (version) DO NOTHING",
    )
    .bind(version)
    .execute(&mut **tx)
    .await
    .map_err(|e| to_store_err("insert schema_version", e))?;
    Ok(())
}

/// v0.7.0 H10 — transaction-bound twin of
/// [`PostgresStore::build_namespace_chain`]. Reads every
/// `namespace_meta.parent_namespace` lookup through the supplied tx so
/// the chain walk shares a snapshot with the downstream policy lookup +
/// pending_actions INSERT. Logic identical to the trait method — the
/// only delta is `fetch_optional(&mut *tx)` instead of `&self.pool`.
///
/// # F-A2A1.2 inheritance recursion cap
///
/// The governance-inheritance walk is capped at
/// [`GOVERNANCE_INHERITANCE_DEPTH_CAP`] (= 5) intermediate levels per the
/// v0.7.0 spec. Both the `/`-derived ancestor chain and the explicit
/// `namespace_meta.parent_namespace` walk are bounded by the same cap so a
/// pathological deep namespace cannot blow the policy resolver's bind list
/// or its connection-hold budget. The implicit `"*"` global standard is
/// always retained and is not counted toward the cap.
async fn build_namespace_chain_in_tx(
    tx: &mut sqlx::Transaction<'_, sqlx::Postgres>,
    namespace: &str,
) -> StoreResult<Vec<String>> {
    let mut chain: Vec<String> = Vec::new();

    if namespace == "*" {
        chain.push("*".to_string());
        return Ok(chain);
    }
    chain.push("*".to_string());

    let mut hierarchy_chain: Vec<String> = crate::models::namespace_ancestors(namespace)
        .into_iter()
        .rev()
        .collect();

    if let Some(root) = hierarchy_chain.first().cloned() {
        let mut explicit_above: Vec<String> = Vec::new();
        let mut current = root;
        for _ in 0..GOVERNANCE_INHERITANCE_DEPTH_CAP {
            let row: Option<(Option<String>,)> =
                sqlx::query_as("SELECT parent_namespace FROM namespace_meta WHERE namespace = $1")
                    .bind(&current)
                    .fetch_optional(&mut **tx)
                    .await
                    .map_err(|e| to_store_err("build_namespace_chain_in_tx parent lookup", e))?;
            let next = row.and_then(|(p,)| p);
            match next {
                Some(p)
                    if p != "*"
                        && !explicit_above.contains(&p)
                        && !hierarchy_chain.contains(&p) =>
                {
                    explicit_above.push(p.clone());
                    current = p;
                }
                _ => break,
            }
        }
        for p in explicit_above.into_iter().rev() {
            if !chain.contains(&p) {
                chain.push(p);
            }
        }
    }
    // F-A2A1.2 — cap the `/`-derived ancestor chain to the same depth as
    // the explicit walk so a deeply nested namespace cannot bypass the
    // resolver's bounded budget. The cap counts the most-specific N
    // levels (the leaf and its closest ancestors) so an over-deep
    // namespace still resolves against its most-relevant policy.
    let drained: Vec<String> = hierarchy_chain.drain(..).collect();
    let drained_len = drained.len();
    let kept: Vec<String> = if drained_len > GOVERNANCE_INHERITANCE_DEPTH_CAP {
        // hierarchy_chain is top-down (root → leaf); keep the LAST
        // GOVERNANCE_INHERITANCE_DEPTH_CAP entries (most-specific).
        drained
            .into_iter()
            .skip(drained_len - GOVERNANCE_INHERITANCE_DEPTH_CAP)
            .collect()
    } else {
        drained
    };
    for entry in kept {
        if !chain.contains(&entry) {
            chain.push(entry);
        }
    }
    Ok(chain)
}

/// F-A2A1.2 — maximum depth of the governance-inheritance walk.
///
/// Bounds both the `/`-derived ancestor decomposition AND the explicit
/// `namespace_meta.parent_namespace` walk to a single cap of 5 levels.
/// The implicit `"*"` global standard is always retained and is not
/// counted toward the cap.
///
/// Pinned to 5 per the v0.7.0 fold-A2A1 spec (see
/// `docs/v0.7.0/a2a-triage-wave4-r2.md` §F-A2A1.2). Real-world
/// namespaces are 3-4 levels deep; the cap leaves headroom for one
/// inherited override beyond the deepest authored ancestor while
/// keeping the per-write resolver's connection-hold budget bounded.
pub const GOVERNANCE_INHERITANCE_DEPTH_CAP: usize = 5;

/// Maximum traversal depth supported by [`PostgresStore::kg_query`].
///
/// Mirrors `crate::db::KG_QUERY_MAX_SUPPORTED_DEPTH` (the SQLite path)
/// so the published depth budget is the same on every backend. Pinned
/// here rather than re-imported because `crate::db` is a SQLite-only
/// module that doesn't compile under the `sal-postgres` test surface
/// when sqlite features are disabled.
const KG_QUERY_MAX_SUPPORTED_DEPTH: usize = 5;

/// Common pre-flight check shared by both `kg_query` branches. Pulled
/// out so the dispatcher's contract — "0 and >5 always error before we
/// touch the wire" — survives a future refactor that splits the
/// branches into separate modules.
fn validate_depth(max_depth: usize) -> StoreResult<()> {
    if max_depth == 0 {
        return Err(StoreError::InvalidInput {
            detail: crate::errors::msg::MAX_DEPTH_MIN.to_string(),
        });
    }
    if max_depth > KG_QUERY_MAX_SUPPORTED_DEPTH {
        return Err(StoreError::InvalidInput {
            detail: format!(
                "max_depth={max_depth} exceeds supported depth={KG_QUERY_MAX_SUPPORTED_DEPTH}"
            ),
        });
    }
    Ok(())
}

/// Default depth used by [`PostgresStore::find_paths`] when the caller
/// omits `max_depth`. Mirrors `crate::db::FIND_PATHS_DEFAULT_DEPTH`.
const FIND_PATHS_DEFAULT_DEPTH_SAL: usize = 4;

/// Hard ceiling on traversal depth supported by
/// [`PostgresStore::find_paths`]. Mirrors
/// `crate::db::FIND_PATHS_MAX_DEPTH`.
const FIND_PATHS_MAX_DEPTH_SAL: usize = 7;

/// Default cap on paths returned by [`PostgresStore::find_paths`] when
/// the caller omits `max_results`. Mirrors
/// `crate::db::FIND_PATHS_DEFAULT_LIMIT`.
const FIND_PATHS_DEFAULT_LIMIT_SAL: usize = 10;

/// Hard ceiling on paths returned by [`PostgresStore::find_paths`].
/// Mirrors `crate::db::FIND_PATHS_MAX_LIMIT`.
const FIND_PATHS_MAX_LIMIT_SAL: usize = 50;

/// Common pre-flight check shared by both `find_paths` branches. Pulled
/// out so the dispatcher's contract — "0 and >FIND_PATHS_MAX_DEPTH_SAL
/// always error before we touch the wire" — survives a future refactor
/// that splits the branches into separate modules.
fn validate_find_paths_depth(max_depth: usize) -> StoreResult<()> {
    if max_depth == 0 {
        return Err(StoreError::InvalidInput {
            detail: crate::errors::msg::MAX_DEPTH_MIN.to_string(),
        });
    }
    if max_depth > FIND_PATHS_MAX_DEPTH_SAL {
        return Err(StoreError::InvalidInput {
            detail: format!(
                "max_depth={max_depth} exceeds supported depth={FIND_PATHS_MAX_DEPTH_SAL}"
            ),
        });
    }
    Ok(())
}

/// Default cap on rows returned by [`PostgresStore::kg_timeline`] when
/// the caller does not specify one.
///
/// Mirrors `crate::db::KG_TIMELINE_DEFAULT_LIMIT` so the default page
/// size is identical on every backend. Pinned here rather than
/// re-imported because `crate::db` is a SQLite-only module that
/// doesn't compile under the `sal-postgres` test surface when sqlite
/// features are disabled.
const KG_TIMELINE_DEFAULT_LIMIT_SAL: usize = 200;

/// Hard ceiling on rows returned by [`PostgresStore::kg_timeline`].
///
/// Mirrors `crate::db::KG_TIMELINE_MAX_LIMIT`.
const KG_TIMELINE_MAX_LIMIT_SAL: usize = 1000;

/// Hard ceiling on rows returned by a single store-level list scan
/// ([`PostgresStore::list_by_namespace_prefix`],
/// [`PostgresStore::list_memories_updated_since`]). Bounds the
/// per-write dispatch and federation-catchup hot paths so one call
/// cannot exhaust the connection pool with an unbounded fetch.
const STORE_LIST_MAX_LIMIT_SAL: i64 = 10_000;

/// Default page cap for [`PostgresStore::list_by_source_uri`] when the
/// caller passes no limit. Mirrors `crate::storage::LIST_DEFAULT_CAP`.
const DEFAULT_LIST_CAP_I64: i64 = 200;

/// Post-clamp `usize → i64` conversion fallback for list/query limits.
/// Mirrors `crate::storage::LIST_FALLBACK_LIMIT`; unreachable in
/// practice (inputs are pre-clamped to `LIST_MAX_LIMIT`, which always
/// fits `i64`).
const LIST_FALLBACK_LIMIT_I64: i64 = 100;

/// Conversion fallback page size for [`PostgresStore::list_archived_pg`].
const ARCHIVED_LIST_FALLBACK_I64: i64 = 50;

/// Page size used by [`PostgresStore::recall_hybrid`] when the caller
/// passes `limit == 0` (also the conversion fallback on the same path).
const RECALL_FALLBACK_LIMIT_I64: i64 = 10;

/// Apply the published timeline page-size policy: default to
/// [`KG_TIMELINE_DEFAULT_LIMIT_SAL`] when the caller didn't pass a
/// limit, then clamp to the `[1, KG_TIMELINE_MAX_LIMIT_SAL]` band so a
/// crafted call cannot exhaust the connection pool with one giant
/// fetch. Pulled into a free function so both backend branches share
/// the same clamping contract.
fn clamp_timeline_limit(limit: Option<usize>) -> usize {
    limit
        .unwrap_or(KG_TIMELINE_DEFAULT_LIMIT_SAL)
        .clamp(1, KG_TIMELINE_MAX_LIMIT_SAL)
}

/// Decode an AGE agtype scalar that may be a quoted string or the
/// agtype `null` token. Returns `None` for `null`, otherwise the
/// dequoted UTF-8 payload.
///
/// AGE's `cypher()` SRF returns each column as `agtype`. Casting to
/// `text` produces `"value"` for strings and the literal token `null`
/// for missing data. The CTE branch returns `Option<String>` directly
/// v0.7.0 Wave-3 Continuation 5 — render an AGE `cypher()` parameters
/// dictionary as a SQL literal. AGE rejects `$1::agtype` (the third
/// argument must be a bare Param node, not a FuncExpr cast); the
/// workaround is to inline the params as `'<json>'::agtype`. Caller
/// sites must pass UUID-validated / RFC3339-validated values so the
/// inline literal is injection-safe.
///
/// The rendered form is `'{"k":"v",...}'::agtype`. Single quotes inside
/// the JSON are escaped as `''` (SQL standard); the agtype JSON dialect
/// uses `"` for string delimiters and `\"` for embedded double quotes,
/// so the only character that needs SQL-side escaping here is `'`.
/// Defense-in-depth check for ids that we inline directly into a
/// cypher() body string (the 2-arg form, where there's no params dict
/// to substitute through). The upstream `validate_memory_id` already
/// constrains the format to a UUIDv4-style alphabet but this assert
/// rejects anything outside `[A-Za-z0-9_-]` so a future code path
/// that bypasses validation still can't SQL-inject through cypher.
fn assert_age_id_safe(id: &str) -> Result<(), String> {
    if id.is_empty() || id.len() > 128 {
        return Err(format!(
            "id length {} out of bounds for cypher inline (1..=128)",
            id.len()
        ));
    }
    if !id
        .bytes()
        .all(|b| b.is_ascii_alphanumeric() || b == b'-' || b == b'_')
    {
        return Err(format!(
            "id contains characters unsafe for cypher inline (allowed: [A-Za-z0-9_-]): {id:?}"
        ));
    }
    Ok(())
}

/// #1689 — builds the current-view `kg_query` Cypher body for the AGE
/// backend, including the per-edge temporal-validity filter that
/// excludes invalidated edges (`r.valid_until` SET by
/// `kg_invalidate_cypher`).
///
/// `max_depth` is interpolated into the variable-length pattern (Cypher
/// forbids a parameter there); it is clamped by `validate_depth` upstream
/// so it carries no injection surface. The start id and the `$now`
/// as-of cut-off are bound through AGE's `$vars` JSON
/// (`age_params_literal`), never interpolated.
///
/// The `ALL(e IN relationships(p) ...)` guard drops any path that
/// traverses an edge whose `valid_until` is non-null and not in the
/// future, mirroring the relational CTE's
/// `valid_until IS NULL OR valid_until > NOW()` filter. The comparison
/// is a lexicographic agtype string compare against an RFC3339 `+00:00`
/// stamp, which orders chronologically because the invalidate write
/// path stores `valid_until` in the same `to_rfc3339` form.
fn build_kg_query_current_view_cypher(max_depth: usize) -> String {
    format!(
        "MATCH p = (a)-[r:related_to*1..{max_depth}]->(b) \
         WHERE a.id = $start_id \
           AND ALL(e IN relationships(p) WHERE e.valid_until IS NULL OR e.valid_until > $now) \
         RETURN b.id AS target_id, \
                last(r).relation AS relation, \
                length(r) AS depth, \
                reduce(s = a.id, n IN nodes(p)[1..] | s + '->' + n.id) AS path"
    )
}

/// #1689 — builds the current-view `find_paths` Cypher body for the AGE
/// backend, including the per-edge temporal-validity filter that excludes
/// invalidated edges.
///
/// `find_paths` uses the 2-arg `cypher()` form (AGE rejects the params dict
/// in the 3-arg form for this shape — see the call-site note), so the
/// source/target ids and the `now` cut-off are INLINED into the Cypher text.
/// The ids are `assert_age_id_safe`-validated at the call site and `now` is
/// an `Utc::now().to_rfc3339()` stamp (no single quote), so the inlined
/// literals carry no injection surface.
///
/// The traversal matches UNTYPED edges (`-[*1..depth]-`); the
/// `e.valid_until IS NULL` arm keeps every edge that was never invalidated
/// (relations like `supersedes`, or never-retracted `related_to`, have no
/// `valid_until` property), so the filter only drops genuinely-invalidated
/// edges — it can never silently drop uninvalidated paths.
fn build_find_paths_current_view_cypher(
    source_id: &str,
    target_id: &str,
    depth: usize,
    cap: usize,
    now_stamp: &str,
) -> String {
    format!(
        "MATCH p = (a)-[*1..{depth}]-(b) \
         WHERE a.id = '{source_id}' AND b.id = '{target_id}' \
           AND ALL(e IN relationships(p) WHERE e.valid_until IS NULL OR e.valid_until > '{now_stamp}') \
         RETURN nodes(p) AS path \
         ORDER BY length(p) ASC \
         LIMIT {cap}"
    )
}

fn age_params_literal(pairs: &[(&str, &str)]) -> String {
    let mut map = serde_json::Map::with_capacity(pairs.len());
    for (k, v) in pairs {
        map.insert(
            (*k).to_string(),
            serde_json::Value::String((*v).to_string()),
        );
    }
    let json = serde_json::Value::Object(map).to_string();
    // SQL-escape single quotes by doubling them.
    let escaped = json.replace('\'', "''");
    format!("'{escaped}'::agtype")
}

/// v0.7.0.1 G2 — sqlx-bindable wrapper for AGE's `agtype` parameter
/// type.
///
/// The cypher() set-returning function's third argument is a `cstring`
/// at the catalog level but AGE 1.5.0's `convert_cypher_to_subquery`
/// analyzer rejects ANY non-`Param` node there: literals
/// (`'…'::agtype`), casts (`$1::agtype`), and scalar subqueries all
/// fail with `third argument of cypher function must be a parameter`.
///
/// PostgreSQL's prepared-statement parameter inference DOES resolve a
/// bare `$N` to `agtype` from the function signature when the caller
/// declares the parameter as untyped (`unknown` OID `705`). sqlx's
/// default `String` encoder declares the parameter as `text`, which
/// overrides inference and re-introduces the literal-cast shape.
///
/// This wrapper carries a JSON-encoded params dictionary and binds
/// itself with the `agtype` type oid name so PostgreSQL ships the
/// parameter as the correct type without needing a SQL-side cast at
/// the cypher() call site. The on-wire format for `agtype` text is
/// the same JSON shape AGE accepts inline (e.g. `{"start_id":"…"}`).
struct Agtype(String);

impl sqlx::Type<sqlx::Postgres> for Agtype {
    fn type_info() -> sqlx::postgres::PgTypeInfo {
        sqlx::postgres::PgTypeInfo::with_name("agtype")
    }
    fn compatible(_ty: &sqlx::postgres::PgTypeInfo) -> bool {
        true
    }
}

impl<'q> sqlx::Encode<'q, sqlx::Postgres> for Agtype {
    fn encode_by_ref(
        &self,
        buf: &mut sqlx::postgres::PgArgumentBuffer,
    ) -> Result<sqlx::encode::IsNull, sqlx::error::BoxDynError> {
        // sqlx 0.8 sends every parameter in PostgreSQL's binary
        // (`Bind`) format. AGE's `agtype_recv` (binary input) expects:
        //
        //   ┌────────────┬─────────────────────────────────┐
        //   │ version u8 │ JSON-text payload (no NUL term) │
        //   └────────────┴─────────────────────────────────┘
        //
        // where `version == 1`. Sending just the JSON bytes makes AGE
        // interpret the first byte (`{` == 0x7B == 123) as a version
        // number and fail with `unsupported agtype version number 123`
        // — see `src/backend/utils/adt/agtype.c::agtype_recv` in the
        // PG16/v1.5.0 AGE branch.
        buf.push(1);
        buf.extend_from_slice(self.0.as_bytes());
        Ok(sqlx::encode::IsNull::No)
    }
}

impl<'r> sqlx::Decode<'r, sqlx::Postgres> for Agtype {
    fn decode(value: sqlx::postgres::PgValueRef<'r>) -> Result<Self, sqlx::error::BoxDynError> {
        // Mirror of the encoder: AGE ships agtype values back as
        // version byte (0x01) followed by the JSON-compatible text
        // payload in binary mode, or just the text in text mode.
        match value.format() {
            sqlx::postgres::PgValueFormat::Binary => {
                let bytes = value.as_bytes()?;
                if bytes.is_empty() {
                    return Err("empty agtype payload".into());
                }
                let version = bytes[0];
                if version != 1 {
                    return Err(format!("unsupported agtype version: {version}").into());
                }
                let text = std::str::from_utf8(&bytes[1..])?.to_string();
                Ok(Agtype(text))
            }
            sqlx::postgres::PgValueFormat::Text => {
                let text = value.as_str()?.to_string();
                Ok(Agtype(text))
            }
        }
    }
}

/// v0.7.0.1 S79 — sanitize a free-text recall query into an OR-joined
/// `tsquery` lexeme list compatible with PostgreSQL's
/// `to_tsquery('english', $1)`.
///
/// Mirrors the SQLite `sanitize_fts_query(_, true)` contract used by
/// `db::recall_hybrid` so postgres-backed daemons return the same
/// candidate pool the FTS5 path returns: every token is wrapped in a
/// quoted lexeme and the lexemes are OR-joined with `|`. The previous
/// `plainto_tsquery('english', $1)` implementation AND-joins every
/// lemma, which surfaces as empty recall on multi-token queries
/// whose terms never co-occur in a single row (HALT v0.7.0 R1 S79:
/// `cat sleeping`, `rust ownership`, `compile time safety` returned
/// zero rows even when the namespace held semantically-related
/// content).
///
/// Sanitization rules:
///   * collapse Unicode whitespace into a single ASCII space
///   * strip every char that is NOT an ASCII alphanumeric or one of
///     `_-` — this blocks the FTS5/tsquery operator surface
///     (`& | ! ( ) : * ' "`) so a malicious query can't smuggle a
///     boolean expression past the matcher
///   * filter out tokens shorter than 2 chars after sanitization
///     (keeps stop-word noise out of the matcher; matches the
///     SQLite minimum-token-length convention)
///   * cap to 16 tokens so a pathologically long query can't blow
///     up the planner
///   * fall back to a sentinel `'_empty_'` lexeme when every token
///     was dropped — `to_tsquery` rejects an empty string with a
///     parse error and we want a clean "no results" rather than a
///     500.
fn build_or_tsquery(query: &str) -> String {
    const MAX_TOKENS: usize = 16;
    let tokens: Vec<String> = query
        .split_whitespace()
        .map(|raw| {
            raw.chars()
                .filter(|c| c.is_ascii_alphanumeric() || *c == '_' || *c == '-')
                .collect::<String>()
        })
        .filter(|t| t.len() >= 2)
        .take(MAX_TOKENS)
        .map(|t| format!("'{}'", t.to_lowercase()))
        .collect();
    if tokens.is_empty() {
        return "'_empty_'".to_string();
    }
    tokens.join(" | ")
}

/// v0.7.0.1 G2 — render an AGE params dict as a JSON string compatible
/// with agtype's text input format. Pair-driven so callers don't drag
/// `serde_json::Value` into the call site.
fn age_params_jsonb(pairs: &[(&str, &str)]) -> String {
    let mut map = serde_json::Map::with_capacity(pairs.len());
    for (k, v) in pairs {
        map.insert(
            (*k).to_string(),
            serde_json::Value::String((*v).to_string()),
        );
    }
    serde_json::Value::Object(map).to_string()
}

/// v0.7.0.1 G4 — bootstrap the `memory_graph` AGE projection.
///
/// Idempotent: AGE returns "graph already exists" / SQLSTATE `42P07`
/// when the projection is present. Both shapes collapse to a clean
/// success because the only states we care about are "graph exists"
/// vs "graph cannot be created" (the latter being an actual operator
/// problem worth surfacing). Called from [`PostgresStore::connect`]
/// when the resolved [`KgBackend`] is [`KgBackend::Age`] so every
/// link write that follows can `MERGE` directly into the projection
/// without racing a separate bootstrap step.
async fn ensure_memory_graph(pool: &PgPool) -> StoreResult<()> {
    // Run inside a transaction so `SET LOCAL search_path` auto-resets
    // on commit. A bare `SET search_path` mutates session GUC state
    // and bleeds into the next checkout of this connection from the
    // pool — `audit_log`, `memories`, and every other public-schema
    // table would then resolve through `ag_catalog` first, surfacing
    // as flaky read-after-write failures elsewhere in the adapter.
    let mut tx = pool
        .begin()
        .await
        .map_err(|e| to_store_err("begin ensure_memory_graph tx", e))?;
    // #1640 — tolerated LOAD (shared helper).
    load_age_tolerated(&mut tx).await?;
    sqlx::query(SQL_SET_AGE_SEARCH_PATH)
        .execute(&mut *tx)
        .await
        .map_err(|e| to_store_err("set search_path (ensure_memory_graph)", e))?;
    // #1639 — the tolerated create_graph failure rides a SAVEPOINT
    // (the #1542 gated pattern, same as project_link_into_age): a
    // tolerated statement error inside an open tx otherwise puts
    // postgres in the aborted-tx state, where the COMMIT below is
    // silently a ROLLBACK that still reports Ok. Benign today only
    // because nothing durable is queued in this tx; any future
    // durable statement would vanish on every steady-state connect.
    sqlx::query("SAVEPOINT create_age_graph")
        .execute(&mut *tx)
        .await
        .map_err(|e| to_store_err("savepoint create_age_graph", e))?;
    match sqlx::query(SQL_CREATE_AGE_GRAPH).execute(&mut *tx).await {
        Ok(_) => {
            sqlx::query("RELEASE SAVEPOINT create_age_graph")
                .execute(&mut *tx)
                .await
                .map_err(|e| to_store_err("release create_age_graph", e))?;
        }
        Err(e) => {
            let msg = e.to_string();
            if !msg.contains(PG_ERR_ALREADY_EXISTS) {
                return Err(to_store_err("create_graph memory_graph", e));
            }
            sqlx::query("ROLLBACK TO SAVEPOINT create_age_graph")
                .execute(&mut *tx)
                .await
                .map_err(|e| to_store_err("rollback create_age_graph savepoint", e))?;
        }
    }
    tx.commit()
        .await
        .map_err(|e| to_store_err("commit ensure_memory_graph tx", e))?;
    Ok(())
}

/// v0.7.0.1 G4 — project a `memory_links` row into the AGE
/// `memory_graph` projection within an open transaction.
///
/// MERGEs both endpoints as `(:Memory {id})` nodes and the relation
/// as `(a)-[:<relation> {relation}]->(b)`, using the SAL-side
/// relation value as the AGE edge label so `kg_query_cypher`'s
/// `[r:related_to*1..N]` matcher resolves directly. Idempotent on
/// every input — Cypher's MERGE collapses repeat projections onto
/// the existing nodes/edges by the `id` / type combo.
///
/// The relation string is interpolated into the Cypher body
/// (Cypher does not accept parameters at the relationship-type
/// position). Validation upstream restricts relations to
/// `[a-z0-9_]+` plus the canonical labelset (see
/// `validate::validate_relation`), so the inlined form is safe; the
/// caller MUST pass a relation that already passed validation.
///
/// Each statement is shaped to fit AGE 1.5.0's `cypher()` analyzer:
///   * the third argument to `cypher()` is a bare `$1` parameter
///     bound through the [`Agtype`] sqlx wrapper (G2 fix);
///   * the cypher body uses `$id` / `$src` / `$dst` / `$rel` against
///     the params map rather than inlining ids as Cypher literals
///     (so caller-supplied UUIDs go through the param surface).
///
/// Called from [`PostgresStore::link_internal`] and
/// [`PostgresStore::apply_remote_link`] inside their respective
/// transactions so the SQL row + the AGE projection commit together
/// — a half-projection with the SQL row but no AGE node would surface
/// as a stale gap on `find_paths` queries.
/// #1640 — tolerated `LOAD 'age'` inside an open transaction: the
/// #1542 gated-SAVEPOINT pattern, hoisted so EVERY age consumer (link
/// projection, the four cypher fns, ensure_memory_graph) shares it.
/// PostgreSQL refuses `LOAD` for non-superuser roles even when
/// `shared_preload_libraries='age'` provides the library (the do-1461
/// fleet posture); pre-#1640 the four cypher read/invalidate fns
/// treated that refusal as FATAL, permanently degrading KG queries to
/// the CTE fallback (write-amplified AGE projections that were never
/// read, and `kg_invalidate`'s AGE-side `SET r.valid_until` never
/// executing). If `age` is genuinely absent, the next cypher
/// statement still fails loudly and the caller's fallback handles it.
async fn load_age_tolerated(tx: &mut sqlx::Transaction<'_, sqlx::Postgres>) -> StoreResult<()> {
    sqlx::query("SAVEPOINT load_age_lib")
        .execute(&mut **tx)
        .await
        .map_err(|e| to_store_err("savepoint load_age_lib", e))?;
    match sqlx::query(SQL_LOAD_AGE).execute(&mut **tx).await {
        Ok(_) => {
            sqlx::query("RELEASE SAVEPOINT load_age_lib")
                .execute(&mut **tx)
                .await
                .map_err(|e| to_store_err("release savepoint load_age_lib", e))?;
        }
        Err(e) => {
            sqlx::query("ROLLBACK TO SAVEPOINT load_age_lib")
                .execute(&mut **tx)
                .await
                .map_err(|e2| to_store_err("rollback savepoint load_age_lib", e2))?;
            tracing::debug!(
                target: TRACE_TARGET_KG,
                err = %e,
                "LOAD 'age' refused for this role — proceeding on the \
                 assumption shared_preload_libraries provides it (#1542/#1640)"
            );
        }
    }
    Ok(())
}

async fn project_link_into_age(
    tx: &mut sqlx::Transaction<'_, sqlx::Postgres>,
    source_id: &str,
    target_id: &str,
    relation: &str,
) -> StoreResult<()> {
    // Defence-in-depth: confirm the relation is in the
    // validator's accepted shape before interpolating it into the
    // Cypher body. Upstream validators already gate this, but the
    // SAL trait surface is reachable from federation replays + any
    // future caller paths, so we keep the local guard cheap.
    if relation.is_empty()
        || !relation
            .chars()
            .all(|c| c.is_ascii_lowercase() || c.is_ascii_digit() || c == '_')
    {
        return Err(StoreError::InvalidInput {
            detail: format!(
                "invalid relation for AGE projection: {relation:?} (must be [a-z0-9_]+)"
            ),
        });
    }

    // #1542/#1640 — shared tolerated-LOAD helper.
    load_age_tolerated(tx).await?;

    // `SET LOCAL` confines the search path to the open transaction
    // (`link_internal` / `apply_remote_link`'s tx) so post-commit
    // checkouts of the same pooled connection don't inherit the
    // `ag_catalog` first-resolution and silently route public-schema
    // reads through the AGE catalog.
    sqlx::query(SQL_SET_AGE_SEARCH_PATH)
        .execute(&mut **tx)
        .await
        .map_err(|e| to_store_err("set search_path (project_link)", e))?;

    // v0.7.0.1 G4 follow-up — self-bootstrap the `memory_graph`
    // projection on every link write so a daemon whose connect-time
    // `ensure_memory_graph` warned-and-continued (e.g. transient AGE
    // load lag, permission blip on `pg_extension`) still ends up
    // with a populated projection on first link write rather than
    // silently dropping every subsequent MERGE on the floor.
    //
    // We wrap `create_graph` in a SAVEPOINT so a duplicate-graph
    // error (the steady-state case once the projection exists)
    // doesn't abort the outer link-write transaction. PostgreSQL
    // marks any explicit transaction as failed on the first error
    // and rejects every subsequent statement until ROLLBACK; the
    // SAVEPOINT lets us roll back JUST the create_graph and keep
    // the outer tx writable for the upcoming MERGE statements.
    // Upgrades the live HTTP path's `POST /api/v1/links` from
    // "depends on connect-time bootstrap succeeding" to "self-heals
    // every write" (HALT R1 v4 S65 — the live cert droplets surfaced
    // 22 SQL link rows alongside 0 AGE nodes, consistent with a
    // connect-time bootstrap that didn't land).
    sqlx::query("SAVEPOINT bootstrap_memory_graph")
        .execute(&mut **tx)
        .await
        .map_err(|e| to_store_err("savepoint bootstrap_memory_graph", e))?;
    match sqlx::query(SQL_CREATE_AGE_GRAPH).execute(&mut **tx).await {
        Ok(_) => {
            sqlx::query("RELEASE SAVEPOINT bootstrap_memory_graph")
                .execute(&mut **tx)
                .await
                .map_err(|e| to_store_err("release savepoint bootstrap_memory_graph", e))?;
        }
        Err(e) => {
            let msg = e.to_string();
            // Roll the outer tx back to the savepoint regardless of
            // the failure mode — without this the link write aborts
            // wholesale. Steady-state ("already exists") collapses
            // to a clean Ok; any other failure surfaces as a typed
            // error after the rollback so the link write 503s rather
            // than silently committing the SQL row alone.
            sqlx::query("ROLLBACK TO SAVEPOINT bootstrap_memory_graph")
                .execute(&mut **tx)
                .await
                .map_err(|err| to_store_err("rollback savepoint bootstrap_memory_graph", err))?;
            sqlx::query("RELEASE SAVEPOINT bootstrap_memory_graph")
                .execute(&mut **tx)
                .await
                .map_err(|err| to_store_err("release savepoint bootstrap_memory_graph", err))?;
            if !msg.contains(PG_ERR_ALREADY_EXISTS) {
                return Err(to_store_err("create_graph memory_graph (project_link)", e));
            }
        }
    }

    // MERGE both endpoint nodes. We emit two separate statements
    // rather than one combined cypher to keep the param-shape
    // narrow — AGE 1.5.0 occasionally trips on multi-MERGE
    // statements with overlapping property names.
    let node_sql = "SELECT n FROM cypher('memory_graph', $$ MERGE (n:Memory {id: $id}) RETURN n $$, $1) \
         AS (n agtype)";
    for id in [source_id, target_id] {
        let params = age_params_jsonb(&[("id", id)]);
        sqlx::query(node_sql)
            .bind(Agtype(params))
            .fetch_all(&mut **tx)
            .await
            .map_err(|e| to_store_err("project memory node into AGE", e))?;
    }

    // MERGE the directional edge typed by the SAL relation value so
    // `kg_query_cypher`'s `[r:related_to*1..N]` matcher resolves
    // directly. The relation property is also stored on the edge so
    // typeless traversals (`find_paths_cypher`) can read it back
    // through `last(r).relation` without a second lookup.
    let edge_cypher = format!(
        "MATCH (a:Memory {{id: $src}}), (b:Memory {{id: $dst}}) \
         MERGE (a)-[r:{relation} {{relation: $rel}}]->(b) RETURN r"
    );
    let edge_sql =
        format!("SELECT r FROM cypher('memory_graph', $$ {edge_cypher} $$, $1) AS (r agtype)");
    let edge_params =
        age_params_jsonb(&[("src", source_id), ("dst", target_id), ("rel", relation)]);
    sqlx::query(&edge_sql)
        .bind(Agtype(edge_params))
        .fetch_all(&mut **tx)
        .await
        .map_err(|e| to_store_err("project memory edge into AGE", e))?;

    Ok(())
}

/// from sqlx; the AGE branch needs this helper to mirror the same
/// shape so the upper-layer handler stays backend-blind.
fn agtype_optional_string(s: &str) -> Option<String> {
    let trimmed = s.trim();
    if trimmed.eq_ignore_ascii_case("null") {
        return None;
    }
    Some(strip_agtype_quotes(trimmed).to_string())
}

/// Strip the surrounding double-quotes that AGE wraps around its
/// agtype string scalars when they get cast to text.
///
/// AGE returns scalar values as text in the form `"value"` (note the
/// embedded quotes). Calling `.trim_matches('"')` is enough to recover
/// the original UTF-8 — agtype escaping for embedded quotes uses `\"`,
/// and the v0.7 KG corpus does not write ids containing literal quote
/// characters. If that contract changes we'll replace this with a
/// dedicated agtype parser; keeping it minimal avoids pulling another
/// crate just to peel a string.
fn strip_agtype_quotes(s: &str) -> &str {
    let trimmed = s.trim();
    if trimmed.len() >= 2 && trimmed.starts_with('"') && trimmed.ends_with('"') {
        &trimmed[1..trimmed.len() - 1]
    } else {
        trimmed
    }
}

/// v0.7 J1 — probe Apache AGE.
///
/// Runs `SELECT 1 FROM pg_extension WHERE extname = 'age'` against the
/// pool and reports the resolved [`KgBackend`]. Errors are *not*
/// surfaced — a transient probe failure (replica lag, permissions on
/// `pg_extension` in a hardened deployment) MUST NOT block adapter
/// bootstrap. We log a debug line and fall back to
/// [`KgBackend::Cte`] which every Postgres install supports.
///
/// Factored out of [`PostgresStore::connect`] so unit tests can hit
/// the SQL builder branch without standing up a real Postgres pool.
pub(crate) async fn detect_kg_backend(pool: &PgPool) -> KgBackend {
    match sqlx::query_scalar::<_, i32>("SELECT 1 FROM pg_extension WHERE extname = 'age'")
        .fetch_optional(pool)
        .await
    {
        Ok(Some(_)) => KgBackend::Age,
        Ok(None) => KgBackend::Cte,
        Err(e) => {
            tracing::debug!(
                target: TRACE_TARGET,
                error = %e,
                "AGE detection probe failed; defaulting to CTE backend"
            );
            KgBackend::Cte
        }
    }
}

fn parse_rfc3339_opt(s: Option<&str>) -> Option<DateTime<Utc>> {
    s.and_then(|raw| DateTime::parse_from_rfc3339(raw).ok().map(Into::into))
}

fn parse_rfc3339_required(s: &str) -> StoreResult<DateTime<Utc>> {
    DateTime::parse_from_rfc3339(s)
        .map(Into::into)
        .map_err(|e| StoreError::IntegrityFailed {
            detail: format!("invalid rfc3339 timestamp {s}: {e}"),
        })
}

/// v0.7.0.1 G3 — clamp a `DateTime<Utc>` to microsecond precision.
///
/// PostgreSQL's `TIMESTAMPTZ` column stores microseconds since epoch
/// as int8; sub-microsecond digits are silently dropped by the type's
/// input function. Pre-fix, the `link_internal` sign path committed to
/// a `chrono::Utc::now()`-derived RFC3339 string with whatever
/// sub-second precision chrono emitted (nanoseconds when non-zero on
/// Linux), then INSERT'd that nanosecond-resolution
/// `chrono::DateTime<Utc>` into the `valid_from` TIMESTAMPTZ column.
/// On `verify_link`, the round-tripped value came back at microsecond
/// precision — the canonical CBOR re-derivation produced different
/// bytes than what was signed, and Ed25519 rejected the signature
/// (HALT R1b finding G3 / S52).
///
/// Truncating to microseconds on both sign and verify paths makes the
/// CBOR shape stable across the storage boundary. We use
/// `with_nanosecond` rather than `Duration` arithmetic because chrono
/// guarantees `with_nanosecond(_)` is total within `[0, 2_000_000_000)`
/// — `(self.nanosecond() / 1000) * 1000` is always in range, so the
/// `unwrap_or(self)` here is purely a typing convenience.
fn truncate_to_microseconds(t: DateTime<Utc>) -> DateTime<Utc> {
    use chrono::Timelike;
    let micros = t.nanosecond() / 1_000;
    t.with_nanosecond(micros * 1_000).unwrap_or(t)
}

/// v0.7.0.1 G1 — resolve the `agent_id` to scope a quota row to.
///
/// Precedence mirrors the SQLite `quotas::check_and_record` shape: the
/// claim baked into `memory.metadata.agent_id` (stamped by
/// `handlers::create_memory` before dispatch to the SAL) wins, falling
/// back to the SAL `CallerContext::agent_id` when metadata is missing
/// the field. The fallback ensures we never silently drop a quota
/// increment because metadata was elided upstream.
fn resolve_quota_agent_id(ctx: &CallerContext, metadata: &serde_json::Value) -> String {
    metadata
        .get("agent_id")
        .and_then(|v| v.as_str())
        .filter(|s| !s.is_empty())
        .map(str::to_string)
        .unwrap_or_else(|| ctx.agent_id.clone())
}

/// v0.7.0.1 G1 — bytes counted toward a memory's storage cap. Mirrors
/// `quotas::storage_bytes_for_memory` (title + content UTF-8 length —
/// ignoring tags/metadata, which is the SQLite parity contract).
fn memory_storage_bytes(memory: &Memory) -> i64 {
    let raw = memory.title.len().saturating_add(memory.content.len());
    i64::try_from(raw).unwrap_or(i64::MAX)
}

/// v0.7.0.1 G1 / v0.7.0 #1156 — increment
/// `agent_quotas.current_memories_today` and `current_storage_bytes`
/// inside an active transaction, auto-rolling the daily counters at
/// UTC midnight. Mirrors the SQLite parity laid out in
/// `quotas::check_and_record`'s memory-op branch.
///
/// Issued as a single statement so a concurrent writer cannot race
/// the counter — the underlying `INSERT ... ON CONFLICT DO UPDATE`
/// runs atomically against the `(agent_id, namespace)` PRIMARY KEY
/// (v50 PK extension; #1156). The day-rollover detection projects the
/// stored `day_started_at` against UTC `now` and resets
/// `current_memories_today` / `current_links_today` in the same
/// statement.
async fn record_memory_quota_in_tx(
    tx: &mut sqlx::Transaction<'_, sqlx::Postgres>,
    agent_id: &str,
    namespace: &str,
    bytes_added: i64,
) -> StoreResult<()> {
    let now = Utc::now();
    sqlx::query(
        "INSERT INTO agent_quotas (
             agent_id, namespace,
             max_memories_per_day, max_storage_bytes, max_links_per_day,
             current_memories_today, current_storage_bytes, current_links_today,
             day_started_at, created_at, updated_at
         ) VALUES ($1, $2, $3, $4, $5, 1, $6, 0, $7, $7, $7)
         ON CONFLICT (agent_id, namespace) DO UPDATE SET
             current_memories_today = CASE
                 WHEN date_trunc('day', agent_quotas.day_started_at) = date_trunc('day', $7)
                     THEN agent_quotas.current_memories_today + 1
                 ELSE 1
             END,
             current_links_today = CASE
                 WHEN date_trunc('day', agent_quotas.day_started_at) = date_trunc('day', $7)
                     THEN agent_quotas.current_links_today
                 ELSE 0
             END,
             current_storage_bytes = agent_quotas.current_storage_bytes + EXCLUDED.current_storage_bytes,
             day_started_at = CASE
                 WHEN date_trunc('day', agent_quotas.day_started_at) = date_trunc('day', $7)
                     THEN agent_quotas.day_started_at
                 ELSE $7
             END,
             updated_at = $7",
    )
    .bind(agent_id)
    .bind(namespace)
    .bind(quota_defaults().max_memories_per_day)
    .bind(quota_defaults().max_storage_bytes)
    .bind(quota_defaults().max_links_per_day)
    .bind(bytes_added)
    .bind(now)
    .execute(&mut **tx)
    .await
    .map_err(|e| to_store_err("record agent_quotas memory increment", e))?;
    Ok(())
}

/// #1481 — count-aware sibling of [`record_memory_quota_in_tx`] for the
/// batch path. Increments `current_memories_today` by `memories_added`
/// and `current_storage_bytes` by the pre-summed `bytes_added` in a
/// single statement, so an N-row bulk ingest by one `(agent, namespace)`
/// pair costs ONE quota round-trip instead of N. The day-rollover reset
/// logic is identical to the single-row form; only the increment width
/// differs (`+ $8` rather than the literal `+ 1`).
async fn record_memory_quota_batch_in_tx(
    tx: &mut sqlx::Transaction<'_, sqlx::Postgres>,
    agent_id: &str,
    namespace: &str,
    memories_added: i64,
    bytes_added: i64,
) -> StoreResult<()> {
    let now = Utc::now();
    sqlx::query(
        "INSERT INTO agent_quotas (
             agent_id, namespace,
             max_memories_per_day, max_storage_bytes, max_links_per_day,
             current_memories_today, current_storage_bytes, current_links_today,
             day_started_at, created_at, updated_at
         ) VALUES ($1, $2, $3, $4, $5, $8, $6, 0, $7, $7, $7)
         ON CONFLICT (agent_id, namespace) DO UPDATE SET
             current_memories_today = CASE
                 WHEN date_trunc('day', agent_quotas.day_started_at) = date_trunc('day', $7)
                     THEN agent_quotas.current_memories_today + $8
                 ELSE $8
             END,
             current_links_today = CASE
                 WHEN date_trunc('day', agent_quotas.day_started_at) = date_trunc('day', $7)
                     THEN agent_quotas.current_links_today
                 ELSE 0
             END,
             current_storage_bytes = agent_quotas.current_storage_bytes + EXCLUDED.current_storage_bytes,
             day_started_at = CASE
                 WHEN date_trunc('day', agent_quotas.day_started_at) = date_trunc('day', $7)
                     THEN agent_quotas.day_started_at
                 ELSE $7
             END,
             updated_at = $7",
    )
    .bind(agent_id)
    .bind(namespace)
    .bind(quota_defaults().max_memories_per_day)
    .bind(quota_defaults().max_storage_bytes)
    .bind(quota_defaults().max_links_per_day)
    .bind(bytes_added)
    .bind(now)
    .bind(memories_added)
    .execute(&mut **tx)
    .await
    .map_err(|e| to_store_err("record agent_quotas batch memory increment", e))?;
    Ok(())
}

#[async_trait]
impl MemoryStore for PostgresStore {
    fn capabilities(&self) -> Capabilities {
        Capabilities::TRANSACTIONS
            | Capabilities::NATIVE_VECTOR
            | Capabilities::FULLTEXT
            | Capabilities::DURABLE
            | Capabilities::STRONG_CONSISTENCY
            | Capabilities::ATOMIC_MULTI_WRITE
    }

    /// v0.7.0.1 S75 — read `MAX(version)` from the live `schema_version`
    /// table so the `/api/v1/capabilities.db_schema_version` field
    /// reflects the actual applied migration ladder rather than a
    /// hard-coded constant. Returns `0` when the table is empty (a
    /// fresh schema-init that didn't stamp any rows yet); callers
    /// that need "unknown" semantics MUST treat `0` as such. The query
    /// is a single scalar lookup so the lock window stays sub-
    /// millisecond — capability polling is fine to do per-request.
    async fn schema_version(&self) -> StoreResult<i64> {
        let v: Option<i32> = sqlx::query_scalar("SELECT MAX(version) FROM schema_version")
            .fetch_one(&self.pool)
            .await
            .map_err(|e| to_store_err("read schema_version max", e))?;
        Ok(i64::from(v.unwrap_or(0)))
    }

    async fn store(&self, ctx: &CallerContext, memory: &Memory) -> StoreResult<String> {
        // ARCH-1 (CRITICAL) — substrate governance pre-write parity with
        // the SQLite path. The `GOVERNANCE_PRE_WRITE` hook is consulted
        // on EVERY substrate write path on EVERY backend; multi-tenant
        // postgres-backed deployments would otherwise silently bypass
        // operator-signed governance. See module-level comment in
        // `src/storage/mod.rs` for the full layering rationale.
        consult_governance_pre_write_pg(memory)?;

        let created_at = parse_rfc3339_required(&memory.created_at)?;
        let updated_at = parse_rfc3339_required(&memory.updated_at)?;
        let last_accessed_at = parse_rfc3339_opt(memory.last_accessed_at.as_deref());
        // v0.7.0 #1466 — backfill the tier-default expiry so a hand-built
        // mid/short Memory with `expires_at: None` is reapable, matching the
        // SQLite `storage::insert` chokepoint. Shared SSOT on `Memory`.
        let expires_at = parse_rfc3339_opt(memory.effective_expires_at().as_deref());
        let tags_json =
            serde_json::to_value(&memory.tags).map_err(|e| StoreError::IntegrityFailed {
                detail: serialize_err("tags", e),
            })?;

        // v0.7.0.1 G1 — INSERT memories + record quota usage in a single
        // transaction so the postgres path matches the SQLite parity laid
        // out in `quotas::check_and_record`. Without this, S61's wire
        // shape stays at `current_memories_today=0` after N successful
        // writes (HALT R1b finding G1).
        let mut tx = self
            .pool
            .begin()
            .await
            .map_err(|e| to_store_err("begin store tx", e))?;

        // Upsert contract matches SQLite: `ON CONFLICT (title, namespace)`.
        // Backed by the UNIQUE INDEX `memories_title_ns_uidx` in
        // postgres_schema.sql. Fix for blocker #294.
        //
        // Agent-id immutability (blocker #295): on conflict we preserve
        // the ORIGINAL `metadata.agent_id` via `jsonb_set`, mirroring the
        // SQLite `json_set` CASE clause in `crate::storage::insert`. The
        // caller-supplied metadata otherwise wins.
        //
        // Tier never downgrades (blocker #296 / SQLite parity): on
        // conflict tier takes max of existing vs new via rank mapping.
        // v0.7.0 #900 — Form-4 fact-provenance + Form-5 confidence
        // provenance columns ride the same INSERT so the PG store
        // round-trips `Memory::source_uri`, `citations`, `source_span`,
        // and the three confidence columns. Pre-#900 the INSERT only
        // wrote 17 columns and `list_by_source_uri` / `search_with_
        // source_uri` returned empty against PG. Pinned by
        // `tests/store_parity_gaps.rs::pg_parity_gap_2_source_uri_column`.
        let citations_json =
            serde_json::to_string(&memory.citations).map_err(|e| StoreError::IntegrityFailed {
                detail: serialize_err("citations", e),
            })?;
        let source_span_json = match memory.source_span {
            Some(span) => {
                Some(
                    serde_json::to_string(&span).map_err(|e| StoreError::IntegrityFailed {
                        detail: serialize_err(COL_SOURCE_SPAN, e),
                    })?,
                )
            }
            None => None,
        };
        let confidence_signals_json = match &memory.confidence_signals {
            Some(s) => Some(
                serde_json::to_string(s).map_err(|e| StoreError::IntegrityFailed {
                    detail: serialize_err(COL_CONFIDENCE_SIGNALS, e),
                })?,
            ),
            None => None,
        };
        // #1383 — denormalise `mentioned_entity_id` from the row's
        // `metadata.entity_id` / `[entity:X]` title marker so that
        // postgres-backed reflection rows are reachable via the
        // `memory_persona_generate` matcher (which queries
        // `WHERE mentioned_entity_id = ?` on the partial index from
        // schema v32). Pre-#1383 the postgres `store()` path dropped
        // this column entirely so every postgres reflection was
        // invisible to persona generation despite the caller passing
        // the entity attribution correctly. Mirrors sqlite at
        // `src/storage/mod.rs:616`. Non-reflection rows return None
        // here, matching the sqlite behaviour.
        let mentioned_entity_id = crate::storage::extract_mentioned_entity_id(memory);

        let id: String = sqlx::query(
            "INSERT INTO memories (
                id, tier, namespace, title, content, tags, priority, confidence,
                source, access_count, created_at, updated_at, last_accessed_at,
                expires_at, metadata, reflection_depth, memory_kind,
                citations, source_uri, source_span,
                confidence_source, confidence_signals, confidence_decayed_at,
                entity_id, persona_version,
                mentioned_entity_id
            ) VALUES ($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)
            ON CONFLICT (title, namespace) DO UPDATE SET
                content = EXCLUDED.content,
                tier = CASE
                    WHEN tier_rank(EXCLUDED.tier) >= tier_rank(memories.tier)
                        THEN EXCLUDED.tier
                    ELSE memories.tier
                END,
                tags = EXCLUDED.tags,
                -- #1629 — sqlite `storage::insert` parity: priority +
                -- confidence take the MAX across upsert so a re-store can
                -- never downgrade either signal.
                priority = GREATEST(memories.priority, EXCLUDED.priority),
                confidence = GREATEST(memories.confidence, EXCLUDED.confidence),
                -- #1629 — sqlite parity: source follows the incoming row.
                source = EXCLUDED.source,
                updated_at = EXCLUDED.updated_at,
                -- #1629 — sqlite parity: long-tier rows pin expiry to NULL;
                -- otherwise an incoming row that omits expiry keeps the
                -- stored one rather than blanking it out.
                expires_at = CASE
                    WHEN EXCLUDED.tier = 'long' OR memories.tier = 'long' THEN NULL
                    ELSE COALESCE(EXCLUDED.expires_at, memories.expires_at)
                END,
                metadata = CASE
                    WHEN memories.metadata ? 'agent_id'
                        THEN jsonb_set(
                            EXCLUDED.metadata,
                            '{agent_id}',
                            memories.metadata -> 'agent_id'
                        )
                    ELSE EXCLUDED.metadata
                END,
                -- v0.7.0 Task 1/8 — recursion depth takes max on upsert so a
                -- newer reflection at higher depth doesn't lose its provenance
                -- signal when re-stored at the same (title, namespace).
                reflection_depth = GREATEST(memories.reflection_depth, EXCLUDED.reflection_depth),
                -- L1-1 — kind is sticky: once Reflection, always Reflection.
                -- #1629 / QW-2 — Persona is also sticky (sqlite parity).
                memory_kind = CASE WHEN memories.memory_kind = 'reflection' THEN 'reflection'
                                   WHEN memories.memory_kind = 'persona' THEN 'persona'
                                   ELSE EXCLUDED.memory_kind END,
                -- v0.7.0 #900 / #1629 — Form-4 fact-provenance follows the
                -- sqlite CASE: a non-empty incoming citations array replaces
                -- (caller re-asserted provenance); an empty one preserves the
                -- stored evidence instead of silently wiping it.
                citations = CASE WHEN EXCLUDED.citations = '[]'
                                 THEN memories.citations
                                 ELSE EXCLUDED.citations END,
                source_uri = COALESCE(EXCLUDED.source_uri, memories.source_uri),
                source_span = COALESCE(EXCLUDED.source_span, memories.source_span),
                -- #1629 — Form-5 sqlite parity: an explicit non-default
                -- provenance replaces; the caller_provided default keeps the
                -- stored (auto-derived / calibrated) signal.
                confidence_source = CASE WHEN EXCLUDED.confidence_source != 'caller_provided'
                                         THEN EXCLUDED.confidence_source
                                         ELSE memories.confidence_source END,
                confidence_signals = COALESCE(EXCLUDED.confidence_signals, memories.confidence_signals),
                confidence_decayed_at = COALESCE(EXCLUDED.confidence_decayed_at, memories.confidence_decayed_at),
                -- #1608 / #1629 — QW-2 persona-artifact columns stay sticky:
                -- the sqlite COALESCE order keeps the value the row was
                -- minted with (old wins), so match it.
                entity_id = COALESCE(memories.entity_id, EXCLUDED.entity_id),
                persona_version = COALESCE(memories.persona_version, EXCLUDED.persona_version),
                -- #1383 — preserve a previously-extracted attribution if
                -- EXCLUDED is NULL (matches the sqlite ON CONFLICT clause
                -- at `src/storage/mod.rs:689`).
                mentioned_entity_id = COALESCE(EXCLUDED.mentioned_entity_id, memories.mentioned_entity_id),
                -- #1632 (pg twin) — upsert-merge IS a mutation, so the Gap-1
                -- optimistic-concurrency counter bumps exactly like
                -- db::update (sqlite landed in 27b45dc2).
                version = memories.version + 1
            RETURNING id",
        )
        .bind(&memory.id)
        .bind(memory.tier.as_str())
        .bind(&memory.namespace)
        .bind(&memory.title)
        .bind(&memory.content)
        .bind(&tags_json)
        .bind(memory.priority)
        .bind(memory.confidence)
        .bind(&memory.source)
        .bind(memory.access_count)
        .bind(created_at)
        .bind(updated_at)
        .bind(last_accessed_at)
        .bind(expires_at)
        .bind(&memory.metadata)
        .bind(memory.reflection_depth)
        .bind(memory.memory_kind.as_str())
        .bind(&citations_json)
        .bind(memory.source_uri.as_deref())
        .bind(source_span_json.as_deref())
        .bind(memory.confidence_source.as_str())
        .bind(confidence_signals_json.as_deref())
        .bind(memory.confidence_decayed_at.as_deref())
        .bind(memory.entity_id.as_deref())
        .bind(memory.persona_version)
        .bind(mentioned_entity_id.as_deref())
        .fetch_one(&mut *tx)
        .await
        .map_err(|e| to_store_err("insert memory", e))?
        .try_get::<String, _>("id")
        .map_err(|e| to_store_err(READ_RETURNED_ID, e))?;

        // v0.7.0.1 G1 / v0.7.0 #1156 — record quota usage in the same
        // tx against the per-namespace accounting row (v50 PK
        // extension). Best-effort resolution of agent_id; a missing
        // claim falls back to the SAL `CallerContext::agent_id` so
        // we never lose the count.
        let quota_agent_id = resolve_quota_agent_id(ctx, &memory.metadata);
        let bytes_added = memory_storage_bytes(memory);
        record_memory_quota_in_tx(&mut tx, &quota_agent_id, &memory.namespace, bytes_added).await?;

        tx.commit()
            .await
            .map_err(|e| to_store_err("commit store tx", e))?;
        Ok(id)
    }

    /// #1481 — single multi-row upsert for the bulk-ingest path. Mirrors
    /// `store`'s INSERT column list, `ON CONFLICT (title, namespace) DO
    /// UPDATE` clause, and quota accounting, but binds every row's values
    /// in ONE statement via `sqlx::QueryBuilder::push_values`, collapsing
    /// the per-row `2N` round-trips (`store` × N) to `1 + G` (one batch
    /// INSERT + one quota upsert per distinct `(agent, namespace)` group,
    /// normally G = 1).
    ///
    /// Atomicity: the whole batch + quota updates ride a single
    /// transaction, so a failure rolls every row back — matching the
    /// trait contract. Governance is NOT consulted here: the caller
    /// (`bulk_create`) already enforces it per row and only hands us the
    /// Allowed set, exactly as the single-row `store` path expects its
    /// caller to have gated.
    ///
    /// Intra-batch dedup: postgres rejects an `ON CONFLICT DO UPDATE`
    /// whose conflict target `(title, namespace)` is affected twice in
    /// one command. We therefore keep only the LAST occurrence of each
    /// `(title, namespace)` — last-write-wins, identical to the final DB
    /// state a sequential `store` loop would leave — and return its id
    /// for every input position that collapsed into it.
    async fn store_batch(
        &self,
        ctx: &CallerContext,
        memories: &[Memory],
    ) -> StoreResult<Vec<String>> {
        if memories.is_empty() {
            return Ok(Vec::new());
        }

        // Substrate governance parity: each row still passes the
        // pre-write hook (the caller's HTTP governance gate is the
        // namespace `write=` rule; this is the operator-signed substrate
        // refuse hook that every backend write path consults).
        for memory in memories {
            consult_governance_pre_write_pg(memory)?;
        }

        // Keep the LAST occurrence of each (title, namespace) so the
        // single INSERT never affects a conflict-target row twice. We
        // record, for every input row, the id of the row it maps to so
        // the returned Vec stays aligned with `memories` 1:1.
        let mut last_index: std::collections::HashMap<(&str, &str), usize> =
            std::collections::HashMap::with_capacity(memories.len());
        for (idx, memory) in memories.iter().enumerate() {
            last_index.insert((memory.title.as_str(), memory.namespace.as_str()), idx);
        }
        let mut keep: Vec<usize> = (0..memories.len())
            .filter(|idx| {
                last_index[&(
                    memories[*idx].title.as_str(),
                    memories[*idx].namespace.as_str(),
                )] == *idx
            })
            .collect();
        keep.sort_unstable();

        let mut tx = self
            .pool
            .begin()
            .await
            .map_err(|e| to_store_err("begin store_batch tx", e))?;

        let mut builder: sqlx::QueryBuilder<sqlx::Postgres> = sqlx::QueryBuilder::new(
            "INSERT INTO memories (
                id, tier, namespace, title, content, tags, priority, confidence,
                source, access_count, created_at, updated_at, last_accessed_at,
                expires_at, metadata, reflection_depth, memory_kind,
                citations, source_uri, source_span,
                confidence_source, confidence_signals, confidence_decayed_at,
                entity_id, persona_version,
                mentioned_entity_id
            ) ",
        );

        // push_values moves each row's bound values into the builder's
        // arg buffer; the owned JSON strings below therefore outlive the
        // statement. Any per-row serialization failure aborts the whole
        // (atomic) batch — these are infallible-in-practice serde
        // encodings of already-validated `Memory` fields.
        let mut push_err: Option<StoreError> = None;
        builder.push_values(keep.iter().copied(), |mut row, idx| {
            let memory = &memories[idx];
            let created_at = match parse_rfc3339_required(&memory.created_at) {
                Ok(v) => v,
                Err(e) => {
                    push_err.get_or_insert(e);
                    return;
                }
            };
            let updated_at = match parse_rfc3339_required(&memory.updated_at) {
                Ok(v) => v,
                Err(e) => {
                    push_err.get_or_insert(e);
                    return;
                }
            };
            let last_accessed_at = parse_rfc3339_opt(memory.last_accessed_at.as_deref());
            let expires_at = parse_rfc3339_opt(memory.effective_expires_at().as_deref());
            let tags_json = match serde_json::to_value(&memory.tags) {
                Ok(v) => v,
                Err(e) => {
                    push_err.get_or_insert(StoreError::IntegrityFailed {
                        detail: serialize_err("tags", e),
                    });
                    return;
                }
            };
            let citations_json = match serde_json::to_string(&memory.citations) {
                Ok(v) => v,
                Err(e) => {
                    push_err.get_or_insert(StoreError::IntegrityFailed {
                        detail: serialize_err("citations", e),
                    });
                    return;
                }
            };
            let source_span_json = match &memory.source_span {
                Some(span) => match serde_json::to_string(span) {
                    Ok(v) => Some(v),
                    Err(e) => {
                        push_err.get_or_insert(StoreError::IntegrityFailed {
                            detail: serialize_err(COL_SOURCE_SPAN, e),
                        });
                        return;
                    }
                },
                None => None,
            };
            let confidence_signals_json = match &memory.confidence_signals {
                Some(s) => match serde_json::to_string(s) {
                    Ok(v) => Some(v),
                    Err(e) => {
                        push_err.get_or_insert(StoreError::IntegrityFailed {
                            detail: serialize_err(COL_CONFIDENCE_SIGNALS, e),
                        });
                        return;
                    }
                },
                None => None,
            };
            let mentioned_entity_id = crate::storage::extract_mentioned_entity_id(memory);

            row.push_bind(memory.id.clone())
                .push_bind(memory.tier.as_str().to_string())
                .push_bind(memory.namespace.clone())
                .push_bind(memory.title.clone())
                .push_bind(memory.content.clone())
                .push_bind(tags_json)
                .push_bind(memory.priority)
                .push_bind(memory.confidence)
                .push_bind(memory.source.clone())
                .push_bind(memory.access_count)
                .push_bind(created_at)
                .push_bind(updated_at)
                .push_bind(last_accessed_at)
                .push_bind(expires_at)
                .push_bind(memory.metadata.clone())
                .push_bind(memory.reflection_depth)
                .push_bind(memory.memory_kind.as_str().to_string())
                .push_bind(citations_json)
                .push_bind(memory.source_uri.clone())
                .push_bind(source_span_json)
                .push_bind(memory.confidence_source.as_str().to_string())
                .push_bind(confidence_signals_json)
                .push_bind(memory.confidence_decayed_at.clone())
                // #1608 — QW-2 persona-artifact parity with `store()`.
                .push_bind(memory.entity_id.clone())
                .push_bind(memory.persona_version)
                .push_bind(mentioned_entity_id);
        });
        if let Some(e) = push_err {
            return Err(e);
        }

        builder.push(
            " ON CONFLICT (title, namespace) DO UPDATE SET
                content = EXCLUDED.content,
                tier = CASE
                    WHEN tier_rank(EXCLUDED.tier) >= tier_rank(memories.tier)
                        THEN EXCLUDED.tier
                    ELSE memories.tier
                END,
                tags = EXCLUDED.tags,
                -- #1629 — sqlite parity: MAX-merge, source follows incoming,
                -- expiry long→NULL + COALESCE (see `store()` for rationale).
                priority = GREATEST(memories.priority, EXCLUDED.priority),
                confidence = GREATEST(memories.confidence, EXCLUDED.confidence),
                source = EXCLUDED.source,
                updated_at = EXCLUDED.updated_at,
                expires_at = CASE
                    WHEN EXCLUDED.tier = 'long' OR memories.tier = 'long' THEN NULL
                    ELSE COALESCE(EXCLUDED.expires_at, memories.expires_at)
                END,
                metadata = CASE
                    WHEN memories.metadata ? 'agent_id'
                        THEN jsonb_set(
                            EXCLUDED.metadata,
                            '{agent_id}',
                            memories.metadata -> 'agent_id'
                        )
                    ELSE EXCLUDED.metadata
                END,
                reflection_depth = GREATEST(memories.reflection_depth, EXCLUDED.reflection_depth),
                memory_kind = CASE WHEN memories.memory_kind = 'reflection' THEN 'reflection'
                                   WHEN memories.memory_kind = 'persona' THEN 'persona'
                                   ELSE EXCLUDED.memory_kind END,
                citations = CASE WHEN EXCLUDED.citations = '[]'
                                 THEN memories.citations
                                 ELSE EXCLUDED.citations END,
                source_uri = COALESCE(EXCLUDED.source_uri, memories.source_uri),
                source_span = COALESCE(EXCLUDED.source_span, memories.source_span),
                confidence_source = CASE WHEN EXCLUDED.confidence_source != 'caller_provided'
                                         THEN EXCLUDED.confidence_source
                                         ELSE memories.confidence_source END,
                confidence_signals = COALESCE(EXCLUDED.confidence_signals, memories.confidence_signals),
                confidence_decayed_at = COALESCE(EXCLUDED.confidence_decayed_at, memories.confidence_decayed_at),
                entity_id = COALESCE(memories.entity_id, EXCLUDED.entity_id),
                persona_version = COALESCE(memories.persona_version, EXCLUDED.persona_version),
                mentioned_entity_id = COALESCE(EXCLUDED.mentioned_entity_id, memories.mentioned_entity_id),
                -- #1632 (pg twin) — upsert-merge bumps the Gap-1 counter.
                version = memories.version + 1
            RETURNING id, title, namespace",
        );

        let rows = builder
            .build()
            .fetch_all(&mut *tx)
            .await
            .map_err(|e| to_store_err("store_batch multi-row insert", e))?;

        // Map (title, namespace) -> returned id so every input position
        // (including the ones that collapsed into a later duplicate) can
        // resolve to its persisted id in 1:1 input order.
        let mut id_by_key: std::collections::HashMap<(String, String), String> =
            std::collections::HashMap::with_capacity(rows.len());
        for row in &rows {
            let id: String = row
                .try_get("id")
                .map_err(|e| to_store_err("store_batch read returned id", e))?;
            let title: String = row
                .try_get("title")
                .map_err(|e| to_store_err("store_batch read returned title", e))?;
            let namespace: String = row
                .try_get("namespace")
                .map_err(|e| to_store_err("store_batch read returned namespace", e))?;
            id_by_key.insert((title, namespace), id);
        }

        // Quota: one upsert per distinct (quota_agent_id, namespace),
        // counting every input row (duplicates included — each was a
        // caller-requested write, matching the sequential `store` count).
        let mut quota_groups: std::collections::HashMap<(String, String), (i64, i64)> =
            std::collections::HashMap::new();
        for memory in memories {
            let quota_agent_id = resolve_quota_agent_id(ctx, &memory.metadata);
            let entry = quota_groups
                .entry((quota_agent_id, memory.namespace.clone()))
                .or_insert((0, 0));
            entry.0 += 1;
            entry.1 = entry.1.saturating_add(memory_storage_bytes(memory));
        }
        for ((agent_id, namespace), (count, bytes)) in &quota_groups {
            record_memory_quota_batch_in_tx(&mut tx, agent_id, namespace, *count, *bytes).await?;
        }

        tx.commit()
            .await
            .map_err(|e| to_store_err("commit store_batch tx", e))?;

        let mut ids = Vec::with_capacity(memories.len());
        for memory in memories {
            let key = (memory.title.clone(), memory.namespace.clone());
            let id = id_by_key
                .get(&key)
                .cloned()
                .ok_or_else(|| StoreError::IntegrityFailed {
                    detail: format!(
                        "store_batch: no RETURNING id for (title, namespace) of memory {}",
                        memory.id
                    ),
                })?;
            ids.push(id);
        }
        Ok(ids)
    }

    /// v0.7.0 #1416 / RFC-0001 — L4 layered-capture idempotent write on
    /// the postgres backend. Twin of the sqlite SSOT
    /// `crate::storage::capture_turn_idempotent`; closes the capability
    /// gap that left postgres-backed daemons with no callable L4
    /// surface despite carrying the v52 `transcript_line_dedup` table.
    ///
    /// Contract (matches the sqlite path byte-for-byte at the row level):
    /// 1. Dedup SELECT on `(host_session_id, host_turn_index)` — the
    ///    `IS NOT NULL` predicate pins the v52 partial index. On hit,
    ///    return the existing id with NO write.
    /// 2. On miss, in ONE transaction: INSERT the memory (same
    ///    `(title, namespace)` upsert as `store`), INSERT the
    ///    `transcript_line_dedup` row, and append the `signed_events`
    ///    chain row (#1415). Any failure rolls all three back.
    ///
    /// Mirrors `store`'s memory INSERT verbatim (the inline-per-tx
    /// pattern used by the reflection-insert path) rather than reusing
    /// `store`, because the audit + dedup rows MUST land in the same
    /// transaction as the memory — `store` owns its own BEGIN/COMMIT.
    /// Unlike `store`, the L4 path does NOT record quota usage, matching
    /// the sqlite path (which routes through `storage::insert`, not the
    /// quota-recording `store` method).
    async fn capture_turn_idempotent(
        &self,
        _ctx: &CallerContext,
        write: &CaptureTurnWrite,
    ) -> StoreResult<CaptureTurnResult> {
        // Step 1 — dedup fast-path (no transaction needed for the read).
        let existing: Option<String> = sqlx::query_scalar(
            "SELECT memory_id FROM transcript_line_dedup \
             WHERE host_session_id IS NOT NULL \
               AND host_session_id = $1 \
               AND host_turn_index = $2",
        )
        .bind(&write.host_session_id)
        .bind(write.host_turn_index)
        .fetch_optional(&self.pool)
        .await
        .map_err(|e| to_store_err("capture_turn dedup query", e))?;

        if let Some(memory_id) = existing {
            return Ok(CaptureTurnResult {
                memory_id,
                dedup_hit: true,
            });
        }

        // ARCH-1 — substrate governance pre-write parity with the sqlite
        // L4 path (`storage::capture_turn_idempotent` → `storage::insert`
        // → `consult_governance_pre_write`).
        let memory = &write.memory;
        consult_governance_pre_write_pg(memory)?;

        let created_at = parse_rfc3339_required(&memory.created_at)?;
        let updated_at = parse_rfc3339_required(&memory.updated_at)?;
        let last_accessed_at = parse_rfc3339_opt(memory.last_accessed_at.as_deref());
        // v0.7.0 #1466 — backfill the tier-default expiry so a hand-built
        // mid/short Memory with `expires_at: None` is reapable, matching the
        // SQLite `storage::insert` chokepoint. Shared SSOT on `Memory`.
        let expires_at = parse_rfc3339_opt(memory.effective_expires_at().as_deref());
        let tags_json =
            serde_json::to_value(&memory.tags).map_err(|e| StoreError::IntegrityFailed {
                detail: serialize_err("tags", e),
            })?;
        let citations_json =
            serde_json::to_string(&memory.citations).map_err(|e| StoreError::IntegrityFailed {
                detail: serialize_err("citations", e),
            })?;
        let source_span_json = match memory.source_span {
            Some(span) => {
                Some(
                    serde_json::to_string(&span).map_err(|e| StoreError::IntegrityFailed {
                        detail: serialize_err(COL_SOURCE_SPAN, e),
                    })?,
                )
            }
            None => None,
        };
        let confidence_signals_json = match &memory.confidence_signals {
            Some(s) => Some(
                serde_json::to_string(s).map_err(|e| StoreError::IntegrityFailed {
                    detail: serialize_err(COL_CONFIDENCE_SIGNALS, e),
                })?,
            ),
            None => None,
        };
        let mentioned_entity_id = crate::storage::extract_mentioned_entity_id(memory);
        let event_ts = parse_rfc3339_required(&write.signed_event.timestamp)?;

        // Step 2 — atomic three-row write.
        let mut tx = self
            .pool
            .begin()
            .await
            .map_err(|e| to_store_err("begin capture_turn tx", e))?;

        let inserted_id: String = sqlx::query(
            "INSERT INTO memories (
                id, tier, namespace, title, content, tags, priority, confidence,
                source, access_count, created_at, updated_at, last_accessed_at,
                expires_at, metadata, reflection_depth, memory_kind,
                citations, source_uri, source_span,
                confidence_source, confidence_signals, confidence_decayed_at,
                mentioned_entity_id
            ) VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9, $10, $11, $12, $13, $14, $15, $16, $17,
                      $18, $19, $20,
                      $21, $22, $23,
                      $24)
            ON CONFLICT (title, namespace) DO UPDATE SET
                content = EXCLUDED.content,
                tier = CASE
                    WHEN tier_rank(EXCLUDED.tier) >= tier_rank(memories.tier)
                        THEN EXCLUDED.tier
                    ELSE memories.tier
                END,
                tags = EXCLUDED.tags,
                -- #1629 — sqlite parity: MAX-merge, source follows incoming,
                -- expiry long→NULL + COALESCE (see `store()` for rationale).
                priority = GREATEST(memories.priority, EXCLUDED.priority),
                confidence = GREATEST(memories.confidence, EXCLUDED.confidence),
                source = EXCLUDED.source,
                updated_at = EXCLUDED.updated_at,
                expires_at = CASE
                    WHEN EXCLUDED.tier = 'long' OR memories.tier = 'long' THEN NULL
                    ELSE COALESCE(EXCLUDED.expires_at, memories.expires_at)
                END,
                metadata = CASE
                    WHEN memories.metadata ? 'agent_id'
                        THEN jsonb_set(
                            EXCLUDED.metadata,
                            '{agent_id}',
                            memories.metadata -> 'agent_id'
                        )
                    ELSE EXCLUDED.metadata
                END,
                reflection_depth = GREATEST(memories.reflection_depth, EXCLUDED.reflection_depth),
                memory_kind = CASE WHEN memories.memory_kind = 'reflection' THEN 'reflection'
                                   WHEN memories.memory_kind = 'persona' THEN 'persona'
                                   ELSE EXCLUDED.memory_kind END,
                citations = CASE WHEN EXCLUDED.citations = '[]'
                                 THEN memories.citations
                                 ELSE EXCLUDED.citations END,
                source_uri = COALESCE(EXCLUDED.source_uri, memories.source_uri),
                source_span = COALESCE(EXCLUDED.source_span, memories.source_span),
                confidence_source = CASE WHEN EXCLUDED.confidence_source != 'caller_provided'
                                         THEN EXCLUDED.confidence_source
                                         ELSE memories.confidence_source END,
                confidence_signals = COALESCE(EXCLUDED.confidence_signals, memories.confidence_signals),
                confidence_decayed_at = COALESCE(EXCLUDED.confidence_decayed_at, memories.confidence_decayed_at),
                mentioned_entity_id = COALESCE(EXCLUDED.mentioned_entity_id, memories.mentioned_entity_id),
                -- #1632 (pg twin) — upsert-merge bumps the Gap-1 counter.
                version = memories.version + 1
            RETURNING id",
        )
        .bind(&memory.id)
        .bind(memory.tier.as_str())
        .bind(&memory.namespace)
        .bind(&memory.title)
        .bind(&memory.content)
        .bind(&tags_json)
        .bind(memory.priority)
        .bind(memory.confidence)
        .bind(&memory.source)
        .bind(memory.access_count)
        .bind(created_at)
        .bind(updated_at)
        .bind(last_accessed_at)
        .bind(expires_at)
        .bind(&memory.metadata)
        .bind(memory.reflection_depth)
        .bind(memory.memory_kind.as_str())
        .bind(&citations_json)
        .bind(memory.source_uri.as_deref())
        .bind(source_span_json.as_deref())
        .bind(memory.confidence_source.as_str())
        .bind(confidence_signals_json.as_deref())
        .bind(memory.confidence_decayed_at.as_deref())
        .bind(mentioned_entity_id.as_deref())
        .fetch_one(&mut *tx)
        .await
        .map_err(|e| to_store_err("capture_turn insert memory", e))?
        .try_get::<String, _>("id")
        .map_err(|e| to_store_err("capture_turn read returned id", e))?;

        // `transcript_line_dedup` row. `ON CONFLICT (sha256) DO NOTHING`
        // guards the rare concurrent-duplicate race that READ COMMITTED
        // would otherwise let through (the sqlite path serializes via
        // BEGIN IMMEDIATE); the memory upsert keyed on (title, namespace)
        // already makes the returned memory_id idempotent.
        sqlx::query(
            "INSERT INTO transcript_line_dedup \
             (sha256, memory_id, host_kind, transcript_path, \
              host_session_id, host_turn_index, recovered_at) \
             VALUES ($1, $2, $3, NULL, $4, $5, $6) \
             ON CONFLICT (sha256) DO NOTHING",
        )
        .bind(&write.sha256)
        .bind(&inserted_id)
        .bind(&write.host_kind)
        .bind(&write.host_session_id)
        .bind(write.host_turn_index)
        .bind(write.recovered_at_ms)
        .execute(&mut *tx)
        .await
        .map_err(|e| to_store_err("capture_turn insert dedup row", e))?;

        // signed_events chain row in the SAME tx (#1415) so audit can
        // prove L4 caught the turn and never lags the data.
        let ev = &write.signed_event;
        pg_append_signed_event_with_chain_in_tx(
            &mut tx,
            PgSignedEventInsert {
                id: &ev.id,
                agent_id: &ev.agent_id,
                event_type: &ev.event_type,
                payload_hash: &ev.payload_hash,
                signature: ev.signature.as_deref(),
                attest_level: &ev.attest_level,
                timestamp: event_ts,
            },
        )
        .await
        .map_err(|e| to_store_err("capture_turn append signed_event", e))?;

        tx.commit()
            .await
            .map_err(|e| to_store_err("commit capture_turn tx", e))?;

        Ok(CaptureTurnResult {
            memory_id: inserted_id,
            dedup_hit: false,
        })
    }

    async fn store_with_embedding(
        &self,
        ctx: &CallerContext,
        memory: &Memory,
        embedding: Option<&[f32]>,
    ) -> StoreResult<String> {
        // ARCH-1 (CRITICAL) — substrate governance pre-write parity.
        // The semantic-recall write path MUST consult the hook just
        // like the plain `store` path; otherwise an operator-signed
        // refuse rule could be bypassed by routing through the
        // embedded-vector path. See `src/storage/mod.rs` for context.
        consult_governance_pre_write_pg(memory)?;

        // Same upsert contract as `store` but additionally writes the
        // pgvector `embedding` column when a vector is supplied. This
        // is the load-bearing path for semantic recall on postgres —
        // without an embedding column the `recall_hybrid` cosine
        // search filters out every row (`WHERE embedding IS NOT NULL`).
        let created_at = parse_rfc3339_required(&memory.created_at)?;
        let updated_at = parse_rfc3339_required(&memory.updated_at)?;
        let last_accessed_at = parse_rfc3339_opt(memory.last_accessed_at.as_deref());
        // v0.7.0 #1466 — backfill the tier-default expiry so a hand-built
        // mid/short Memory with `expires_at: None` is reapable, matching the
        // SQLite `storage::insert` chokepoint. Shared SSOT on `Memory`.
        let expires_at = parse_rfc3339_opt(memory.effective_expires_at().as_deref());
        let tags_json =
            serde_json::to_value(&memory.tags).map_err(|e| StoreError::IntegrityFailed {
                detail: serialize_err("tags", e),
            })?;
        let emb_pgvec = embedding.map(|v| pgvector::Vector::from(v.to_vec()));
        // #1608 — Form-4 / Form-5 / QW-2 column parity with `store()`
        // and `apply_remote_memory`. Pre-#1608 this INSERT listed only
        // 19 columns, so the embed-before-store hot path (the HTTP
        // create anchor on postgres daemons) silently dropped
        // citations / source_uri / source_span / confidence_source /
        // confidence_signals / confidence_decayed_at / entity_id /
        // persona_version — every attested HTTP create landed with the
        // schema-default `confidence_source = 'caller_provided'` while
        // the wire response and the federation SHIP envelope carried
        // the truthful handler-stamped value (the #1588 DO-leg lived
        // contradiction: anchor row lied, receiver rows were correct).
        // Same defect class as #1029 on `apply_remote_memory`.
        let citations_json =
            serde_json::to_string(&memory.citations).map_err(|e| StoreError::IntegrityFailed {
                detail: serialize_err("citations", e),
            })?;
        let source_span_json = match &memory.source_span {
            Some(span) => {
                Some(
                    serde_json::to_string(span).map_err(|e| StoreError::IntegrityFailed {
                        detail: serialize_err(COL_SOURCE_SPAN, e),
                    })?,
                )
            }
            None => None,
        };
        let confidence_signals_json = match &memory.confidence_signals {
            Some(s) => Some(
                serde_json::to_string(s).map_err(|e| StoreError::IntegrityFailed {
                    detail: serialize_err(COL_CONFIDENCE_SIGNALS, e),
                })?,
            ),
            None => None,
        };

        // v0.7.0.1 G1 — wrap INSERT + quota record in a single tx (see
        // store() above for context).
        let mut tx = self
            .pool
            .begin()
            .await
            .map_err(|e| to_store_err("begin store tx", e))?;

        // #1383 — same denormalisation rationale as the regular
        // `store()` path above. Reflection-kind rows passed through
        // `store_with_embedding` (the recall-hybrid hot path) must
        // still light up the `mentioned_entity_id` partial index.
        let mentioned_entity_id = crate::storage::extract_mentioned_entity_id(memory);

        let id: String = sqlx::query(
            "INSERT INTO memories (
                id, tier, namespace, title, content, tags, priority, confidence,
                source, access_count, created_at, updated_at, last_accessed_at,
                expires_at, metadata, reflection_depth, memory_kind,
                citations, source_uri, source_span,
                confidence_source, confidence_signals, confidence_decayed_at,
                entity_id, persona_version, embedding,
                mentioned_entity_id
            ) VALUES ($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)
            ON CONFLICT (title, namespace) DO UPDATE SET
                content = EXCLUDED.content,
                tier = CASE
                    WHEN tier_rank(EXCLUDED.tier) >= tier_rank(memories.tier)
                        THEN EXCLUDED.tier
                    ELSE memories.tier
                END,
                tags = EXCLUDED.tags,
                -- #1629 — sqlite parity: MAX-merge, source follows incoming,
                -- expiry long→NULL + COALESCE (see `store()` for rationale).
                priority = GREATEST(memories.priority, EXCLUDED.priority),
                confidence = GREATEST(memories.confidence, EXCLUDED.confidence),
                source = EXCLUDED.source,
                updated_at = EXCLUDED.updated_at,
                expires_at = CASE
                    WHEN EXCLUDED.tier = 'long' OR memories.tier = 'long' THEN NULL
                    ELSE COALESCE(EXCLUDED.expires_at, memories.expires_at)
                END,
                metadata = CASE
                    WHEN memories.metadata ? 'agent_id'
                        THEN jsonb_set(
                            EXCLUDED.metadata,
                            '{agent_id}',
                            memories.metadata -> 'agent_id'
                        )
                    ELSE EXCLUDED.metadata
                END,
                -- v0.7.0 Task 1/8 — recursion depth takes max on upsert.
                reflection_depth = GREATEST(memories.reflection_depth, EXCLUDED.reflection_depth),
                -- L1-1 — kind is sticky (reflection AND persona, #1629).
                memory_kind = CASE WHEN memories.memory_kind = 'reflection' THEN 'reflection'
                                   WHEN memories.memory_kind = 'persona' THEN 'persona'
                                   ELSE EXCLUDED.memory_kind END,
                -- #1608 / #1629 — Form-4 / Form-5 / QW-2 arms mirror `store()`
                -- (sqlite shape): re-store doesn't blank out provenance.
                citations = CASE WHEN EXCLUDED.citations = '[]'
                                 THEN memories.citations
                                 ELSE EXCLUDED.citations END,
                source_uri = COALESCE(EXCLUDED.source_uri, memories.source_uri),
                source_span = COALESCE(EXCLUDED.source_span, memories.source_span),
                confidence_source = CASE WHEN EXCLUDED.confidence_source != 'caller_provided'
                                         THEN EXCLUDED.confidence_source
                                         ELSE memories.confidence_source END,
                confidence_signals = COALESCE(EXCLUDED.confidence_signals, memories.confidence_signals),
                confidence_decayed_at = COALESCE(EXCLUDED.confidence_decayed_at, memories.confidence_decayed_at),
                entity_id = COALESCE(memories.entity_id, EXCLUDED.entity_id),
                persona_version = COALESCE(memories.persona_version, EXCLUDED.persona_version),
                embedding = COALESCE(EXCLUDED.embedding, memories.embedding),
                -- #1383 — preserve a previously-extracted attribution
                -- if EXCLUDED is NULL (sqlite parity).
                mentioned_entity_id = COALESCE(EXCLUDED.mentioned_entity_id, memories.mentioned_entity_id),
                -- #1632 (pg twin) — upsert-merge bumps the Gap-1 counter.
                version = memories.version + 1
            RETURNING id",
        )
        .bind(&memory.id)
        .bind(memory.tier.as_str())
        .bind(&memory.namespace)
        .bind(&memory.title)
        .bind(&memory.content)
        .bind(&tags_json)
        .bind(memory.priority)
        .bind(memory.confidence)
        .bind(&memory.source)
        .bind(memory.access_count)
        .bind(created_at)
        .bind(updated_at)
        .bind(last_accessed_at)
        .bind(expires_at)
        .bind(&memory.metadata)
        .bind(memory.reflection_depth)
        .bind(memory.memory_kind.as_str())
        .bind(&citations_json)
        .bind(memory.source_uri.as_deref())
        .bind(source_span_json.as_deref())
        .bind(memory.confidence_source.as_str())
        .bind(confidence_signals_json.as_deref())
        .bind(memory.confidence_decayed_at.as_deref())
        .bind(memory.entity_id.as_deref())
        .bind(memory.persona_version)
        .bind(emb_pgvec)
        .bind(mentioned_entity_id.as_deref())
        .fetch_one(&mut *tx)
        .await
        .map_err(|e| to_store_err("insert memory_with_embedding", e))?
        .try_get::<String, _>("id")
        .map_err(|e| to_store_err(READ_RETURNED_ID, e))?;

        // v0.7.0 #1156 — per-namespace quota dimension (v50 PK).
        let quota_agent_id = resolve_quota_agent_id(ctx, &memory.metadata);
        let bytes_added = memory_storage_bytes(memory);
        record_memory_quota_in_tx(&mut tx, &quota_agent_id, &memory.namespace, bytes_added).await?;

        tx.commit()
            .await
            .map_err(|e| to_store_err("commit store tx", e))?;
        Ok(id)
    }

    async fn update_embedding(
        &self,
        _ctx: &CallerContext,
        id: &str,
        embedding: Option<&[f32]>,
    ) -> StoreResult<()> {
        let emb_pgvec = embedding.map(|v| pgvector::Vector::from(v.to_vec()));
        sqlx::query("UPDATE memories SET embedding = $2 WHERE id = $1")
            .bind(id)
            .bind(emb_pgvec)
            .execute(&self.pool)
            .await
            .map_err(|e| to_store_err("update_embedding", e))?;
        Ok(())
    }

    /// #1579 A4 — bounded NULL-embedding scan for the serve-boot
    /// backfill sweep. Oldest-first so the sweep replays the v29
    /// dim-migration damage in insertion order; the `LIMIT` keeps each
    /// pass bounded (F5.6 semantics — the sweep loop in
    /// [`crate::store::run_embedding_backfill_on_store`] re-scans
    /// until empty).
    async fn list_unembedded(
        &self,
        ctx: &CallerContext,
        limit: usize,
    ) -> StoreResult<Vec<(String, String, String)>> {
        // #1586 (SEC) — this method returns id+title+content of EVERY
        // unembedded row regardless of namespace/scope, so it is an
        // admin-only sweep primitive. The sole production caller is the
        // serve-boot backfill sweep under `CallerContext::for_admin`.
        // Refuse a non-admin context (`bypass_visibility == false`) with
        // an empty result so a future handler that wires this method
        // without re-gating cannot leak cross-tenant private content —
        // matching the scope-gate convention every sibling SAL read
        // applies. The `ctx` is load-bearing, not decorative.
        if !ctx.bypass_visibility {
            return Ok(Vec::new());
        }
        let cap: i64 = i64::try_from(limit).unwrap_or(LIST_FALLBACK_LIMIT_I64);
        let rows = sqlx::query(
            "SELECT id, title, content FROM memories \
              WHERE embedding IS NULL \
              ORDER BY created_at ASC \
              LIMIT $1",
        )
        .bind(cap)
        .fetch_all(&self.pool)
        .await
        .map_err(|e| to_store_err("list_unembedded", e))?;
        rows.iter()
            .map(|r| {
                Ok((
                    r.try_get::<String, _>("id")
                        .map_err(|e| to_store_err("read unembedded id", e))?,
                    r.try_get::<String, _>("title")
                        .map_err(|e| to_store_err("read unembedded title", e))?,
                    r.try_get::<String, _>("content")
                        .map_err(|e| to_store_err("read unembedded content", e))?,
                ))
            })
            .collect()
    }

    /// #1579 A4 — single-transaction batch embedding write. One commit
    /// per chunk instead of N autocommit round-trips; the postgres twin
    /// of sqlite's `db::set_embeddings_batch`. Returns rows actually
    /// updated (a row deleted between scan and write counts 0).
    async fn set_embeddings_batch(
        &self,
        _ctx: &CallerContext,
        entries: &[(String, Vec<f32>)],
    ) -> StoreResult<usize> {
        if entries.is_empty() {
            return Ok(0);
        }
        let mut tx = self
            .pool
            .begin()
            .await
            .map_err(|e| to_store_err("begin set_embeddings_batch tx", e))?;
        let mut written = 0usize;
        for (id, vec) in entries {
            let emb_pgvec = pgvector::Vector::from(vec.clone());
            let res = sqlx::query("UPDATE memories SET embedding = $2 WHERE id = $1")
                .bind(id)
                .bind(emb_pgvec)
                .execute(&mut *tx)
                .await
                .map_err(|e| to_store_err("set_embeddings_batch update", e))?;
            written += usize::try_from(res.rows_affected()).unwrap_or(0);
        }
        tx.commit()
            .await
            .map_err(|e| to_store_err("commit set_embeddings_batch tx", e))?;
        Ok(written)
    }

    async fn get(&self, ctx: &CallerContext, id: &str) -> StoreResult<Memory> {
        let row = sqlx::query("SELECT * FROM memories WHERE id = $1")
            .bind(id)
            .fetch_optional(&self.pool)
            .await
            .map_err(|e| to_store_err("select by id", e))?;
        match row {
            Some(r) => {
                let mem = Self::row_to_memory(&r)?;
                // #910 SAL-level scope=private gate — fold permission
                // denials into NotFound so the trait does not leak
                // existence to callers that lack read permission.
                // Admin/migrate paths set `bypass_visibility`.
                if ctx.bypass_visibility || is_visible_to_caller(&mem, ctx.effective_principal()) {
                    Ok(mem)
                } else {
                    Err(StoreError::NotFound { id: id.to_string() })
                }
            }
            None => Err(StoreError::NotFound { id: id.to_string() }),
        }
    }

    async fn update(&self, ctx: &CallerContext, id: &str, patch: UpdatePatch) -> StoreResult<()> {
        // v0.7.0 #1412 (CRITICAL, 2026-05-30) — SAL-side caller-owns
        // gate. Pre-fix `PostgresStore::update` discarded `_ctx` and
        // let any authenticated HTTP/MCP caller rewrite any tenant's
        // memory row by id; the sqlite HTTP handler enforced the gate
        // via `require_caller_owns_memory(existing, &caller, false)`
        // but the postgres handler routed through `app.store.update`
        // which bypassed the check entirely. The mirror gate lives on
        // the SAL layer so EVERY caller (HTTP / MCP / CLI / federation
        // / future surfaces) is owner-checked uniformly.
        //
        // Admin paths (`bypass_visibility = true`) skip the gate, same
        // as the SAL-level scope=private read filter — operator-mode
        // surfaces (migrate, federation catchup, GC sweeps) round-trip
        // every row regardless of ownership. Tenant-facing handlers
        // MUST NOT pass a bypass context.
        // #1628 refactor — shared caller-owns gate (byte-equal wire
        // errors; see assert_caller_owns_for_mutation).
        self.assert_caller_owns_for_mutation(ctx, id, "update", REASON_UNSTAMPED_TENANT_WRITE)
            .await?;

        // One-shot COALESCE update — each patch field overrides only if
        // Some, otherwise falls through to the existing value.
        //
        // Blocker #296: tier never downgrades. When a patch proposes a
        // tier of lower rank than the current row's tier, the DB keeps
        // the higher tier via `GREATEST(tier_rank(...))`.
        //
        // Blocker #295: `metadata.agent_id` is SQL-layer-immutable. If
        // the current row has an agent_id we preserve it against any
        // patch; otherwise the patch's metadata (if provided) wins.
        //
        // v0.7.0 Provenance Gap 2 (#906): `source_uri` follows COALESCE
        // semantics — a patch that doesn't touch source_uri leaves the
        // stored value alone; a patch that supplies one rewrites the
        // row's source_uri verbatim.
        // #1024 (CRITICAL, 2026-05-21): bump `version` on every trait
        // `update`. Pre-#1024 the SET list omitted `version = version + 1`,
        // so postgres-backed daemons answering `PUT /api/v1/memories/:id`
        // without `If-Match` (which routes through this trait method)
        // left `version` permanently at 1 — concurrent optimistic-
        // concurrency detection was silently broken on postgres while
        // the surface looked identical to sqlite. SQLite bumps version
        // in `src/storage/mod.rs`.
        // #1628 (2026-06-11): PUTs WITH a parseable `If-Match` no longer
        // reach this method — the handler routes them through the
        // version-gated inherent `update_with_expected_version` helper,
        // which applies the same owner gate + SET semantics and refuses
        // stale versions with the typed VersionConflict envelope.
        let rows_affected = sqlx::query(
            "UPDATE memories SET
                title = COALESCE($2, title),
                content = COALESCE($3, content),
                tier = CASE
                    WHEN $4::TEXT IS NULL THEN tier
                    WHEN tier_rank($4::TEXT) >= tier_rank(tier) THEN $4::TEXT
                    ELSE tier
                END,
                namespace = COALESCE($5, namespace),
                tags = COALESCE($6, tags),
                priority = COALESCE($7, priority),
                confidence = COALESCE($8, confidence),
                metadata = CASE
                    WHEN $9::JSONB IS NULL THEN metadata
                    WHEN metadata ? 'agent_id' THEN jsonb_set(
                        $9::JSONB,
                        '{agent_id}',
                        metadata -> 'agent_id'
                    )
                    ELSE $9::JSONB
                END,
                source_uri = COALESCE($10, source_uri),
                -- #1626 — tier→long ⇒ expires_at = NULL. A patch that
                -- promotes to 'long' always wins the tier ladder above,
                -- so the row must shed its expiry or GC reaps the
                -- promoted row at the stale mid/short deadline. Rule:
                -- when the patch tier IS long the clear wins over any
                -- explicitly-supplied $11 (matching the sqlite upsert
                -- semantics: expiry is only cleared when the new tier
                -- is long, and the sqlite promote handler's explicit
                -- `UPDATE memories SET expires_at = NULL`); when the
                -- patch tier is NOT long an explicit $11 wins and an
                -- absent $11 leaves the stored value untouched.
                expires_at = CASE
                    WHEN $4::TEXT = 'long' THEN NULL
                    ELSE COALESCE($11, expires_at)
                END,
                version = version + 1,
                updated_at = NOW()
             WHERE id = $1",
        )
        .bind(id)
        .bind(patch.title)
        .bind(patch.content)
        .bind(patch.tier.as_ref().map(Tier::as_str))
        .bind(patch.namespace)
        .bind(
            patch
                .tags
                .map(serde_json::to_value)
                .transpose()
                .map_err(|e| StoreError::IntegrityFailed {
                    detail: format!("serialize tags patch: {e}"),
                })?,
        )
        .bind(patch.priority)
        .bind(patch.confidence)
        .bind(patch.metadata)
        .bind(patch.source_uri)
        // v0.7.0 #1423 — bind expires_at COALESCE slot ($11). The
        // postgres column is `TIMESTAMPTZ`; parse the RFC3339 string
        // into a DateTime so sqlx binds the right type. None → NULL
        // → COALESCE leaves stored value untouched. #1626: when the
        // patch tier is 'long' the SET clause above ignores $11 and
        // clears the expiry unconditionally.
        .bind(parse_rfc3339_opt(patch.expires_at.as_deref()))
        .execute(&self.pool)
        .await
        .map_err(|e| to_store_err("update", e))?
        .rows_affected();

        if rows_affected == 0 {
            Err(StoreError::NotFound { id: id.to_string() })
        } else {
            Ok(())
        }
    }

    async fn delete(&self, ctx: &CallerContext, id: &str) -> StoreResult<()> {
        // v0.7.0 #1412 (CRITICAL, 2026-05-30) — SAL-side caller-owns
        // gate. Sister fix to `PostgresStore::update` above; same
        // threat model (cross-tenant write hijack on postgres-backed
        // daemons) and same gate semantics (admin paths skip via
        // `bypass_visibility`, tenant-facing handlers MUST NOT bypass).
        // #1628 refactor — shared caller-owns gate (byte-equal wire
        // errors; see assert_caller_owns_for_mutation).
        self.assert_caller_owns_for_mutation(ctx, id, "delete", REASON_UNSTAMPED_TENANT_DELETE)
            .await?;

        // #1642 — parity with sqlite `storage::delete`
        // (`src/storage/mod.rs:1747-1751`): if this memory is registered
        // as a namespace standard, drop the `namespace_meta` row(s)
        // pointing at it BEFORE deleting the memory, mirroring the
        // sqlite ordering. Pre-fix the postgres delete left a dangling
        // `namespace_meta.standard_id` so governance kept resolving a
        // standard whose backing memory no longer existed.
        sqlx::query(SQL_DELETE_NAMESPACE_META_BY_STANDARD_ID)
            .bind(id)
            .execute(&self.pool)
            .await
            .map_err(|e| to_store_err("delete: namespace_meta cleanup", e))?;

        let rows_affected = sqlx::query(SQL_DELETE_MEMORY_BY_ID)
            .bind(id)
            .execute(&self.pool)
            .await
            .map_err(|e| to_store_err("delete", e))?
            .rows_affected();
        if rows_affected == 0 {
            Err(StoreError::NotFound { id: id.to_string() })
        } else {
            Ok(())
        }
    }

    async fn list(&self, ctx: &CallerContext, filter: &Filter) -> StoreResult<Vec<Memory>> {
        let limit: i64 = filter
            .limit
            .clamp(1, crate::storage::LIST_MAX_LIMIT)
            .try_into()
            .unwrap_or(LIST_FALLBACK_LIMIT_I64);
        // #910 SAL-level scope=private gate — push the visibility
        // predicate into SQL so the row filter runs server-side and
        // the result-set size scales with what the caller can see,
        // not what exists. `metadata->>'scope'` defaults to 'private'
        // when missing (matches the CLAUDE.md NHI contract +
        // SQLite's COALESCE-to-'private' generated column).
        //
        // Admin/migrate paths set `bypass_visibility`; we pass NULL
        // as the visibility-bypass sentinel which short-circuits the
        // `(scope <> 'private' OR agent_id = caller)` test via the
        // leading `$7 IS NULL` clause.
        let caller = ctx.effective_principal();
        let caller_opt: Option<&str> = if ctx.bypass_visibility {
            None
        } else {
            Some(caller)
        };
        // #1030 (HIGH, 2026-05-21) — honor `filter.agent_id` on the
        // postgres list path. Pre-#1030 the trait's `Filter.agent_id`
        // was bound to no SQL parameter — `/api/v1/memories?agent_id=alice`
        // returned every agent's rows on postgres while sqlite filtered
        // correctly (a privacy/NHI leak + permission-by-side-effect
        // divergence between the two backends). The new $7 binding
        // matches sqlite's `db::list` shape.
        // #1473 — make the namespace filter sargable. The OR-NULL
        // optional-filter idiom `($1 IS NULL OR namespace = $1)` is
        // non-sargable under sqlx's generic prepared-statement plan:
        // the planner can't prove at plan time that `$1` is non-null,
        // so it emits a Seq Scan even when the caller passes an explicit
        // namespace — a full-table scan on every namespace-filtered
        // read. When a namespace IS supplied we emit the bare equality
        // `namespace = $1`, which the planner turns into an `Index Cond`
        // on `memories_namespace_idx`. Exact-match semantics are
        // preserved — this is equality, NOT the prefix byte-range band
        // `list_by_namespace_prefix` uses. When namespace is absent we
        // keep the OR-NULL no-op form: an unfiltered list has no index
        // to use, so the scan is unavoidable and correct.
        let ns_predicate = if filter.namespace.is_some() {
            NS_FILTER_SARGABLE
        } else {
            NS_FILTER_OPTIONAL
        };
        let list_sql = format!(
            "SELECT * FROM memories
             WHERE {ns_predicate}
               AND ($2::text IS NULL OR tier = $2)
               AND (expires_at IS NULL OR expires_at > NOW())
               AND ($3::timestamptz IS NULL OR created_at >= $3)
               AND ($4::timestamptz IS NULL OR created_at <= $4)
               AND (
                   $6::text IS NULL
                   OR COALESCE(metadata->>'scope', 'private') <> 'private'
                   OR metadata->>'agent_id' = $6
                   OR metadata->>'target_agent_id' = $6
               )
               AND ($7::text IS NULL OR metadata->>'agent_id' = $7)
             ORDER BY priority DESC, updated_at DESC
             LIMIT $5"
        );
        let rows = sqlx::query(&list_sql)
            .bind(filter.namespace.as_ref())
            .bind(filter.tier.as_ref().map(Tier::as_str))
            .bind(filter.since)
            .bind(filter.until)
            .bind(limit)
            .bind(caller_opt)
            .bind(filter.agent_id.as_ref())
            .fetch_all(&self.pool)
            .await
            .map_err(|e| to_store_err("list", e))?;

        // Belt-and-suspenders: re-apply the predicate in-process so a
        // hypothetical SQL drift between the WHERE clause above and
        // the canonical Rust predicate cannot widen the visibility
        // window. Costs O(returned-rows); negligible.
        let mems: Vec<Memory> = rows
            .iter()
            .map(Self::row_to_memory)
            .collect::<StoreResult<Vec<_>>>()?;
        if ctx.bypass_visibility {
            return Ok(mems);
        }
        Ok(mems
            .into_iter()
            .filter(|m| is_visible_to_caller(m, caller))
            .collect())
    }

    async fn list_by_namespace_prefix(
        &self,
        _ctx: &CallerContext,
        prefix: &str,
        limit: usize,
    ) -> StoreResult<Vec<Memory>> {
        let limit: i64 = (limit as i64).clamp(1, STORE_LIST_MAX_LIMIT_SAL);
        // Sargable prefix scan via a half-open byte range on the
        // `namespace` btree (`memories_namespace_idx`). The database
        // collation is byte-ordered (C.UTF-8), so
        //   namespace >= prefix AND namespace < upper_bound(prefix)
        // selects exactly the rows whose namespace starts with `prefix`
        // — and the planner turns it into an `Index Cond` even under the
        // generic prepared-statement plan sqlx uses (a parameterized
        // `LIKE`/`~>=~` does NOT: it degrades to a full index Filter
        // scan). This is the per-write dispatch hot path; the prior
        // `list(namespace=None)` here seq-scanned the entire table on
        // every write.
        let upper = prefix_upper_bound(prefix);
        let rows = match upper {
            Some(ref upper) => {
                sqlx::query(
                    "SELECT * FROM memories
                     WHERE namespace >= $1 AND namespace < $2
                     ORDER BY namespace
                     LIMIT $3",
                )
                .bind(prefix)
                .bind(upper)
                .bind(limit)
                .fetch_all(&self.pool)
                .await
            }
            None => {
                sqlx::query(
                    "SELECT * FROM memories
                     WHERE namespace >= $1
                     ORDER BY namespace
                     LIMIT $2",
                )
                .bind(prefix)
                .bind(limit)
                .fetch_all(&self.pool)
                .await
            }
        }
        .map_err(|e| to_store_err("list_by_namespace_prefix", e))?;

        // Belt-and-suspenders: re-apply the prefix predicate in-process
        // so the result is correct even if the byte-range bounds ever
        // drift from the requested prefix.
        rows.iter()
            .map(Self::row_to_memory)
            .collect::<StoreResult<Vec<_>>>()
            .map(|mems| {
                mems.into_iter()
                    .filter(|m| m.namespace.starts_with(prefix))
                    .collect()
            })
    }

    async fn search(
        &self,
        ctx: &CallerContext,
        query: &str,
        filter: &Filter,
    ) -> StoreResult<Vec<Memory>> {
        let limit: i64 = filter
            .limit
            .clamp(1, crate::storage::LIST_MAX_LIMIT)
            .try_into()
            .unwrap_or(LIST_FALLBACK_LIMIT_I64);
        let caller = ctx.effective_principal();
        // Adapter parity with SQLite (#302 item 3): threads the full
        // Filter (namespace, tier, tags_any, agent_id) into the query.
        // Prior implementation ignored `tags_any` and `agent_id` so
        // identical calls returned different result sets on the two
        // adapters.
        //
        // `tags_any`:  match if any of the requested tags is present in
        //              memories.tags (JSONB array). Uses @> over a
        //              single-element JSONB array per requested tag,
        //              OR'd together via sqlx bind array.
        // `agent_id`:  match if metadata->>'agent_id' == $agent_id.
        //
        // ────────────────────────────────────────────────────────────
        // v0.7.0 F6 Gap 7 — recall scoring parity with SQLite.
        //
        // SQLite's `db::recall` scores each FTS hit with a 6-factor
        // blend (crate::storage::recall):
        //
        //     fts.rank        * (-1)
        //   + priority        * 0.5
        //   + min(access_count, 50) * 0.1
        //   + confidence      * 2.0
        //   + tier_bonus      (long=3.0, mid=1.0, short=0.0)
        //   + recency_factor  (1 / (1 + age_days * 0.1))
        //
        // Pre-v0.7.0 the Postgres adapter shipped a 2-factor blend
        // (`ts_rank DESC, priority DESC`) so identical FTS calls
        // produced different orderings on the two backends. This
        // brings them to byte-equivalent rank up to a small swap
        // tolerance (covered in tests/recall_scoring_parity.rs).
        //
        // SQLite's `fts.rank` is BM25-style and negative; multiplying
        // by `-1` makes higher-rank hits score positive. Postgres'
        // `ts_rank` is already positive so we use it directly without
        // sign flipping. The relative magnitudes line up well enough
        // for top-K ordering parity in practice — see the parity test
        // suite for tolerance bounds.
        //
        // The recency_factor uses `EXTRACT(EPOCH FROM (NOW() -
        // updated_at)) / 86400.0` as the day-age, mirroring SQLite's
        // `julianday('now') - julianday(m.updated_at)` (also days).
        let tags_first: Option<&str> = filter.tags_any.first().map(String::as_str);
        // v0.7.0.1 S79 — build the OR-joined tsquery on the rust side
        // so multi-token queries surface every row that matches AT
        // LEAST one token. `plainto_tsquery` is AND-joined and
        // diverges from sqlite's FTS5 `OR` contract — see
        // `build_or_tsquery` for the sanitization rules.
        let or_tsquery = build_or_tsquery(query);
        // #910 SAL-level scope=private gate — push the visibility
        // predicate into SQL via `$7` (caller principal). Admin paths
        // pass NULL to bypass.
        let caller_opt: Option<&str> = if ctx.bypass_visibility {
            None
        } else {
            Some(caller)
        };
        // #1579 B2 — rank + match read the stored generated `tsv`
        // column (schema v57). Pre-fix, `ts_rank(to_tsvector(...))`
        // recomputed the tsvector PER MATCHED ROW (~305 of 306 ms at
        // 8k rows in the P3 fleet audit); the GIN expression index
        // only ever served the `@@` match, never the rank.
        let rows = sqlx::query(
            "SELECT *,
                    ts_rank(tsv, to_tsquery('english', $1))
                    + (priority * 0.5)
                    + (LEAST(access_count, 50) * 0.1)
                    + (confidence * 2.0)
                    + CASE tier
                          WHEN 'long' THEN 3.0
                          WHEN 'mid'  THEN 1.0
                          ELSE 0.0
                      END
                    + (1.0 / (1.0 +
                        EXTRACT(EPOCH FROM (NOW() - updated_at)) / 86400.0 * 0.1))
                      AS rank
             FROM memories
             WHERE tsv @@ to_tsquery('english', $1)
               AND ($2::text IS NULL OR namespace = $2)
               AND ($3::text IS NULL OR tier = $3)
               AND ($4::text IS NULL OR tags @> to_jsonb(ARRAY[$4]))
               AND ($5::text IS NULL OR metadata ->> 'agent_id' = $5)
               AND (expires_at IS NULL OR expires_at > NOW())
               AND (
                   $7::text IS NULL
                   OR COALESCE(metadata->>'scope', 'private') <> 'private'
                   OR metadata->>'agent_id' = $7
                   OR metadata->>'target_agent_id' = $7
               )
             ORDER BY rank DESC, priority DESC
             LIMIT $6",
        )
        .bind(&or_tsquery)
        .bind(filter.namespace.as_ref())
        .bind(filter.tier.as_ref().map(Tier::as_str))
        .bind(tags_first)
        .bind(filter.agent_id.as_ref())
        .bind(limit)
        .bind(caller_opt)
        .fetch_all(&self.pool)
        .await
        .map_err(|e| to_store_err("search", e))?;

        // Belt-and-suspenders: re-apply the predicate in-process.
        let mems: Vec<Memory> = rows
            .iter()
            .map(Self::row_to_memory)
            .collect::<StoreResult<Vec<_>>>()?;
        if ctx.bypass_visibility {
            return Ok(mems);
        }
        Ok(mems
            .into_iter()
            .filter(|m| is_visible_to_caller(m, caller))
            .collect())
    }

    async fn verify(&self, _ctx: &CallerContext, id: &str) -> StoreResult<VerifyReport> {
        // Minimal verify: confirm the row is readable and the tier +
        // timestamps parse. Integrity signatures land with the
        // provenance work on the Postgres track next sprint.
        let mem = self.get(_ctx, id).await?;
        // #1624 — shared finding-checks (`store::integrity_findings`);
        // a malformed created_at is now a FINDING (parity with sqlite)
        // instead of a postgres-only IntegrityFailed hard error.
        let findings = super::integrity_findings(&mem);
        Ok(VerifyReport {
            memory_id: id.to_string(),
            integrity_ok: findings.is_empty(),
            findings,
            // v0.6.0 does NOT perform signature verification; real
            // cryptographic verify lands with Task 1.4. See #302.
            signature_verified: false,
        })
    }

    async fn link(&self, _ctx: &CallerContext, link: &MemoryLink) -> StoreResult<()> {
        // F6 Gap 3 (v0.7.0) — unsigned link write. The trait method
        // does not surface a keypair so we always land the row with
        // `attest_level = "unsigned"`. Callers that want signing route
        // through [`MemoryStore::link_signed`].
        self.link_internal(link, None).await.map(|_| ())
    }

    async fn link_signed(
        &self,
        _ctx: &CallerContext,
        link: &MemoryLink,
        keypair: Option<&crate::identity::keypair::AgentKeypair>,
    ) -> StoreResult<&'static str> {
        self.link_internal(link, keypair).await
    }

    async fn list_links(&self, namespace: Option<&str>) -> StoreResult<Vec<MemoryLink>> {
        // F6 Gap 2 (v0.7.0) — surface the full link table to the
        // migrate runner. The namespace filter matches the **source**
        // memory's namespace (links live with their source — the same
        // affinity SQLite's `migrate` uses for memories), so a
        // namespace-scoped migrate captures every outbound edge.
        //
        // Ordering by `(source_id, target_id, relation)` is the SAL
        // contract — deterministic across calls and matches the unique
        // key, so a paginated migrate can resume without losing rows.
        //
        // v0.7.0 issue #860 — SELECT was widened to include `attest_level`
        // so the Postgres SAL surfaces the same attestation column the
        // SQLite `db::get_links` path promises in the
        // `memory_get_links` MCP tool docstring.
        let rows = sqlx::query(
            "SELECT ml.source_id, ml.target_id, ml.relation, ml.created_at,
                    ml.valid_from, ml.valid_until, ml.observed_by, ml.signature,
                    ml.attest_level
             FROM memory_links ml
             WHERE ($1::text IS NULL
                    OR EXISTS (SELECT 1 FROM memories m
                               WHERE m.id = ml.source_id AND m.namespace = $1))
             ORDER BY ml.source_id, ml.target_id, ml.relation",
        )
        .bind(namespace)
        .fetch_all(&self.pool)
        .await
        .map_err(|e| to_store_err("list_links", e))?;

        rows.iter()
            .map(|r| {
                let created_at: DateTime<Utc> = r
                    .try_get::<DateTime<Utc>, _>(field_names::CREATED_AT)
                    .map_err(|e| to_store_err(READ_CREATED_AT, e))?;
                let valid_from: Option<DateTime<Utc>> = r
                    .try_get::<Option<DateTime<Utc>>, _>(field_names::VALID_FROM)
                    .map_err(|e| to_store_err(READ_VALID_FROM, e))?;
                let valid_until: Option<DateTime<Utc>> = r
                    .try_get::<Option<DateTime<Utc>>, _>(field_names::VALID_UNTIL)
                    .map_err(|e| to_store_err(READ_VALID_UNTIL, e))?;
                let observed_by: Option<String> = r
                    .try_get::<Option<String>, _>(field_names::OBSERVED_BY)
                    .map_err(|e| to_store_err(READ_OBSERVED_BY, e))?;
                let signature: Option<Vec<u8>> = r
                    .try_get::<Option<Vec<u8>>, _>("signature")
                    .map_err(|e| to_store_err("read signature", e))?;
                let relation_str: String = r
                    .try_get::<String, _>("relation")
                    .map_err(|e| to_store_err(READ_RELATION, e))?;
                let attest_level: Option<String> = r
                    .try_get::<Option<String>, _>(field_names::ATTEST_LEVEL)
                    .map_err(|e| to_store_err(READ_ATTEST_LEVEL, e))?;
                Ok(MemoryLink {
                    source_id: r
                        .try_get::<String, _>("source_id")
                        .map_err(|e| to_store_err(READ_SOURCE_ID, e))?,
                    target_id: r
                        .try_get::<String, _>("target_id")
                        .map_err(|e| to_store_err(READ_TARGET_ID, e))?,
                    // v0.7.0 fix campaign R1-M4 — parse closed-set
                    // relation. Unknown values fall back to default so
                    // the read path never errors; the SQL CHECK on the
                    // write side keeps new rows in the closed set.
                    relation: crate::models::MemoryLinkRelation::from_str(&relation_str)
                        .unwrap_or_default(),
                    created_at: created_at.to_rfc3339(),
                    signature,
                    observed_by,
                    valid_from: valid_from.map(|t| t.to_rfc3339()),
                    valid_until: valid_until.map(|t| t.to_rfc3339()),
                    // v0.7.0 issue #860 — surface attest_level on the
                    // Postgres SAL `list_links` read path so the
                    // adapter matches the `memory_get_links` MCP
                    // tool's docstring promise.
                    attest_level,
                })
            })
            .collect()
    }

    /// v0.7.0 ARCH-2 followup (FX-C2) — per-anchor edge probe over
    /// Postgres. Mirrors the SQLite `db::get_links` shape: returns every
    /// row where `anchor_id` is either source or target, projects the
    /// `attest_level` + temporal-validity columns the
    /// `memory_get_links` MCP tool's docstring promises, leaves
    /// `signature` as `None` (the verifier owns that surface).
    ///
    /// Ordering: descending by `created_at`. The SQLite path naturally
    /// returns rows in this order via the legacy projection; the
    /// Postgres path makes it explicit so cross-backend wire shape is
    /// stable.
    async fn get_links_for_anchor(&self, anchor_id: &str) -> StoreResult<Vec<MemoryLink>> {
        let rows = sqlx::query(
            "SELECT source_id, target_id, relation, created_at,
                    valid_from, valid_until, observed_by, attest_level
             FROM memory_links
             WHERE source_id = $1 OR target_id = $1
             ORDER BY created_at DESC",
        )
        .bind(anchor_id)
        .fetch_all(&self.pool)
        .await
        .map_err(|e| to_store_err("get_links_for_anchor", e))?;

        rows.iter()
            .map(|r| {
                let created_at: DateTime<Utc> = r
                    .try_get::<DateTime<Utc>, _>(field_names::CREATED_AT)
                    .map_err(|e| to_store_err(READ_CREATED_AT, e))?;
                let valid_from: Option<DateTime<Utc>> = r
                    .try_get::<Option<DateTime<Utc>>, _>(field_names::VALID_FROM)
                    .map_err(|e| to_store_err(READ_VALID_FROM, e))?;
                let valid_until: Option<DateTime<Utc>> = r
                    .try_get::<Option<DateTime<Utc>>, _>(field_names::VALID_UNTIL)
                    .map_err(|e| to_store_err(READ_VALID_UNTIL, e))?;
                let observed_by: Option<String> = r
                    .try_get::<Option<String>, _>(field_names::OBSERVED_BY)
                    .map_err(|e| to_store_err(READ_OBSERVED_BY, e))?;
                let relation_str: String = r
                    .try_get::<String, _>("relation")
                    .map_err(|e| to_store_err(READ_RELATION, e))?;
                let attest_level: Option<String> = r
                    .try_get::<Option<String>, _>(field_names::ATTEST_LEVEL)
                    .map_err(|e| to_store_err(READ_ATTEST_LEVEL, e))?;
                Ok(MemoryLink {
                    source_id: r
                        .try_get::<String, _>("source_id")
                        .map_err(|e| to_store_err(READ_SOURCE_ID, e))?,
                    target_id: r
                        .try_get::<String, _>("target_id")
                        .map_err(|e| to_store_err(READ_TARGET_ID, e))?,
                    // Closed-set relation parse — unknown values fall
                    // back to the canonical default. Mirrors the SQLite
                    // path's `from_str(...).unwrap_or_default()` posture.
                    relation: crate::models::MemoryLinkRelation::from_str(&relation_str)
                        .unwrap_or_default(),
                    created_at: created_at.to_rfc3339(),
                    // Signature is intentionally not surfaced on this
                    // read path — owned by the verifier (mirrors the
                    // SQLite `db::get_links` decision).
                    signature: None,
                    observed_by,
                    valid_from: valid_from.map(|t| t.to_rfc3339()),
                    valid_until: valid_until.map(|t| t.to_rfc3339()),
                    attest_level,
                })
            })
            .collect()
    }

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

    // ----- v0.7.0 Wave-3 Continuation 2 — federation surface ---------
    //
    // The Postgres path mirrors the sqlite `db::memories_updated_since`
    // + `db::insert_if_newer` contracts so the wire shape is byte-
    // identical regardless of which backend a peer runs on. Tier never
    // downgrades; `metadata.agent_id` is preserved across upsert.

    async fn list_memories_updated_since(
        &self,
        since: Option<&str>,
        limit: usize,
    ) -> StoreResult<Vec<Memory>> {
        let limit_i: i64 = (limit as i64).clamp(1, STORE_LIST_MAX_LIMIT_SAL);
        let since_dt = match since {
            None => None,
            Some(s) => Some(parse_rfc3339_required(s)?),
        };
        // #1028 (HIGH, 2026-05-21) — REVERTED via QC pass-2: the first
        // pass added a SAL-level `metadata->>'scope' <> 'private'`
        // filter here. That bypassed the federation visibility gate's
        // owner-signed-private + inbox-target + federation_share
        // branches and broke 5 federation_legacy_row_visibility_978
        // tests. The visibility gate runs downstream of this method
        // and already refuses to project rows that shouldn't
        // federate. Re-fix at the federation handler layer is
        // tracked as a follow-up.
        // #1476 — sargable split. The former
        // `($1 IS NULL OR updated_at > $1)` predicate is non-sargable:
        // even with `idx_memories_updated_at` present the generic
        // (bind-param) plan degrades to `Index Scan + Filter` rather than
        // a true `Index Cond` range scan, because the planner cannot push
        // an OR-NULL branch into the index range. Splitting on `since`
        // gives each path a predicate the planner can fold into the index
        // (`Index Cond: updated_at > $1`) or drop entirely (None branch),
        // with early-stop under the LIMIT. Verified via EXPLAIN
        // GENERIC_PLAN on a 200k-row probe (full-scan cost 7177 → 2396).
        let rows = match since_dt {
            None => sqlx::query(
                "SELECT * FROM memories \
                     ORDER BY updated_at ASC \
                     LIMIT $1",
            )
            .bind(limit_i)
            .fetch_all(&self.pool)
            .await
            .map_err(|e| to_store_err("list memories updated since", e))?,
            Some(dt) => sqlx::query(
                "SELECT * FROM memories \
                     WHERE updated_at > $1 \
                     ORDER BY updated_at ASC \
                     LIMIT $2",
            )
            .bind(dt)
            .bind(limit_i)
            .fetch_all(&self.pool)
            .await
            .map_err(|e| to_store_err("list memories updated since", e))?,
        };

        rows.iter().map(Self::row_to_memory).collect()
    }

    async fn apply_remote_memory(
        &self,
        _ctx: &CallerContext,
        memory: &Memory,
    ) -> StoreResult<String> {
        // ARCH-1 (CRITICAL) — substrate governance pre-write parity.
        // Federation-pushed memories must clear the same pre-write
        // hook as locally-authored writes; otherwise a peer could push
        // a row that the local operator's signed governance rules
        // would refuse to accept on the local write path. The SQLite
        // mirror is `crate::storage::insert_if_newer`
        // (src/storage/mod.rs:6218).
        consult_governance_pre_write_pg(memory)?;

        // Mirrors sqlite db::insert_if_newer:
        //   1. INSERT verbatim if no row matches.
        //   2. On (title, namespace) collision: UPDATE only if the
        //      incoming `updated_at` is strictly greater than the
        //      stored `updated_at`. Tier never downgrades.
        //      `metadata.agent_id` is preserved if the existing row had
        //      one.
        //   3. Else NOOP — return the existing id.
        let created_at = parse_rfc3339_required(&memory.created_at)?;
        let updated_at = parse_rfc3339_required(&memory.updated_at)?;
        let last_accessed_at = parse_rfc3339_opt(memory.last_accessed_at.as_deref());
        // v0.7.0 #1466 — backfill the tier-default expiry so a hand-built
        // mid/short Memory with `expires_at: None` is reapable, matching the
        // SQLite `storage::insert` chokepoint. Shared SSOT on `Memory`.
        let expires_at = parse_rfc3339_opt(memory.effective_expires_at().as_deref());
        let tags_json =
            serde_json::to_value(&memory.tags).map_err(|e| StoreError::IntegrityFailed {
                detail: serialize_err("tags", e),
            })?;

        // #1029 (HIGH, 2026-05-21): extend the federation upsert to
        // carry the full v0.7.0 column set. Pre-#1029 the INSERT
        // listed 17 columns; the v0.7.0 Memory struct carries 26.
        // Missing: citations, source_uri, source_span (Form-4 fact
        // provenance), confidence_source, confidence_signals,
        // confidence_decayed_at (Form-5 confidence calibration),
        // entity_id, persona_version (QW-2 persona artefact), version
        // (Gap-1 optimistic concurrency). Federation push between two
        // postgres peers lost all 9 fields on every cross-node sync.
        //
        // Serialize the JSON-shaped columns (citations, source_span,
        // confidence_signals) to String via serde_json::to_string,
        // matching the pattern used by the local INSERT path at
        // `store` (~line 6758).
        let citations_json =
            serde_json::to_string(&memory.citations).map_err(|e| StoreError::IntegrityFailed {
                detail: serialize_err("citations", e),
            })?;
        let source_span_json = match &memory.source_span {
            Some(span) => {
                Some(
                    serde_json::to_string(span).map_err(|e| StoreError::IntegrityFailed {
                        detail: serialize_err(COL_SOURCE_SPAN, e),
                    })?,
                )
            }
            None => None,
        };
        let confidence_signals_json = match &memory.confidence_signals {
            Some(s) => Some(
                serde_json::to_string(s).map_err(|e| StoreError::IntegrityFailed {
                    detail: serialize_err(COL_CONFIDENCE_SIGNALS, e),
                })?,
            ),
            None => None,
        };
        let confidence_decayed_at = parse_rfc3339_opt(memory.confidence_decayed_at.as_deref());
        // #1383 — federation `apply_remote_memory` parity. When a peer
        // pushes a reflection row, the receiver must populate
        // `mentioned_entity_id` from the row's own metadata so that
        // post-replication `memory_persona_generate` queries against
        // the receiver also reach the synced reflection. Pre-#1383 a
        // federated reflection landed invisible to the matcher on the
        // receiver — a silent loss of persona-generation coverage on
        // multi-peer deployments.
        let mentioned_entity_id = crate::storage::extract_mentioned_entity_id(memory);
        let row = sqlx::query(
            "INSERT INTO memories (
                id, tier, namespace, title, content, tags, priority, confidence,
                source, access_count, created_at, updated_at, last_accessed_at,
                expires_at, metadata, reflection_depth, memory_kind,
                citations, source_uri, source_span,
                confidence_source, confidence_signals, confidence_decayed_at,
                entity_id, persona_version, version,
                mentioned_entity_id
            ) VALUES (
                $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
            )
            ON CONFLICT (title, namespace) DO UPDATE SET
                -- #1631 — every newer-wins arm carries the sqlite
                -- `insert_if_newer` equal-timestamp id tiebreak
                -- (src/storage/mod.rs:7320-7321) so two peers that wrote
                -- in the same millisecond converge on ONE deterministic
                -- winner (total order: updated_at, then id) instead of
                -- diverging per receive order.
                content = CASE
                    WHEN EXCLUDED.updated_at > memories.updated_at
                         OR (EXCLUDED.updated_at = memories.updated_at
                             AND EXCLUDED.id > memories.id)
                        THEN EXCLUDED.content
                    ELSE memories.content
                END,
                -- #1631 — tier upgrades are monotone REGARDLESS of the
                -- timestamp (sqlite parity): a stale peer that promoted
                -- a row to long must not lose the promotion.
                tier = CASE WHEN EXCLUDED.tier = 'long' THEN 'long'
                            WHEN memories.tier = 'long' THEN 'long'
                            WHEN EXCLUDED.tier = 'mid' THEN 'mid'
                            ELSE memories.tier END,
                tags = CASE
                    WHEN EXCLUDED.updated_at > memories.updated_at
                         OR (EXCLUDED.updated_at = memories.updated_at
                             AND EXCLUDED.id > memories.id)
                        THEN EXCLUDED.tags
                    ELSE memories.tags
                END,
                -- #1631 — sqlite parity: priority + confidence MAX-merge.
                priority = GREATEST(memories.priority, EXCLUDED.priority),
                confidence = GREATEST(memories.confidence, EXCLUDED.confidence),
                -- #1631 — sqlite parity: source rides the winning row.
                source = CASE
                    WHEN EXCLUDED.updated_at > memories.updated_at
                         OR (EXCLUDED.updated_at = memories.updated_at
                             AND EXCLUDED.id > memories.id)
                        THEN EXCLUDED.source
                    ELSE memories.source
                END,
                updated_at = GREATEST(memories.updated_at, EXCLUDED.updated_at),
                -- #1631 — sqlite parity: access_count converges on MAX.
                access_count = GREATEST(memories.access_count, EXCLUDED.access_count),
                -- #1631 — sqlite parity: long-tier pins expiry to NULL;
                -- otherwise a peer push that omits expiry keeps the local
                -- one rather than blanking it out.
                expires_at = CASE
                    WHEN EXCLUDED.tier = 'long' OR memories.tier = 'long' THEN NULL
                    ELSE COALESCE(EXCLUDED.expires_at, memories.expires_at)
                END,
                metadata = CASE
                    WHEN EXCLUDED.updated_at > memories.updated_at
                         OR (EXCLUDED.updated_at = memories.updated_at
                             AND EXCLUDED.id > memories.id) THEN
                        CASE
                            WHEN memories.metadata ? 'agent_id'
                                THEN jsonb_set(
                                    EXCLUDED.metadata,
                                    '{agent_id}',
                                    memories.metadata -> 'agent_id'
                                )
                            ELSE EXCLUDED.metadata
                        END
                    ELSE memories.metadata
                END,
                -- v0.7.0 Task 1/8 — recursion depth takes max so the reflection
                -- signal isn't lost on newer-wins federation merges.
                reflection_depth = GREATEST(memories.reflection_depth, EXCLUDED.reflection_depth),
                -- L1-1 — kind is sticky across federation merges.
                -- #1631 / QW-2 — Persona is also sticky (sqlite parity).
                memory_kind = CASE WHEN memories.memory_kind = 'reflection' THEN 'reflection'
                                   WHEN memories.memory_kind = 'persona' THEN 'persona'
                                   ELSE EXCLUDED.memory_kind END,
                -- #1029 / #1631 — Form-4 provenance + Form-5 calibration:
                -- newer-wins WITH the id tiebreak; source_uri / source_span
                -- follow COALESCE so a merge lacking provenance does not
                -- blank out a value the local row already had (sqlite
                -- parity, src/storage/mod.rs:7376-7395).
                citations = CASE
                    WHEN EXCLUDED.updated_at > memories.updated_at
                         OR (EXCLUDED.updated_at = memories.updated_at
                             AND EXCLUDED.id > memories.id)
                        THEN EXCLUDED.citations
                    ELSE memories.citations
                END,
                source_uri = COALESCE(EXCLUDED.source_uri, memories.source_uri),
                source_span = COALESCE(EXCLUDED.source_span, memories.source_span),
                confidence_source = CASE
                    WHEN EXCLUDED.updated_at > memories.updated_at
                         OR (EXCLUDED.updated_at = memories.updated_at
                             AND EXCLUDED.id > memories.id)
                        THEN EXCLUDED.confidence_source
                    ELSE memories.confidence_source
                END,
                confidence_signals = CASE
                    WHEN EXCLUDED.updated_at > memories.updated_at
                         OR (EXCLUDED.updated_at = memories.updated_at
                             AND EXCLUDED.id > memories.id)
                        THEN EXCLUDED.confidence_signals
                    ELSE memories.confidence_signals
                END,
                confidence_decayed_at = CASE
                    WHEN EXCLUDED.updated_at > memories.updated_at
                         OR (EXCLUDED.updated_at = memories.updated_at
                             AND EXCLUDED.id > memories.id)
                        THEN EXCLUDED.confidence_decayed_at
                    ELSE memories.confidence_decayed_at
                END,
                -- #1631 / QW-2 — entity_id + persona_version are immutable
                -- once set (sqlite COALESCE order: old wins) so a federation
                -- merge can't drop the persona discriminator off a
                -- `memory_kind = 'persona'` row.
                entity_id = COALESCE(memories.entity_id, EXCLUDED.entity_id),
                persona_version = COALESCE(memories.persona_version, EXCLUDED.persona_version),
                -- version IS replicated state (#1029 contract, decide-once):
                -- advance to MAX so an out-of-order federation push doesn't
                -- roll a peer back to a stale version.
                version = GREATEST(memories.version, EXCLUDED.version),
                -- #1383 — newer-wins for the denormalised attribution
                -- column. Matches the metadata / citations / etc.
                -- merge shape above (a newer remote write that drops
                -- the attribution shouldn't clobber the local one;
                -- a newer remote write that ADDS one replaces it).
                mentioned_entity_id = CASE
                    WHEN EXCLUDED.updated_at > memories.updated_at
                         OR (EXCLUDED.updated_at = memories.updated_at
                             AND EXCLUDED.id > memories.id)
                        THEN COALESCE(EXCLUDED.mentioned_entity_id, memories.mentioned_entity_id)
                    ELSE memories.mentioned_entity_id
                END
            RETURNING id",
        )
        .bind(&memory.id)
        .bind(memory.tier.as_str())
        .bind(&memory.namespace)
        .bind(&memory.title)
        .bind(&memory.content)
        .bind(&tags_json)
        .bind(memory.priority)
        .bind(memory.confidence)
        .bind(&memory.source)
        .bind(memory.access_count)
        .bind(created_at)
        .bind(updated_at)
        .bind(last_accessed_at)
        .bind(expires_at)
        .bind(&memory.metadata)
        .bind(memory.reflection_depth)
        .bind(memory.memory_kind.as_str())
        .bind(&citations_json)
        .bind(memory.source_uri.as_ref())
        .bind(source_span_json.as_deref())
        .bind(memory.confidence_source.as_str())
        .bind(confidence_signals_json.as_deref())
        .bind(confidence_decayed_at)
        .bind(memory.entity_id.as_ref())
        .bind(memory.persona_version)
        .bind(memory.version)
        .bind(mentioned_entity_id.as_deref())
        .fetch_one(&self.pool)
        .await
        .map_err(|e| to_store_err("apply_remote_memory upsert", e))?;

        row.try_get::<String, _>("id")
            .map_err(|e| to_store_err(READ_RETURNED_ID, e))
    }

    async fn apply_remote_link(
        &self,
        _ctx: &CallerContext,
        link: &MemoryLink,
        attest_level: &str,
    ) -> StoreResult<()> {
        // Mirrors sqlite db::create_link_inbound. The unique
        // (source_id, target_id, relation) index makes duplicate
        // pushes a no-op (ON CONFLICT DO NOTHING), so retries and
        // peer-to-peer fanouts converge cleanly.
        let created_at = parse_rfc3339_required(&link.created_at)?;
        let valid_from = parse_rfc3339_opt(link.valid_from.as_deref());
        let valid_until = parse_rfc3339_opt(link.valid_until.as_deref());

        // v0.7.0.1 G4 — federation replay must keep the AGE
        // projection in sync with the SQL `memory_links` table the
        // same way the local-write path does. A single transaction
        // lets the SQL row + AGE MERGE commit atomically.
        let mut tx = self
            .pool
            .begin()
            .await
            .map_err(|e| to_store_err("begin apply_remote_link tx", e))?;

        sqlx::query(
            "INSERT INTO memory_links (
                source_id, target_id, relation, created_at,
                valid_from, valid_until, observed_by, signature, attest_level
            ) VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9)
            ON CONFLICT (source_id, target_id, relation) DO NOTHING",
        )
        .bind(&link.source_id)
        .bind(&link.target_id)
        .bind(link.relation.as_str())
        .bind(created_at)
        .bind(valid_from)
        .bind(valid_until)
        .bind(link.observed_by.as_ref())
        .bind(link.signature.as_ref())
        .bind(attest_level)
        .execute(&mut *tx)
        .await
        .map_err(|e| to_store_err("apply_remote_link", e))?;

        if matches!(self.kg_backend, KgBackend::Age) {
            // #1542 — same SAVEPOINT isolation + warn-on-runtime-failure
            // semantics as `link_internal`. Pre-#1542 this site
            // propagated the projection error with `?` AFTER the
            // relational INSERT had been queued in the tx, so a
            // fleet-wide `LOAD 'age'` refusal made every federated
            // link replay fail forever (DLQ churn) even though the
            // canonical row could have landed. The relational
            // `memory_links` row is the source of truth; the AGE
            // mirror degrades to the CTE fallback.
            sqlx::query("SAVEPOINT age_link_projection")
                .execute(&mut *tx)
                .await
                .map_err(|e| to_store_err("savepoint age_link_projection", e))?;
            match project_link_into_age(
                &mut tx,
                &link.source_id,
                &link.target_id,
                link.relation.as_str(),
            )
            .await
            {
                Ok(()) => {
                    sqlx::query("RELEASE SAVEPOINT age_link_projection")
                        .execute(&mut *tx)
                        .await
                        .map_err(|e| to_store_err("release savepoint age_link_projection", e))?;
                }
                Err(e) if is_age_runtime_failure(&e) => {
                    sqlx::query("ROLLBACK TO SAVEPOINT age_link_projection")
                        .execute(&mut *tx)
                        .await
                        .map_err(|e2| to_store_err("rollback savepoint age_link_projection", e2))?;
                    warn_age_fallback("apply_remote_link", &link.source_id, &e);
                }
                Err(e) => return Err(e),
            }
        }

        tx.commit()
            .await
            .map_err(|e| to_store_err("commit apply_remote_link tx", e))?;
        Ok(())
    }

    async fn apply_remote_deletion(&self, _ctx: &CallerContext, id: &str) -> StoreResult<bool> {
        let rows_affected = sqlx::query(SQL_DELETE_MEMORY_BY_ID)
            .bind(id)
            .execute(&self.pool)
            .await
            .map_err(|e| to_store_err("apply_remote_deletion", e))?
            .rows_affected();
        Ok(rows_affected > 0)
    }

    // ----- v0.7.0 Wave-3 Continuation 2 — full hybrid recall ---------
    //
    // Mirrors db::recall_hybrid (sqlite path) on top of pgvector +
    // tsvector + ts_rank. The 6-factor FTS sub-score matches the
    // shape SQLite produces; the semantic component comes from
    // (1 - cosine_distance) over the `embedding` column; the adaptive
    // blend (semantic_weight 0.50→0.15 by content length) plus tier
    // decay matches sqlite byte-for-byte at the trait surface.

    async fn recall_hybrid(
        &self,
        ctx: &CallerContext,
        query: &str,
        query_embedding: Option<&[f32]>,
        filter: &Filter,
    ) -> StoreResult<Vec<(Memory, f64)>> {
        let limit_eff: i64 = if filter.limit == 0 {
            RECALL_FALLBACK_LIMIT_I64
        } else {
            i64::try_from(filter.limit.min(crate::storage::LIST_MAX_LIMIT))
                .unwrap_or(RECALL_FALLBACK_LIMIT_I64)
        };
        // Pull a wider FTS candidate pool (3x limit) so the blend has
        // material to rank, mirroring sqlite at db.rs:4757.
        let fts_pool: i64 = (limit_eff * 3).max(30);
        let tags_first: Option<&str> = filter.tags_any.first().map(String::as_str);
        // v0.7.0.1 S79 — build the OR-joined tsquery so the postgres
        // FTS pool mirrors sqlite's FTS5 OR contract. Pre-fix the
        // `plainto_tsquery` AND-joined the lemmas; multi-token
        // queries that didn't co-occur in a single row dropped to
        // the empty bucket, pulling mean Jaccard@5 below the 0.20
        // floor (HALT v0.7.0 R1 S79).
        let or_tsquery = build_or_tsquery(query);
        // #910 SAL-level scope=private gate — caller principal for the
        // visibility predicate pushed into both FTS + semantic SQL.
        // Admin paths pass NULL to bypass.
        let caller = ctx.effective_principal();
        let caller_opt: Option<&str> = if ctx.bypass_visibility {
            None
        } else {
            Some(caller)
        };
        // FTS candidates with the existing 6-factor blend baked into
        // `rank` (see search() above). Also surfaces content_len so
        // the trait-side adaptive blend can compute semantic_weight
        // per row.
        // #1579 B2 — rank + match read the stored generated `tsv`
        // column (schema v57); see search() above for the rationale.
        let fts_rows = sqlx::query(
            "SELECT *,
                    ts_rank(tsv, to_tsquery('english', $1))
                    + (priority * 0.5)
                    + (LEAST(access_count, 50) * 0.1)
                    + (confidence * 2.0)
                    + CASE tier
                          WHEN 'long' THEN 3.0
                          WHEN 'mid'  THEN 1.0
                          ELSE 0.0
                      END
                    + (1.0 / (1.0 +
                        EXTRACT(EPOCH FROM (NOW() - updated_at)) / 86400.0 * 0.1))
                      AS fts_score,
                    octet_length(content) AS content_len
             FROM memories
             WHERE tsv @@ to_tsquery('english', $1)
               AND ($2::text IS NULL OR namespace = $2)
               AND ($3::text IS NULL OR tier = $3)
               AND ($4::text IS NULL OR tags @> to_jsonb(ARRAY[$4]))
               AND ($5::text IS NULL OR metadata ->> 'agent_id' = $5)
               AND ($6::timestamptz IS NULL OR created_at >= $6)
               AND ($7::timestamptz IS NULL OR created_at <= $7)
               AND (expires_at IS NULL OR expires_at > NOW())
               AND (
                   $9::text IS NULL
                   OR COALESCE(metadata->>'scope', 'private') <> 'private'
                   OR metadata->>'agent_id' = $9
                   OR metadata->>'target_agent_id' = $9
               )
             ORDER BY fts_score DESC
             LIMIT $8",
        )
        .bind(&or_tsquery)
        .bind(filter.namespace.as_ref())
        .bind(filter.tier.as_ref().map(Tier::as_str))
        .bind(tags_first)
        .bind(filter.agent_id.as_ref().or(ctx.as_agent.as_ref()))
        .bind(filter.since)
        .bind(filter.until)
        .bind(fts_pool)
        .bind(caller_opt)
        .fetch_all(&self.pool)
        .await
        .map_err(|e| to_store_err("recall_hybrid fts pool", e))?;

        let mut max_fts: f64 = 1.0;
        let mut scored: std::collections::HashMap<String, (Memory, f64, f64, i64)> =
            std::collections::HashMap::new();
        for r in &fts_rows {
            let mem = Self::row_to_memory(r)?;
            let fts_score: f64 = r.try_get("fts_score").unwrap_or(0.0);
            let content_len: i64 = r.try_get::<i32, _>(COL_CONTENT_LEN).map_or_else(
                |_| {
                    r.try_get::<i64, _>(COL_CONTENT_LEN)
                        .unwrap_or_else(|_| i64::try_from(mem.content.len()).unwrap_or(0))
                },
                i64::from,
            );
            if fts_score > max_fts {
                max_fts = fts_score;
            }
            scored.insert(mem.id.clone(), (mem, fts_score, 0.0, content_len));
        }

        // Semantic candidates via pgvector cosine_distance. We use the
        // `<=>` operator (cosine distance) and convert to similarity as
        // `1 - distance`. The 0.2 cosine gate matches sqlite's
        // db::recall_hybrid (S18 iteration: relaxed 0.3 → 0.2 to admit
        // legitimately-related content with phrasing variance).
        if let Some(qe) = query_embedding {
            let ann_pool: i64 = (limit_eff * 5).max(50);
            let qvec = pgvector::Vector::from(qe.to_vec());
            // #910 SAL-level scope=private gate via $9.
            let sem_rows = sqlx::query(
                "SELECT *, (1.0 - (embedding <=> $1)) AS cosine_sim,
                          octet_length(content) AS content_len
                 FROM memories
                 WHERE embedding IS NOT NULL
                   AND ($2::text IS NULL OR namespace = $2)
                   AND ($3::text IS NULL OR tier = $3)
                   AND ($4::text IS NULL OR tags @> to_jsonb(ARRAY[$4]))
                   AND ($5::text IS NULL OR metadata ->> 'agent_id' = $5)
                   AND ($6::timestamptz IS NULL OR created_at >= $6)
                   AND ($7::timestamptz IS NULL OR created_at <= $7)
                   AND (expires_at IS NULL OR expires_at > NOW())
                   AND (1.0 - (embedding <=> $1)) > 0.2
                   AND (
                       $9::text IS NULL
                       OR COALESCE(metadata->>'scope', 'private') <> 'private'
                       OR metadata->>'agent_id' = $9
                   )
                 ORDER BY embedding <=> $1
                 LIMIT $8",
            )
            .bind(&qvec)
            .bind(filter.namespace.as_ref())
            .bind(filter.tier.as_ref().map(Tier::as_str))
            .bind(tags_first)
            .bind(filter.agent_id.as_ref().or(ctx.as_agent.as_ref()))
            .bind(filter.since)
            .bind(filter.until)
            .bind(ann_pool)
            .bind(caller_opt)
            .fetch_all(&self.pool)
            .await
            .map_err(|e| to_store_err("recall_hybrid semantic pool", e))?;

            for r in &sem_rows {
                let mem = Self::row_to_memory(r)?;
                let cosine: f64 = r.try_get("cosine_sim").unwrap_or(0.0);
                let content_len: i64 = r.try_get::<i32, _>(COL_CONTENT_LEN).map_or_else(
                    |_| {
                        r.try_get::<i64, _>(COL_CONTENT_LEN)
                            .unwrap_or_else(|_| i64::try_from(mem.content.len()).unwrap_or(0))
                    },
                    i64::from,
                );
                scored
                    .entry(mem.id.clone())
                    .and_modify(|entry| {
                        if cosine > entry.2 {
                            entry.2 = cosine;
                        }
                    })
                    .or_insert((mem, 0.0, cosine, content_len));
            }
        }

        // Adaptive blend: semantic_weight 0.50 (≤500 chars) → 0.15
        // (≥5000 chars). Same lerp formula as sqlite (db.rs:4990).
        let mut results: Vec<(Memory, f64)> = scored
            .into_values()
            .map(|(mem, fts_score, cosine, content_len)| {
                let norm_fts = if max_fts > 0.0 {
                    fts_score / max_fts
                } else {
                    0.0
                };
                #[allow(clippy::cast_precision_loss)]
                let cl = content_len as f64;
                let semantic_weight = if cl <= 500.0 {
                    0.50
                } else if cl >= 5000.0 {
                    0.15
                } else {
                    0.50 - 0.35 * ((cl - 500.0) / 4500.0)
                };
                let blended = semantic_weight * cosine + (1.0 - semantic_weight) * norm_fts;
                (mem, blended)
            })
            .collect();

        results.sort_by(|a, b| b.1.partial_cmp(&a.1).unwrap_or(std::cmp::Ordering::Equal));
        // Belt-and-suspenders: drop any row that slipped past the SQL
        // predicate (defense-in-depth against SQL drift). Filter then
        // truncate so the limit reflects what the caller can actually
        // see.
        if !ctx.bypass_visibility {
            results.retain(|(m, _)| is_visible_to_caller(m, caller));
        }
        results.truncate(filter.limit.max(1));
        Ok(results)
    }

    async fn pending_decide(
        &self,
        _ctx: &CallerContext,
        id: &str,
        approve: bool,
        decided_by: &str,
    ) -> StoreResult<bool> {
        let new_status = if approve { "approved" } else { "rejected" };
        let rows_affected = sqlx::query(
            "UPDATE pending_actions SET status = $1, decided_by = $2, decided_at = NOW()
             WHERE id = $3 AND status = 'pending'",
        )
        .bind(new_status)
        .bind(decided_by)
        .bind(id)
        .execute(&self.pool)
        .await
        .map_err(|e| to_store_err("pending_decide", e))?
        .rows_affected();
        Ok(rows_affected > 0)
    }

    async fn get_pending(
        &self,
        _ctx: &CallerContext,
        id: &str,
    ) -> StoreResult<Option<crate::models::PendingAction>> {
        let row = sqlx::query(
            "SELECT id, action_type, memory_id, namespace, payload, requested_by,
                    requested_at, status, decided_by, decided_at, approvals
             FROM pending_actions WHERE id = $1",
        )
        .bind(id)
        .fetch_optional(&self.pool)
        .await
        .map_err(|e| to_store_err("get_pending", e))?;
        let Some(r) = row else {
            return Ok(None);
        };
        let requested_at: DateTime<Utc> = r
            .try_get(field_names::REQUESTED_AT)
            .map_err(|e| to_store_err("read requested_at", e))?;
        let decided_at: Option<DateTime<Utc>> = r
            .try_get(field_names::DECIDED_AT)
            .map_err(|e| to_store_err("read decided_at", e))?;
        let approvals_v: serde_json::Value = r
            .try_get("approvals")
            .unwrap_or(serde_json::Value::Array(vec![]));
        let approvals: Vec<crate::models::Approval> =
            serde_json::from_value(approvals_v).unwrap_or_default();
        Ok(Some(crate::models::PendingAction {
            id: r
                .try_get::<String, _>("id")
                .map_err(|e| to_store_err("read id", e))?,
            action_type: r
                .try_get::<String, _>(field_names::ACTION_TYPE)
                .map_err(|e| to_store_err("read action_type", e))?,
            memory_id: r.try_get::<Option<String>, _>("memory_id").unwrap_or(None),
            namespace: r
                .try_get::<String, _>("namespace")
                .map_err(|e| to_store_err(READ_NAMESPACE, e))?,
            payload: r
                .try_get::<serde_json::Value, _>("payload")
                .unwrap_or(serde_json::Value::Null),
            requested_by: r
                .try_get::<String, _>(field_names::REQUESTED_BY)
                .map_err(|e| to_store_err("read requested_by", e))?,
            requested_at: requested_at.to_rfc3339(),
            status: r
                .try_get::<String, _>("status")
                .map_err(|e| to_store_err("read status", e))?,
            decided_by: r
                .try_get::<Option<String>, _>(field_names::DECIDED_BY)
                .unwrap_or(None),
            decided_at: decided_at.map(|d| d.to_rfc3339()),
            approvals,
        }))
    }

    async fn set_namespace_standard(
        &self,
        _ctx: &CallerContext,
        namespace: &str,
        standard_id: &str,
        parent: Option<&str>,
    ) -> StoreResult<()> {
        // Require the standard memory to exist first (parity with
        // sqlite db::set_namespace_standard).
        let exists: Option<(String,)> = sqlx::query_as(SQL_SELECT_MEMORY_ID_BY_ID)
            .bind(standard_id)
            .fetch_optional(&self.pool)
            .await
            .map_err(|e| to_store_err("set_namespace_standard verify memory", e))?;
        if exists.is_none() {
            return Err(StoreError::NotFound {
                id: standard_id.to_string(),
            });
        }
        if parent.is_some_and(|p| p == namespace) {
            return Err(StoreError::InvalidInput {
                detail: "namespace cannot be its own parent".to_string(),
            });
        }
        sqlx::query(
            "INSERT INTO namespace_meta (namespace, standard_id, updated_at, parent_namespace)
             VALUES ($1, $2, NOW(), $3)
             ON CONFLICT (namespace) DO UPDATE
                SET standard_id = EXCLUDED.standard_id,
                    updated_at = EXCLUDED.updated_at,
                    parent_namespace = EXCLUDED.parent_namespace",
        )
        .bind(namespace)
        .bind(standard_id)
        .bind(parent)
        .execute(&self.pool)
        .await
        .map_err(|e| to_store_err("set_namespace_standard", e))?;
        Ok(())
    }

    async fn clear_namespace_standard(
        &self,
        _ctx: &CallerContext,
        namespace: &str,
    ) -> StoreResult<bool> {
        let rows_affected = sqlx::query("DELETE FROM namespace_meta WHERE namespace = $1")
            .bind(namespace)
            .execute(&self.pool)
            .await
            .map_err(|e| to_store_err("clear_namespace_standard", e))?
            .rows_affected();
        Ok(rows_affected > 0)
    }

    async fn get_namespace_standard(
        &self,
        _ctx: &CallerContext,
        namespace: &str,
    ) -> StoreResult<Option<(String, Option<String>)>> {
        let row: Option<(String, Option<String>)> = sqlx::query_as(
            "SELECT standard_id, parent_namespace FROM namespace_meta WHERE namespace = $1",
        )
        .bind(namespace)
        .fetch_optional(&self.pool)
        .await
        .map_err(|e| to_store_err("get_namespace_standard", e))?;
        Ok(row)
    }

    async fn touch_after_recall(&self, ids: &[String]) -> StoreResult<()> {
        if ids.is_empty() {
            return Ok(());
        }
        // Touch ops (atomic): increment access_count, extend TTL
        // (1h short / 1d mid), auto-promote mid→long at 5 accesses,
        // increment priority every 10 accesses.
        //
        // Wave-2 Tier-A4 (#852) — collapsed three sequential UPDATEs
        // into a single statement with CASE expressions. The previous
        // implementation issued one prepare+execute roundtrip per
        // operation (3 prepares, 3 executes, plus an explicit
        // transaction); the single-UPDATE form removes the per-call
        // tx framing (statement-level atomicity covers it) and brings
        // the wire cost to one parse + one bind + one execute. The
        // SQL preserves the original semantics exactly:
        //
        //   * access_count = LEAST(access_count + 1, 1_000_000)
        //   * last_accessed_at = NOW()
        //   * expires_at — extension FLOOR per tier (#1607, the
        //     postgres twin of the sqlite #1596 fix):
        //     GREATEST(expires_at, NOW() + window) with 1h short /
        //     1d mid windows (cleared when a mid→long promotion
        //     fires this round). An access can extend a row's life
        //     but can never move its expiry EARLIER — the pre-#1607
        //     replacement form pulled a fresh mid-tier row's +7d
        //     create-time backstop in to now+1d on first recall.
        //   * tier — auto-promote mid → long once access_count + 1
        //     would land at or above PROMOTION_THRESHOLD (5)
        //   * updated_at — bumped only when the tier flip actually
        //     fires, matching the original two-statement contract
        //   * priority — bumped by 1 (capped at 10) every 10th
        //     touch, evaluated against the post-increment / capped
        //     access_count to remain bit-identical with the original
        //     two-statement sequence even at the 1_000_000 ceiling
        //
        // All CASE predicates read the pre-UPDATE row values per the
        // SQL standard (RHS of SET evaluates against the OLD row),
        // so the `access_count + 1` / `LEAST(...)` arithmetic
        // mirrors what the original ordered sequence saw.
        sqlx::query(
            "UPDATE memories SET
                access_count = LEAST(access_count + 1, 1000000),
                last_accessed_at = NOW(),
                expires_at = CASE
                    WHEN tier = 'mid' AND access_count + 1 >= 5 THEN NULL
                    WHEN tier = 'long' THEN expires_at
                    WHEN tier = 'short' AND expires_at IS NOT NULL
                        THEN GREATEST(expires_at, NOW() + INTERVAL '1 hour')
                    WHEN tier = 'mid' AND expires_at IS NOT NULL
                        THEN GREATEST(expires_at, NOW() + INTERVAL '1 day')
                    ELSE expires_at
                END,
                tier = CASE
                    WHEN tier = 'mid' AND access_count + 1 >= 5 THEN 'long'
                    ELSE tier
                END,
                updated_at = CASE
                    WHEN tier = 'mid' AND access_count + 1 >= 5 THEN NOW()
                    ELSE updated_at
                END,
                priority = CASE
                    WHEN LEAST(access_count + 1, 1000000) > 0
                         AND LEAST(access_count + 1, 1000000) % 10 = 0
                         AND priority < 10
                        THEN LEAST(priority + 1, 10)
                    ELSE priority
                END
             WHERE id = ANY($1)",
        )
        .bind(ids)
        .execute(&self.pool)
        .await
        .map_err(|e| to_store_err("touch_after_recall", e))?;

        // #1572 (M1 residual) — postgres parity for the sqlite
        // recall-path confidence-decay touch
        // (`src/store/sqlite.rs::touch_after_recall` →
        // `crate::confidence::decay::apply_decay_touch`). Pre-fix the
        // decay opt-in (`AI_MEMORY_CONFIDENCE_DECAY=1`) was honored on
        // the sqlite read path only; a postgres-backed daemon silently
        // never decayed. Same gate, same math
        // (`base * 2^(-age_days / half_life)`, age anchored on
        // `confidence_decayed_at` falling back to `created_at`,
        // negative age clamped to 0, result clamped to [0,1]), same
        // provenance stamps (`confidence_source = 'decayed'`, fresh
        // RFC3339 `confidence_decayed_at`), same non-version-bumping
        // contract (#1036). Set-based single UPDATE instead of the
        // sqlite per-id loop since the whole computation is
        // expressible in SQL. Failures degrade to a WARN, matching
        // the sqlite arm — decay is opportunistic, never a recall
        // failure.
        if crate::confidence::decay::decay_enabled() {
            #[allow(clippy::cast_precision_loss)]
            let secs_per_day = crate::SECS_PER_DAY as f64;
            let now_stamp = Utc::now().to_rfc3339();
            let source = crate::models::ConfidenceSource::Decayed.as_str();
            // n15 — when per-namespace half-life overrides are configured,
            // the divisor becomes a `CASE namespace ... ELSE default END`
            // so the postgres bulk path applies the SAME per-namespace
            // half-life the sqlite per-id path does (no backend drift).
            // The common case (no overrides) keeps the original simple
            // single-half-life UPDATE. QueryBuilder makes the dynamic
            // CASE injection-safe (every namespace + half-life is a bind).
            let result = if let Some(overrides) =
                crate::confidence::decay::namespace_half_life_overrides()
            {
                let mut qb = sqlx::QueryBuilder::new(
                    "UPDATE memories SET confidence = LEAST(GREATEST(confidence * POWER(2.0, -(\
                     GREATEST(EXTRACT(EPOCH FROM (NOW() - COALESCE(confidence_decayed_at::timestamptz, \
                     created_at))), 0.0) / ",
                );
                qb.push_bind(secs_per_day);
                qb.push(") / (CASE namespace");
                for (ns, hl) in overrides {
                    qb.push(" WHEN ");
                    qb.push_bind(ns.clone());
                    qb.push(" THEN ");
                    qb.push_bind(*hl);
                }
                qb.push(" ELSE ");
                qb.push_bind(crate::confidence::DEFAULT_HALF_LIFE_DAYS);
                qb.push(" END))), 0.0), 1.0), confidence_source = ");
                qb.push_bind(source);
                qb.push(", confidence_decayed_at = ");
                qb.push_bind(now_stamp.clone());
                qb.push(" WHERE id = ANY(");
                qb.push_bind(ids);
                qb.push(")");
                qb.build().execute(&self.pool).await
            } else {
                sqlx::query(
                    "UPDATE memories SET
                        confidence = LEAST(GREATEST(
                            confidence * POWER(2.0, -(
                                GREATEST(EXTRACT(EPOCH FROM
                                    (NOW() - COALESCE(confidence_decayed_at::timestamptz,
                                                      created_at))), 0.0)
                                / $2) / $3),
                            0.0), 1.0),
                        confidence_source = $4,
                        confidence_decayed_at = $5
                     WHERE id = ANY($1)",
                )
                .bind(ids)
                .bind(secs_per_day)
                .bind(crate::confidence::DEFAULT_HALF_LIFE_DAYS)
                .bind(source)
                .bind(now_stamp)
                .execute(&self.pool)
                .await
            };
            if let Err(e) = result {
                tracing::warn!(
                    target: TRACE_TARGET,
                    "confidence decay touch failed for {} memories: {e}",
                    ids.len()
                );
            }
        }

        Ok(())
    }

    async fn register_agent(
        &self,
        ctx: &CallerContext,
        agent: &AgentRegistration,
    ) -> StoreResult<()> {
        // F6 Gap 4 (v0.7.0) — agent registration parity with SQLite.
        //
        // SQLite's `db::register_agent` writes into the `memories`
        // table at namespace `_agents` with `title = "agent:<id>"` and
        // tier `Long`, preserving `registered_at` across re-registration
        // (caller-observable provenance). We mirror that here so
        // `list_agents` (which reads from the same `_agents` namespace)
        // works against either backend identically.
        //
        // Re-registration semantics: `(title, namespace)` upsert is
        // already wired at the schema level (`memories_title_ns_uidx`),
        // so re-INSERTing the same `agent:<id>` row collapses to an
        // UPDATE. We pre-read the existing `metadata.registered_at` so
        // the upsert preserves the original stamp; without that step,
        // every re-registration would reset it.
        use crate::models::AGENTS_NAMESPACE;

        let title = crate::models::agent_registration_title(&agent.agent_id);
        let now_rfc = Utc::now().to_rfc3339();

        // Preserve the original registered_at across re-registration.
        let existing: Option<(serde_json::Value,)> =
            sqlx::query_as(SQL_SELECT_METADATA_BY_NS_TITLE)
                .bind(AGENTS_NAMESPACE)
                .bind(&title)
                .fetch_optional(&self.pool)
                .await
                .map_err(|e| to_store_err("read existing agent metadata", e))?;

        let registered_at = existing
            .as_ref()
            .and_then(|(m,)| m.get(field_names::REGISTERED_AT))
            .and_then(serde_json::Value::as_str)
            .map_or_else(|| now_rfc.clone(), str::to_string);

        let metadata = serde_json::json!({
            "agent_id": agent.agent_id,
            (field_names::AGENT_TYPE): agent.agent_type,
            (field_names::CAPABILITIES): agent.capabilities,
            (field_names::REGISTERED_AT): registered_at,
            (field_names::LAST_SEEN_AT): now_rfc,
            // #910 (SAL-level enforcement) — agent-registration rows
            // are a public roster. Mirrors the sqlite path's stamp.
            "scope": crate::models::MemoryScope::Collective.as_str(),
        });

        let content =
            serde_json::to_string(&metadata).map_err(|e| StoreError::IntegrityFailed {
                detail: format!("serialize agent registration: {e}"),
            })?;

        let mem = Memory {
            id: uuid::Uuid::new_v4().to_string(),
            tier: Tier::Long,
            namespace: AGENTS_NAMESPACE.to_string(),
            title,
            content,
            tags: vec!["agent-registration".to_string()],
            priority: 5,
            confidence: 1.0,
            source: "system".to_string(),
            access_count: 0,
            created_at: now_rfc.clone(),
            updated_at: now_rfc,
            last_accessed_at: None,
            expires_at: None,
            metadata,
            reflection_depth: 0,
            memory_kind: crate::models::MemoryKind::Observation,
            entity_id: None,
            persona_version: None,
            citations: Vec::new(),
            source_uri: None,
            source_span: None,
            confidence_source: ConfidenceSource::CallerProvided,
            confidence_signals: None,
            confidence_decayed_at: None,
            version: 1,
        };

        self.store(ctx, &mem).await.map(|_| ())
    }

    async fn bind_agent_pubkey(
        &self,
        _ctx: &CallerContext,
        agent_id: &str,
        pubkey_b64: &str,
    ) -> StoreResult<()> {
        // #626 Layer-3 (Task 1.3 / C3) — parity with
        // `db::bind_agent_pubkey` on the sqlite path. Read the existing
        // `_agents` row metadata, augment it with `agent_pubkey` +
        // `pubkey_bound_at`, and write both `metadata` (jsonb) and the
        // mirrored `content` (text) so `list_agents` / the verifier
        // observe a consistent row. The agent must already be
        // registered; re-binding rotates the key.
        use crate::models::AGENTS_NAMESPACE;

        let title = crate::models::agent_registration_title(agent_id);
        let now = Utc::now().to_rfc3339();

        let existing: Option<(serde_json::Value,)> =
            sqlx::query_as(SQL_SELECT_METADATA_BY_NS_TITLE)
                .bind(AGENTS_NAMESPACE)
                .bind(&title)
                .fetch_optional(&self.pool)
                .await
                .map_err(|e| to_store_err("read agent metadata for pubkey bind", e))?;

        let Some((mut meta,)) = existing else {
            return Err(StoreError::InvalidInput {
                detail: format!(
                    "cannot bind pubkey: agent '{agent_id}' is not registered (register it first)"
                ),
            });
        };

        if let Some(obj) = meta.as_object_mut() {
            obj.insert(
                field_names::AGENT_PUBKEY.to_string(),
                serde_json::Value::String(pubkey_b64.to_string()),
            );
            obj.insert(
                "pubkey_bound_at".to_string(),
                serde_json::Value::String(now.clone()),
            );
        }

        let content = serde_json::to_string(&meta).map_err(|e| StoreError::IntegrityFailed {
            detail: format!("serialize agent metadata for pubkey bind: {e}"),
        })?;

        sqlx::query(
            "UPDATE memories SET metadata = $3, content = $4, updated_at = $5::timestamptz
             WHERE namespace = $1 AND title = $2",
        )
        .bind(AGENTS_NAMESPACE)
        .bind(&title)
        .bind(&meta)
        .bind(&content)
        .bind(&now)
        .execute(&self.pool)
        .await
        .map_err(|e| to_store_err(crate::handlers::BIND_AGENT_PUBKEY_ACTION, e))?;

        Ok(())
    }

    async fn agent_pubkey(&self, agent_id: &str) -> StoreResult<Option<String>> {
        use crate::models::AGENTS_NAMESPACE;
        let title = crate::models::agent_registration_title(agent_id);
        let row: Option<(Option<String>,)> = sqlx::query_as(
            "SELECT metadata->>'agent_pubkey' FROM memories
             WHERE namespace = $1 AND title = $2",
        )
        .bind(AGENTS_NAMESPACE)
        .bind(&title)
        .fetch_optional(&self.pool)
        .await
        .map_err(|e| to_store_err(field_names::AGENT_PUBKEY, e))?;
        Ok(row.and_then(|(pk,)| pk))
    }

    async fn revoke_agent_pubkey(&self, _ctx: &CallerContext, agent_id: &str) -> StoreResult<()> {
        // #626 Layer-3 (Task 1.3 / C5) — parity with
        // `db::revoke_agent_pubkey` on the sqlite path. Strip the
        // `agent_pubkey` + `pubkey_bound_at` keys from both `metadata`
        // (jsonb) and the mirrored `content` (text), stamping a
        // `pubkey_revoked_at` marker. The agent must already be
        // registered; revoking an unbound agent is a no-op success.
        use crate::models::AGENTS_NAMESPACE;

        let title = crate::models::agent_registration_title(agent_id);
        let now = Utc::now().to_rfc3339();

        let existing: Option<(serde_json::Value,)> =
            sqlx::query_as(SQL_SELECT_METADATA_BY_NS_TITLE)
                .bind(AGENTS_NAMESPACE)
                .bind(&title)
                .fetch_optional(&self.pool)
                .await
                .map_err(|e| to_store_err("read agent metadata for pubkey revoke", e))?;

        let Some((mut meta,)) = existing else {
            return Err(StoreError::InvalidInput {
                detail: format!(
                    "cannot revoke pubkey: agent '{agent_id}' is not registered (register it first)"
                ),
            });
        };

        if let Some(obj) = meta.as_object_mut() {
            obj.remove(field_names::AGENT_PUBKEY);
            obj.remove("pubkey_bound_at");
            obj.insert(
                "pubkey_revoked_at".to_string(),
                serde_json::Value::String(now.clone()),
            );
        }

        let content = serde_json::to_string(&meta).map_err(|e| StoreError::IntegrityFailed {
            detail: format!("serialize agent metadata for pubkey revoke: {e}"),
        })?;

        sqlx::query(
            "UPDATE memories SET metadata = $3, content = $4, updated_at = $5::timestamptz
             WHERE namespace = $1 AND title = $2",
        )
        .bind(AGENTS_NAMESPACE)
        .bind(&title)
        .bind(&meta)
        .bind(&content)
        .bind(&now)
        .execute(&self.pool)
        .await
        .map_err(|e| to_store_err("revoke_agent_pubkey", e))?;

        Ok(())
    }

    // v0.7.0 Wave-3 Continuation 3 — lifecycle write paths on postgres.

    async fn forget(
        &self,
        _ctx: &CallerContext,
        namespace: Option<&str>,
        pattern: Option<&str>,
        tier: Option<&Tier>,
        archive: bool,
    ) -> StoreResult<usize> {
        if namespace.is_none() && pattern.is_none() && tier.is_none() {
            return Err(StoreError::InvalidInput {
                detail: crate::errors::msg::FORGET_FILTER_REQUIRED.to_string(),
            });
        }
        // Postgres uses ILIKE for the pattern match (no FTS5 here); the
        // sqlite path uses an FTS query. Both are case-insensitive
        // substring/token matches against title+content; we land on
        // ILIKE over title || ' ' || content so the wire contract
        // ("forget anything matching this string") is preserved.
        let tier_str = tier.map(|t| t.as_str().to_string());
        let pattern_like = pattern.map(|p| format!("%{p}%"));
        let now = chrono::Utc::now().to_rfc3339();

        if archive {
            // Insert matching rows into archived_memories before deletion.
            sqlx::query(
                "INSERT INTO archived_memories (
                    id, tier, namespace, title, content, tags, priority, confidence,
                    source, access_count, created_at, updated_at, last_accessed_at,
                    expires_at, archived_at, archive_reason, metadata,
                    embedding, embedding_dim, original_tier, original_expires_at,
                    -- #1025 (CRITICAL, 2026-05-21) — full v0.7.0 column carry.
                    reflection_depth, atomised_into, atom_of, memory_kind,
                    entity_id, persona_version, citations, source_uri, source_span,
                    confidence_source, confidence_signals, confidence_decayed_at,
                    mentioned_entity_id, version
                )
                SELECT id, tier, namespace, title, content, tags, priority, confidence,
                       source, access_count, created_at, updated_at, last_accessed_at,
                       expires_at, $4::timestamptz, 'forget', metadata,
                       embedding, embedding_dim, tier, expires_at,
                       reflection_depth, atomised_into, atom_of, memory_kind,
                       entity_id, persona_version, citations, source_uri, source_span,
                       confidence_source, confidence_signals, confidence_decayed_at,
                       mentioned_entity_id, version
                FROM memories
                WHERE ($1::text IS NULL OR namespace = $1)
                  AND ($2::text IS NULL OR tier = $2)
                  AND ($3::text IS NULL
                       OR title ILIKE $3
                       OR content ILIKE $3)
                ON CONFLICT (id) DO UPDATE SET
                    archived_at = EXCLUDED.archived_at,
                    archive_reason = EXCLUDED.archive_reason",
            )
            .bind(namespace)
            .bind(tier_str.as_deref())
            .bind(pattern_like.as_deref())
            .bind(parse_rfc3339_required(&now)?)
            .execute(&self.pool)
            .await
            .map_err(|e| to_store_err("forget archive copy", e))?;
        }

        let res = sqlx::query(
            "DELETE FROM memories
             WHERE ($1::text IS NULL OR namespace = $1)
               AND ($2::text IS NULL OR tier = $2)
               AND ($3::text IS NULL
                    OR title ILIKE $3
                    OR content ILIKE $3)",
        )
        .bind(namespace)
        .bind(tier_str.as_deref())
        .bind(pattern_like.as_deref())
        .execute(&self.pool)
        .await
        .map_err(|e| to_store_err("forget delete", e))?;

        Ok(usize::try_from(res.rows_affected()).unwrap_or(0))
    }

    async fn consolidate(
        &self,
        _ctx: &CallerContext,
        ids: &[String],
        title: &str,
        summary: &str,
        namespace: &str,
        tier: &Tier,
        source: &str,
        consolidator_agent_id: &str,
    ) -> StoreResult<String> {
        if ids.is_empty() {
            return Err(StoreError::InvalidInput {
                detail: "consolidate requires at least one source id".to_string(),
            });
        }
        let mut tx = self
            .pool
            .begin()
            .await
            .map_err(|e| to_store_err("begin consolidate tx", e))?;

        // Fetch source rows in one query, ordered by the input.
        let mut max_priority: i32 = 5;
        let mut all_tags: Vec<String> = Vec::new();
        let mut total_access: i64 = 0;
        let mut merged_metadata = serde_json::Map::new();
        let mut source_agent_ids: Vec<String> = Vec::new();

        for id in ids {
            use sqlx::Row;
            let row = sqlx::query(
                "SELECT tags, priority, access_count, metadata FROM memories WHERE id = $1",
            )
            .bind(id)
            .fetch_optional(&mut *tx)
            .await
            .map_err(|e| to_store_err("consolidate fetch source", e))?;
            let Some(row) = row else {
                return Err(StoreError::NotFound { id: id.clone() });
            };
            let priority: i32 = row.try_get("priority").unwrap_or(5);
            max_priority = max_priority.max(priority);
            let access_count: i64 = row.try_get(field_names::ACCESS_COUNT).unwrap_or(0);
            total_access = total_access.saturating_add(access_count);
            let tags_json: serde_json::Value = row.try_get("tags").unwrap_or(serde_json::json!([]));
            if let Some(arr) = tags_json.as_array() {
                for t in arr {
                    if let Some(s) = t.as_str() {
                        all_tags.push(s.to_string());
                    }
                }
            }
            let metadata: serde_json::Value =
                row.try_get("metadata").unwrap_or(serde_json::json!({}));
            if let serde_json::Value::Object(map) = metadata {
                for (k, v) in map {
                    if k == "agent_id" {
                        if let serde_json::Value::String(aid) = &v
                            && !source_agent_ids.contains(aid)
                        {
                            source_agent_ids.push(aid.clone());
                        }
                        continue;
                    }
                    merged_metadata.insert(k, v);
                }
            }
        }

        all_tags.sort();
        all_tags.dedup();

        merged_metadata.insert(
            crate::models::MemoryLinkRelation::DerivedFrom
                .as_str()
                .to_string(),
            serde_json::Value::Array(
                ids.iter()
                    .map(|id| serde_json::Value::String(id.clone()))
                    .collect(),
            ),
        );
        merged_metadata.insert(
            "agent_id".to_string(),
            serde_json::Value::String(consolidator_agent_id.to_string()),
        );
        if !source_agent_ids.is_empty() {
            merged_metadata.insert(
                "consolidated_from_agents".to_string(),
                serde_json::Value::Array(
                    source_agent_ids
                        .into_iter()
                        .map(serde_json::Value::String)
                        .collect(),
                ),
            );
        }
        let merged_metadata_value = serde_json::Value::Object(merged_metadata);

        let new_id = uuid::Uuid::new_v4().to_string();
        let now = chrono::Utc::now();
        let tags_value =
            serde_json::to_value(&all_tags).map_err(|e| StoreError::IntegrityFailed {
                detail: format!("serialize consolidated tags: {e}"),
            })?;

        // FX-C5 — substrate governance pre-write hook parity. Consolidate
        // mints a fresh memory via a raw INSERT inside this transaction
        // that bypasses `PostgresStore::store(..)` (which is where
        // ARCH-1 wired in the `consult_governance_pre_write_pg` adapter
        // at line 7001). Compose the candidate memory shape the way the
        // INSERT below will persist it and fire the hook BEFORE the
        // INSERT. A refusal short-circuits the transaction (the tx is
        // implicitly dropped on the early-return without commit, leaving
        // the substrate clean — source rows untouched).
        let now_rfc = now.to_rfc3339();
        let candidate = Memory {
            id: new_id.clone(),
            tier: tier.clone(),
            namespace: namespace.to_string(),
            title: title.to_string(),
            content: summary.to_string(),
            tags: all_tags.clone(),
            priority: max_priority,
            confidence: 1.0,
            source: source.to_string(),
            access_count: total_access,
            created_at: now_rfc.clone(),
            updated_at: now_rfc,
            last_accessed_at: None,
            expires_at: None,
            metadata: merged_metadata_value.clone(),
            reflection_depth: 0,
            memory_kind: crate::models::MemoryKind::Observation,
            entity_id: None,
            persona_version: None,
            citations: Vec::new(),
            source_uri: None,
            source_span: None,
            // #1633 — engine-pinned confidence=1.0 ⇒ honest provenance
            // is CuratorDerived (the #1242 audit-honesty invariant);
            // sqlite twin stamped the same in storage::consolidate.
            confidence_source: crate::models::ConfidenceSource::CuratorDerived,
            confidence_signals: None,
            confidence_decayed_at: None,
            version: crate::models::default_memory_version(),
        };
        consult_governance_pre_write_pg(&candidate)?;

        // Plan C R4 / R5 cert finding: the prior implementation was a plain
        // INSERT that exploded with `duplicate key value violates unique
        // constraint "memories_title_ns_uidx"` when an operator re-ran a
        // consolidate at the same (title, namespace) — common during
        // repeat cert runs against the same persistent postgres database.
        // The scenario reads `consolidated_id` out of the response, so we
        // must always return a real id; ON CONFLICT (title, namespace) DO
        // UPDATE re-uses the existing row's id and updates the content +
        // tags + metadata in place, matching the upsert contract of every
        // other insert site in this adapter. `RETURNING id` yields the
        // existing id on update so the caller sees a single canonical
        // memory at that (title, namespace).
        // #1630 (#1466 class) — consolidate mints a fresh memory via this
        // raw INSERT, so it must carry the tier-default expiry too ($11 =
        // `candidate.effective_expires_at()`); otherwise a consolidated
        // mid/short row landed NULL `expires_at` on postgres (immortal,
        // never GC-reaped) while the sqlite twin
        // (`src/storage/mod.rs::consolidate`) backfilled it. Long-tier
        // consolidations keep NULL (long has no TTL). The UPSERT branch
        // intentionally has no `expires_at` SET clause (keep the existing
        // row's expiry — same convention as `reflection_depth` below).
        let inserted_id: String = sqlx::query_scalar(
            "INSERT INTO memories (
                id, tier, namespace, title, content, tags, priority, confidence,
                source, access_count, created_at, updated_at, expires_at, metadata,
                confidence_source
            ) VALUES ($1, $2, $3, $4, $5, $6, $7, 1.0, $8, $9, $10, $10, $11, $12, $13)
            ON CONFLICT (title, namespace) DO UPDATE SET
                tier = CASE
                    WHEN tier_rank(EXCLUDED.tier) >= tier_rank(memories.tier)
                        THEN EXCLUDED.tier
                    ELSE memories.tier
                END,
                content = EXCLUDED.content,
                tags = EXCLUDED.tags,
                priority = EXCLUDED.priority,
                confidence = EXCLUDED.confidence,
                source = EXCLUDED.source,
                access_count = EXCLUDED.access_count,
                updated_at = EXCLUDED.updated_at,
                metadata = CASE
                    WHEN memories.metadata ? 'agent_id'
                        THEN jsonb_set(
                            EXCLUDED.metadata,
                            '{agent_id}',
                            memories.metadata -> 'agent_id'
                        )
                    ELSE EXCLUDED.metadata
                END
                -- reflection_depth intentionally not surfaced here: the
                -- consolidate path mints a fresh memory and the DB column
                -- DEFAULT 0 applies. The UPSERT branch preserves the
                -- existing row's reflection_depth (no SET clause = keep).
            RETURNING id",
        )
        .bind(&new_id)
        .bind(tier.as_str())
        .bind(namespace)
        .bind(title)
        .bind(summary)
        .bind(&tags_value)
        .bind(max_priority)
        .bind(source)
        .bind(total_access)
        .bind(now)
        // #1630 — tier-default expiry backfill (mid/short → created_at +
        // tier TTL; long → NULL). `candidate.created_at == now` so the
        // backfill anchors on the same instant as the $10 bind.
        .bind(parse_rfc3339_opt(
            candidate.effective_expires_at().as_deref(),
        ))
        .bind(&merged_metadata_value)
        // #1633 — $13: honest engine provenance for the pinned 1.0.
        .bind(candidate.confidence_source.as_str())
        .fetch_one(&mut *tx)
        .await
        .map_err(|e| to_store_err("consolidate upsert", e))?;
        let new_id = inserted_id;

        // Delete source rows.
        //
        // Plan C R6 cert finding: when the UPSERT branch resolves a
        // `(title, namespace)` conflict it returns the EXISTING row's
        // id (RETURNING id). Some callers (S5 cert harness) re-include
        // the prior consolidated row in `ids` — they fetched every
        // memory in the namespace and the prior consolidation result
        // is one of them. If we delete every id in `ids` indiscriminately,
        // we delete the row we just upserted into and leave the caller
        // with a 201-but-vanished memory. Skip the deletion for the
        // upserted-into row; only the genuine source rows go away.
        for id in ids {
            if id == &new_id {
                continue;
            }
            sqlx::query(SQL_DELETE_MEMORY_BY_ID)
                .bind(id)
                .execute(&mut *tx)
                .await
                .map_err(|e| to_store_err("consolidate delete source", e))?;
        }

        tx.commit()
            .await
            .map_err(|e| to_store_err("consolidate commit", e))?;
        Ok(new_id)
    }

    async fn reflect(
        &self,
        ctx: &CallerContext,
        input: &crate::storage::reflect::ReflectInput,
        signing_key: Option<&crate::identity::keypair::AgentKeypair>,
    ) -> Result<crate::storage::reflect::ReflectOutcome, crate::storage::reflect::ReflectError>
    {
        // Delegate to the fully-implemented inherent native-sqlx port
        // (validation → source load → depth → governance cap →
        // depth-exceeded signed_events audit → atomic memory + signed
        // reflects_on links). `signing_key` threads through to
        // `create_link_signed` so the edges land `self_signed`.
        let mut hooks = crate::db::ReflectHooks::empty();
        hooks.active_keypair = signing_key;
        self.reflect_with_hooks(ctx, input, &hooks).await
    }

    async fn get_reflection_origin(
        &self,
        id: &str,
    ) -> StoreResult<Option<crate::federation::reflection_bookkeeping::ReflectionOrigin>> {
        // Parity with the sqlite path: `reflection_origin` derives the
        // record from an UNSCOPED row fetch (it returns only provenance
        // metadata — peer-origin, signing agent, depth — never content),
        // so fetch the raw row directly rather than through the
        // visibility-gated `get`.
        let row = sqlx::query("SELECT * FROM memories WHERE id = $1")
            .bind(id)
            .fetch_optional(&self.pool)
            .await
            .map_err(|e| to_store_err("select for reflection_origin", e))?;
        match row {
            Some(r) => {
                let mem = Self::row_to_memory(&r)?;
                Ok(Some(
                    crate::federation::reflection_bookkeeping::reflection_origin_from_memory(&mem),
                ))
            }
            None => Ok(None),
        }
    }

    async fn list_recall_observations(
        &self,
        recall_id: Option<&str>,
        consumed: Option<bool>,
        since: Option<&str>,
        until: Option<&str>,
        limit: usize,
    ) -> StoreResult<Vec<crate::observations::Observation>> {
        use sqlx::Row;
        // Postgres twin of `crate::observations::list_observations`.
        // Dynamic filters via QueryBuilder so each predicate is a bound
        // parameter (no string interpolation of caller input).
        let mut qb: sqlx::QueryBuilder<sqlx::Postgres> = sqlx::QueryBuilder::new(
            "SELECT recall_id, memory_id, retriever, rank, score, consumed, \
                    observed_at, consumed_at, consumed_by_memory_id \
               FROM recall_observations WHERE TRUE",
        );
        if let Some(rid) = recall_id {
            qb.push(" AND recall_id = ").push_bind(rid.to_string());
        }
        if let Some(c) = consumed {
            qb.push(" AND consumed = ").push_bind(c);
        }
        if let Some(s) = since {
            qb.push(" AND observed_at >= ").push_bind(s.to_string());
        }
        if let Some(u) = until {
            qb.push(" AND observed_at <= ").push_bind(u.to_string());
        }
        let lim_i64 = i64::try_from(limit).unwrap_or(i64::MAX);
        qb.push(" ORDER BY observed_at DESC LIMIT ")
            .push_bind(lim_i64);
        let rows = qb
            .build()
            .fetch_all(&self.pool)
            .await
            .map_err(|e| to_store_err("list_recall_observations", e))?;
        let mut out = Vec::with_capacity(rows.len());
        for r in &rows {
            let observed_at: chrono::DateTime<chrono::Utc> = r
                .try_get("observed_at")
                .map_err(|e| to_store_err("obs.observed_at", e))?;
            let consumed_at: Option<chrono::DateTime<chrono::Utc>> = r
                .try_get("consumed_at")
                .map_err(|e| to_store_err("obs.consumed_at", e))?;
            out.push(crate::observations::Observation {
                recall_id: r
                    .try_get("recall_id")
                    .map_err(|e| to_store_err("obs.recall_id", e))?,
                memory_id: r
                    .try_get("memory_id")
                    .map_err(|e| to_store_err("obs.memory_id", e))?,
                retriever: r
                    .try_get("retriever")
                    .map_err(|e| to_store_err("obs.retriever", e))?,
                rank: r.try_get("rank").map_err(|e| to_store_err("obs.rank", e))?,
                score: r
                    .try_get("score")
                    .map_err(|e| to_store_err("obs.score", e))?,
                consumed: r
                    .try_get("consumed")
                    .map_err(|e| to_store_err("obs.consumed", e))?,
                observed_at: observed_at.to_rfc3339(),
                consumed_at: consumed_at.map(|t| t.to_rfc3339()),
                consumed_by_memory_id: r.try_get("consumed_by_memory_id").ok(),
            });
        }
        Ok(out)
    }

    async fn run_gc(&self, archive: bool) -> StoreResult<usize> {
        // #1026 (CRITICAL, 2026-05-21): wrap archive-INSERT + live-DELETE
        // in a single transaction. Pre-#1026 each statement auto-committed
        // on the unwrapped pool — a crash, statement_timeout, or pool
        // checkout failure between them could leave rows in BOTH tables
        // (or rows archive-copied with stale data on later re-run since
        // ON CONFLICT DO UPDATE clobbers archived_at/archive_reason).
        // Pinned by `tests/store_parity_gaps.rs::run_gc_is_transactional_1026`
        // (crash-injection: drop tx mid-flow, assert no orphans).
        let now = chrono::Utc::now();
        let mut tx = self
            .pool
            .begin()
            .await
            .map_err(|e| to_store_err("gc begin tx", e))?;

        if archive {
            sqlx::query(
                "INSERT INTO archived_memories (
                    id, tier, namespace, title, content, tags, priority, confidence,
                    source, access_count, created_at, updated_at, last_accessed_at,
                    expires_at, archived_at, archive_reason, metadata,
                    embedding, embedding_dim, original_tier, original_expires_at,
                    -- #1025 (CRITICAL, 2026-05-21) — full v0.7.0 column carry.
                    reflection_depth, atomised_into, atom_of, memory_kind,
                    entity_id, persona_version, citations, source_uri, source_span,
                    confidence_source, confidence_signals, confidence_decayed_at,
                    mentioned_entity_id, version
                )
                SELECT id, tier, namespace, title, content, tags, priority, confidence,
                       source, access_count, created_at, updated_at, last_accessed_at,
                       expires_at, $1::timestamptz, 'ttl_expired', metadata,
                       embedding, embedding_dim, tier, expires_at,
                       reflection_depth, atomised_into, atom_of, memory_kind,
                       entity_id, persona_version, citations, source_uri, source_span,
                       confidence_source, confidence_signals, confidence_decayed_at,
                       mentioned_entity_id, version
                FROM memories
                WHERE expires_at IS NOT NULL AND expires_at < $1
                ON CONFLICT (id) DO UPDATE SET
                    archived_at = EXCLUDED.archived_at,
                    archive_reason = EXCLUDED.archive_reason",
            )
            .bind(now)
            .execute(&mut *tx)
            .await
            .map_err(|e| to_store_err("gc archive copy", e))?;
        }

        let res =
            sqlx::query("DELETE FROM memories WHERE expires_at IS NOT NULL AND expires_at < $1")
                .bind(now)
                .execute(&mut *tx)
                .await
                .map_err(|e| to_store_err("gc delete", e))?;

        tx.commit()
            .await
            .map_err(|e| to_store_err("gc commit", e))?;

        // Best-effort cleanup of namespace_meta dangling references.
        let _ = sqlx::query(
            "DELETE FROM namespace_meta \
             WHERE standard_id NOT IN (SELECT id FROM memories)",
        )
        .execute(&self.pool)
        .await;

        Ok(usize::try_from(res.rows_affected()).unwrap_or(0))
    }

    async fn archive_restore(&self, _ctx: &CallerContext, id: &str) -> StoreResult<bool> {
        let mut tx = self
            .pool
            .begin()
            .await
            .map_err(|e| to_store_err("begin archive_restore tx", e))?;

        let exists: Option<(String,)> =
            sqlx::query_as("SELECT id FROM archived_memories WHERE id = $1")
                .bind(id)
                .fetch_optional(&mut *tx)
                .await
                .map_err(|e| to_store_err("archive_restore lookup", e))?;
        if exists.is_none() {
            return Ok(false);
        }

        // Reject if the id is already in active memories.
        let active: Option<(String,)> = sqlx::query_as(SQL_SELECT_MEMORY_ID_BY_ID)
            .bind(id)
            .fetch_optional(&mut *tx)
            .await
            .map_err(|e| to_store_err("archive_restore active lookup", e))?;
        if active.is_some() {
            return Err(StoreError::Conflict { id: id.to_string() });
        }

        // FX-C5 — substrate governance pre-write hook parity. Restoring
        // an archived row mints a fresh live row via a raw INSERT...SELECT
        // that bypasses `PostgresStore::store(..)` (which is where ARCH-1
        // wired in the `consult_governance_pre_write_pg` adapter at
        // line 7001). Without this call, an operator's signed governance
        // rule could be bypassed by restoring a row whose `(title,
        // namespace)` would otherwise be refused on a direct write.
        // Load the archived row shaped as a `Memory` and fire the hook
        // BEFORE the INSERT lands.
        let candidate = Self::load_archived_as_memory_pg(&mut *tx, id).await?;
        consult_governance_pre_write_pg(&candidate)?;

        let now = chrono::Utc::now();
        // #1025 (CRITICAL, 2026-05-21) — full v0.7.0 column carry on
        // archive→restore. Pre-#1025 the SELECT pulled only 17 columns
        // from archived_memories, so the restored row landed in
        // memories with reflection_depth=0, memory_kind='observation'
        // (the live-table DEFAULT), citations=[], version=1, etc. —
        // silent loss of provenance + persona + confidence calibration.
        // Now copies all 26 v0.7.0 fields (with COALESCE defaults for
        // pre-#1025 archived rows where the columns are NULL).
        sqlx::query(
            "INSERT INTO memories (
                id, tier, namespace, title, content, tags, priority, confidence,
                source, access_count, created_at, updated_at, last_accessed_at,
                expires_at, metadata, embedding, embedding_dim,
                reflection_depth, atomised_into, atom_of, memory_kind,
                entity_id, persona_version, citations, source_uri, source_span,
                confidence_source, confidence_signals, confidence_decayed_at,
                mentioned_entity_id, version
            )
            SELECT id, COALESCE(original_tier, 'long'), namespace, title, content,
                   tags, priority, confidence, source, access_count, created_at,
                   $1::timestamptz, last_accessed_at, original_expires_at, metadata,
                   embedding, embedding_dim,
                   COALESCE(reflection_depth, 0),
                   atomised_into,
                   atom_of,
                   COALESCE(memory_kind, 'observation'),
                   entity_id, persona_version,
                   COALESCE(citations, '[]'),
                   source_uri, source_span,
                   COALESCE(confidence_source, 'caller_provided'),
                   confidence_signals, confidence_decayed_at,
                   mentioned_entity_id,
                   COALESCE(version, 1)
            FROM archived_memories WHERE id = $2",
        )
        .bind(now)
        .bind(id)
        .execute(&mut *tx)
        .await
        .map_err(|e| to_store_err("archive_restore insert", e))?;

        sqlx::query("DELETE FROM archived_memories WHERE id = $1")
            .bind(id)
            .execute(&mut *tx)
            .await
            .map_err(|e| to_store_err("archive_restore delete", e))?;

        tx.commit()
            .await
            .map_err(|e| to_store_err("archive_restore commit", e))?;
        Ok(true)
    }

    async fn archive_purge(
        &self,
        ctx: &CallerContext,
        older_than_days: Option<i64>,
    ) -> StoreResult<usize> {
        if let Some(days) = older_than_days {
            if days < 0 {
                return Err(StoreError::InvalidInput {
                    detail: crate::errors::msg::older_than_days_negative(days),
                });
            }
        }

        // #936 (security-critical, 2026-05-20) — owner-vs-caller gate.
        // Pre-#936 the postgres branch issued an unconstrained DELETE so
        // any authenticated HTTP caller could destroy every owner's
        // archive corpus. We now constrain the DELETE to rows whose
        // `metadata.agent_id` matches the caller (with the
        // `_inbox/<target>` carve-out: rows where
        // `metadata.target_agent_id == caller` are also purgeable by
        // the inbox owner — mirrors the [`is_visible_to_caller`]
        // visibility predicate). The operator/admin surface skips
        // the gate by setting `ctx.bypass_visibility = true` via
        // [`CallerContext::for_admin`], which the SHIP cluster admin
        // role gate at `handlers::admin_role::require_admin`
        // exclusively controls.
        let caller = ctx.effective_principal();
        let bypass = ctx.bypass_visibility;

        let res = match (older_than_days, bypass) {
            // Admin path — full owner-blind purge. The route's role
            // gate ensures only admin callers can reach this branch.
            (Some(days), true) => {
                let cutoff = chrono::Utc::now() - chrono::Duration::days(days);
                sqlx::query("DELETE FROM archived_memories WHERE archived_at < $1")
                    .bind(cutoff)
                    .execute(&self.pool)
                    .await
                    .map_err(|e| to_store_err("archive_purge admin", e))?
            }
            (None, true) => sqlx::query("DELETE FROM archived_memories")
                .execute(&self.pool)
                .await
                .map_err(|e| to_store_err("archive_purge admin all", e))?,
            // Owner-scoped path — narrow to rows the caller owns
            // (`metadata.agent_id == caller` OR the inbox-target
            // carve-out `metadata.target_agent_id == caller`).
            (Some(days), false) => {
                let cutoff = chrono::Utc::now() - chrono::Duration::days(days);
                sqlx::query(
                    "DELETE FROM archived_memories \
                     WHERE archived_at < $1 \
                       AND ( \
                         (metadata->>'agent_id') = $2 OR \
                         (metadata->>'target_agent_id') = $2 \
                       )",
                )
                .bind(cutoff)
                .bind(caller)
                .execute(&self.pool)
                .await
                .map_err(|e| to_store_err("archive_purge owner", e))?
            }
            (None, false) => sqlx::query(
                "DELETE FROM archived_memories \
                 WHERE \
                   (metadata->>'agent_id') = $1 OR \
                   (metadata->>'target_agent_id') = $1",
            )
            .bind(caller)
            .execute(&self.pool)
            .await
            .map_err(|e| to_store_err("archive_purge owner all", e))?,
        };
        Ok(usize::try_from(res.rows_affected()).unwrap_or(0))
    }

    async fn archive_by_ids(
        &self,
        _ctx: &CallerContext,
        ids: &[String],
        reason: Option<&str>,
    ) -> StoreResult<usize> {
        if ids.is_empty() {
            return Ok(0);
        }
        let mut moved = 0usize;
        let now = chrono::Utc::now();
        let archive_reason = reason.unwrap_or("manual");
        let mut tx = self
            .pool
            .begin()
            .await
            .map_err(|e| to_store_err("begin archive_by_ids tx", e))?;

        for id in ids {
            // Probe existence first so we can return an accurate count.
            let exists: Option<(String,)> = sqlx::query_as(SQL_SELECT_MEMORY_ID_BY_ID)
                .bind(id)
                .fetch_optional(&mut *tx)
                .await
                .map_err(|e| to_store_err("archive_by_ids exists", e))?;
            if exists.is_none() {
                continue;
            }
            sqlx::query(
                "INSERT INTO archived_memories (
                    id, tier, namespace, title, content, tags, priority, confidence,
                    source, access_count, created_at, updated_at, last_accessed_at,
                    expires_at, archived_at, archive_reason, metadata,
                    embedding, embedding_dim, original_tier, original_expires_at,
                    -- #1025 (CRITICAL, 2026-05-21) — full v0.7.0 column carry.
                    reflection_depth, atomised_into, atom_of, memory_kind,
                    entity_id, persona_version, citations, source_uri, source_span,
                    confidence_source, confidence_signals, confidence_decayed_at,
                    mentioned_entity_id, version
                )
                SELECT id, tier, namespace, title, content, tags, priority, confidence,
                       source, access_count, created_at, updated_at, last_accessed_at,
                       expires_at, $1::timestamptz, $2::text, metadata,
                       embedding, embedding_dim, tier, expires_at,
                       reflection_depth, atomised_into, atom_of, memory_kind,
                       entity_id, persona_version, citations, source_uri, source_span,
                       confidence_source, confidence_signals, confidence_decayed_at,
                       mentioned_entity_id, version
                FROM memories WHERE id = $3
                ON CONFLICT (id) DO UPDATE SET
                    archived_at = EXCLUDED.archived_at,
                    archive_reason = EXCLUDED.archive_reason",
            )
            .bind(now)
            .bind(archive_reason)
            .bind(id)
            .execute(&mut *tx)
            .await
            .map_err(|e| to_store_err("archive_by_ids insert", e))?;
            sqlx::query(SQL_DELETE_MEMORY_BY_ID)
                .bind(id)
                .execute(&mut *tx)
                .await
                .map_err(|e| to_store_err("archive_by_ids delete", e))?;
            moved += 1;
        }

        tx.commit()
            .await
            .map_err(|e| to_store_err("archive_by_ids commit", e))?;
        Ok(moved)
    }

    async fn export_memories(&self) -> StoreResult<Vec<Memory>> {
        // Reuse the existing list path with an unbounded filter — postgres
        // adapter's `list` already projects the full Memory shape and the
        // ATOMIC_MULTI_WRITE-class semantics make a snapshot read safe.
        //
        // #955 SECURITY-medium (Track A QC sweep, 2026-05-20) — use
        // `for_admin` instead of `for_agent("export")`. The trait method
        // does not yet take a caller, and the only HTTP entry
        // (`handlers::admin::export_memories`) is already admin-gated via
        // `require_admin`; `for_admin` matches that contract by bypassing
        // the SAL #910 scope=private visibility filter so the export
        // returns the FULL corpus rather than silently dropping any row
        // whose `metadata.agent_id != "export"`. Reserved for operator
        // surfaces per the `for_admin` docs.
        let ctx = CallerContext::for_admin(crate::identity::sentinels::EXPORT_INTERNAL);
        let filter = Filter {
            limit: 100_000,
            ..Filter::default()
        };
        self.list(&ctx, &filter).await
    }

    async fn export_links(&self) -> StoreResult<Vec<MemoryLink>> {
        // Delegate to the existing `list_links` trait method (no
        // namespace filter ⇒ full graph).
        self.list_links(None).await
    }

    async fn notify(
        &self,
        ctx: &CallerContext,
        target_agent: &str,
        title: &str,
        payload: &str,
        priority: Option<i32>,
        tier: Option<&Tier>,
    ) -> StoreResult<String> {
        let now = chrono::Utc::now().to_rfc3339();
        let resolved_tier = tier.cloned().unwrap_or(Tier::Short);
        let priority = priority.unwrap_or(5);
        let metadata = serde_json::json!({
            "agent_id": &ctx.agent_id,
            (field_names::TARGET_AGENT_ID): target_agent,
            "notify": true,
        });
        let mem = Memory {
            id: uuid::Uuid::new_v4().to_string(),
            tier: resolved_tier,
            namespace: crate::inbox_namespace(target_agent),
            title: title.to_string(),
            content: payload.to_string(),
            tags: vec!["notify".to_string()],
            priority,
            confidence: 1.0,
            source: "notify".to_string(),
            access_count: 0,
            created_at: now.clone(),
            updated_at: now,
            last_accessed_at: None,
            expires_at: None,
            metadata,
            reflection_depth: 0,
            memory_kind: crate::models::MemoryKind::Observation,
            entity_id: None,
            persona_version: None,
            citations: Vec::new(),
            source_uri: None,
            source_span: None,
            confidence_source: ConfidenceSource::CallerProvided,
            confidence_signals: None,
            confidence_decayed_at: None,
            version: 1,
        };
        self.store(ctx, &mem).await
    }

    // v0.7.0 Wave-3 Continuation 3 (Phase 20) — full governance pipeline
    // on postgres: namespace inheritance walk, governance policy
    // resolution, multi-vote consensus state machine.

    async fn build_namespace_chain(&self, namespace: &str) -> StoreResult<Vec<String>> {
        // F-A2A1.2 — the governance-inheritance walk caps at
        // [`GOVERNANCE_INHERITANCE_DEPTH_CAP`] (= 5) intermediate levels per
        // the v0.7.0 spec, matching the bound the in-tx companion
        // [`build_namespace_chain_in_tx`] uses. See that helper's docstring
        // for the rationale and trade-offs.
        let mut chain: Vec<String> = Vec::new();

        if namespace == "*" {
            chain.push("*".to_string());
            return Ok(chain);
        }
        chain.push("*".to_string());

        // /-derived ancestors (root → leaf via namespace_ancestors which
        // returns most-specific-first; reverse for top-down).
        let mut hierarchy_chain: Vec<String> = crate::models::namespace_ancestors(namespace)
            .into_iter()
            .rev()
            .collect();

        // Walk explicit `namespace_meta.parent_namespace` chain above the
        // root, bounded + cycle-safe.
        if let Some(root) = hierarchy_chain.first().cloned() {
            let mut explicit_above: Vec<String> = Vec::new();
            let mut current = root;
            for _ in 0..GOVERNANCE_INHERITANCE_DEPTH_CAP {
                let row: Option<(Option<String>,)> = sqlx::query_as(
                    "SELECT parent_namespace FROM namespace_meta WHERE namespace = $1",
                )
                .bind(&current)
                .fetch_optional(&self.pool)
                .await
                .map_err(|e| to_store_err("build_namespace_chain parent lookup", e))?;
                let next = row.and_then(|(p,)| p);
                match next {
                    Some(p)
                        if p != "*"
                            && !explicit_above.contains(&p)
                            && !hierarchy_chain.contains(&p) =>
                    {
                        explicit_above.push(p.clone());
                        current = p;
                    }
                    _ => break,
                }
            }
            for p in explicit_above.into_iter().rev() {
                if !chain.contains(&p) {
                    chain.push(p);
                }
            }
        }
        // F-A2A1.2 — same `/`-derived cap as the in-tx companion. Keep the
        // most-specific GOVERNANCE_INHERITANCE_DEPTH_CAP levels so a deeply
        // nested namespace still resolves against its closest authored
        // policy without blowing the resolver's connection-hold budget.
        let drained: Vec<String> = hierarchy_chain.drain(..).collect();
        let drained_len = drained.len();
        let kept: Vec<String> = if drained_len > GOVERNANCE_INHERITANCE_DEPTH_CAP {
            drained
                .into_iter()
                .skip(drained_len - GOVERNANCE_INHERITANCE_DEPTH_CAP)
                .collect()
        } else {
            drained
        };
        for entry in kept {
            if !chain.contains(&entry) {
                chain.push(entry);
            }
        }
        Ok(chain)
    }

    async fn resolve_governance_policy(
        &self,
        namespace: &str,
    ) -> StoreResult<Option<crate::models::GovernancePolicy>> {
        // Walk leaf → root and return the most-specific policy.
        let chain = self.build_namespace_chain(namespace).await?;
        for ns in chain.into_iter().rev() {
            // Look up the standard memory.
            let row: Option<(Option<String>,)> =
                sqlx::query_as("SELECT standard_id FROM namespace_meta WHERE namespace = $1")
                    .bind(&ns)
                    .fetch_optional(&self.pool)
                    .await
                    .map_err(|e| to_store_err("resolve_governance_policy lookup", e))?;
            let Some((Some(standard_id),)) = row else {
                continue;
            };
            // Read the standard's metadata.
            //
            // #955 SECURITY-medium (Track A QC sweep, 2026-05-20) —
            // use `for_admin` instead of `for_agent("governance")`.
            // This is a substrate-internal policy read (called by
            // other trait methods that have already resolved their
            // own caller context); the standard memory is governance
            // policy that the substrate itself needs to read
            // regardless of `metadata.scope`. `for_admin` bypasses
            // the #910 visibility filter to match that contract;
            // `for_agent("governance")` would mismatch the standard's
            // owner and drop the policy row when scope=private,
            // breaking governance resolution for private namespaces.
            let ctx = CallerContext::for_admin(crate::identity::sentinels::GOVERNANCE_INTERNAL);
            let mem = match self.get(&ctx, &standard_id).await {
                Ok(m) => m,
                Err(StoreError::NotFound { .. }) => continue,
                Err(e) => return Err(e),
            };
            if let Some(Ok(p)) = crate::models::GovernancePolicy::from_metadata(&mem.metadata) {
                return Ok(Some(p));
            }
        }
        Ok(None)
    }

    async fn governance_approve_with_consensus(
        &self,
        ctx: &CallerContext,
        pending_id: &str,
        approver_agent_id: &str,
    ) -> StoreResult<super::ApproveOutcome> {
        // Load the pending row + assert state. Missing pending_id surfaces
        // as StoreError::NotFound so the HTTP layer maps it to 404 (the
        // contract the sqlite path provides via db::approve_with_approver_type's
        // ApproveOutcome::NotFound variant). Returning Rejected here would
        // collapse "missing row" into the "policy refused" 403 bucket, which
        // hides a real distinction from operators.
        let pa = self
            .get_pending(ctx, pending_id)
            .await?
            .ok_or_else(|| StoreError::NotFound {
                id: pending_id.to_string(),
            })?;
        if pa.status != "pending" {
            return Ok(super::ApproveOutcome::Rejected(format!(
                "already decided: status={}",
                pa.status
            )));
        }

        // Resolve namespace policy → approver type.
        let approver = self
            .resolve_governance_policy(&pa.namespace)
            .await?
            .map_or(crate::models::ApproverType::Human, |p| p.core.approver);

        match approver {
            crate::models::ApproverType::Human => {
                let ok = self
                    .pending_decide(ctx, pending_id, true, approver_agent_id)
                    .await?;
                if ok {
                    Ok(super::ApproveOutcome::Approved)
                } else {
                    Ok(super::ApproveOutcome::Rejected(
                        crate::errors::msg::DECISION_WRITE_FAILED.to_string(),
                    ))
                }
            }
            crate::models::ApproverType::Agent(required) => {
                if approver_agent_id != required {
                    return Ok(super::ApproveOutcome::Rejected(format!(
                        "designated approver is '{required}'; got '{approver_agent_id}'"
                    )));
                }
                let ok = self
                    .pending_decide(ctx, pending_id, true, approver_agent_id)
                    .await?;
                if ok {
                    Ok(super::ApproveOutcome::Approved)
                } else {
                    Ok(super::ApproveOutcome::Rejected(
                        crate::errors::msg::DECISION_WRITE_FAILED.to_string(),
                    ))
                }
            }
            crate::models::ApproverType::Consensus(quorum) => {
                if !self.is_registered_agent(approver_agent_id).await? {
                    return Ok(super::ApproveOutcome::Rejected(format!(
                        "consensus voter '{approver_agent_id}' is not a registered agent"
                    )));
                }
                let canonical_id = approver_agent_id.to_ascii_lowercase();
                let mut approvals = pa.approvals.clone();
                if approvals
                    .iter()
                    .any(|a| a.agent_id.eq_ignore_ascii_case(&canonical_id))
                {
                    return Ok(super::ApproveOutcome::Pending {
                        votes: approvals.len(),
                        quorum,
                    });
                }
                approvals.push(crate::models::Approval {
                    agent_id: canonical_id.clone(),
                    approved_at: chrono::Utc::now().to_rfc3339(),
                });
                let approvals_json =
                    serde_json::to_value(&approvals).map_err(|e| StoreError::IntegrityFailed {
                        detail: format!("serialize approvals: {e}"),
                    })?;
                sqlx::query(
                    "UPDATE pending_actions SET approvals = $1 \
                     WHERE id = $2 AND status = 'pending'",
                )
                .bind(&approvals_json)
                .bind(pending_id)
                .execute(&self.pool)
                .await
                .map_err(|e| to_store_err("update consensus approvals", e))?;
                let votes = approvals.len();
                if u32::try_from(votes).unwrap_or(u32::MAX) >= quorum {
                    let ok = self
                        .pending_decide(ctx, pending_id, true, &canonical_id)
                        .await?;
                    if ok {
                        return Ok(super::ApproveOutcome::Approved);
                    }
                    return Ok(super::ApproveOutcome::Rejected(
                        "decision write failed at consensus threshold".to_string(),
                    ));
                }
                Ok(super::ApproveOutcome::Pending { votes, quorum })
            }
        }
    }

    async fn execute_pending_action(
        &self,
        ctx: &CallerContext,
        pending_id: &str,
    ) -> StoreResult<Option<String>> {
        // Mirror sqlite `db::execute_pending_action`. Loads the row,
        // asserts status='approved', and applies the action via the
        // standard SAL surfaces (`store_with_embedding` for create-
        // style, `delete` for delete, `update` for promote). Idempotent
        // re-execute is the caller's responsibility.
        let pa = match self.get_pending(ctx, pending_id).await? {
            Some(p) => p,
            None => {
                return Err(StoreError::InvalidInput {
                    detail: crate::errors::msg::pending_action_not_found(pending_id),
                });
            }
        };
        if pa.status != "approved" {
            return Err(StoreError::InvalidInput {
                detail: format!("cannot execute non-approved action (status={})", pa.status),
            });
        }
        match pa.action_type.as_str() {
            "store" => {
                let mut mem: Memory = match serde_json::from_value(pa.payload.clone()) {
                    Ok(m) => m,
                    Err(e) => {
                        return Err(StoreError::IntegrityFailed {
                            detail: format!("invalid store payload: {e}"),
                        });
                    }
                };
                // Stamp fresh id + timestamps for idempotent replay.
                mem.id = uuid::Uuid::new_v4().to_string();
                let now = Utc::now().to_rfc3339();
                mem.created_at.clone_from(&now);
                mem.updated_at = now;
                mem.access_count = 0;
                let id = self.store(ctx, &mem).await?;
                Ok(Some(id))
            }
            "delete" => {
                if let Some(mid) = pa.memory_id.clone() {
                    self.delete(ctx, &mid).await?;
                    Ok(Some(mid))
                } else {
                    Ok(None)
                }
            }
            "promote" => {
                if let Some(mid) = pa.memory_id.clone() {
                    let patch = crate::store::UpdatePatch {
                        tier: Some(Tier::Long),
                        ..Default::default()
                    };
                    self.update(ctx, &mid, patch).await?;
                    Ok(Some(mid))
                } else {
                    Ok(None)
                }
            }
            other => Err(StoreError::InvalidInput {
                detail: format!("unsupported action_type: {other}"),
            }),
        }
    }

    async fn is_registered_agent(&self, agent_id: &str) -> StoreResult<bool> {
        use crate::models::AGENTS_NAMESPACE;
        let title = crate::models::agent_registration_title(agent_id);
        let row: Option<(String,)> =
            sqlx::query_as("SELECT id FROM memories WHERE namespace = $1 AND title = $2")
                .bind(AGENTS_NAMESPACE)
                .bind(&title)
                .fetch_optional(&self.pool)
                .await
                .map_err(|e| to_store_err("is_registered_agent", e))?;
        Ok(row.is_some())
    }

    async fn enforce_governance_action(
        &self,
        action: super::GovernedAction,
        namespace: &str,
        agent_id: &str,
        memory_id: Option<&str>,
        memory_owner: Option<&str>,
        payload: &serde_json::Value,
    ) -> StoreResult<crate::models::GovernanceDecision> {
        use crate::config::{
            PermissionsMode, active_permissions_mode, record_permissions_decision,
        };
        use crate::models::{GovernanceDecision, GovernanceLevel};

        let mode = active_permissions_mode();
        record_permissions_decision(mode);

        if mode == PermissionsMode::Off {
            return Ok(GovernanceDecision::Allow);
        }

        // v0.7.0 H10 — open a SERIALIZABLE-equivalent transaction up-front
        // so every policy lookup AND the conditional pending_actions
        // INSERT ride a single connection. Pre-fix, the policy resolve
        // ran on connection A while the INSERT ran on connection B —
        // under concurrent governance writes the resolve and the INSERT
        // could observe different snapshots of namespace_meta /
        // pending_actions, producing a Pending decision whose row never
        // landed in the audit table.
        //
        // The transaction wraps the same surface area the sqlite path
        // serializes under its single rusqlite connection mutex, closing
        // the race without ratcheting backend-wide isolation level.
        let mut tx = self
            .pool
            .begin()
            .await
            .map_err(|e| to_store_err("begin enforce_governance_action tx", e))?;

        // Resolve the policy via the leaf-first walk — inline here so
        // every namespace_meta + memories.metadata read shares the same
        // tx snapshot as the INSERT below.
        let chain = build_namespace_chain_in_tx(&mut tx, namespace).await?;
        let mut resolved_policy: Option<crate::models::GovernancePolicy> = None;
        for ns in chain.iter().rev() {
            let row: Option<(Option<String>,)> =
                sqlx::query_as("SELECT standard_id FROM namespace_meta WHERE namespace = $1")
                    .bind(ns)
                    .fetch_optional(&mut *tx)
                    .await
                    .map_err(|e| to_store_err("resolve_governance_policy lookup (tx)", e))?;
            let Some((Some(standard_id),)) = row else {
                continue;
            };
            let meta: Option<(serde_json::Value,)> =
                sqlx::query_as("SELECT metadata FROM memories WHERE id = $1")
                    .bind(&standard_id)
                    .fetch_optional(&mut *tx)
                    .await
                    .map_err(|e| to_store_err("read governance standard metadata", e))?;
            if let Some((m,)) = meta
                && let Some(Ok(p)) = crate::models::GovernancePolicy::from_metadata(&m)
            {
                resolved_policy = Some(p);
                break;
            }
        }
        let Some(policy) = resolved_policy else {
            // No policy in the chain → Allow. Drop the tx (no writes).
            return Ok(GovernanceDecision::Allow);
        };
        let level = match action {
            super::GovernedAction::Store => &policy.core.write,
            super::GovernedAction::Delete => &policy.core.delete,
            super::GovernedAction::Promote => &policy.core.promote,
            // v0.7.0 L1-8: Reflect is gated by require_approval_above_depth
            // in the MCP handler; conservative fallback maps to write level.
            super::GovernedAction::Reflect => &policy.core.write,
        };

        // v0.7.0 Wave-3 Continuation 4 (Bucket C / S60+S80) — resolve
        // the namespace owner via the inheritance chain. Walks leaf→root
        // under the same tx snapshot as the policy lookup above.
        let ns_owner = if matches!(action, super::GovernedAction::Store) {
            let mut found: Option<String> = None;
            for ns in chain.iter().rev() {
                let row: Option<(Option<String>,)> = sqlx::query_as(
                    "SELECT m.metadata->>'agent_id' AS agent_id \
                     FROM namespace_meta nm \
                     JOIN memories m ON m.id = nm.standard_id \
                     WHERE nm.namespace = $1",
                )
                .bind(ns)
                .fetch_optional(&mut *tx)
                .await
                .map_err(|e| to_store_err("namespace_owner chain lookup (tx)", e))?;
                if let Some((Some(o),)) = row {
                    found = Some(o);
                    break;
                }
            }
            found
        } else {
            None
        };

        // Inline is_registered_agent under the same tx — the existing
        // helper takes &self.pool; we reproduce its single-row probe.
        let registered_agent_check = if matches!(level, GovernanceLevel::Registered) {
            use crate::models::AGENTS_NAMESPACE;
            let title = crate::models::agent_registration_title(agent_id);
            let row: Option<(String,)> =
                sqlx::query_as("SELECT id FROM memories WHERE namespace = $1 AND title = $2")
                    .bind(AGENTS_NAMESPACE)
                    .bind(&title)
                    .fetch_optional(&mut *tx)
                    .await
                    .map_err(|e| to_store_err("is_registered_agent (tx)", e))?;
            row.is_some()
        } else {
            false
        };

        // Evaluate the level. Same rules as the sqlite path:
        // - Any: always allow
        // - Registered: caller must be in `_agents` namespace
        // - Owner: caller must equal `memory_owner` (delete/promote) or
        //   `namespace_owner` (store)
        // - Approve: caller is non-owner ⇒ queue pending action
        // #963 Phase 2: build the typed governance-action enum that the
        // refusal envelope carries. The SAL `super::GovernedAction` and
        // the model-layer `crate::models::GovernedAction` are distinct
        // enums (the SAL one is a backend-trait abstraction; the model
        // one is the persisted serde shape). Map here once.
        let model_action = match action {
            super::GovernedAction::Store => crate::models::GovernedAction::Store,
            super::GovernedAction::Delete => crate::models::GovernedAction::Delete,
            super::GovernedAction::Promote => crate::models::GovernedAction::Promote,
            super::GovernedAction::Reflect => crate::models::GovernedAction::Reflect,
        };
        let decision = match level {
            GovernanceLevel::Any => GovernanceDecision::Allow,
            GovernanceLevel::Registered => {
                if registered_agent_check {
                    GovernanceDecision::Allow
                } else {
                    GovernanceDecision::Deny(
                        crate::governance::GovernanceRefusal::new(
                            model_action,
                            GovernanceLevel::Registered,
                            agent_id,
                            format!(
                                "agent '{agent_id}' is not registered for namespace '{namespace}'"
                            ),
                        )
                        .with_namespace(namespace),
                    )
                }
            }
            GovernanceLevel::Owner => {
                let owner_to_compare = match action {
                    super::GovernedAction::Store => ns_owner.as_deref(),
                    _ => memory_owner,
                };
                match owner_to_compare {
                    Some(o) if o == agent_id => GovernanceDecision::Allow,
                    Some(o) => GovernanceDecision::Deny(
                        crate::governance::GovernanceRefusal::new(
                            model_action,
                            GovernanceLevel::Owner,
                            agent_id,
                            format!(
                                "owner-only namespace '{namespace}': caller '{agent_id}' is not '{o}'"
                            ),
                        )
                        .with_namespace(namespace)
                        .with_owner(o),
                    ),
                    None => GovernanceDecision::Allow,
                }
            }
            GovernanceLevel::Approve => {
                let owner_to_compare = match action {
                    super::GovernedAction::Store => ns_owner.as_deref(),
                    _ => memory_owner,
                };
                if matches!(owner_to_compare, Some(o) if o == agent_id) {
                    GovernanceDecision::Allow
                } else {
                    GovernanceDecision::Pending(String::new())
                }
            }
        };

        if mode == PermissionsMode::Advisory {
            // Drop the tx (no writes); advisory mode is read-only.
            return Ok(GovernanceDecision::Allow);
        }

        // Enforce mode — Pending queues a pending_actions row inside
        // the same tx so the audit trail is atomic with the decision.
        if let GovernanceDecision::Pending(_) = decision {
            let pending_id = uuid::Uuid::new_v4().to_string();
            let now = chrono::Utc::now();
            let action_str = match action {
                super::GovernedAction::Store => "store",
                super::GovernedAction::Delete => "delete",
                super::GovernedAction::Promote => "promote",
                // v0.7.0 L1-8: Reflect action type for pending_actions row.
                super::GovernedAction::Reflect => "reflect",
            };
            sqlx::query(
                "INSERT INTO pending_actions \
                 (id, action_type, memory_id, namespace, payload, requested_by, requested_at, status) \
                 VALUES ($1, $2, $3, $4, $5, $6, $7, 'pending')",
            )
            .bind(&pending_id)
            .bind(action_str)
            .bind(memory_id)
            .bind(namespace)
            .bind(payload)
            .bind(agent_id)
            .bind(now)
            .execute(&mut *tx)
            .await
            .map_err(|e| to_store_err("queue_pending_action (tx)", e))?;
            tx.commit()
                .await
                .map_err(|e| to_store_err("commit enforce_governance_action tx", e))?;
            return Ok(GovernanceDecision::Pending(pending_id));
        }
        // Allow / Deny: no write, but commit the (read-only) tx so the
        // connection is returned cleanly to the pool.
        tx.commit()
            .await
            .map_err(|e| to_store_err("commit enforce_governance_action tx (read-only)", e))?;
        Ok(decision)
    }

    // -----------------------------------------------------------------
    // v0.7.0 Wave-3 Continuation 6 — quota + verify-link parity.
    // -----------------------------------------------------------------

    async fn quota_status(&self, agent_id: &str) -> StoreResult<QuotaStatus> {
        // v0.7.0 #1156 — aggregate rollup across every namespace the
        // agent has written into. Auto-inserts a `_global` row when
        // the agent has no rows at all (matches SQLite parity in
        // `quotas::get_aggregate_status`).
        let now = Utc::now();
        sqlx::query(
            "INSERT INTO agent_quotas (
                agent_id, namespace,
                max_memories_per_day, max_storage_bytes, max_links_per_day,
                current_memories_today, current_storage_bytes, current_links_today,
                day_started_at, created_at, updated_at
            ) VALUES ($1, $2, $3, $4, $5, 0, 0, 0, $6, $6, $6)
            ON CONFLICT (agent_id, namespace) DO NOTHING",
        )
        .bind(agent_id)
        .bind(crate::quotas::GLOBAL_NAMESPACE)
        .bind(quota_defaults().max_memories_per_day)
        .bind(quota_defaults().max_storage_bytes)
        .bind(quota_defaults().max_links_per_day)
        .bind(now)
        .execute(&self.pool)
        .await
        .map_err(|e| to_store_err("ensure aggregate _global agent_quotas row", e))?;

        // Aggregate rollup: sum counters across every namespace.
        let row = sqlx::query(
            "SELECT
                $1::text AS agent_id,
                '_global'::text AS namespace,
                COALESCE(MAX(max_memories_per_day), 0) AS max_memories_per_day,
                COALESCE(MAX(max_storage_bytes), 0) AS max_storage_bytes,
                COALESCE(MAX(max_links_per_day), 0) AS max_links_per_day,
                COALESCE(SUM(current_memories_today), 0)::BIGINT AS current_memories_today,
                COALESCE(SUM(current_storage_bytes), 0)::BIGINT AS current_storage_bytes,
                COALESCE(SUM(current_links_today), 0)::BIGINT AS current_links_today,
                COALESCE(MIN(day_started_at), $2) AS day_started_at,
                COALESCE(MIN(created_at), $2) AS created_at,
                COALESCE(MAX(updated_at), $2) AS updated_at
             FROM agent_quotas WHERE agent_id = $1",
        )
        .bind(agent_id)
        .bind(now)
        .fetch_one(&self.pool)
        .await
        .map_err(|e| to_store_err("read aggregate agent_quotas row", e))?;

        row_to_quota_status(&row)
    }

    async fn quota_status_ns(&self, agent_id: &str, namespace: &str) -> StoreResult<QuotaStatus> {
        // v0.7.0 #1156 — per-(agent, namespace) single-row lookup.
        // Auto-inserts a default row when none exists.
        let now = Utc::now();
        sqlx::query(
            "INSERT INTO agent_quotas (
                agent_id, namespace,
                max_memories_per_day, max_storage_bytes, max_links_per_day,
                current_memories_today, current_storage_bytes, current_links_today,
                day_started_at, created_at, updated_at
            ) VALUES ($1, $2, $3, $4, $5, 0, 0, 0, $6, $6, $6)
            ON CONFLICT (agent_id, namespace) DO NOTHING",
        )
        .bind(agent_id)
        .bind(namespace)
        .bind(quota_defaults().max_memories_per_day)
        .bind(quota_defaults().max_storage_bytes)
        .bind(quota_defaults().max_links_per_day)
        .bind(now)
        .execute(&self.pool)
        .await
        .map_err(|e| to_store_err("ensure (agent, namespace) agent_quotas row", e))?;

        let row = sqlx::query(
            "SELECT agent_id, namespace,
                    max_memories_per_day, max_storage_bytes, max_links_per_day,
                    current_memories_today, current_storage_bytes, current_links_today,
                    day_started_at, created_at, updated_at
             FROM agent_quotas WHERE agent_id = $1 AND namespace = $2",
        )
        .bind(agent_id)
        .bind(namespace)
        .fetch_one(&self.pool)
        .await
        .map_err(|e| to_store_err("read (agent, namespace) agent_quotas row", e))?;

        row_to_quota_status(&row)
    }

    async fn quota_status_list(&self) -> StoreResult<Vec<QuotaStatus>> {
        let rows = sqlx::query(
            "SELECT agent_id, namespace,
                    max_memories_per_day, max_storage_bytes, max_links_per_day,
                    current_memories_today, current_storage_bytes, current_links_today,
                    day_started_at, created_at, updated_at
             FROM agent_quotas ORDER BY agent_id ASC, namespace ASC",
        )
        .fetch_all(&self.pool)
        .await
        .map_err(|e| to_store_err("list agent_quotas rows", e))?;

        rows.iter().map(row_to_quota_status).collect()
    }

    async fn quota_status_list_ns(&self, namespace: &str) -> StoreResult<Vec<QuotaStatus>> {
        let rows = sqlx::query(
            "SELECT agent_id, namespace,
                    max_memories_per_day, max_storage_bytes, max_links_per_day,
                    current_memories_today, current_storage_bytes, current_links_today,
                    day_started_at, created_at, updated_at
             FROM agent_quotas
             WHERE namespace = $1
             ORDER BY agent_id ASC, namespace ASC",
        )
        .bind(namespace)
        .fetch_all(&self.pool)
        .await
        .map_err(|e| to_store_err("list (namespace) agent_quotas rows", e))?;

        rows.iter().map(row_to_quota_status).collect()
    }

    async fn verify_link(&self, filter: VerifyFilter) -> StoreResult<VerifyLinkReport> {
        if filter.source_id.is_none() && filter.link_id.is_none() {
            return Err(StoreError::InvalidInput {
                detail: crate::errors::msg::VERIFY_LINK_ARGS_REQUIRED.to_string(),
            });
        }
        // Resolve the (source, target?, relation?) triple identically
        // to the SQLite path so the wire shape is stable.
        let (source_id, target_id, relation_filter) = if let Some(link_id) =
            filter.link_id.as_deref()
        {
            let parts: Vec<&str> = link_id.split('|').collect();
            if parts.len() != 3 {
                return Err(StoreError::InvalidInput {
                    detail: format!(
                        "link_id must be canonical source_id|target_id|relation triple, got {link_id}"
                    ),
                });
            }
            (
                parts[0].to_string(),
                Some(parts[1].to_string()),
                Some(parts[2].to_string()),
            )
        } else {
            (filter.source_id.unwrap_or_default(), filter.target_id, None)
        };

        let row_opt = match (target_id.as_deref(), relation_filter.as_deref()) {
            (Some(t), Some(r)) => sqlx::query(
                "SELECT source_id, target_id, relation, valid_from, valid_until, \
                        observed_by, signature, attest_level
                 FROM memory_links \
                 WHERE source_id = $1 AND target_id = $2 AND relation = $3 \
                 LIMIT 1",
            )
            .bind(&source_id)
            .bind(t)
            .bind(r)
            .fetch_optional(&self.pool)
            .await
            .map_err(|e| to_store_err(CTX_VERIFY_LINK_SELECT, e))?,
            (Some(t), None) => sqlx::query(
                "SELECT source_id, target_id, relation, valid_from, valid_until, \
                        observed_by, signature, attest_level
                 FROM memory_links \
                 WHERE source_id = $1 AND target_id = $2 \
                 ORDER BY created_at ASC LIMIT 1",
            )
            .bind(&source_id)
            .bind(t)
            .fetch_optional(&self.pool)
            .await
            .map_err(|e| to_store_err(CTX_VERIFY_LINK_SELECT, e))?,
            (None, _) => sqlx::query(
                "SELECT source_id, target_id, relation, valid_from, valid_until, \
                        observed_by, signature, attest_level
                 FROM memory_links \
                 WHERE source_id = $1 \
                 ORDER BY created_at ASC LIMIT 1",
            )
            .bind(&source_id)
            .fetch_optional(&self.pool)
            .await
            .map_err(|e| to_store_err(CTX_VERIFY_LINK_SELECT, e))?,
        };

        let Some(row) = row_opt else {
            return Err(StoreError::NotFound {
                id: format!(
                    "link {source_id} -> {} {}",
                    target_id.as_deref().unwrap_or("?"),
                    relation_filter.as_deref().unwrap_or("?")
                ),
            });
        };

        let src: String = row
            .try_get("source_id")
            .map_err(|e| to_store_err(READ_SOURCE_ID, e))?;
        let tgt: String = row
            .try_get("target_id")
            .map_err(|e| to_store_err(READ_TARGET_ID, e))?;
        let rel: String = row
            .try_get("relation")
            .map_err(|e| to_store_err(READ_RELATION, e))?;
        let vf: Option<DateTime<Utc>> = row
            .try_get(field_names::VALID_FROM)
            .map_err(|e| to_store_err(READ_VALID_FROM, e))?;
        let vu: Option<DateTime<Utc>> = row
            .try_get(field_names::VALID_UNTIL)
            .map_err(|e| to_store_err(READ_VALID_UNTIL, e))?;
        let obs: Option<String> = row
            .try_get(field_names::OBSERVED_BY)
            .map_err(|e| to_store_err(READ_OBSERVED_BY, e))?;
        let sig: Option<Vec<u8>> = row
            .try_get("signature")
            .map_err(|e| to_store_err("read signature", e))?;
        let attest: Option<String> = row
            .try_get(field_names::ATTEST_LEVEL)
            .map_err(|e| to_store_err(READ_ATTEST_LEVEL, e))?;

        let attest_level =
            attest.unwrap_or_else(|| crate::models::AttestLevel::Unsigned.as_str().to_string());
        let signature_present = sig.is_some();
        let mut findings: Vec<String> = Vec::new();

        // v0.7.0.1 G3 — re-derive the canonical RFC3339 strings from
        // the microsecond-precision TIMESTAMPTZ round-trip. The sign
        // path in `link_internal` truncates to microseconds before
        // signing AND before INSERT, so the verify path's CBOR bytes
        // must come from the same precision. `to_rfc3339()` on a value
        // already truncated to µs is a no-op, so this is defensive
        // belt-and-braces — if a future writer commits a higher-
        // precision value, this normalization clamps it back to what
        // the column actually stored.
        let vf_str = vf.map(|t| truncate_to_microseconds(t).to_rfc3339());
        let vu_str = vu.map(|t| truncate_to_microseconds(t).to_rfc3339());

        let verified = if signature_present {
            let observed = obs.as_deref().unwrap_or("");
            match crate::identity::verify::lookup_peer_public_key(observed) {
                None => {
                    findings.push(format!(
                        "signature present but no enrolled public key for observed_by={observed}"
                    ));
                    false
                }
                Some(pubkey) => {
                    let signable = crate::identity::sign::SignableLink {
                        src_id: &src,
                        dst_id: &tgt,
                        relation: &rel,
                        observed_by: obs.as_deref(),
                        valid_from: vf_str.as_deref(),
                        valid_until: vu_str.as_deref(),
                    };
                    let sig_bytes = sig.as_deref().unwrap_or(&[]);
                    match crate::identity::verify::verify(&pubkey, &signable, sig_bytes) {
                        Ok(()) => true,
                        Err(e) => {
                            findings.push(crate::errors::msg::signature_verify_failed(e));
                            false
                        }
                    }
                }
            }
        } else {
            true
        };

        Ok(VerifyLinkReport {
            source_id: src,
            target_id: tgt,
            relation: rel,
            verified,
            attest_level,
            signature_present,
            observed_by: obs,
            findings,
        })
    }

    async fn find_paths(
        &self,
        ctx: &CallerContext,
        source_id: &str,
        target_id: &str,
        max_depth: Option<usize>,
        max_results: Option<usize>,
    ) -> StoreResult<Vec<Vec<String>>> {
        // Inherent `PostgresStore::find_paths` already routes AGE vs CTE
        // off `self.kg_backend`; the trait method forwards then applies
        // the #910 SAL-level visibility filter (path-traversal
        // flavour). Any path whose node set touches a scope=private
        // memory the caller does not own is dropped. Fail-closed: a
        // node that cannot be resolved drops every path that touches
        // it.
        let paths =
            PostgresStore::find_paths(self, source_id, target_id, max_depth, max_results).await?;
        if ctx.bypass_visibility {
            return Ok(paths);
        }
        let caller = ctx.effective_principal();
        let mut visible_cache: std::collections::HashMap<String, bool> =
            std::collections::HashMap::new();
        let mut filtered: Vec<Vec<String>> = Vec::with_capacity(paths.len());
        'outer: for path in paths {
            for node in &path {
                // Cache hit avoids round-trips for the diamond /
                // re-visit-node case common in graph-walks.
                let visible = if let Some(v) = visible_cache.get(node) {
                    *v
                } else {
                    let row = sqlx::query("SELECT metadata FROM memories WHERE id = $1")
                        .bind(node)
                        .fetch_optional(&self.pool)
                        .await
                        .map_err(|e| to_store_err("find_paths visibility fetch", e))?;
                    // v0.7.0 F-E3 fix (#1436): route through the
                    // canonical predicate via META_KEY_* + MemoryScope
                    // SSOTs. The string compare against
                    // `MemoryScope::Private.as_str()` preserves the
                    // pre-refactor permissive semantics (any non-private
                    // scope is visible, matching
                    // `is_visible_to_caller`). We can't call
                    // `crate::visibility::is_visible_to_caller` directly
                    // here because we only have the metadata blob (not
                    // a full Memory struct), but we route through the
                    // SAME META_KEY_* / MemoryScope::Private.as_str()
                    // SSOTs so a future rename touches one place.
                    let v = match row {
                        Some(r) => {
                            let meta: serde_json::Value = r
                                .try_get("metadata")
                                .map_err(|e| to_store_err("read metadata", e))?;
                            let scope = meta
                                .get(crate::META_KEY_SCOPE)
                                .and_then(serde_json::Value::as_str)
                                .unwrap_or(crate::models::namespace::MemoryScope::Private.as_str());
                            if scope != crate::models::namespace::MemoryScope::Private.as_str() {
                                true
                            } else {
                                let owner = meta
                                    .get(crate::META_KEY_AGENT_ID)
                                    .and_then(serde_json::Value::as_str)
                                    .unwrap_or("");
                                owner == caller
                            }
                        }
                        // Fail-closed: missing node ⇒ drop the path.
                        None => false,
                    };
                    visible_cache.insert(node.clone(), v);
                    v
                };
                if !visible {
                    continue 'outer;
                }
            }
            filtered.push(path);
        }
        Ok(filtered)
    }

    // ----- v0.7.0 ARCH-2 followup (FX-C2-batch3) read-only impls --------
    //
    // sqlx-native equivalents of the legacy `db::*` free-functions.
    // Wire shape pinned byte-for-byte against the SQLite adapter by the
    // `sqlite_postgres_parity_*` tests in this file (gated on
    // `AI_MEMORY_TEST_POSTGRES_URL`).

    async fn list_namespaces(&self) -> StoreResult<Vec<crate::models::NamespaceCount>> {
        let now_dt = Utc::now();
        let rows = sqlx::query(
            "SELECT namespace, COUNT(*)::BIGINT AS c FROM memories
             WHERE expires_at IS NULL OR expires_at > $1
             GROUP BY namespace
             ORDER BY c DESC, namespace ASC",
        )
        .bind(now_dt)
        .fetch_all(&self.pool)
        .await
        .map_err(|e| to_store_err("list_namespaces", e))?;

        rows.iter()
            .map(|r| {
                let namespace: String = r
                    .try_get::<String, _>("namespace")
                    .map_err(|e| to_store_err(READ_NAMESPACE, e))?;
                let c: i64 = r
                    .try_get::<i64, _>("c")
                    .map_err(|e| to_store_err("read count", e))?;
                Ok(crate::models::NamespaceCount {
                    namespace,
                    count: usize::try_from(c).unwrap_or(0),
                })
            })
            .collect()
    }

    async fn get_taxonomy(
        &self,
        namespace_prefix: Option<&str>,
        max_depth: usize,
        limit: usize,
    ) -> StoreResult<crate::models::Taxonomy> {
        // Mirror the SQLite adapter's clamp semantics so callers see the
        // same `truncated` behavior across backends — one shared knob,
        // not a local re-declaration that can drift.
        let effective_limit = limit.min(crate::storage::TAXONOMY_MAX_LIMIT);
        let effective_depth = max_depth.min(crate::models::MAX_NAMESPACE_DEPTH);
        let prefix = namespace_prefix.unwrap_or("");
        // #1531 L5 — escape LIKE metacharacters in the descendant
        // pattern (mirrors `taxonomy_namespaces` above and the sqlite
        // `get_taxonomy` twin) so a prefix containing a literal `%` /
        // `_` cannot over-match unrelated subtrees.
        let descendant_pattern = format!(
            "{}/%",
            prefix
                .replace('\\', "\\\\")
                .replace('%', "\\%")
                .replace('_', "\\_")
        );
        let now_dt = Utc::now();

        // Total count is computed independently of the row-walk so the
        // caller-observable `total_count` stays honest under truncation.
        let total_count: i64 = if prefix.is_empty() {
            sqlx::query_scalar(
                "SELECT COUNT(*)::BIGINT FROM memories
                 WHERE expires_at IS NULL OR expires_at > $1",
            )
            .bind(now_dt)
            .fetch_one(&self.pool)
            .await
            .map_err(|e| to_store_err("get_taxonomy total", e))?
        } else {
            sqlx::query_scalar(
                "SELECT COUNT(*)::BIGINT FROM memories
                 WHERE (expires_at IS NULL OR expires_at > $1)
                   AND (namespace = $2 OR namespace LIKE $3 ESCAPE '\\')",
            )
            .bind(now_dt)
            .bind(prefix)
            .bind(&descendant_pattern)
            .fetch_one(&self.pool)
            .await
            .map_err(|e| to_store_err("get_taxonomy prefix total", e))?
        };

        let limit_i64: i64 = i64::try_from(effective_limit).unwrap_or(i64::MAX);
        let groups: Vec<(String, i64)> = if prefix.is_empty() {
            sqlx::query_as(
                "SELECT namespace, COUNT(*)::BIGINT FROM memories
                 WHERE expires_at IS NULL OR expires_at > $1
                 GROUP BY namespace
                 ORDER BY COUNT(*) DESC, namespace ASC
                 LIMIT $2",
            )
            .bind(now_dt)
            .bind(limit_i64)
            .fetch_all(&self.pool)
            .await
            .map_err(|e| to_store_err("get_taxonomy groups", e))?
        } else {
            sqlx::query_as(
                "SELECT namespace, COUNT(*)::BIGINT FROM memories
                 WHERE (expires_at IS NULL OR expires_at > $1)
                   AND (namespace = $2 OR namespace LIKE $3 ESCAPE '\\')
                 GROUP BY namespace
                 ORDER BY COUNT(*) DESC, namespace ASC
                 LIMIT $4",
            )
            .bind(now_dt)
            .bind(prefix)
            .bind(&descendant_pattern)
            .bind(limit_i64)
            .fetch_all(&self.pool)
            .await
            .map_err(|e| to_store_err("get_taxonomy prefix groups", e))?
        };

        // Re-use the SQLite adapter's tree-folding logic; it operates
        // purely on the `(namespace, count)` rows so it's backend-blind.
        // Truncation flag mirrors SQLite: walked sum < total iff the
        // LIMIT chopped some rows out.
        let total_usize = usize::try_from(total_count).unwrap_or(0);
        let group_rows: Vec<(String, usize)> = groups
            .into_iter()
            .map(|(ns, c)| (ns, usize::try_from(c).unwrap_or(0)))
            .collect();
        let walked_count: usize = group_rows.iter().map(|(_, c)| *c).sum();
        let truncated = walked_count < total_usize;
        // `effective_limit` is referenced here for symmetry with the
        // SQLite path's clamp; the actual SQL `LIMIT` already enforces
        // it. Bind to `_` to keep clippy from flagging the unused
        // local while preserving the doc-binding for future debugging.
        let _ = effective_limit;
        Ok(crate::storage::fold_taxonomy_groups(
            prefix,
            effective_depth,
            total_usize,
            truncated,
            group_rows,
        ))
    }

    async fn list_agents(&self) -> StoreResult<Vec<AgentRegistration>> {
        use crate::models::AGENTS_NAMESPACE;
        let now_dt = Utc::now();
        let rows = sqlx::query(
            "SELECT metadata FROM memories
             WHERE namespace = $1
               AND (expires_at IS NULL OR expires_at > $2)
             ORDER BY (metadata->>'registered_at') ASC NULLS LAST",
        )
        .bind(AGENTS_NAMESPACE)
        .bind(now_dt)
        .fetch_all(&self.pool)
        .await
        .map_err(|e| to_store_err("list_agents", e))?;

        let mut agents = Vec::with_capacity(rows.len());
        for r in &rows {
            let meta: serde_json::Value = r
                .try_get::<serde_json::Value, _>("metadata")
                .map_err(|e| to_store_err("read agent metadata", e))?;
            let agent_id = meta
                .get("agent_id")
                .and_then(serde_json::Value::as_str)
                .unwrap_or_default()
                .to_string();
            let agent_type = meta
                .get(field_names::AGENT_TYPE)
                .and_then(serde_json::Value::as_str)
                .unwrap_or_default()
                .to_string();
            let capabilities: Vec<String> = meta
                .get(field_names::CAPABILITIES)
                .and_then(serde_json::Value::as_array)
                .map(|arr| {
                    arr.iter()
                        .filter_map(|v| v.as_str().map(String::from))
                        .collect()
                })
                .unwrap_or_default();
            let registered_at = meta
                .get(field_names::REGISTERED_AT)
                .and_then(serde_json::Value::as_str)
                .unwrap_or_default()
                .to_string();
            let last_seen_at = meta
                .get(field_names::LAST_SEEN_AT)
                .and_then(serde_json::Value::as_str)
                .unwrap_or_default()
                .to_string();
            agents.push(AgentRegistration {
                agent_id,
                agent_type,
                capabilities,
                registered_at,
                last_seen_at,
            });
        }
        Ok(agents)
    }

    async fn list_pending_actions(
        &self,
        status: Option<&str>,
        limit: usize,
    ) -> StoreResult<Vec<crate::models::PendingAction>> {
        let limit_i64: i64 = i64::try_from(limit).unwrap_or(i64::MAX);
        let rows = sqlx::query(
            "SELECT id, action_type, memory_id, namespace, payload, requested_by,
                    requested_at, status, decided_by, decided_at, approvals
             FROM pending_actions
             WHERE ($1::TEXT IS NULL OR status = $1)
             ORDER BY requested_at DESC
             LIMIT $2",
        )
        .bind(status)
        .bind(limit_i64)
        .fetch_all(&self.pool)
        .await
        .map_err(|e| to_store_err("list_pending_actions", e))?;

        let mut out = Vec::with_capacity(rows.len());
        for r in &rows {
            let requested_at: DateTime<Utc> = r
                .try_get(field_names::REQUESTED_AT)
                .map_err(|e| to_store_err("read requested_at", e))?;
            let decided_at: Option<DateTime<Utc>> = r
                .try_get(field_names::DECIDED_AT)
                .map_err(|e| to_store_err("read decided_at", e))?;
            let approvals_v: serde_json::Value = r
                .try_get("approvals")
                .unwrap_or(serde_json::Value::Array(vec![]));
            let approvals: Vec<crate::models::Approval> =
                serde_json::from_value(approvals_v).unwrap_or_default();
            out.push(crate::models::PendingAction {
                id: r
                    .try_get::<String, _>("id")
                    .map_err(|e| to_store_err("read id", e))?,
                action_type: r
                    .try_get::<String, _>(field_names::ACTION_TYPE)
                    .map_err(|e| to_store_err("read action_type", e))?,
                memory_id: r.try_get::<Option<String>, _>("memory_id").unwrap_or(None),
                namespace: r
                    .try_get::<String, _>("namespace")
                    .map_err(|e| to_store_err(READ_NAMESPACE, e))?,
                payload: r
                    .try_get::<serde_json::Value, _>("payload")
                    .unwrap_or(serde_json::Value::Null),
                requested_by: r
                    .try_get::<String, _>(field_names::REQUESTED_BY)
                    .map_err(|e| to_store_err("read requested_by", e))?,
                requested_at: requested_at.to_rfc3339(),
                status: r
                    .try_get::<String, _>("status")
                    .map_err(|e| to_store_err("read status", e))?,
                decided_by: r
                    .try_get::<Option<String>, _>(field_names::DECIDED_BY)
                    .unwrap_or(None),
                decided_at: decided_at.map(|d| d.to_rfc3339()),
                approvals,
            });
        }
        Ok(out)
    }

    async fn entity_get_by_alias(
        &self,
        alias: &str,
        namespace: Option<&str>,
    ) -> StoreResult<Option<crate::models::EntityRecord>> {
        use crate::models::{ENTITY_KIND, EntityRecord};
        let trimmed = alias.trim();
        if trimmed.is_empty() {
            return Ok(None);
        }

        let row = if let Some(ns) = namespace {
            sqlx::query(
                "SELECT m.id, m.title, m.namespace
                 FROM entity_aliases ea
                 JOIN memories m ON m.id = ea.entity_id
                 WHERE ea.alias = $1
                   AND m.namespace = $2
                   AND COALESCE(m.metadata->>'kind', '') = $3
                 ORDER BY m.created_at DESC
                 LIMIT 1",
            )
            .bind(trimmed)
            .bind(ns)
            .bind(ENTITY_KIND)
            .fetch_optional(&self.pool)
            .await
            .map_err(|e| to_store_err("entity_get_by_alias ns", e))?
        } else {
            sqlx::query(
                "SELECT m.id, m.title, m.namespace
                 FROM entity_aliases ea
                 JOIN memories m ON m.id = ea.entity_id
                 WHERE ea.alias = $1
                   AND COALESCE(m.metadata->>'kind', '') = $2
                 ORDER BY m.created_at DESC
                 LIMIT 1",
            )
            .bind(trimmed)
            .bind(ENTITY_KIND)
            .fetch_optional(&self.pool)
            .await
            .map_err(|e| to_store_err("entity_get_by_alias", e))?
        };

        let Some(r) = row else {
            return Ok(None);
        };
        let entity_id: String = r
            .try_get::<String, _>("id")
            .map_err(|e| to_store_err("read entity id", e))?;
        let canonical_name: String = r
            .try_get::<String, _>("title")
            .map_err(|e| to_store_err("read entity title", e))?;
        let ns_resolved: String = r
            .try_get::<String, _>("namespace")
            .map_err(|e| to_store_err("read entity namespace", e))?;

        let alias_rows =
            sqlx::query("SELECT alias FROM entity_aliases WHERE entity_id = $1 ORDER BY alias")
                .bind(&entity_id)
                .fetch_all(&self.pool)
                .await
                .map_err(|e| to_store_err("list aliases for entity", e))?;
        let aliases: Vec<String> = alias_rows
            .iter()
            .filter_map(|r| r.try_get::<String, _>("alias").ok())
            .collect();

        Ok(Some(EntityRecord {
            entity_id,
            canonical_name,
            namespace: ns_resolved,
            aliases,
        }))
    }

    async fn health_check(&self) -> StoreResult<bool> {
        // Postgres equivalent of SQLite's FTS integrity probe: a cheap
        // SELECT against the memories table plus a SELECT 1 round-trip
        // so connection-pool / network-layer failures surface.
        let _: i64 = sqlx::query_scalar("SELECT COUNT(*)::BIGINT FROM memories")
            .fetch_one(&self.pool)
            .await
            .map_err(|e| to_store_err("health_check count", e))?;
        let one: i32 = sqlx::query_scalar("SELECT 1")
            .fetch_one(&self.pool)
            .await
            .map_err(|e| to_store_err("health_check ping", e))?;
        Ok(one == 1)
    }

    async fn stats(&self) -> StoreResult<crate::models::Stats> {
        // Mirrors the SQLite adapter's `db::stats` shape; postgres has
        // no on-disk file path so `db_size_bytes` reports the size of
        // the `memories` table via pg_total_relation_size — best-effort
        // (returns 0 if the function call errors so stats stays callable
        // for least-privileged Postgres users).
        let total: i64 = sqlx::query_scalar("SELECT COUNT(*)::BIGINT FROM memories")
            .fetch_one(&self.pool)
            .await
            .map_err(|e| to_store_err("stats total", e))?;
        let total_usize = usize::try_from(total).unwrap_or(0);

        let tier_rows = sqlx::query(
            "SELECT tier, COUNT(*)::BIGINT AS c FROM memories
             GROUP BY tier ORDER BY c DESC",
        )
        .fetch_all(&self.pool)
        .await
        .map_err(|e| to_store_err("stats by_tier", e))?;
        let by_tier: Vec<crate::models::TierCount> = tier_rows
            .iter()
            .map(|r| {
                let tier: String = r
                    .try_get::<String, _>("tier")
                    .map_err(|e| to_store_err("read tier", e))?;
                let c: i64 = r
                    .try_get::<i64, _>("c")
                    .map_err(|e| to_store_err("read tier count", e))?;
                Ok(crate::models::TierCount {
                    tier,
                    count: usize::try_from(c).unwrap_or(0),
                })
            })
            .collect::<StoreResult<Vec<_>>>()?;

        let ns_rows = sqlx::query(
            "SELECT namespace, COUNT(*)::BIGINT AS c FROM memories
             GROUP BY namespace ORDER BY c DESC",
        )
        .fetch_all(&self.pool)
        .await
        .map_err(|e| to_store_err("stats by_namespace", e))?;
        let by_namespace: Vec<crate::models::NamespaceCount> = ns_rows
            .iter()
            .map(|r| {
                let namespace: String = r
                    .try_get::<String, _>("namespace")
                    .map_err(|e| to_store_err(READ_NAMESPACE, e))?;
                let c: i64 = r
                    .try_get::<i64, _>("c")
                    .map_err(|e| to_store_err("read namespace count", e))?;
                Ok(crate::models::NamespaceCount {
                    namespace,
                    count: usize::try_from(c).unwrap_or(0),
                })
            })
            .collect::<StoreResult<Vec<_>>>()?;

        let now_dt = Utc::now();
        let one_hour = now_dt + chrono::Duration::hours(1);
        let expiring_soon: i64 = sqlx::query_scalar(
            "SELECT COUNT(*)::BIGINT FROM memories
             WHERE expires_at IS NOT NULL AND expires_at > $1 AND expires_at <= $2",
        )
        .bind(now_dt)
        .bind(one_hour)
        .fetch_one(&self.pool)
        .await
        .map_err(|e| to_store_err("stats expiring_soon", e))?;

        let links_count: i64 = sqlx::query_scalar("SELECT COUNT(*)::BIGINT FROM memory_links")
            .fetch_one(&self.pool)
            .await
            .unwrap_or(0);

        // Best-effort table size — least-privileged Postgres users may
        // lack EXECUTE on pg_total_relation_size; tolerate failure so
        // the stats endpoint stays callable.
        let db_size_bytes: i64 =
            sqlx::query_scalar("SELECT COALESCE(pg_total_relation_size('memories'), 0)::BIGINT")
                .fetch_one(&self.pool)
                .await
                .unwrap_or(0);

        Ok(crate::models::Stats {
            total: total_usize,
            by_tier,
            by_namespace,
            expiring_soon: usize::try_from(expiring_soon).unwrap_or(0),
            links_count: usize::try_from(links_count).unwrap_or(0),
            db_size_bytes: u64::try_from(db_size_bytes).unwrap_or(0),
            // Dim violations + HNSW evictions are sqlite-only concepts;
            // postgres uses pgvector indexes which don't expose either.
            dim_violations: 0,
            index_evictions_total: 0,
        })
    }

    async fn find_by_title_namespace(
        &self,
        title: &str,
        namespace: &str,
    ) -> StoreResult<Option<String>> {
        // Mirror SQLite's `db::find_by_title_namespace`: project the id
        // for the first live row matching `(title, namespace)`. The
        // SAL contract is "no live row matches" → `Ok(None)`, not an
        // error — `fetch_optional` is the right primitive.
        let id: Option<String> = sqlx::query_scalar(
            "SELECT id FROM memories WHERE title = $1 AND namespace = $2 LIMIT 1",
        )
        .bind(title)
        .bind(namespace)
        .fetch_optional(&self.pool)
        .await
        .map_err(|e| to_store_err("find_by_title_namespace", e))?;
        Ok(id)
    }

    async fn next_versioned_title(&self, base_title: &str, namespace: &str) -> StoreResult<String> {
        // Byte-for-byte mirror of `db::next_versioned_title` — try the
        // base title first, then `(2)`, `(3)`, ... up to the substrate's
        // hard cap. The cap (1024) prevents pathological infinite loops
        // and matches SQLite's `MAX_VERSION_SUFFIX` exactly so the wire
        // shape stays identical across backends.
        const MAX_VERSION_SUFFIX: u32 = 1024;
        if self
            .find_by_title_namespace(base_title, namespace)
            .await?
            .is_none()
        {
            return Ok(base_title.to_string());
        }
        for n in 2..=MAX_VERSION_SUFFIX {
            let candidate = format!("{base_title} ({n})");
            if self
                .find_by_title_namespace(&candidate, namespace)
                .await?
                .is_none()
            {
                return Ok(candidate);
            }
        }
        // Match SQLite's UniqueConflict envelope; the substrate
        // exposes it as `StorageError::UniqueConflict` on that side.
        // At the SAL layer we surface it as `IntegrityFailed` because
        // `StoreError` doesn't yet carry a `UniqueConflict` variant
        // (#962 tracks the trait-side typed envelope).
        Err(StoreError::IntegrityFailed {
            detail: format!(
                "could not find a free versioned title for '{base_title}' in namespace '{namespace}' within {MAX_VERSION_SUFFIX} attempts"
            ),
        })
    }

    async fn find_contradictions(&self, title: &str, namespace: &str) -> StoreResult<Vec<Memory>> {
        // Postgres FTS via the stored generated `tsv` column (#1579 B2,
        // schema v57) + `plainto_tsquery`, mirroring the SQLite
        // `memories_fts MATCH` semantics — top 5 candidates in the
        // same namespace, ranked by relevance.
        let rows = sqlx::query(
            "SELECT m.* FROM memories m
             WHERE m.namespace = $2
               AND m.tsv @@ plainto_tsquery('english', $1)
             ORDER BY ts_rank(m.tsv, plainto_tsquery('english', $1)) DESC
             LIMIT 5",
        )
        .bind(title)
        .bind(namespace)
        .fetch_all(&self.pool)
        .await
        .map_err(|e| to_store_err("find_contradictions", e))?;

        let mut out = Vec::with_capacity(rows.len());
        for r in &rows {
            out.push(Self::row_to_memory(r)?);
        }
        Ok(out)
    }

    async fn invalidate_link(
        &self,
        source_id: &str,
        target_id: &str,
        relation: &str,
        valid_until: Option<&str>,
    ) -> StoreResult<KgInvalidateRow> {
        // Delegate to the inherent `kg_invalidate` method which carries
        // the AGE↔CTE dual-path fallback discipline. The trait method
        // is the canonical surface; `kg_invalidate_via_store` (the
        // pre-trait `as_any_for_postgres` downcast hatch) is preserved
        // for back-compat but new callers should reach via the trait.
        self.kg_invalidate(source_id, target_id, relation, valid_until)
            .await
    }

    async fn check_duplicate_with_text(
        &self,
        query_embedding: &[f32],
        query_text: &str,
        namespace: Option<&str>,
        threshold: f32,
    ) -> StoreResult<crate::models::DuplicateCheck> {
        use sha2::{Digest, Sha256};
        // Phase 1 — SHA-256 exact-match short-circuit (parity with
        // `db::check_duplicate_with_text`). Hash `format!("{title}
        // {content}")` for every live, namespace-scoped row and
        // return similarity=1.0 on byte-equal hits. This sidesteps
        // the embedding-prefix asymmetry that caps cosine at ~0.92
        // for legitimately-identical inputs.
        let effective_threshold = threshold.max(0.5_f32); // mirrors DUPLICATE_THRESHOLD_MIN
        let now_dt = Utc::now();
        let rows = if let Some(ns) = namespace {
            sqlx::query(
                "SELECT id, title, namespace, content FROM memories
                 WHERE (expires_at IS NULL OR expires_at > $1)
                   AND namespace = $2",
            )
            .bind(now_dt)
            .bind(ns)
            .fetch_all(&self.pool)
            .await
            .map_err(|e| to_store_err("check_duplicate_with_text scan", e))?
        } else {
            sqlx::query(
                "SELECT id, title, namespace, content FROM memories
                 WHERE (expires_at IS NULL OR expires_at > $1)",
            )
            .bind(now_dt)
            .fetch_all(&self.pool)
            .await
            .map_err(|e| to_store_err("check_duplicate_with_text scan", e))?
        };

        let mut query_hasher = Sha256::new();
        query_hasher.update(query_text.as_bytes());
        let query_hash = query_hasher.finalize();

        let candidates_scanned = rows.len();
        for r in &rows {
            let id: String = r.try_get("id").map_err(|e| to_store_err("read id", e))?;
            let title: String = r
                .try_get("title")
                .map_err(|e| to_store_err(READ_TITLE, e))?;
            let ns_v: String = r
                .try_get("namespace")
                .map_err(|e| to_store_err(READ_NAMESPACE, e))?;
            let content: String = r
                .try_get("content")
                .map_err(|e| to_store_err("read content", e))?;
            let row_text = crate::embeddings::embedding_document(&title, &content);
            let mut row_hasher = Sha256::new();
            row_hasher.update(row_text.as_bytes());
            let row_hash = row_hasher.finalize();
            if row_hash == query_hash {
                return Ok(crate::models::DuplicateCheck {
                    is_duplicate: true,
                    threshold: effective_threshold,
                    nearest: Some(crate::models::DuplicateMatch {
                        id,
                        title,
                        namespace: ns_v,
                        similarity: 1.0,
                    }),
                    candidates_scanned,
                });
            }
        }

        // Phase 2 — fall through to the embedding-based nearest-
        // neighbor scan via the SAL `recall_hybrid` shape so callers
        // still get a "closest existing memory" signal on near hits.
        // Empty-embedding shortcut: if no vector was supplied (caller
        // is keyword-only), report "no duplicate found".
        if query_embedding.is_empty() {
            return Ok(crate::models::DuplicateCheck {
                is_duplicate: false,
                threshold: effective_threshold,
                nearest: None,
                candidates_scanned,
            });
        }

        // Use pgvector cosine distance directly — `1 - distance` gives
        // similarity in `[0, 1]`. We mirror SQLite's `check_duplicate`
        // scan shape: live rows in `namespace` (or all live rows when
        // `namespace=None`) with a non-null embedding, ordered by
        // cosine ascending (= most similar first), limit 1.
        let emb_pgvec = pgvector::Vector::from(query_embedding.to_vec());
        let nearest_row = if let Some(ns) = namespace {
            sqlx::query(
                "SELECT id, title, namespace,
                        1 - (embedding <=> $1) AS sim
                 FROM memories
                 WHERE embedding IS NOT NULL
                   AND namespace = $2
                   AND (expires_at IS NULL OR expires_at > $3)
                 ORDER BY embedding <=> $1
                 LIMIT 1",
            )
            .bind(&emb_pgvec)
            .bind(ns)
            .bind(now_dt)
            .fetch_optional(&self.pool)
            .await
            .map_err(|e| to_store_err("check_duplicate_with_text cosine", e))?
        } else {
            sqlx::query(
                "SELECT id, title, namespace,
                        1 - (embedding <=> $1) AS sim
                 FROM memories
                 WHERE embedding IS NOT NULL
                   AND (expires_at IS NULL OR expires_at > $2)
                 ORDER BY embedding <=> $1
                 LIMIT 1",
            )
            .bind(&emb_pgvec)
            .bind(now_dt)
            .fetch_optional(&self.pool)
            .await
            .map_err(|e| to_store_err("check_duplicate_with_text cosine", e))?
        };

        let nearest = match nearest_row {
            Some(r) => {
                let id: String = r.try_get("id").map_err(|e| to_store_err("read id", e))?;
                let title: String = r
                    .try_get("title")
                    .map_err(|e| to_store_err(READ_TITLE, e))?;
                let ns_v: String = r
                    .try_get("namespace")
                    .map_err(|e| to_store_err(READ_NAMESPACE, e))?;
                let sim: f64 = r.try_get("sim").map_err(|e| to_store_err("read sim", e))?;
                #[allow(clippy::cast_possible_truncation)]
                let sim_f32 = sim as f32;
                Some(crate::models::DuplicateMatch {
                    id,
                    title,
                    namespace: ns_v,
                    similarity: sim_f32,
                })
            }
            None => None,
        };

        let is_duplicate = nearest
            .as_ref()
            .is_some_and(|n| n.similarity >= effective_threshold);

        Ok(crate::models::DuplicateCheck {
            is_duplicate,
            threshold: effective_threshold,
            nearest,
            candidates_scanned,
        })
    }

    // ------------------------------------------------------------------
    // v0.7.0 ARCH-2 FX-C2-batch5 — final 6 trait additions
    // ------------------------------------------------------------------

    /// FX-C2-batch5 — outbound knowledge-graph traversal via the SAL
    /// trait. Delegates to the inherent `kg_query_with_history` (the
    /// 3-arg variant) which itself resolves AGE vs the CTE fallback at
    /// adapter connect time.
    async fn kg_query(
        &self,
        source_id: &str,
        max_depth: usize,
        include_invalidated: bool,
    ) -> StoreResult<Vec<super::KgQueryRow>> {
        self.kg_query_with_history(source_id, max_depth, include_invalidated)
            .await
    }

    /// FX-C2-batch5 — knowledge-graph timeline scan via the SAL trait.
    /// Inlines the AGE↔CTE dispatch from the inherent
    /// `kg_timeline` so the trait method can land in this impl block
    /// without a name-collision against the inherent helper (the
    /// inherent stays in `impl PostgresStore` for external test
    /// callers that bind to the concrete type).
    async fn kg_timeline(
        &self,
        source_id: &str,
        since: Option<&str>,
        until: Option<&str>,
        limit: Option<usize>,
    ) -> StoreResult<Vec<super::KgTimelineRow>> {
        match self.kg_backend {
            KgBackend::Age => {
                match self
                    .kg_timeline_cypher(source_id, since, until, limit)
                    .await
                {
                    Ok(rows) => Ok(rows),
                    Err(err) if is_age_runtime_failure(&err) => {
                        warn_age_fallback("kg_timeline", source_id, &err);
                        self.kg_timeline_cte(source_id, since, until, limit).await
                    }
                    Err(err) => Err(err),
                }
            }
            KgBackend::Cte => self.kg_timeline_cte(source_id, since, until, limit).await,
        }
    }

    /// FX-C2-batch5 — register a knowledge-graph entity via the SAL
    /// trait. Idempotent on `(canonical_name, namespace)`. Mirrors the
    /// pre-trait handler-side path in `kg.rs::entity_register` for the
    /// postgres branch: lists prior entity row by title-eq, unions
    /// aliases, then upserts via `store_with_embedding` (preserving
    /// the SAL-canonical embedding-on-write contract). Returns the
    /// resolved [`crate::models::EntityRegistration`] so callers can
    /// drop the bespoke handler-side alias-union walk.
    async fn entity_register(
        &self,
        ctx: &CallerContext,
        canonical_name: &str,
        namespace: &str,
        aliases: &[String],
        extra_metadata: &serde_json::Value,
        agent_id: Option<&str>,
    ) -> StoreResult<crate::models::EntityRegistration> {
        use crate::models::{ConfidenceSource, ENTITY_KIND, EntityRegistration, MemoryKind, Tier};

        // Resolve effective agent_id: explicit arg wins; otherwise
        // fall back to the caller context's agent_id.
        let resolved_agent = agent_id
            .map(str::to_string)
            .unwrap_or_else(|| ctx.agent_id.clone());

        // Look up any prior entity row in this namespace via the
        // SAL `list` surface (namespace-scoped). We match by
        // (title == canonical_name) AND (metadata.kind == "entity").
        let filter = super::Filter {
            namespace: Some(namespace.to_string()),
            limit: 10_000,
            ..Default::default()
        };
        let candidates = self.list(ctx, &filter).await?;
        let prior = candidates.into_iter().find(|m| {
            m.title == canonical_name
                && m.metadata.get("kind").and_then(serde_json::Value::as_str) == Some(ENTITY_KIND)
        });

        // Detect a colliding non-entity row at (title, namespace).
        // The list-then-filter above only finds entity rows; a
        // non-entity collision lives in `find_by_title_namespace`.
        if prior.is_none() {
            if let Some(existing_id) = self
                .find_by_title_namespace(canonical_name, namespace)
                .await?
            {
                return Err(StoreError::Conflict { id: existing_id });
            }
        }

        // Union the alias sets: prior aliases first, then new
        // aliases, de-duped case-sensitively to match
        // `db::entity_register`.
        let prior_aliases: Vec<String> = prior
            .as_ref()
            .and_then(|m| {
                m.metadata
                    .get("aliases")
                    .and_then(|v| v.as_array())
                    .map(|a| {
                        a.iter()
                            .filter_map(|x| x.as_str().map(str::to_string))
                            .collect()
                    })
            })
            .unwrap_or_default();
        let mut union: Vec<String> = Vec::new();
        for a in prior_aliases.iter().chain(aliases.iter()) {
            if !a.trim().is_empty() && !union.iter().any(|x| x == a) {
                union.push(a.clone());
            }
        }

        // Build the entity memory's metadata: caller-supplied object
        // merged, kind forced to "entity", aliases set to the union,
        // agent_id preserved from the resolved caller.
        let mut metadata = match extra_metadata {
            serde_json::Value::Object(m) => serde_json::Value::Object(m.clone()),
            _ => serde_json::json!({}),
        };
        let meta_map = metadata.as_object_mut().expect("metadata is an object");
        meta_map.insert(
            "kind".to_string(),
            serde_json::Value::String(ENTITY_KIND.to_string()),
        );
        meta_map.insert("aliases".to_string(), serde_json::json!(union.clone()));
        meta_map
            .entry("agent_id".to_string())
            .or_insert(serde_json::Value::String(resolved_agent.clone()));

        let now = chrono::Utc::now().to_rfc3339();
        let resolved_id = prior
            .as_ref()
            .map(|m| m.id.clone())
            .unwrap_or_else(|| uuid::Uuid::new_v4().to_string());
        let mem = Memory {
            id: resolved_id.clone(),
            tier: Tier::Long,
            namespace: namespace.to_string(),
            title: canonical_name.to_string(),
            content: canonical_name.to_string(),
            tags: vec!["entity".to_string()],
            priority: 7,
            confidence: 1.0,
            source: "api".to_string(),
            access_count: 0,
            created_at: now.clone(),
            updated_at: now,
            last_accessed_at: None,
            expires_at: None,
            metadata,
            reflection_depth: 0,
            memory_kind: MemoryKind::Observation,
            entity_id: None,
            persona_version: None,
            citations: Vec::new(),
            source_uri: None,
            source_span: None,
            confidence_source: ConfidenceSource::CallerProvided,
            confidence_signals: None,
            confidence_decayed_at: None,
            version: 1,
        };
        let written_id = self.store(ctx, &mem).await?;
        let created = prior.is_none();

        // #1654 — populate the `entity_aliases` join table. The SAL
        // trait `entity_get_by_alias` resolves by JOINing `entity_aliases`
        // (NOT `metadata.aliases`), so without this insert a SAL-trait-
        // registered entity is never alias-resolvable. Idempotent:
        // PK (entity_id, alias) + ON CONFLICT DO NOTHING, so a re-register
        // that unions new aliases only adds the missing rows. Mirrors the
        // kg-handler `INSERT INTO entity_aliases` path so the two SAL
        // methods are consistent.
        for alias in &union {
            sqlx::query(
                "INSERT INTO entity_aliases (entity_id, alias) VALUES ($1, $2)
                 ON CONFLICT (entity_id, alias) DO NOTHING",
            )
            .bind(&written_id)
            .bind(alias)
            .execute(&self.pool)
            .await
            .map_err(|e| to_store_err("entity_register populate entity_aliases", e))?;
        }

        Ok(EntityRegistration {
            entity_id: written_id,
            canonical_name: canonical_name.to_string(),
            namespace: namespace.to_string(),
            aliases: union,
            created,
        })
    }

    /// FX-C2-batch5 — list archived memories via the SAL trait.
    /// Delegates to the inherent `list_archived_pg` (renamed from
    /// `list_archived` so the trait method can land in the
    /// `impl MemoryStore for PostgresStore` block without a name
    /// collision). External callers that previously reached for the
    /// inherent through `list_archived_via_store` continue to work
    /// because the helper now calls `list_archived_pg` under the hood.
    async fn list_archived(
        &self,
        namespace: Option<&str>,
        limit: usize,
        offset: usize,
    ) -> StoreResult<Vec<serde_json::Value>> {
        self.list_archived_pg(namespace, limit, offset).await
    }
}

/// v0.7.0 Continuation 6 — adapter row-to-`QuotaStatus` projection.
/// Lifted to a free function so both `quota_status` and
/// `quota_status_list` can reuse the same shape.
fn row_to_quota_status(row: &sqlx::postgres::PgRow) -> StoreResult<QuotaStatus> {
    let agent_id: String = row
        .try_get("agent_id")
        .map_err(|e| to_store_err("read quota agent_id", e))?;
    // v0.7.0 #1156 — namespace column added in schema v50. Tolerate
    // its absence (returns `_global` sentinel) so rollup queries that
    // synthesise columns can reuse this helper.
    let namespace: String = row
        .try_get("namespace")
        .unwrap_or_else(|_| crate::quotas::GLOBAL_NAMESPACE.to_string());
    let max_memories_per_day: i64 = row
        .try_get("max_memories_per_day")
        .map_err(|e| to_store_err("read max_memories_per_day", e))?;
    let max_storage_bytes: i64 = row
        .try_get("max_storage_bytes")
        .map_err(|e| to_store_err("read max_storage_bytes", e))?;
    let max_links_per_day: i64 = row
        .try_get("max_links_per_day")
        .map_err(|e| to_store_err("read max_links_per_day", e))?;
    let current_memories_today: i64 = row
        .try_get("current_memories_today")
        .map_err(|e| to_store_err("read current_memories_today", e))?;
    let current_storage_bytes: i64 = row
        .try_get("current_storage_bytes")
        .map_err(|e| to_store_err("read current_storage_bytes", e))?;
    let current_links_today: i64 = row
        .try_get("current_links_today")
        .map_err(|e| to_store_err("read current_links_today", e))?;
    let day_started_at: DateTime<Utc> = row
        .try_get("day_started_at")
        .map_err(|e| to_store_err("read day_started_at", e))?;
    let created_at: DateTime<Utc> = row
        .try_get(field_names::CREATED_AT)
        .map_err(|e| to_store_err(READ_CREATED_AT, e))?;
    let updated_at: DateTime<Utc> = row
        .try_get(field_names::UPDATED_AT)
        .map_err(|e| to_store_err("read updated_at", e))?;
    Ok(QuotaStatus {
        agent_id,
        namespace,
        max_memories_per_day,
        max_storage_bytes,
        max_links_per_day,
        current_memories_today,
        current_storage_bytes,
        current_links_today,
        day_started_at: day_started_at.to_rfc3339(),
        created_at: created_at.to_rfc3339(),
        updated_at: updated_at.to_rfc3339(),
    })
}

// ----------------------------------------------------------------------
// v0.7.0 Wave-3 Continuation — postgres-only helpers used by HTTP
// handlers when `app.storage_backend == Postgres`. These intentionally
// do NOT live on the `MemoryStore` trait yet — the trait surface is
// stabilising; the helpers below cover archive read paths that will
// eventually move onto the trait once the SQLite adapter has parity.
// ----------------------------------------------------------------------

/// Project the Postgres `archived_memories` table into the JSON wire
/// shape produced by the SQLite `db::list_archived` for HTTP parity.
/// Takes an `Arc<dyn MemoryStore>` rather than a concrete pool so the
/// caller can pass the daemon's `app.store` handle directly.
///
/// # Errors
///
/// Returns [`StoreError::BackendUnavailable`] when the underlying
/// adapter is not a [`PostgresStore`] or when the SQL query fails.
pub async fn list_archived_via_store(
    store: &std::sync::Arc<dyn MemoryStore>,
    namespace: Option<&str>,
    limit: usize,
    offset: usize,
) -> StoreResult<Vec<serde_json::Value>> {
    let pg = downcast_postgres(store)?;
    pg.list_archived_pg(namespace, limit, offset).await
}

/// Outbound multi-hop knowledge-graph traversal for postgres-backed
/// daemons. Dispatches to [`PostgresStore::kg_query`] which itself
/// resolves Apache AGE vs the CTE fallback at adapter connect time.
///
/// # Errors
///
/// See [`PostgresStore::kg_query`].
pub async fn kg_query_via_store(
    store: &std::sync::Arc<dyn MemoryStore>,
    source_id: &str,
    max_depth: usize,
    include_invalidated: bool,
) -> StoreResult<Vec<crate::store::KgQueryRow>> {
    let pg = downcast_postgres(store)?;
    pg.kg_query_with_history(source_id, max_depth, include_invalidated)
        .await
}

/// Knowledge-graph timeline scan for postgres-backed daemons.
/// Mirrors the SQLite `db::kg_timeline` wire envelope so the HTTP
/// handler can stay backend-blind. `since` / `until` / `limit` are
/// passed through.
///
/// # Errors
///
/// See [`PostgresStore::kg_timeline`].
pub async fn kg_timeline_via_store(
    store: &std::sync::Arc<dyn MemoryStore>,
    source_id: &str,
    since: Option<&str>,
    until: Option<&str>,
    limit: Option<usize>,
) -> StoreResult<Vec<crate::store::KgTimelineRow>> {
    let pg = downcast_postgres(store)?;
    pg.kg_timeline(source_id, since, until, limit).await
}

/// Knowledge-graph link supersession for postgres-backed daemons.
/// Mirrors the SQLite `db::invalidate_link` contract — returns a
/// [`KgInvalidateRow`] whose `found` flag distinguishes "matched and
/// updated" from "no triple matched the predicate".
///
/// # Errors
///
/// See [`PostgresStore::kg_invalidate`].
pub async fn kg_invalidate_via_store(
    store: &std::sync::Arc<dyn MemoryStore>,
    source_id: &str,
    target_id: &str,
    relation: &str,
    valid_until: Option<&str>,
) -> StoreResult<crate::store::KgInvalidateRow> {
    let pg = downcast_postgres(store)?;
    pg.kg_invalidate(source_id, target_id, relation, valid_until)
        .await
}

/// Project the Postgres `archived_memories` aggregate stats into the
/// same JSON wire shape produced by SQLite's `db::archive_stats`.
///
/// # Errors
///
/// Same surface as [`list_archived_via_store`].
pub async fn archive_stats_via_store(
    store: &std::sync::Arc<dyn MemoryStore>,
) -> StoreResult<serde_json::Value> {
    let pg = downcast_postgres(store)?;
    pg.archive_stats().await
}

/// v0.7.0 Wave-3 Continuation 4 (Bucket E / S44) — postgres taxonomy walk.
///
/// Returns `(namespace, count)` pairs (densest first) under an optional
/// prefix subtree. The HTTP `GET /api/v1/taxonomy` handler shapes these
/// into the hierarchical tree wire envelope (per-node `count` +
/// transitive `subtree_count` + an honest `total_count` /
/// `truncated` flag).
///
/// # Errors
///
/// Surfaces [`StoreError::BackendUnavailable`] when the active store is
/// not a [`PostgresStore`]; storage errors propagate from
/// [`PostgresStore::taxonomy_namespaces`].
pub async fn taxonomy_namespaces_via_store(
    store: &std::sync::Arc<dyn MemoryStore>,
    prefix: Option<&str>,
) -> StoreResult<Vec<(String, i64)>> {
    let pg = downcast_postgres(store)?;
    pg.taxonomy_namespaces(prefix).await
}

/// List pending governance actions for postgres-backed daemons.
///
/// Surfaces rows from the `pending_actions` table filtered by
/// optional `status` (`pending` / `approved` / `rejected`) and
/// optional `namespace` (S34's per-namespace queue view).
///
/// # Errors
///
/// Returns [`StoreError::BackendUnavailable`] when the underlying
/// adapter is not a [`PostgresStore`] or when the SQL query fails.
pub async fn list_pending_actions_via_store(
    store: &std::sync::Arc<dyn MemoryStore>,
    status: Option<&str>,
    namespace: Option<&str>,
    limit: usize,
) -> StoreResult<Vec<serde_json::Value>> {
    let pg = downcast_postgres(store)?;
    pg.list_pending_actions(status, namespace, limit).await
}

fn downcast_postgres(store: &std::sync::Arc<dyn MemoryStore>) -> StoreResult<&PostgresStore> {
    // Trait objects don't expose downcast directly; we rely on the fact
    // that the daemon only constructs a `PostgresStore` when the
    // operator passes `--store-url postgres://...` so the storage_backend
    // flag is the load-bearing discriminator. Use `Any` projection via
    // a private hatch.
    let any = store.as_any();
    any.downcast_ref::<PostgresStore>()
        .ok_or_else(|| StoreError::BackendUnavailable {
            backend: "postgres".to_string(),
            detail: "active store is not a PostgresStore".to_string(),
        })
}

impl PostgresStore {
    /// Project the `archived_memories` table into the same wire shape
    /// `db::list_archived` produces for SQLite. Tags are stored as a
    /// JSONB array; we serialize back to a string-formatted JSON to
    /// match SQLite's `tags` text-encoded shape.
    ///
    /// ARCH-2 FX-C2-batch5 (2026-05-27): renamed from `list_archived`
    /// to `list_archived_pg` so the SAL trait method
    /// `MemoryStore::list_archived` can land on the trait impl block
    /// without a name collision. The trait impl delegates to this
    /// inherent helper.
    pub(super) async fn list_archived_pg(
        &self,
        namespace: Option<&str>,
        limit: usize,
        offset: usize,
    ) -> StoreResult<Vec<serde_json::Value>> {
        let limit_i: i64 = limit
            .clamp(1, crate::storage::LIST_MAX_LIMIT)
            .try_into()
            .unwrap_or(ARCHIVED_LIST_FALLBACK_I64);
        let offset_i: i64 = offset.try_into().unwrap_or(0);
        let rows = sqlx::query(
            "SELECT id, tier, namespace, title, content, tags, priority, confidence, \
             source, access_count, created_at, updated_at, last_accessed_at, \
             expires_at, archived_at, archive_reason, metadata, \
             reflection_depth, memory_kind, entity_id, persona_version, \
             citations, source_uri, source_span, confidence_source, \
             confidence_signals, confidence_decayed_at, version, \
             atomised_into, atom_of, mentioned_entity_id \
             FROM archived_memories \
             WHERE ($1::text IS NULL OR namespace = $1) \
             ORDER BY archived_at DESC \
             LIMIT $2 OFFSET $3",
        )
        .bind(namespace)
        .bind(limit_i)
        .bind(offset_i)
        .fetch_all(&self.pool)
        .await
        .map_err(|e| to_store_err("list archived memories", e))?;

        // v0.7.0 #1080 (SR-2 #3, MEDIUM) — propagate row-decode
        // errors instead of substituting silent defaults. Pre-#1080
        // every column decode used `.unwrap_or(default)` /
        // `.unwrap_or_else(|_| <fake>)`, which on any sqlx decode
        // failure (schema drift, NULL where NOT NULL was expected,
        // JSONB shape drift) silently minted fake column values and
        // serialised them into the audit-trail-facing payload. The
        // SQLite-side `list_archived` propagates via `?` — the
        // postgres adapter must match. NOT NULL columns
        // (id/tier/namespace/title/content/tags/priority/
        // confidence/source/access_count/created_at/updated_at/
        // archived_at/archive_reason/metadata) hard-propagate;
        // genuinely-nullable columns (last_accessed_at, expires_at)
        // decode as Option<T>.
        let mut out = Vec::with_capacity(rows.len());
        for row in rows {
            use sqlx::Row;
            let tags_jsonb: serde_json::Value = row
                .try_get("tags")
                .map_err(|e| to_store_err("list_archived tags decode", e))?;
            let tags_string =
                serde_json::to_string(&tags_jsonb).map_err(|e| StoreError::InvalidInput {
                    detail: format!("list_archived tags serialise: {e}"),
                })?;
            let metadata: serde_json::Value = row
                .try_get("metadata")
                .map_err(|e| to_store_err("list_archived metadata decode", e))?;
            let last_accessed_at: Option<DateTime<Utc>> = row
                .try_get(field_names::LAST_ACCESSED_AT)
                .map_err(|e| to_store_err("list_archived last_accessed_at decode", e))?;
            let expires_at: Option<DateTime<Utc>> = row
                .try_get(field_names::EXPIRES_AT)
                .map_err(|e| to_store_err("list_archived expires_at decode", e))?;
            let archived_at: DateTime<Utc> = row
                .try_get(field_names::ARCHIVED_AT)
                .map_err(|e| to_store_err("list_archived archived_at decode", e))?;
            let created_at: DateTime<Utc> = row
                .try_get(field_names::CREATED_AT)
                .map_err(|e| to_store_err("list_archived created_at decode", e))?;
            let updated_at: DateTime<Utc> = row
                .try_get(field_names::UPDATED_AT)
                .map_err(|e| to_store_err("list_archived updated_at decode", e))?;
            let id: String = row
                .try_get("id")
                .map_err(|e| to_store_err("list_archived id decode", e))?;
            let tier: String = row
                .try_get("tier")
                .map_err(|e| to_store_err("list_archived tier decode", e))?;
            let namespace: String = row
                .try_get("namespace")
                .map_err(|e| to_store_err("list_archived namespace decode", e))?;
            let title: String = row
                .try_get("title")
                .map_err(|e| to_store_err("list_archived title decode", e))?;
            let content: String = row
                .try_get("content")
                .map_err(|e| to_store_err("list_archived content decode", e))?;
            let priority: i32 = row
                .try_get("priority")
                .map_err(|e| to_store_err("list_archived priority decode", e))?;
            let confidence: f64 = row
                .try_get(field_names::CONFIDENCE)
                .map_err(|e| to_store_err("list_archived confidence decode", e))?;
            let source: String = row
                .try_get("source")
                .map_err(|e| to_store_err("list_archived source decode", e))?;
            let access_count: i64 = row
                .try_get(field_names::ACCESS_COUNT)
                .map_err(|e| to_store_err("list_archived access_count decode", e))?;
            let archive_reason: String = row
                .try_get(field_names::ARCHIVE_REASON)
                .map_err(|e| to_store_err("list_archived archive_reason decode", e))?;
            // #1637 — the v49 columns (in the table since #1025; restore
            // was lossless but the LISTING projection hid them). All
            // nullable per the v49 additive migration; decode failures
            // hard-propagate per the #1080 posture.
            let reflection_depth: Option<i32> = row
                .try_get(field_names::REFLECTION_DEPTH)
                .map_err(|e| to_store_err("list_archived reflection_depth decode", e))?;
            let memory_kind: Option<String> = row
                .try_get(field_names::MEMORY_KIND)
                .map_err(|e| to_store_err("list_archived memory_kind decode", e))?;
            let entity_id: Option<String> = row
                .try_get("entity_id")
                .map_err(|e| to_store_err("list_archived entity_id decode", e))?;
            let persona_version: Option<i32> = row
                .try_get(field_names::PERSONA_VERSION)
                .map_err(|e| to_store_err("list_archived persona_version decode", e))?;
            let citations: Option<String> = row
                .try_get("citations")
                .map_err(|e| to_store_err("list_archived citations decode", e))?;
            let source_uri: Option<String> = row
                .try_get(field_names::SOURCE_URI)
                .map_err(|e| to_store_err("list_archived source_uri decode", e))?;
            let source_span: Option<String> = row
                .try_get(field_names::SOURCE_SPAN)
                .map_err(|e| to_store_err("list_archived source_span decode", e))?;
            let confidence_source: Option<String> = row
                .try_get(field_names::CONFIDENCE_SOURCE)
                .map_err(|e| to_store_err("list_archived confidence_source decode", e))?;
            let confidence_signals: Option<String> =
                row.try_get(field_names::CONFIDENCE_SIGNALS)
                    .map_err(|e| to_store_err("list_archived confidence_signals decode", e))?;
            let confidence_decayed_at: Option<String> = row
                .try_get(field_names::CONFIDENCE_DECAYED_AT)
                .map_err(|e| to_store_err("list_archived confidence_decayed_at decode", e))?;
            let version: Option<i64> = row
                .try_get("version")
                .map_err(|e| to_store_err("list_archived version decode", e))?;
            let atomised_into: Option<i32> = row
                .try_get(field_names::ATOMISED_INTO)
                .map_err(|e| to_store_err("list_archived atomised_into decode", e))?;
            let atom_of: Option<String> = row
                .try_get(field_names::ATOM_OF)
                .map_err(|e| to_store_err("list_archived atom_of decode", e))?;
            let mentioned_entity_id: Option<String> = row
                .try_get(field_names::MENTIONED_ENTITY_ID)
                .map_err(|e| to_store_err("list_archived mentioned_entity_id decode", e))?;
            out.push(serde_json::json!({
                "id": id,
                "tier": tier,
                "namespace": namespace,
                "title": title,
                "content": content,
                "tags": tags_string,
                "priority": priority,
                (field_names::CONFIDENCE): confidence,
                "source": source,
                (field_names::ACCESS_COUNT): access_count,
                (field_names::CREATED_AT): created_at.to_rfc3339(),
                (field_names::UPDATED_AT): updated_at.to_rfc3339(),
                (field_names::LAST_ACCESSED_AT): last_accessed_at.map(|d| d.to_rfc3339()),
                (field_names::EXPIRES_AT): expires_at.map(|d| d.to_rfc3339()),
                (field_names::ARCHIVED_AT): archived_at.to_rfc3339(),
                (field_names::ARCHIVE_REASON): archive_reason,
                "metadata": metadata,
                (field_names::REFLECTION_DEPTH): reflection_depth.unwrap_or(0),
                (field_names::MEMORY_KIND): memory_kind,
                "entity_id": entity_id,
                (field_names::PERSONA_VERSION): persona_version,
                "citations": citations
                    .and_then(|c| serde_json::from_str::<serde_json::Value>(&c).ok())
                    .unwrap_or_else(|| serde_json::json!([])),
                (field_names::SOURCE_URI): source_uri,
                (field_names::SOURCE_SPAN): source_span
                    .and_then(|c| serde_json::from_str::<serde_json::Value>(&c).ok()),
                (field_names::CONFIDENCE_SOURCE): confidence_source,
                (field_names::CONFIDENCE_SIGNALS): confidence_signals
                    .and_then(|c| serde_json::from_str::<serde_json::Value>(&c).ok()),
                (field_names::CONFIDENCE_DECAYED_AT): confidence_decayed_at,
                "version": version.unwrap_or(1),
                (field_names::ATOMISED_INTO): atomised_into,
                (field_names::ATOM_OF): atom_of,
                (field_names::MENTIONED_ENTITY_ID): mentioned_entity_id,
            }));
        }
        Ok(out)
    }

    /// Aggregate `archived_memories` rows into the same JSON shape
    /// `db::archive_stats` returns for SQLite.
    /// v0.7.0 Wave-3 Continuation 4 (Bucket E / S44) — list every
    /// `(namespace, count)` pair across the live `memories` projection,
    /// optionally filtered to a prefix subtree. Returns the densest
    /// namespaces first; the caller is responsible for limit-trimming.
    ///
    /// Used by [`taxonomy_namespaces_via_store`] to power the
    /// hierarchical `GET /api/v1/taxonomy` walk on a postgres-backed
    /// daemon. The trait-level `list` cannot do this because it caps
    /// at 1000 rows and only matches namespaces exactly; the taxonomy
    /// walk needs prefix-match + dense-aggregate semantics that map
    /// cleanly onto a single `GROUP BY namespace` SQL query.
    pub async fn taxonomy_namespaces(
        &self,
        prefix: Option<&str>,
    ) -> StoreResult<Vec<(String, i64)>> {
        use sqlx::Row;
        let rows = if let Some(p) = prefix {
            // Match the subtree exactly OR any descendant via `<prefix>/...`.
            // The `LIKE` clause uses ESCAPE '\\' so a literal `_` or `%` in
            // the supplied prefix doesn't widen the match. Both conditions
            // are joined under a single OR for the dense-aggregate result.
            let escaped = p
                .replace('\\', "\\\\")
                .replace('%', "\\%")
                .replace('_', "\\_");
            let descendant = format!("{escaped}/%");
            sqlx::query(
                "SELECT namespace, COUNT(*) AS cnt
                 FROM memories
                 WHERE (expires_at IS NULL OR expires_at > NOW())
                   AND (namespace = $1 OR namespace LIKE $2 ESCAPE '\\')
                 GROUP BY namespace
                 ORDER BY cnt DESC, namespace ASC",
            )
            .bind(p)
            .bind(descendant)
            .fetch_all(&self.pool)
            .await
            .map_err(|e| to_store_err("taxonomy_namespaces prefix", e))?
        } else {
            sqlx::query(
                "SELECT namespace, COUNT(*) AS cnt
                 FROM memories
                 WHERE (expires_at IS NULL OR expires_at > NOW())
                 GROUP BY namespace
                 ORDER BY cnt DESC, namespace ASC",
            )
            .fetch_all(&self.pool)
            .await
            .map_err(|e| to_store_err("taxonomy_namespaces all", e))?
        };
        let mut out: Vec<(String, i64)> = Vec::with_capacity(rows.len());
        for r in rows {
            let ns: String = r.try_get("namespace").unwrap_or_default();
            let cnt: i64 = r.try_get("cnt").unwrap_or(0);
            out.push((ns, cnt));
        }
        Ok(out)
    }

    /// List pending governance actions filtered by optional status
    /// + namespace. Mirrors the sqlite `db::list_pending_actions`
    /// wire shape but projects directly from the postgres
    /// `pending_actions` table; on a fresh schema-init the row set
    /// is empty and the handler returns `count=0` cleanly.
    pub async fn list_pending_actions(
        &self,
        status: Option<&str>,
        namespace: Option<&str>,
        limit: usize,
    ) -> StoreResult<Vec<serde_json::Value>> {
        use sqlx::Row;
        let limit_i: i64 = limit
            .clamp(1, crate::storage::LIST_MAX_LIMIT)
            .try_into()
            .unwrap_or(LIST_FALLBACK_LIMIT_I64);
        let rows = sqlx::query(
            "SELECT id, action_type, memory_id, namespace, payload, requested_by, \
                    requested_at, status, decided_by, decided_at, approvals, \
                    default_timeout_seconds, expired_at \
             FROM pending_actions \
             WHERE ($1::text IS NULL OR status = $1) \
               AND ($2::text IS NULL OR namespace = $2) \
             ORDER BY requested_at DESC \
             LIMIT $3",
        )
        .bind(status)
        .bind(namespace)
        .bind(limit_i)
        .fetch_all(&self.pool)
        .await
        .map_err(|e| to_store_err("list_pending_actions", e))?;
        let mut out: Vec<serde_json::Value> = Vec::with_capacity(rows.len());
        for r in &rows {
            let id: String = r.try_get("id").unwrap_or_default();
            let action_type: String = r.try_get(field_names::ACTION_TYPE).unwrap_or_default();
            let memory_id: Option<String> = r.try_get("memory_id").ok();
            let ns: String = r.try_get("namespace").unwrap_or_default();
            let payload: serde_json::Value =
                r.try_get("payload").unwrap_or(serde_json::Value::Null);
            let requested_by: String = r.try_get(field_names::REQUESTED_BY).unwrap_or_default();
            let requested_at: chrono::DateTime<chrono::Utc> = r
                .try_get(field_names::REQUESTED_AT)
                .unwrap_or_else(|_| chrono::Utc::now());
            let status_v: String = r.try_get("status").unwrap_or_default();
            let decided_by: Option<String> = r.try_get(field_names::DECIDED_BY).ok();
            let decided_at: Option<chrono::DateTime<chrono::Utc>> =
                r.try_get(field_names::DECIDED_AT).ok();
            let approvals: serde_json::Value = r
                .try_get("approvals")
                .unwrap_or(serde_json::Value::Array(Vec::new()));
            let default_timeout_seconds: Option<i64> =
                r.try_get(field_names::DEFAULT_TIMEOUT_SECONDS).ok();
            let expired_at: Option<chrono::DateTime<chrono::Utc>> =
                r.try_get(field_names::EXPIRED_AT).ok();
            out.push(serde_json::json!({
                "id": id,
                (field_names::ACTION_TYPE): action_type,
                "memory_id": memory_id,
                "namespace": ns,
                "payload": payload,
                (field_names::REQUESTED_BY): requested_by,
                (field_names::REQUESTED_AT): requested_at.to_rfc3339(),
                "status": status_v,
                (field_names::DECIDED_BY): decided_by,
                (field_names::DECIDED_AT): decided_at.map(|t| t.to_rfc3339()),
                "approvals": approvals,
                (field_names::DEFAULT_TIMEOUT_SECONDS): default_timeout_seconds,
                (field_names::EXPIRED_AT): expired_at.map(|t| t.to_rfc3339()),
            }));
        }
        Ok(out)
    }

    async fn archive_stats(&self) -> StoreResult<serde_json::Value> {
        use sqlx::Row;
        let total: i64 = sqlx::query_scalar("SELECT COUNT(*) FROM archived_memories")
            .fetch_one(&self.pool)
            .await
            .map_err(|e| to_store_err("archive stats total", e))?;

        let by_reason_rows = sqlx::query(
            "SELECT archive_reason, COUNT(*) AS cnt FROM archived_memories \
             GROUP BY archive_reason ORDER BY cnt DESC",
        )
        .fetch_all(&self.pool)
        .await
        .map_err(|e| to_store_err("archive stats by_reason", e))?;
        let mut by_reason: serde_json::Map<String, serde_json::Value> = serde_json::Map::new();
        for r in by_reason_rows {
            let reason: String = r.try_get(field_names::ARCHIVE_REASON).unwrap_or_default();
            let cnt: i64 = r.try_get("cnt").unwrap_or(0);
            by_reason.insert(reason, serde_json::json!(cnt));
        }

        let by_namespace_rows = sqlx::query(
            "SELECT namespace, COUNT(*) AS cnt FROM archived_memories \
             GROUP BY namespace ORDER BY cnt DESC LIMIT 100",
        )
        .fetch_all(&self.pool)
        .await
        .map_err(|e| to_store_err("archive stats by_namespace", e))?;
        let mut by_namespace: serde_json::Map<String, serde_json::Value> = serde_json::Map::new();
        for r in by_namespace_rows {
            let ns: String = r.try_get("namespace").unwrap_or_default();
            let cnt: i64 = r.try_get("cnt").unwrap_or(0);
            by_namespace.insert(ns, serde_json::json!(cnt));
        }

        Ok(serde_json::json!({
            "total_archived": total,
            "by_reason": by_reason,
            (field_names::BY_NAMESPACE): by_namespace,
        }))
    }
}

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

    // prefix_upper_bound underpins the sargable namespace-prefix range
    // used by `list_by_namespace_prefix` (the per-write dispatch hot
    // path). Under the byte-ordered (C) collation, the half-open range
    // [prefix, upper) must contain EXACTLY the strings starting with
    // `prefix` — a wrong bound silently drops or duplicates subscribers.
    #[test]
    fn prefix_upper_bound_increments_last_byte() {
        // '/' is 0x2F → '0' is 0x30.
        assert_eq!(
            prefix_upper_bound("_subscriptions/").as_deref(),
            Some("_subscriptions0")
        );
        assert_eq!(prefix_upper_bound("a").as_deref(), Some("b"));
        assert_eq!(prefix_upper_bound("ns/").as_deref(), Some("ns0"));
    }

    #[test]
    fn prefix_upper_bound_bounds_exactly_the_prefix_band() {
        // Every string starting with the prefix sorts inside [lo, hi);
        // the nearest non-matching neighbours sort outside it.
        let lo = "_subscriptions/";
        let hi = prefix_upper_bound(lo).unwrap();
        for inside in [
            "_subscriptions/",
            "_subscriptions/alice",
            "_subscriptions/zzz",
            "_subscriptions/\u{10FFFF}",
        ] {
            assert!(inside >= lo && inside < hi.as_str(), "{inside}");
        }
        for outside in [
            "_subscriptions",   // shorter, not in the namespace
            "_subscriptions.",  // '.' = 0x2E < '/'
            "_subscriptions0",  // == hi, excluded
            "_subscriptions0a", // beyond hi
            "_subscriptionz",   // 'z' > 's'… diverges before the slash
        ] {
            assert!(
                !(outside >= lo && outside < hi.as_str()),
                "{outside} must fall outside [{lo}, {hi})"
            );
        }
    }

    #[test]
    fn prefix_upper_bound_empty_and_non_ascii_degrade_to_none() {
        // Empty prefix → no upper bound (open-ended `>=` lower bound
        // only; the in-process starts_with filter keeps the result
        // correct).
        assert_eq!(prefix_upper_bound(""), None);
        // A prefix whose last UTF-8 byte increments into an invalid
        // continuation (e.g. 'ÿ' = 0xC3 0xBF → 0xC3 0xC0) yields no
        // valid-UTF-8 successor → None, the same safe degrade. We never
        // pass non-ASCII namespace prefixes, but the path must not panic.
        assert_eq!(prefix_upper_bound("\u{00ff}"), None);
        // ASCII always has a clean successor.
        assert_eq!(prefix_upper_bound("_inbox/").as_deref(), Some("_inbox0"));
    }

    // QC Obs #6 (2026-05-20) — `assert_age_id_safe` is a security
    // primitive: it gates whether a caller-supplied id can be inlined
    // into a `cypher()` body string (2-arg form, no params dict). A
    // regression that loosened the regex would surface as cypher
    // injection. These unit tests pin the alphabet (only ASCII
    // alphanumeric + `-_`), length bounds (1..=128), and every
    // adversarial char class we'd see in an injection attempt.
    #[test]
    fn assert_age_id_safe_accepts_canonical_uuid() {
        assert!(assert_age_id_safe("a0a15bb5-5aa2-4219-96bd-d15f27618eb8").is_ok());
    }

    #[test]
    fn assert_age_id_safe_accepts_alphanumeric_dash_underscore() {
        assert!(assert_age_id_safe("AaZz09-_").is_ok());
        assert!(assert_age_id_safe("single").is_ok());
    }

    #[test]
    fn assert_age_id_safe_rejects_empty() {
        assert!(assert_age_id_safe("").is_err());
    }

    #[test]
    fn assert_age_id_safe_rejects_over_max_length() {
        let s = "a".repeat(129);
        assert!(assert_age_id_safe(&s).is_err());
        let s = "a".repeat(128);
        assert!(assert_age_id_safe(&s).is_ok(), "boundary 128 is inclusive");
    }

    #[test]
    fn assert_age_id_safe_rejects_single_quote() {
        // Closes the cypher-string-literal escape vector.
        assert!(assert_age_id_safe("a'b").is_err());
        assert!(assert_age_id_safe("a''b").is_err());
    }

    #[test]
    fn assert_age_id_safe_rejects_double_quote_and_backtick() {
        assert!(assert_age_id_safe("a\"b").is_err());
        assert!(assert_age_id_safe("a`b").is_err());
    }

    #[test]
    fn assert_age_id_safe_rejects_dollar_sign() {
        // Closes the cypher dollar-quote / param-reference vector.
        assert!(assert_age_id_safe("$start").is_err());
        assert!(assert_age_id_safe("a$$b").is_err());
    }

    #[test]
    fn assert_age_id_safe_rejects_braces_brackets_parens() {
        // Closes pattern / property / function injection.
        assert!(assert_age_id_safe("a{b").is_err());
        assert!(assert_age_id_safe("a}b").is_err());
        assert!(assert_age_id_safe("a[b").is_err());
        assert!(assert_age_id_safe("a]b").is_err());
        assert!(assert_age_id_safe("a(b").is_err());
        assert!(assert_age_id_safe("a)b").is_err());
    }

    #[test]
    fn assert_age_id_safe_rejects_semicolon_and_comma() {
        // Closes statement-terminator + list-separator vectors.
        assert!(assert_age_id_safe("a;b").is_err());
        assert!(assert_age_id_safe("a,b").is_err());
    }

    #[test]
    fn assert_age_id_safe_rejects_comment_chars() {
        // Closes `--` comment, `/* */` block comment.
        assert!(assert_age_id_safe("a/b").is_err());
        assert!(assert_age_id_safe("a*b").is_err());
        // `-` is allowed (UUID separator) but `--` is just two allowed
        // chars; injection via comment requires `--` followed by chars
        // that the regex would reject (whitespace/colon/etc), so the
        // structural defense holds even with `--` permitted.
        assert!(assert_age_id_safe("a--b").is_ok());
    }

    #[test]
    fn assert_age_id_safe_rejects_whitespace() {
        // Closes pattern-break + cypher-keyword smuggling.
        assert!(assert_age_id_safe("a b").is_err());
        assert!(assert_age_id_safe("a\tb").is_err());
        assert!(assert_age_id_safe("a\nb").is_err());
        assert!(assert_age_id_safe("a\rb").is_err());
    }

    #[test]
    fn assert_age_id_safe_rejects_age_type_tags() {
        // The decode strips `::vertex` / `::edge` / `::path` — if an
        // id contained one of those it'd be silently shortened on
        // round-trip. The colon character rejects them outright.
        assert!(assert_age_id_safe("a::vertex").is_err());
        assert!(assert_age_id_safe("a:b").is_err());
    }

    #[test]
    fn assert_age_id_safe_rejects_unicode_homoglyphs() {
        // Closes lookalike-character bypass attempts.
        assert!(assert_age_id_safe("аbc").is_err()); // cyrillic 'а'
        assert!(assert_age_id_safe("a\u{200B}b").is_err()); // zero-width space
        assert!(assert_age_id_safe("⟨admin⟩").is_err());
    }

    #[test]
    fn assert_age_id_safe_rejects_null_byte() {
        assert!(assert_age_id_safe("a\0b").is_err());
    }

    #[test]
    fn capabilities_advertise_native_vector() {
        // The Postgres backend must advertise NATIVE_VECTOR + FULLTEXT
        // so callers can skip the in-process HNSW fallback.
        // We can't construct a real PostgresStore without a connection,
        // so we check the constant bits directly via a dummy pool-less
        // match. This is a trait-surface test only.
        let caps = Capabilities::TRANSACTIONS
            | Capabilities::NATIVE_VECTOR
            | Capabilities::FULLTEXT
            | Capabilities::DURABLE
            | Capabilities::STRONG_CONSISTENCY
            | Capabilities::ATOMIC_MULTI_WRITE;
        assert!(caps.contains(Capabilities::NATIVE_VECTOR));
        assert!(caps.contains(Capabilities::FULLTEXT));
        assert!(caps.contains(Capabilities::STRONG_CONSISTENCY));
        assert!(!caps.contains(Capabilities::TTL_NATIVE));
    }

    #[test]
    fn parse_rfc3339_opt_handles_some_and_none() {
        assert!(parse_rfc3339_opt(None).is_none());
        assert!(parse_rfc3339_opt(Some("not a date")).is_none());
        let parsed = parse_rfc3339_opt(Some("2026-04-19T16:00:00Z"));
        assert!(parsed.is_some());
    }

    #[test]
    fn parse_rfc3339_required_rejects_garbage() {
        assert!(parse_rfc3339_required("garbage").is_err());
        assert!(parse_rfc3339_required("2026-04-19T16:00:00Z").is_ok());
    }

    #[test]
    fn init_schema_contains_vector_extension_and_indexes() {
        // Sanity: make sure the bootstrap SQL references the critical
        // constructs so a typo'd rename catches here in CI.
        assert!(INIT_SCHEMA.contains("CREATE EXTENSION IF NOT EXISTS vector"));
        assert!(INIT_SCHEMA.contains("memories_embedding_hnsw"));
        assert!(INIT_SCHEMA.contains("to_tsvector"));
    }

    #[test]
    fn init_schema_contains_schema_version_table() {
        // Verify the schema_version table is created for migration tracking.
        assert!(INIT_SCHEMA.contains("CREATE TABLE IF NOT EXISTS schema_version"));
        assert!(INIT_SCHEMA.contains("version    INTEGER PRIMARY KEY"));
    }

    // ------------------------------------------------------------------
    // v0.7.0 L3 — `vector(N)` template substitution.
    //
    // The bundled `postgres_schema.sql` uses `vector({EMBEDDING_DIM})`
    // as a placeholder for the embedding-column dim. `render_schema_sql`
    // is the single substitution point invoked by `connect_with_dim`.
    // These tests verify the placeholder lives in the template AND
    // that the substitution leaves no stray placeholders behind.
    // ------------------------------------------------------------------

    // ------------------------------------------------------------------
    // F-A2A1.2 (#700) — governance inheritance depth cap.
    //
    // These tests pin the depth-cap constant + the chain-build behaviour
    // that does NOT require a live Postgres connection. The cap value is
    // surface-visible via `GOVERNANCE_INHERITANCE_DEPTH_CAP`; the chain
    // walk semantics (most-specific-N levels retained) ride the same
    // helper for both the pool-side `build_namespace_chain` and the
    // tx-side `build_namespace_chain_in_tx`. Live-PG variants below
    // exercise the same paths through `enforce_governance_action` end-
    // to-end against a real schema; the unit tests here are the
    // structural pin so a future refactor cannot silently drift the cap.
    // ------------------------------------------------------------------

    #[test]
    fn governance_inheritance_depth_cap_is_five() {
        // Pinned to 5 per the v0.7.0 fold-A2A1 spec. Any change to this
        // value must be reflected in
        // `docs/v0.7.0/a2a-triage-wave4-r2.md` §F-A2A1.2 and
        // accompanied by a CHANGELOG entry — the cap shapes the
        // bind-list size and connection-hold budget of every governed
        // write on postgres.
        assert_eq!(super::GOVERNANCE_INHERITANCE_DEPTH_CAP, 5);
    }

    #[test]
    fn namespace_ancestors_within_cap_pass_through() {
        // A namespace at or below the depth cap retains every level
        // (root → leaf). This is the common case: real-world
        // namespaces are 3-4 segments deep, so the cap should be a
        // no-op for ordinary writes.
        let ancestors: Vec<String> = crate::models::namespace_ancestors("a/b/c")
            .into_iter()
            .rev()
            .collect();
        // 3 levels: "a", "a/b", "a/b/c" — all retained.
        assert_eq!(ancestors.len(), 3);
        assert_eq!(ancestors[0], "a");
        assert_eq!(ancestors[2], "a/b/c");
    }

    #[test]
    fn namespace_ancestors_at_max_namespace_depth() {
        // The compile-time `MAX_NAMESPACE_DEPTH` is 8; namespaces at
        // that depth produce 8 ancestor levels. Our cap of 5 trims
        // such a chain when applied in the governance walker.
        let deep = "l1/l2/l3/l4/l5/l6/l7/l8";
        let ancestors: Vec<String> = crate::models::namespace_ancestors(deep)
            .into_iter()
            .rev()
            .collect();
        assert_eq!(ancestors.len(), 8);
        // Simulate the cap: keep last N most-specific entries.
        let cap = super::GOVERNANCE_INHERITANCE_DEPTH_CAP;
        let kept: Vec<String> = if ancestors.len() > cap {
            ancestors
                .iter()
                .skip(ancestors.len() - cap)
                .cloned()
                .collect()
        } else {
            ancestors
        };
        assert_eq!(kept.len(), cap);
        // The most-specific entry is the leaf itself.
        assert_eq!(kept.last().map(String::as_str), Some(deep));
        // The least-specific kept entry is the (cap-1)-from-leaf
        // ancestor, NOT the root. The root ("l1") is dropped under
        // the cap so resolution stays bounded — operators who want a
        // root-level policy applied to deep children must seat that
        // policy on a level within the cap reach.
        assert_eq!(kept.first().map(String::as_str), Some("l1/l2/l3/l4"));
    }

    #[test]
    fn namespace_ancestors_star_short_circuits() {
        // The synthetic `"*"` global standard is never decomposed by
        // `namespace_ancestors` — the chain walker prepends it
        // unconditionally instead. Verify the input shape so a future
        // refactor that auto-prefixes everything with `*` doesn't
        // silently double-count.
        let ancestors = crate::models::namespace_ancestors("*");
        assert_eq!(ancestors, vec!["*".to_string()]);
    }

    #[test]
    fn schema_template_carries_embedding_dim_placeholder() {
        // The schema file must hold the placeholder verbatim — otherwise
        // substitution becomes a silent no-op.
        assert!(
            INIT_SCHEMA.contains(EMBEDDING_DIM_PLACEHOLDER),
            "postgres_schema.sql must contain {EMBEDDING_DIM_PLACEHOLDER}"
        );
        // And it must NOT contain a hardcoded `vector(384)` /
        // `vector(768)` outside the placeholder — the template is the
        // single source of truth for column dim.
        assert!(
            !INIT_SCHEMA.contains("vector(384)"),
            "postgres_schema.sql must not contain hardcoded vector(384)"
        );
        assert!(
            !INIT_SCHEMA.contains("vector(768)"),
            "postgres_schema.sql must not contain hardcoded vector(768)"
        );
    }

    #[test]
    fn render_schema_sql_substitutes_768() {
        let rendered = render_schema_sql(INIT_SCHEMA, 768);
        assert!(rendered.contains("vector(768)"), "missing vector(768)");
        assert!(!rendered.contains("vector(384)"), "stray vector(384)");
        assert!(
            !rendered.contains(EMBEDDING_DIM_PLACEHOLDER),
            "placeholder not substituted: {rendered}"
        );
    }

    #[test]
    fn render_schema_sql_substitutes_384() {
        let rendered = render_schema_sql(INIT_SCHEMA, 384);
        assert!(rendered.contains("vector(384)"), "missing vector(384)");
        assert!(
            !rendered.contains(EMBEDDING_DIM_PLACEHOLDER),
            "placeholder not substituted: {rendered}"
        );
    }

    #[test]
    fn render_schema_sql_handles_arbitrary_dim() {
        // The rendering helper itself doesn't gate on supported dims —
        // the gate lives in `connect_with_dim` / `migrate_embedding_dim`.
        // This test just verifies the substitution is purely textual.
        let rendered = render_schema_sql("vector({EMBEDDING_DIM})", 1024);
        assert_eq!(rendered, "vector(1024)");
    }

    #[test]
    fn supported_embedding_dims_match_compiled_embedders() {
        // `SUPPORTED_EMBEDDING_DIMS` MUST mirror the values returned
        // by `EmbeddingModel::dim()` (config.rs). If either side gains
        // a new embedder we want the test to catch the drift.
        assert_eq!(SUPPORTED_EMBEDDING_DIMS, &[384, 768]);
    }

    // ------------------------------------------------------------------
    // v0.7 J1 — AGE detection unit + live tests.
    //
    // The pool-less unit tests here only exercise the static surface
    // (default tag, accessor wiring through the type) so they can run
    // on any host. The live AGE probe runs iff `AI_MEMORY_TEST_AGE_URL`
    // is set; otherwise it skips cleanly. CI configures the env var
    // for the AGE-postgres job (see Track J5 plan).
    // ------------------------------------------------------------------

    fn age_url() -> Option<String> {
        std::env::var("AI_MEMORY_TEST_AGE_URL").ok()
    }

    #[test]
    fn kg_backend_default_tag_is_cte() {
        // Substrate sanity: the fallback path is `Cte`. J2-J7 dispatch
        // on this — flipping the default would silently route every
        // SQLite-class deployment through Cypher and crash on first
        // call. Pin the default so a future refactor can't drift it.
        assert_eq!(KgBackend::Cte.as_str(), "cte");
        assert_eq!(KgBackend::Age.as_str(), "age");
    }

    #[tokio::test]
    async fn live_kg_backend_resolves_to_age_when_extension_present() {
        // Runs against a real AGE-enabled Postgres ONLY when
        // AI_MEMORY_TEST_AGE_URL is set. Skips cleanly otherwise so
        // the default `cargo test` flow stays offline. Contract: the
        // SAL handle must report `KgBackend::Age` against this URL.
        let Some(url) = age_url() else {
            eprintln!("skip: AI_MEMORY_TEST_AGE_URL not set");
            return;
        };
        let store = PostgresStore::connect(&url).await.expect("connect");
        assert_eq!(
            store.kg_backend(),
            KgBackend::Age,
            "AGE-enabled Postgres must resolve to KgBackend::Age"
        );
    }

    #[tokio::test]
    async fn live_kg_backend_resolves_to_cte_without_age() {
        // Runs against a Postgres WITHOUT the AGE extension installed.
        // CI may set AI_MEMORY_TEST_POSTGRES_URL to a vanilla pgvector
        // Postgres while AI_MEMORY_TEST_AGE_URL points at the AGE
        // image — when the vanilla URL is set and AGE is NOT, we get
        // a real-Postgres-real-fallback assertion. Skips cleanly
        // otherwise.
        let Some(url) = postgres_url() else {
            eprintln!("skip: AI_MEMORY_TEST_POSTGRES_URL not set");
            return;
        };
        // #1272 — detect AGE on the connected DB rather than comparing
        // URL strings. Operators commonly point both env vars at the
        // same single AGE-enabled fixture (e.g. infra/lan-parity-test/
        // PG+AGE container) or omit AI_MEMORY_TEST_AGE_URL entirely;
        // either way the string-equality check was unreliable. The
        // backend-detection skip is the structurally correct test for
        // "is AGE present on this URL?".
        let store = PostgresStore::connect(&url).await.expect("connect");
        if store.kg_backend() == KgBackend::Age {
            eprintln!(
                "skip: connected DB has AGE installed; this test exercises the                  CTE-fallback path (#1272)"
            );
            return;
        }
        assert_eq!(
            store.kg_backend(),
            KgBackend::Cte,
            "Postgres without AGE must resolve to KgBackend::Cte"
        );
    }

    #[tokio::test]
    async fn live_detect_kg_backend_returns_cte_on_missing_extension() {
        // Same fallback assertion through the lower-level helper,
        // which J2-J7 will reach when they want to re-probe (e.g.
        // post-CREATE EXTENSION operator action). Skips cleanly when
        // no Postgres URL is set.
        let Some(url) = postgres_url() else {
            return;
        };
        let store = PostgresStore::connect(&url).await.expect("connect");
        let probed = detect_kg_backend(&store.pool).await;
        if probed == KgBackend::Age {
            eprintln!(
                "skip: connected DB has AGE installed; this test exercises the                  CTE-fallback path (#1272)"
            );
            return;
        }
        assert_eq!(probed, KgBackend::Cte);
    }

    // ------------------------------------------------------------------
    // v0.7 J2 — Cypher kg_query unit + live tests.
    //
    // Pool-less unit tests cover the offline surface — depth validation
    // + agtype string-peeling — so the dispatcher contract holds even
    // when no Postgres is available. Live tests run against an
    // AGE-enabled Postgres (`AI_MEMORY_TEST_AGE_URL`) and skip cleanly
    // otherwise so the default `cargo test` flow stays offline.
    // ------------------------------------------------------------------

    #[test]
    fn validate_depth_rejects_zero_and_overflow() {
        // Routing contract: the dispatcher MUST refuse depth=0 (no
        // traversal possible) and depth>5 (above the published budget)
        // *before* hitting the wire on either backend. Pinning the
        // boundary here so a future refactor can't silently widen it.
        assert!(matches!(
            validate_depth(0),
            Err(StoreError::InvalidInput { .. })
        ));
        assert!(matches!(
            validate_depth(KG_QUERY_MAX_SUPPORTED_DEPTH + 1),
            Err(StoreError::InvalidInput { .. })
        ));
        assert!(validate_depth(1).is_ok());
        assert!(validate_depth(KG_QUERY_MAX_SUPPORTED_DEPTH).is_ok());
    }

    #[test]
    fn strip_agtype_quotes_recovers_scalar_payload() {
        // AGE wraps text scalars in literal double-quotes when cast to
        // text via `::text`. The decoder MUST peel them so the row
        // shape matches the CTE branch byte-for-byte; otherwise the
        // dispatcher would leak the agtype quoting into upper layers.
        assert_eq!(strip_agtype_quotes("\"mem-1\""), "mem-1");
        assert_eq!(strip_agtype_quotes("3"), "3");
        assert_eq!(strip_agtype_quotes("  \"mem-1\"  "), "mem-1");
        // No surrounding quotes -> passthrough (numeric agtype scalars).
        assert_eq!(strip_agtype_quotes("42"), "42");
        // Single quote shouldn't trigger the strip (defensive).
        assert_eq!(strip_agtype_quotes("\""), "\"");
    }

    fn age_kg_url() -> Option<String> {
        std::env::var("AI_MEMORY_TEST_AGE_URL").ok()
    }

    #[tokio::test]
    async fn live_kg_query_dispatches_to_cypher_under_age() {
        // Routing contract: when AGE is the resolved backend, calling
        // `kg_query` must route through `kg_query_cypher` rather than
        // the CTE branch. We don't assert a specific result set here
        // (the J5 dual-path tests own equivalence) — just that the
        // call returns Ok against an AGE-enabled URL with a
        // bootstrapped `memory_graph` projection. Skips cleanly when
        // either piece is missing so CI without AGE stays green.
        let Some(url) = age_kg_url() else {
            eprintln!("skip: AI_MEMORY_TEST_AGE_URL not set");
            return;
        };
        let store = PostgresStore::connect(&url).await.expect("connect");
        assert_eq!(store.kg_backend(), KgBackend::Age);
        // Use a synthetic id we don't expect to find — the test asserts
        // routing, not corpus contents. A missing graph projection
        // surfaces as BackendUnavailable; that's still informative
        // (caller learns the AGE setup needs running) so we report it
        // through the test name rather than silently skipping.
        match store.kg_query("nonexistent-source", 1).await {
            Ok(rows) => {
                assert!(
                    rows.is_empty() || rows.iter().all(|r| !r.target_id.is_empty()),
                    "rows must have non-empty target_ids when present"
                );
            }
            Err(StoreError::BackendUnavailable { detail, .. }) => {
                eprintln!(
                    "AGE graph projection appears unbootstrapped on this URL: {detail}; \
                     run the J1 graph-prep script before re-running this test"
                );
            }
            Err(other) => panic!("unexpected error from AGE kg_query: {other:?}"),
        }
    }

    #[tokio::test]
    async fn live_kg_query_routes_to_cte_without_age() {
        // Inverse of the AGE routing test: against vanilla Postgres
        // (no AGE) the dispatcher must hand the call to the CTE
        // branch. We verify by calling `kg_query_cte` directly against
        // a known-empty source and asserting an empty result set, then
        // confirming `kg_query` produces the same empty set through the
        // dispatcher. Skips cleanly when no Postgres URL is configured.
        let Some(url) = postgres_url() else {
            eprintln!("skip: AI_MEMORY_TEST_POSTGRES_URL not set");
            return;
        };
        let store = PostgresStore::connect(&url).await.expect("connect");
        if store.kg_backend() == KgBackend::Age {
            eprintln!(
                "skip: connected DB has AGE installed; this test exercises the                  CTE-fallback path (#1272)"
            );
            return;
        }
        assert_eq!(
            store.kg_backend(),
            KgBackend::Cte,
            "vanilla Postgres must resolve to KgBackend::Cte"
        );
        let direct = store
            .kg_query_cte("nonexistent-source", 1)
            .await
            .expect("cte direct");
        let dispatched = store
            .kg_query("nonexistent-source", 1)
            .await
            .expect("cte via dispatcher");
        assert!(direct.is_empty(), "no rows expected for synthetic id");
        assert_eq!(
            direct, dispatched,
            "dispatcher must return the same shape as the direct CTE call"
        );
    }

    #[tokio::test]
    async fn live_kg_query_rejects_out_of_range_depth() {
        // Both backends share `validate_depth` — exercise the public
        // dispatcher against a real connection (either AGE or vanilla)
        // so the wire-side InvalidInput contract is pinned end-to-end.
        let Some(url) = age_kg_url().or_else(postgres_url) else {
            eprintln!("skip: no Postgres test URL set");
            return;
        };
        let store = PostgresStore::connect(&url).await.expect("connect");
        let zero = store.kg_query("any", 0).await;
        let over = store
            .kg_query("any", KG_QUERY_MAX_SUPPORTED_DEPTH + 1)
            .await;
        assert!(matches!(zero, Err(StoreError::InvalidInput { .. })));
        assert!(matches!(over, Err(StoreError::InvalidInput { .. })));
    }

    // ------------------------------------------------------------------
    // v0.7 J3 — Cypher kg_timeline unit + live tests.
    //
    // Pool-less unit tests cover the offline surface (limit clamping +
    // agtype optional decoding) so the dispatcher contract holds even
    // when no Postgres is available. The live test runs against an
    // AGE-enabled Postgres (`AI_MEMORY_TEST_AGE_URL`) and skips
    // cleanly otherwise so the default `cargo test` flow stays
    // offline.
    // ------------------------------------------------------------------

    #[test]
    fn clamp_timeline_limit_applies_default_and_ceiling() {
        // Routing contract: callers that omit the limit must get the
        // published default; callers that pass a value above the
        // ceiling must be silently clamped to the ceiling rather
        // than fanning out an unbounded scan. Pinning the band so a
        // future refactor can't widen the page-size budget.
        assert_eq!(clamp_timeline_limit(None), KG_TIMELINE_DEFAULT_LIMIT_SAL);
        assert_eq!(clamp_timeline_limit(Some(0)), 1);
        assert_eq!(clamp_timeline_limit(Some(50)), 50);
        assert_eq!(
            clamp_timeline_limit(Some(KG_TIMELINE_MAX_LIMIT_SAL)),
            KG_TIMELINE_MAX_LIMIT_SAL
        );
        assert_eq!(
            clamp_timeline_limit(Some(KG_TIMELINE_MAX_LIMIT_SAL + 999)),
            KG_TIMELINE_MAX_LIMIT_SAL
        );
    }

    #[test]
    fn age_params_literal_renders_json_dict() {
        // v0.7.0 Wave-3 Continuation 5 — wire-shape contract for the
        // AGE `cypher()` third-arg helper. AGE rejects `$1::agtype`
        // (the third arg must be a bare Param, not a FuncExpr cast),
        // so we inline the params as a SQL agtype literal. Single
        // quotes in the JSON value must be SQL-escaped (`''`); the
        // outer wrap is `'…'::agtype`.
        assert_eq!(age_params_literal(&[("k", "v")]), "'{\"k\":\"v\"}'::agtype");
        assert_eq!(
            age_params_literal(&[("a", "1"), ("b", "two")]),
            "'{\"a\":\"1\",\"b\":\"two\"}'::agtype"
        );
        // SQL-escape: a literal apostrophe in the value gets doubled.
        assert_eq!(
            age_params_literal(&[("name", "O'Reilly")]),
            "'{\"name\":\"O''Reilly\"}'::agtype"
        );
        // Empty dict is harmless (AGE accepts an empty params object).
        assert_eq!(age_params_literal(&[]), "'{}'::agtype");
    }

    #[test]
    fn issue_1689_kg_query_cypher_excludes_invalidated_edges() {
        // #1689 — the AGE current-view kg_query body MUST carry a
        // per-edge temporal-validity guard so invalidated edges (which
        // `kg_invalidate_cypher` SETs `valid_until` on rather than
        // deleting) never appear in a current-view traversal. This pins
        // the query text without needing a live AGE instance; the
        // dispatcher's CTE fallback covers the runtime-rejection case.
        let depth = 3usize;
        let cypher = build_kg_query_current_view_cypher(depth);
        assert!(
            cypher.contains(
                "ALL(e IN relationships(p) WHERE e.valid_until IS NULL OR e.valid_until > $now)"
            ),
            "current-view kg_query Cypher missing the valid_until guard: {cypher}"
        );
        // The bounded depth is interpolated, not parameterised.
        assert!(
            cypher.contains(&format!("related_to*1..{depth}")),
            "depth not interpolated: {cypher}"
        );
        // The start id stays a bound `$vars` param, never interpolated.
        assert!(
            cypher.contains("a.id = $start_id"),
            "start id not parameterised: {cypher}"
        );
    }

    #[test]
    fn issue_1689_find_paths_cypher_excludes_invalidated_edges() {
        // #1689 — the AGE current-view find_paths body MUST carry the same
        // per-edge temporal-validity guard as kg_query / the CTE path, so a
        // retracted link no longer influences path-finding. find_paths inlines
        // its ids + cut-off (2-arg cypher form), so the guard compares against
        // an inlined RFC3339 literal rather than a `$now` param.
        //
        // These are arbitrary INPUT fixtures fed to the builder; the
        // assertions below prove the builder round-trips each input verbatim
        // into the emitted Cypher (the format text — `a.id =`, `[*1..N]`,
        // `LIMIT` — is the generic openCypher the builder produces).
        let (src, dst, depth, cap, now) = (
            "11111111-1111-1111-1111-111111111111",
            "22222222-2222-2222-2222-222222222222",
            4usize,
            10usize,
            "2026-06-15T00:00:00+00:00",
        );
        let cypher = build_find_paths_current_view_cypher(src, dst, depth, cap, now);
        assert!(
            cypher.contains(&format!(
                "ALL(e IN relationships(p) WHERE e.valid_until IS NULL OR e.valid_until > '{now}')"
            )),
            "find_paths Cypher missing the valid_until guard: {cypher}"
        );
        // Bounded depth interpolated into the untyped variable-length pattern.
        assert!(
            cypher.contains(&format!("[*1..{depth}]")),
            "depth not interpolated: {cypher}"
        );
        // Source/target ids inlined (2-arg cypher form) and the cap applied.
        assert!(
            cypher.contains(&format!("a.id = '{src}'")),
            "source id not inlined: {cypher}"
        );
        assert!(
            cypher.contains(&format!("b.id = '{dst}'")),
            "target id not inlined: {cypher}"
        );
        assert!(
            cypher.contains(&format!("LIMIT {cap}")),
            "cap not applied: {cypher}"
        );
    }

    #[test]
    fn build_or_tsquery_or_joins_lexemes() {
        // v0.7.0.1 S79 — wire-shape contract for the OR-joined
        // tsquery helper. Mirrors sqlite's `sanitize_fts_query(_, true)`
        // OR-joined output so multi-token queries surface every row
        // matching AT LEAST one token.
        assert_eq!(build_or_tsquery("rust ownership"), "'rust' | 'ownership'");
        assert_eq!(build_or_tsquery("dog field"), "'dog' | 'field'");
        // Lower-cases tokens (postgres `to_tsquery('english', _)` lemma
        // matching is case-folded but the lexeme bytes must be the
        // post-fold form).
        assert_eq!(build_or_tsquery("Rust Ownership"), "'rust' | 'ownership'");
        // Single-token queries surface the bare lexeme.
        assert_eq!(build_or_tsquery("dog"), "'dog'");
    }

    #[test]
    fn build_or_tsquery_strips_tsquery_operators() {
        // S79 — tokens must not carry tsquery operators
        // (`& | ! ( ) : * '`) into the parser, which would let a
        // crafted query smuggle a boolean expression past the
        // matcher. Sanitization keeps only ASCII alphanumerics
        // plus `_-` so e.g. `cat | exec()` collapses to two harmless
        // lexemes.
        let got = build_or_tsquery("cat | drop ' table");
        assert!(
            !got.contains('&') && !got.contains('!') && !got.contains('('),
            "build_or_tsquery must drop tsquery operators: got {got}"
        );
        assert!(got.contains("'cat'"), "must keep the cat lexeme: {got}");
        assert!(got.contains("'drop'"), "must keep the drop lexeme: {got}");
        assert!(got.contains("'table'"), "must keep the table lexeme: {got}");
    }

    #[test]
    fn build_or_tsquery_drops_short_tokens() {
        // S79 — single-character tokens are noise (postgres' english
        // text-search config drops them as stop words anyway). Keep
        // tokens >= 2 chars.
        assert_eq!(build_or_tsquery("a brown dog"), "'brown' | 'dog'");
        assert_eq!(build_or_tsquery("x y z"), "'_empty_'");
    }

    #[test]
    fn build_or_tsquery_falls_back_to_sentinel_for_empty_input() {
        // S79 — `to_tsquery('english', '')` errors with a parse
        // failure; the helper substitutes a no-match sentinel so the
        // recall surface returns a clean empty pool instead of a
        // 500.
        assert_eq!(build_or_tsquery(""), "'_empty_'");
        assert_eq!(build_or_tsquery("    "), "'_empty_'");
        assert_eq!(build_or_tsquery("!@# $%^"), "'_empty_'");
    }

    #[test]
    fn build_or_tsquery_caps_token_count() {
        // S79 — pathologically long queries get truncated to 16
        // tokens so the planner doesn't blow up on a 10K-token
        // adversarial input.
        let long = (0..50)
            .map(|i| format!("tok{i:02}"))
            .collect::<Vec<_>>()
            .join(" ");
        let got = build_or_tsquery(&long);
        let lexeme_count = got.matches('|').count() + 1;
        assert_eq!(
            lexeme_count, 16,
            "build_or_tsquery must cap to 16 tokens: got {lexeme_count} from {got}"
        );
    }

    #[test]
    fn agtype_optional_string_decodes_null_and_quoted() {
        // Wire-shape contract: AGE's `cypher()` SRF returns missing
        // values as the literal token `null` and present strings as
        // `"value"`. The decoder MUST collapse `null` to `None` and
        // peel the surrounding quotes from present strings; otherwise
        // the dispatcher would surface the agtype quoting in the
        // upper layer and break parity with the SQLite shape.
        assert_eq!(agtype_optional_string("null"), None);
        assert_eq!(agtype_optional_string("NULL"), None);
        assert_eq!(
            agtype_optional_string("\"agent-1\""),
            Some("agent-1".to_string())
        );
        assert_eq!(
            agtype_optional_string("  \"agent-1\"  "),
            Some("agent-1".to_string())
        );
        assert_eq!(agtype_optional_string("\"\""), Some(String::new()));
    }

    #[tokio::test]
    async fn live_kg_timeline_dispatches_to_cypher_under_age() {
        // Routing contract: when AGE is the resolved backend, calling
        // `kg_timeline` must route through `kg_timeline_cypher` rather
        // than the SQL branch. We don't assert a specific result set
        // here (the J5 dual-path tests own equivalence) — just that
        // the call returns Ok against an AGE-enabled URL with a
        // bootstrapped `memory_graph` projection. Skips cleanly when
        // either piece is missing so CI without AGE stays green.
        let Some(url) = age_kg_url() else {
            eprintln!("skip: AI_MEMORY_TEST_AGE_URL not set");
            return;
        };
        let store = PostgresStore::connect(&url).await.expect("connect");
        assert_eq!(store.kg_backend(), KgBackend::Age);
        // Use a synthetic id we don't expect to find — the test asserts
        // routing, not corpus contents.
        match store
            .kg_timeline("nonexistent-source", None, None, Some(10))
            .await
        {
            Ok(rows) => {
                assert!(
                    rows.is_empty() || rows.iter().all(|r| !r.target_id.is_empty()),
                    "rows must have non-empty target_ids when present"
                );
            }
            Err(StoreError::BackendUnavailable { detail, .. }) => {
                eprintln!(
                    "AGE graph projection appears unbootstrapped on this URL: {detail}; \
                     run the J1 graph-prep script before re-running this test"
                );
            }
            Err(other) => panic!("unexpected error from AGE kg_timeline: {other:?}"),
        }
    }

    #[tokio::test]
    async fn live_kg_timeline_routes_to_cte_without_age() {
        // Inverse of the AGE routing test: against vanilla Postgres
        // (no AGE) the dispatcher must hand the call to the SQL
        // branch. We verify by calling `kg_timeline_cte` directly
        // against a known-empty source and asserting an empty result
        // set, then confirming `kg_timeline` produces the same empty
        // set through the dispatcher.
        let Some(url) = postgres_url() else {
            eprintln!("skip: AI_MEMORY_TEST_POSTGRES_URL not set");
            return;
        };
        let store = PostgresStore::connect(&url).await.expect("connect");
        if store.kg_backend() == KgBackend::Age {
            eprintln!(
                "skip: connected DB has AGE installed; this test exercises the                  CTE-fallback path (#1272)"
            );
            return;
        }
        assert_eq!(
            store.kg_backend(),
            KgBackend::Cte,
            "vanilla Postgres must resolve to KgBackend::Cte"
        );
        let direct = store
            .kg_timeline_cte("nonexistent-source", None, None, None)
            .await
            .expect("cte direct");
        let dispatched = store
            .kg_timeline("nonexistent-source", None, None, None)
            .await
            .expect("cte via dispatcher");
        assert!(direct.is_empty(), "no rows expected for synthetic id");
        assert_eq!(
            direct, dispatched,
            "dispatcher must return the same shape as the direct CTE call"
        );
    }

    // ------------------------------------------------------------------
    // v0.7 J4 — Cypher kg_invalidate unit + live tests.
    //
    // Pool-less unit tests cover the offline surface (the SAL row
    // shape contract) so the dispatcher behaviour holds even when no
    // Postgres is available. The live tests run against an
    // AGE-enabled Postgres (`AI_MEMORY_TEST_AGE_URL`) and skip
    // cleanly otherwise so the default `cargo test` flow stays
    // offline. SQLite-side regression for `db::invalidate_link` lives
    // in `mcp.rs` (`handle_kg_invalidate_*` tests, untouched here).
    // ------------------------------------------------------------------

    #[test]
    fn kg_invalidate_row_default_no_match_shape() {
        // Routing contract: a missed triple at the SAL layer surfaces
        // as `found = false` with empty `valid_until` and `None`
        // `previous_valid_until`. Pinning the shape so the upper-layer
        // handler can branch on `found` without inspecting the inner
        // strings (which the SQLite path leaves unset for the same
        // case via `Option::None` from `db::invalidate_link`).
        let row = KgInvalidateRow {
            found: false,
            valid_until: String::new(),
            previous_valid_until: None,
        };
        assert!(!row.found);
        assert!(row.valid_until.is_empty());
        assert!(row.previous_valid_until.is_none());
    }

    #[test]
    fn kg_invalidate_row_serialises_to_stable_json_keys() {
        // The wire shape is a stable JSON contract — integrators pin
        // against `found / valid_until / previous_valid_until`. A
        // future rename of the struct fields would break their
        // parsers; assert the JSON keys here so the rename surfaces
        // as a test failure rather than a silent drift.
        let row = KgInvalidateRow {
            found: true,
            valid_until: "2026-05-05T12:00:00+00:00".to_string(),
            previous_valid_until: Some("2026-05-04T11:00:00+00:00".to_string()),
        };
        let v = serde_json::to_value(&row).expect("serialise");
        assert_eq!(v["found"], serde_json::Value::Bool(true));
        assert_eq!(v["valid_until"], "2026-05-05T12:00:00+00:00");
        assert_eq!(v["previous_valid_until"], "2026-05-04T11:00:00+00:00");
    }

    #[tokio::test]
    async fn live_kg_invalidate_dispatches_to_cypher_under_age() {
        // Routing contract: when AGE is the resolved backend, calling
        // `kg_invalidate` must route through `kg_invalidate_cypher`
        // rather than the CTE branch. We don't assert a specific
        // result set here (the J5 dual-path tests own equivalence) —
        // just that the call returns Ok against an AGE-enabled URL
        // with a bootstrapped `memory_graph` projection. Skips
        // cleanly when either piece is missing so CI without AGE
        // stays green.
        let Some(url) = age_kg_url() else {
            eprintln!("skip: AI_MEMORY_TEST_AGE_URL not set");
            return;
        };
        let store = PostgresStore::connect(&url).await.expect("connect");
        assert_eq!(store.kg_backend(), KgBackend::Age);
        // Use synthetic ids we don't expect to find — the test asserts
        // routing, not corpus contents. A missing graph projection
        // surfaces as BackendUnavailable; that's still informative
        // (caller learns the AGE setup needs running) so we report it
        // through the test name rather than silently skipping.
        match store
            .kg_invalidate(
                "nonexistent-source",
                "nonexistent-target",
                "related_to",
                None,
            )
            .await
        {
            Ok(row) => {
                assert!(!row.found, "synthetic ids must not match an existing edge");
                assert!(row.valid_until.is_empty());
                assert!(row.previous_valid_until.is_none());
            }
            Err(StoreError::BackendUnavailable { detail, .. }) => {
                eprintln!(
                    "AGE graph projection appears unbootstrapped on this URL: {detail}; \
                     run the J1 graph-prep script before re-running this test"
                );
            }
            Err(other) => panic!("unexpected error from AGE kg_invalidate: {other:?}"),
        }
    }

    #[tokio::test]
    async fn live_kg_invalidate_routes_to_cte_without_age() {
        // Inverse of the AGE routing test: against vanilla Postgres
        // (no AGE) the dispatcher must hand the call to the SQL
        // branch. We verify by calling `kg_invalidate_cte` directly
        // against a known-missing triple and asserting `found=false`,
        // then confirming `kg_invalidate` produces the same shape
        // through the dispatcher.
        let Some(url) = postgres_url() else {
            eprintln!("skip: AI_MEMORY_TEST_POSTGRES_URL not set");
            return;
        };
        let store = PostgresStore::connect(&url).await.expect("connect");
        if store.kg_backend() == KgBackend::Age {
            eprintln!(
                "skip: connected DB has AGE installed; this test exercises the                  CTE-fallback path (#1272)"
            );
            return;
        }
        assert_eq!(
            store.kg_backend(),
            KgBackend::Cte,
            "vanilla Postgres must resolve to KgBackend::Cte"
        );
        let direct = store
            .kg_invalidate_cte(
                "nonexistent-source",
                "nonexistent-target",
                "related_to",
                None,
            )
            .await
            .expect("cte direct");
        let dispatched = store
            .kg_invalidate(
                "nonexistent-source",
                "nonexistent-target",
                "related_to",
                None,
            )
            .await
            .expect("cte via dispatcher");
        assert!(!direct.found, "synthetic triple must not match");
        assert_eq!(
            direct, dispatched,
            "dispatcher must return the same shape as the direct CTE call"
        );
    }

    // ------------------------------------------------------------------
    // Live-Postgres integration tests.
    //
    // Run iff AI_MEMORY_TEST_POSTGRES_URL is set; otherwise they skip
    // cleanly so the default `cargo test` flow stays offline.
    //
    // Quick-start:
    //   docker compose -f packaging/docker-compose.postgres.yml up -d
    //   export AI_MEMORY_TEST_POSTGRES_URL=postgres://ai_memory:ai_memory_test@localhost:5433/ai_memory_test
    //   cargo test --features sal-postgres store::postgres -- --nocapture
    // ------------------------------------------------------------------

    fn postgres_url() -> Option<String> {
        std::env::var("AI_MEMORY_TEST_POSTGRES_URL").ok()
    }

    fn sample_memory(id: &str, ns: &str, title: &str, content: &str) -> Memory {
        let now = chrono::Utc::now().to_rfc3339();
        Memory {
            id: id.to_string(),
            tier: Tier::Mid,
            namespace: ns.to_string(),
            title: title.to_string(),
            content: content.to_string(),
            tags: vec!["test".to_string()],
            priority: 5,
            confidence: 1.0,
            source: "sal-integration".to_string(),
            access_count: 0,
            created_at: now.clone(),
            updated_at: now,
            last_accessed_at: None,
            expires_at: None,
            metadata: serde_json::json!({"agent_id":"ai:sal-test"}),
            reflection_depth: 0,
            memory_kind: crate::models::MemoryKind::Observation,
            entity_id: None,
            persona_version: None,
            citations: Vec::new(),
            source_uri: None,
            source_span: None,
            confidence_source: ConfidenceSource::CallerProvided,
            confidence_signals: None,
            confidence_decayed_at: None,
            version: 1,
        }
    }

    #[tokio::test]
    async fn live_store_get_roundtrip() {
        let Some(url) = postgres_url() else {
            eprintln!("skip: AI_MEMORY_TEST_POSTGRES_URL not set");
            return;
        };
        let store = PostgresStore::connect(&url).await.expect("connect");
        let ctx = CallerContext::for_agent("ai:sal-test");
        // #1278 — uuid-randomize namespace so the (title, namespace)
        // upsert-by-title path can't collide with a prior test run's
        // row when the postgres DB is shared across runs.
        let ns = format!("sal-test-{}", uuid::Uuid::new_v4());
        let mem = sample_memory(
            &format!("test-{}", uuid::Uuid::new_v4()),
            &ns,
            "hello",
            "quick brown fox jumps over the lazy dog",
        );
        let returned = store.store(&ctx, &mem).await.expect("store");
        assert_eq!(returned, mem.id);
        let fetched = store.get(&ctx, &mem.id).await.expect("get");
        assert_eq!(fetched.title, "hello");
        assert_eq!(fetched.namespace, ns);
    }

    #[tokio::test]
    async fn live_search_finds_fts_match() {
        let Some(url) = postgres_url() else {
            return;
        };
        let store = PostgresStore::connect(&url).await.unwrap();
        let ctx = CallerContext::for_agent("ai:sal-test");
        // #1278 — uuid-randomize namespace so the (title, namespace)
        // upsert path can't return a stale prior-run row id.
        let ns = format!("sal-search-{}", uuid::Uuid::new_v4());
        let id = format!("search-test-{}", uuid::Uuid::new_v4());
        let mem = sample_memory(
            &id,
            &ns,
            "uniquephrase xyzzy42",
            "body containing uniquephrase xyzzy42 as a distinctive token",
        );
        store.store(&ctx, &mem).await.unwrap();
        let filter = Filter {
            namespace: Some(ns.clone()),
            limit: 5,
            ..Filter::default()
        };
        let hits = store
            .search(&ctx, "xyzzy42", &filter)
            .await
            .expect("search");
        assert!(hits.iter().any(|m| m.id == id));
    }

    #[tokio::test]
    async fn live_delete_removes_row() {
        let Some(url) = postgres_url() else {
            return;
        };
        let store = PostgresStore::connect(&url).await.unwrap();
        let ctx = CallerContext::for_agent("ai:sal-test");
        // #1278 — uuid-randomize namespace.
        let ns = format!("sal-del-{}", uuid::Uuid::new_v4());
        let id = format!("del-test-{}", uuid::Uuid::new_v4());
        let mem = sample_memory(&id, &ns, "to be deleted", "soon gone");
        store.store(&ctx, &mem).await.unwrap();
        store.delete(&ctx, &id).await.expect("delete");
        let err = store.get(&ctx, &id).await.unwrap_err();
        match err {
            StoreError::NotFound { id: missing } => assert_eq!(missing, id),
            other => panic!("expected NotFound, got {other:?}"),
        }
    }

    // ------------------------------------------------------------------
    // Regression tests for v0.6.0 blockers #294, #295, #296.
    // ------------------------------------------------------------------

    /// Blocker #294 — upsert on (title, namespace) matches SQLite.
    ///
    /// Two stores with identical (title, namespace) but different ids
    /// must collapse into one row on Postgres (keyed by the existing
    /// row's id) rather than producing two rows.
    #[tokio::test]
    async fn upserts_by_title_namespace_not_id() {
        let Some(url) = postgres_url() else {
            return;
        };
        let store = PostgresStore::connect(&url).await.unwrap();
        let ctx = CallerContext::for_agent("ai:sal-test");
        let ns = format!("sal-upsert-{}", uuid::Uuid::new_v4());
        // #1278 — uuid-randomize id to avoid pkey collision on test re-run
        // against a non-truncated postgres DB.
        let id_a = format!("upsert-a-{}", uuid::Uuid::new_v4());
        let id_b = format!("upsert-b-{}", uuid::Uuid::new_v4());
        let first = sample_memory(&id_a, &ns, "shared title", "first body");
        let second = sample_memory(&id_b, &ns, "shared title", "second body");
        let id_first = store.store(&ctx, &first).await.unwrap();
        let id_second = store.store(&ctx, &second).await.unwrap();
        assert_eq!(id_first, id_second, "upsert should return the same id");
        // Namespace list must contain exactly one row with the shared title.
        let filter = Filter {
            namespace: Some(ns.clone()),
            limit: 10,
            ..Filter::default()
        };
        let listed = store.list(&ctx, &filter).await.unwrap();
        assert_eq!(listed.len(), 1, "expected single upserted row");
        assert_eq!(listed[0].content, "second body");
    }

    /// Blocker #295 — metadata.agent_id is SQL-layer-immutable on UPSERT.
    #[tokio::test]
    async fn upsert_preserves_agent_id() {
        let Some(url) = postgres_url() else {
            return;
        };
        let store = PostgresStore::connect(&url).await.unwrap();
        // Use admin ctx so the SAL-level scope=private filter (#910) doesn't
        // mask the row — this test is about agent_id IMMUTABILITY (Blocker
        // #295), not visibility scoping. With `for_agent("ai:sal-test")`
        // the .get() post-filter returns NotFound against an
        // "ai:alice"-owned row.
        let ctx = CallerContext::for_admin("ai:sal-test");
        let ns = format!("sal-agent-{}", uuid::Uuid::new_v4());

        // #1278 — uuid-randomize id to avoid pkey collision on test re-run
        // against a non-truncated postgres DB.
        let id_a = format!("agent-1-{}", uuid::Uuid::new_v4());
        let id_b = format!("agent-2-{}", uuid::Uuid::new_v4());
        let mut first = sample_memory(&id_a, &ns, "owned-by-alice", "original");
        first.metadata = serde_json::json!({"agent_id": "ai:alice"});
        store.store(&ctx, &first).await.unwrap();

        // Second store with the same (title, ns) but claims a different agent_id.
        let mut second = sample_memory(&id_b, &ns, "owned-by-alice", "replayed");
        second.metadata = serde_json::json!({"agent_id": "ai:attacker"});
        store.store(&ctx, &second).await.unwrap();

        let got = store
            .get(&ctx, &store.store(&ctx, &second).await.unwrap())
            .await
            .unwrap();
        assert_eq!(
            got.metadata.get("agent_id").and_then(|v| v.as_str()),
            Some("ai:alice"),
            "agent_id must be pinned to the original writer"
        );
    }

    /// Blocker #296 — tier never downgrades on UPDATE.
    #[tokio::test]
    async fn update_refuses_tier_downgrade() {
        let Some(url) = postgres_url() else {
            return;
        };
        let store = PostgresStore::connect(&url).await.unwrap();
        let ctx = CallerContext::for_agent("ai:sal-test");

        // #1278 — uuid-randomize namespace so the (title, namespace)
        // upsert path can't return a stale prior-run row id.
        let ns = format!("sal-tier-{}", uuid::Uuid::new_v4());
        let id = format!("tier-test-{}", uuid::Uuid::new_v4());
        let mut mem = sample_memory(&id, &ns, "long-pinned", "must not downgrade");
        mem.tier = Tier::Long;
        store.store(&ctx, &mem).await.unwrap();

        // Attempt to downgrade Long -> Short via update patch.
        let patch = UpdatePatch {
            tier: Some(Tier::Short),
            ..UpdatePatch::default()
        };
        store.update(&ctx, &id, patch).await.unwrap();

        let got = store.get(&ctx, &id).await.unwrap();
        assert!(
            matches!(got.tier, Tier::Long),
            "tier must remain Long (got {:?})",
            got.tier
        );
    }

    /// Verify migration is idempotent: running twice produces the same result.
    /// Tests that ALTER TABLE/CREATE INDEX operations are guarded with
    /// IF NOT EXISTS checks, and that schema_version is correctly recorded.
    #[tokio::test]
    async fn migration_v15_is_idempotent() {
        let Some(url) = postgres_url() else {
            eprintln!("skipping: no AI_MEMORY_TEST_POSTGRES_URL");
            return;
        };
        let store = PostgresStore::connect(&url).await.expect("connect");

        // Read schema version after first connect (migration runs implicitly).
        let first_version: Option<i32> =
            sqlx::query_scalar("SELECT COALESCE(MAX(version), 0) FROM schema_version")
                .fetch_optional(&store.pool)
                .await
                .expect("read version after first connect");

        // Run migration again explicitly (should be a no-op).
        store.migrate().await.expect("migrate again");

        // Verify schema version hasn't changed (idempotent).
        let second_version: Option<i32> =
            sqlx::query_scalar("SELECT COALESCE(MAX(version), 0) FROM schema_version")
                .fetch_optional(&store.pool)
                .await
                .expect("read version after second migrate");

        assert_eq!(
            first_version, second_version,
            "schema version must be stable across repeated migrations"
        );

        // Verify the v15 columns exist (created or already existed).
        let has_valid_from: Option<(i32,)> = sqlx::query_as(
            "SELECT 1 FROM information_schema.columns
             WHERE table_name='memory_links' AND column_name='valid_from'",
        )
        .fetch_optional(&store.pool)
        .await
        .expect("check valid_from column");
        assert!(has_valid_from.is_some(), "valid_from column must exist");

        let has_entity_aliases_idx: Option<(String,)> = sqlx::query_as(
            "SELECT indexname FROM pg_indexes WHERE indexname='idx_entity_aliases_alias'",
        )
        .fetch_optional(&store.pool)
        .await
        .expect("check entity_aliases index");
        assert!(
            has_entity_aliases_idx.is_some(),
            "idx_entity_aliases_alias must exist"
        );
    }

    // ------------------------------------------------------------------
    // v0.7.0 Wave 2 — schema parity v17 → v28.
    //
    // Each test below either asserts the bootstrap shape (CREATE TABLE
    // / CREATE INDEX present after `connect`) or exercises a tiny CRUD
    // round-trip against the new substrate. All tests skip cleanly
    // when AI_MEMORY_TEST_POSTGRES_URL is unset so the default offline
    // flow stays green.
    // ------------------------------------------------------------------

    #[test]
    fn init_schema_advertises_full_v28_shape() {
        // Sanity-check the bootstrap SQL covers every load-bearing
        // table/column added between v17 and v28. A typo'd rename or
        // an accidental drop catches here in CI rather than on the
        // first live `connect()` against a populated host.
        for needle in [
            // v17 — governance.inherit (no DDL, runtime backfill only).
            // v18 — embedding_dim columns + archive lossless.
            "embedding_dim",
            "original_tier",
            "original_expires_at",
            // v19 — webhook event_types + index.
            "event_types",
            "idx_subscriptions_event_types",
            // v20 — capability-expansion audit_log.
            "CREATE TABLE IF NOT EXISTS audit_log",
            "idx_audit_log_agent_id",
            // v21 — pending_actions timeout sweeper.
            "default_timeout_seconds",
            "expired_at",
            "pending_actions_status_requested_idx",
            // v22 — memory_transcripts substrate.
            "CREATE TABLE IF NOT EXISTS memory_transcripts",
            "idx_memory_transcripts_namespace_created",
            // v23 — memory_links.attest_level.
            "idx_memory_links_attest_level",
            // v24 — memory_transcript_links join table.
            "CREATE TABLE IF NOT EXISTS memory_transcript_links",
            "idx_mtl_transcript",
            "idx_mtl_memory",
            // v25 — transcript archive lifecycle.
            "idx_memory_transcripts_archived_at",
            // v26 — signed_events audit chain.
            "CREATE TABLE IF NOT EXISTS signed_events",
            "idx_signed_events_agent",
            // v27 — A2A correlation IDs + DLQ.
            "CREATE TABLE IF NOT EXISTS subscription_events",
            "CREATE TABLE IF NOT EXISTS subscription_dlq",
            "idx_subscription_events_correlation",
            "idx_subscription_dlq_correlation",
            // v28 — agent_quotas.
            "CREATE TABLE IF NOT EXISTS agent_quotas",
            "idx_agent_quotas_agent_id",
        ] {
            assert!(
                INIT_SCHEMA.contains(needle),
                "postgres_schema.sql missing expected v17-v28 fragment: {needle}"
            );
        }
    }

    #[test]
    fn current_schema_version_matches_sqlite_ladder() {
        // Pin the parity invariant: Postgres tracks the SQLite
        // CURRENT_SCHEMA_VERSION except for the postgres-only ladder
        // steps below. v29 is Postgres-only (in-place `vector(N)`
        // conversion helper); v30 is Postgres-only too (M15 —
        // `memories_metadata_is_object` CHECK; SQLite doesn't carry an
        // analogue because the SQLite metadata column has no JSON
        // type-checking primitive equivalent to `jsonb_typeof`). v31
        // mirrors SQLite v29 (`memories.reflection_depth`, v0.7.0
        // Task 1/8 — recursive learning). v32 mirrors SQLite v33 — the
        // v0.7.1-fold (#687/#688) SQL-side CHECK constraint on
        // `memory_links.relation`. v33 mirrors SQLite v34 — V-4
        // closeout (#698) signed_events cross-row hash chain.
        //
        // v42-v46 land via #894 (PG+AGE parity for provenance Gaps 1-7):
        //   v42 = memories.version BIGINT (Gap 1 #884)
        //   v43 = memories.source_uri upgrade-path + partial index (Gap 2 #885)
        //   v44 = recall_observations table (Gap 3 #886)
        //   v45 = edit_source archive metadata + lookup indexes (Gap 5 #888)
        //   v46 = memory_links temporal columns (Gap 7 / #860)
        //   v47 = memory_links persona-signing atomicity CHECK (#902)
        //   v48 = federation_push_dlq table (Track D #933)
        //   v49 = archived_memories full v0.7.0 column carry (#1025) —
        //         adds 14 columns (reflection_depth, atomised_into, atom_of,
        //         memory_kind, entity_id, persona_version, citations,
        //         source_uri, source_span, confidence_source,
        //         confidence_signals, confidence_decayed_at,
        //         mentioned_entity_id, version) so archive → restore is
        //         lossless for the full v0.7.0 Memory shape.
        //   v50 = per-namespace K8 quota dimension (#1156) — extends
        //         `agent_quotas` PRIMARY KEY from `(agent_id)` to
        //         `(agent_id, namespace)` so per-namespace allotments
        //         hold even when a single agent operates across many
        //         namespaces.
        //
        // A future bump on either side without the corresponding port
        // re-trips this assertion before the migration runner gets a
        // chance to write a partial schema to disk. No hardcoded
        // literal — the cross-adapter SSOT tripwire pins
        // `postgres::CURRENT_SCHEMA_VERSION` against the sqlite
        // `storage::migrations::current_schema_version()` accessor.
        assert_eq!(
            i64::from(CURRENT_SCHEMA_VERSION),
            crate::storage::migrations::current_schema_version(),
            "postgres CURRENT_SCHEMA_VERSION must track the sqlite SSOT \
             (storage::migrations::CURRENT_SCHEMA_VERSION). A bump on either \
             side without the corresponding port re-trips this assertion."
        );
    }

    #[tokio::test]
    async fn live_migration_reaches_current_schema_version() {
        let Some(url) = postgres_url() else {
            eprintln!("skip: AI_MEMORY_TEST_POSTGRES_URL not set");
            return;
        };
        let store = PostgresStore::connect(&url).await.expect("connect");

        let stamped: Option<i32> = sqlx::query_scalar("SELECT MAX(version) FROM schema_version")
            .fetch_optional(&store.pool)
            .await
            .expect("read max schema_version");
        assert_eq!(
            stamped,
            Some(CURRENT_SCHEMA_VERSION),
            "schema_version must reach CURRENT_SCHEMA_VERSION"
        );
    }

    #[tokio::test]
    async fn live_migration_v17_to_current_is_idempotent() {
        // Run migrate() twice and assert the schema_version is stable;
        // the IF NOT EXISTS DDL + column-existence guards mean every
        // migrate_vN must be a no-op on a populated database.
        let Some(url) = postgres_url() else {
            eprintln!("skip: AI_MEMORY_TEST_POSTGRES_URL not set");
            return;
        };
        let store = PostgresStore::connect(&url).await.expect("connect");

        let first: Option<i32> = sqlx::query_scalar("SELECT MAX(version) FROM schema_version")
            .fetch_optional(&store.pool)
            .await
            .expect("read first version");

        store.migrate().await.expect("migrate again");

        let second: Option<i32> = sqlx::query_scalar("SELECT MAX(version) FROM schema_version")
            .fetch_optional(&store.pool)
            .await
            .expect("read second version");

        assert_eq!(first, second, "migrate() must be idempotent");
        assert_eq!(second, Some(CURRENT_SCHEMA_VERSION));
    }

    /// Helper: assert a named relation (table or view) exists.
    async fn assert_relation_exists(pool: &PgPool, relname: &str) {
        let exists: Option<i32> = sqlx::query_scalar(
            "SELECT 1 FROM pg_class WHERE relname = $1 AND relkind IN ('r','v')",
        )
        .bind(relname)
        .fetch_optional(pool)
        .await
        .expect("query pg_class");
        assert!(exists.is_some(), "expected relation {relname} to exist");
    }

    /// Helper: assert a named index exists.
    async fn assert_index_exists(pool: &PgPool, indexname: &str) {
        let exists: Option<String> =
            sqlx::query_scalar("SELECT indexname FROM pg_indexes WHERE indexname = $1")
                .bind(indexname)
                .fetch_optional(pool)
                .await
                .expect("query pg_indexes");
        assert!(exists.is_some(), "expected index {indexname} to exist");
    }

    /// Helper: assert a column on a table exists.
    async fn assert_column_exists(pool: &PgPool, table: &str, column: &str) {
        let exists: Option<i32> = sqlx::query_scalar(
            "SELECT 1 FROM information_schema.columns
             WHERE table_name = $1 AND column_name = $2",
        )
        .bind(table)
        .bind(column)
        .fetch_optional(pool)
        .await
        .expect("query information_schema");
        assert!(
            exists.is_some(),
            "expected column {table}.{column} to exist"
        );
    }

    #[tokio::test]
    async fn live_v18_data_integrity_columns_present() {
        let Some(url) = postgres_url() else {
            eprintln!("skip: AI_MEMORY_TEST_POSTGRES_URL not set");
            return;
        };
        let store = PostgresStore::connect(&url).await.expect("connect");
        for (table, column) in [
            ("memories", "embedding_dim"),
            ("archived_memories", "embedding"),
            ("archived_memories", "embedding_dim"),
            ("archived_memories", "original_tier"),
            ("archived_memories", "original_expires_at"),
        ] {
            assert_column_exists(&store.pool, table, column).await;
        }
        assert_index_exists(&store.pool, "idx_memories_embedding_dim").await;
        assert_index_exists(&store.pool, "idx_memories_ns_dim").await;
    }

    #[tokio::test]
    async fn live_v19_webhook_event_types_present() {
        let Some(url) = postgres_url() else {
            eprintln!("skip: AI_MEMORY_TEST_POSTGRES_URL not set");
            return;
        };
        let store = PostgresStore::connect(&url).await.expect("connect");
        assert_column_exists(&store.pool, "subscriptions", "event_types").await;
        assert_index_exists(&store.pool, "idx_subscriptions_event_types").await;
    }

    #[tokio::test]
    async fn live_v20_audit_log_table_present() {
        let Some(url) = postgres_url() else {
            eprintln!("skip: AI_MEMORY_TEST_POSTGRES_URL not set");
            return;
        };
        let store = PostgresStore::connect(&url).await.expect("connect");
        assert_relation_exists(&store.pool, "audit_log").await;
        assert_index_exists(&store.pool, "idx_audit_log_agent_id").await;
        assert_index_exists(&store.pool, "idx_audit_log_timestamp").await;
        assert_index_exists(&store.pool, "idx_audit_log_event_type").await;

        // CRUD round-trip — the K8 attested-cortex epic queries this
        // by (agent_id, timestamp). Insert / read / delete to prove the
        // table is functionally writable, not just present.
        let now = chrono::Utc::now();
        let id = format!("audit-{}", uuid::Uuid::new_v4());
        sqlx::query(
            "INSERT INTO audit_log
             (id, agent_id, event_type, requested_family, granted, attestation_tier, timestamp)
             VALUES ($1, $2, $3, $4, $5, $6, $7)",
        )
        .bind(&id)
        .bind("ai:test")
        .bind("capability_expansion")
        .bind("kg")
        .bind(true)
        .bind(Option::<&str>::None)
        .bind(now)
        .execute(&store.pool)
        .await
        .expect("insert audit_log row");

        let granted: bool = sqlx::query_scalar("SELECT granted FROM audit_log WHERE id = $1")
            .bind(&id)
            .fetch_one(&store.pool)
            .await
            .expect("read audit_log row");
        assert!(granted, "round-trip should preserve granted=true");

        sqlx::query("DELETE FROM audit_log WHERE id = $1")
            .bind(&id)
            .execute(&store.pool)
            .await
            .expect("delete audit_log row");
    }

    #[tokio::test]
    async fn live_v21_pending_actions_timeout_columns_present() {
        let Some(url) = postgres_url() else {
            eprintln!("skip: AI_MEMORY_TEST_POSTGRES_URL not set");
            return;
        };
        let store = PostgresStore::connect(&url).await.expect("connect");
        assert_column_exists(&store.pool, "pending_actions", "default_timeout_seconds").await;
        assert_column_exists(&store.pool, "pending_actions", "expired_at").await;
        assert_index_exists(&store.pool, "pending_actions_status_requested_idx").await;
    }

    #[tokio::test]
    async fn live_v22_memory_transcripts_table_present() {
        let Some(url) = postgres_url() else {
            eprintln!("skip: AI_MEMORY_TEST_POSTGRES_URL not set");
            return;
        };
        let store = PostgresStore::connect(&url).await.expect("connect");
        assert_relation_exists(&store.pool, "memory_transcripts").await;
        assert_index_exists(&store.pool, "idx_memory_transcripts_namespace_created").await;
    }

    #[tokio::test]
    async fn live_v24_transcript_links_and_kg_views_present() {
        let Some(url) = postgres_url() else {
            eprintln!("skip: AI_MEMORY_TEST_POSTGRES_URL not set");
            return;
        };
        let store = PostgresStore::connect(&url).await.expect("connect");
        assert_relation_exists(&store.pool, "memory_transcript_links").await;
        assert_index_exists(&store.pool, "idx_mtl_transcript").await;
        assert_index_exists(&store.pool, "idx_mtl_memory").await;
        // F6 KG views are the Postgres-only addition tied to the v24 stamp.
        assert_relation_exists(&store.pool, "kg_query_view").await;
        assert_relation_exists(&store.pool, "kg_timeline_view").await;
        // kg_find_paths is a function — probe via pg_proc.
        let fn_exists: Option<i32> =
            sqlx::query_scalar("SELECT 1 FROM pg_proc WHERE proname = 'kg_find_paths'")
                .fetch_optional(&store.pool)
                .await
                .expect("query pg_proc for kg_find_paths");
        assert!(fn_exists.is_some(), "kg_find_paths function must exist");
    }

    #[tokio::test]
    async fn live_v25_transcript_archive_lifecycle_present() {
        let Some(url) = postgres_url() else {
            eprintln!("skip: AI_MEMORY_TEST_POSTGRES_URL not set");
            return;
        };
        let store = PostgresStore::connect(&url).await.expect("connect");
        assert_column_exists(&store.pool, "memory_transcripts", "archived_at").await;
        assert_index_exists(&store.pool, "idx_memory_transcripts_archived_at").await;
    }

    #[tokio::test]
    async fn live_v26_signed_events_table_present() {
        let Some(url) = postgres_url() else {
            eprintln!("skip: AI_MEMORY_TEST_POSTGRES_URL not set");
            return;
        };
        let store = PostgresStore::connect(&url).await.expect("connect");
        assert_relation_exists(&store.pool, "signed_events").await;
        for idx in [
            "idx_signed_events_agent",
            "idx_signed_events_type",
            "idx_signed_events_timestamp",
        ] {
            assert_index_exists(&store.pool, idx).await;
        }

        // Append-only round-trip — INSERT then SELECT. Mirrors the
        // single-writer contract documented on signed_events: no
        // UPDATE / DELETE call site is allowed to land in production
        // src/ (enforced by the
        // `append_only_invariant_no_mutators_in_src` test in
        // src/signed_events.rs). The test row uses a UUIDv4 id so
        // re-runs against the same disposable database accumulate
        // bounded inert rows rather than colliding.
        let id = format!("se-{}", uuid::Uuid::new_v4());
        let payload_hash = vec![0u8; 32];
        let now = chrono::Utc::now();
        sqlx::query(
            "INSERT INTO signed_events
             (id, agent_id, event_type, payload_hash, signature, attest_level, timestamp)
             VALUES ($1, $2, $3, $4, $5, $6, $7)",
        )
        .bind(&id)
        .bind("ai:test")
        .bind("memory_link.created")
        .bind(&payload_hash)
        .bind(Option::<Vec<u8>>::None)
        .bind("unsigned")
        .bind(now)
        .execute(&store.pool)
        .await
        .expect("insert signed_events row");

        let level: String =
            sqlx::query_scalar("SELECT attest_level FROM signed_events WHERE id = $1")
                .bind(&id)
                .fetch_one(&store.pool)
                .await
                .expect("read signed_events row");
        assert_eq!(level, "unsigned");
    }

    #[tokio::test]
    async fn live_v27_subscription_events_and_dlq_present() {
        let Some(url) = postgres_url() else {
            eprintln!("skip: AI_MEMORY_TEST_POSTGRES_URL not set");
            return;
        };
        let store = PostgresStore::connect(&url).await.expect("connect");
        assert_relation_exists(&store.pool, "subscription_events").await;
        assert_relation_exists(&store.pool, "subscription_dlq").await;
        for idx in [
            "idx_subscription_events_correlation",
            "idx_subscription_events_subscription",
            "idx_subscription_dlq_subscription",
            "idx_subscription_dlq_correlation",
        ] {
            assert_index_exists(&store.pool, idx).await;
        }
        assert_column_exists(&store.pool, "subscription_events", "correlation_id").await;
    }

    #[tokio::test]
    async fn live_v28_agent_quotas_table_present_and_writable() {
        let Some(url) = postgres_url() else {
            eprintln!("skip: AI_MEMORY_TEST_POSTGRES_URL not set");
            return;
        };
        let store = PostgresStore::connect(&url).await.expect("connect");
        assert_relation_exists(&store.pool, "agent_quotas").await;
        assert_index_exists(&store.pool, "idx_agent_quotas_agent_id").await;

        // Round-trip — INSERT defaults, SELECT defaults, UPDATE counter,
        // DELETE. Proves the BIGINT defaults match the SQLite ones
        // (1000/100MiB/5000) byte-for-byte so the K8 sweep loop's
        // "first-write" path will produce identical rows on either
        // backend.
        let agent = format!("ai:quota-test-{}", uuid::Uuid::new_v4());
        let now = chrono::Utc::now();
        sqlx::query(
            "INSERT INTO agent_quotas
             (agent_id, day_started_at, created_at, updated_at)
             VALUES ($1, $2, $3, $4)",
        )
        .bind(&agent)
        .bind(now)
        .bind(now)
        .bind(now)
        .execute(&store.pool)
        .await
        .expect("insert agent_quotas row");

        let (max_mem, max_bytes, max_links): (i64, i64, i64) = sqlx::query_as(
            "SELECT max_memories_per_day, max_storage_bytes, max_links_per_day
             FROM agent_quotas WHERE agent_id = $1",
        )
        .bind(&agent)
        .fetch_one(&store.pool)
        .await
        .expect("read agent_quotas row");
        assert_eq!(max_mem, 1000);
        assert_eq!(max_bytes, 104_857_600);
        assert_eq!(max_links, 5000);

        sqlx::query("DELETE FROM agent_quotas WHERE agent_id = $1")
            .bind(&agent)
            .execute(&store.pool)
            .await
            .expect("delete agent_quotas row");
    }

    // ------------------------------------------------------------------
    // F-A2A1.2 (#700) — live-PG governance enforcement tests.
    //
    // These pin the postgres adapter's `enforce_governance_action` end-
    // to-end against a real schema: seed a namespace standard with a
    // governance policy, walk inheritance through deep children, and
    // assert the per-level decision matches the SQLite reference.
    // Skipped when `AI_MEMORY_TEST_POSTGRES_URL` is unset (matches the
    // discipline of the existing live tests above).
    //
    // Mapping to the failing A2A scenarios:
    // - `live_governance_allow_owner_at_leaf`           — S53 phase B (owner write 201)
    // - `live_governance_deny_non_owner_inherited`      — S53/S60/S80 (intruder 403)
    // - `live_governance_pending_on_approve_level`      — S34 (write goes pending)
    // - `live_governance_inheritance_cap_at_five`       — depth-cap spec pin
    // ------------------------------------------------------------------

    /// Seed a namespace standard memory and register it via
    /// `namespace_meta`. Returns the standard_id. Owner is the
    /// metadata.agent_id stamped on the standard memory.
    async fn seed_governance_standard(
        pool: &sqlx::PgPool,
        namespace: &str,
        owner: &str,
        policy_json: serde_json::Value,
    ) -> String {
        let standard_id = uuid::Uuid::new_v4().to_string();
        let now = chrono::Utc::now();
        let metadata = serde_json::json!({
            "agent_id": owner,
            "governance": policy_json,
        });
        sqlx::query(
            "INSERT INTO memories (
                id, tier, namespace, title, content, tags, priority, confidence,
                source, access_count, created_at, updated_at, metadata
            ) VALUES ($1, 'long', $2, $3, 'standard', '[]'::jsonb, 5, 1.0,
                      'test', 0, $4, $4, $5)",
        )
        .bind(&standard_id)
        .bind(namespace)
        .bind(format!("standard:{namespace}"))
        .bind(now)
        .bind(&metadata)
        .execute(pool)
        .await
        .expect("seed standard memory");

        sqlx::query(
            "INSERT INTO namespace_meta (namespace, standard_id, parent_namespace) \
             VALUES ($1, $2, NULL) \
             ON CONFLICT (namespace) DO UPDATE SET standard_id = EXCLUDED.standard_id",
        )
        .bind(namespace)
        .bind(&standard_id)
        .execute(pool)
        .await
        .expect("seed namespace_meta");

        standard_id
    }

    async fn cleanup_governance_ns(pool: &sqlx::PgPool, namespace: &str) {
        let _ = sqlx::query("DELETE FROM pending_actions WHERE namespace LIKE $1")
            .bind(format!("{namespace}%"))
            .execute(pool)
            .await;
        let _ = sqlx::query("DELETE FROM namespace_meta WHERE namespace LIKE $1")
            .bind(format!("{namespace}%"))
            .execute(pool)
            .await;
        let _ = sqlx::query("DELETE FROM memories WHERE namespace LIKE $1")
            .bind(format!("{namespace}%"))
            .execute(pool)
            .await;
    }

    #[tokio::test]
    async fn live_governance_allow_owner_at_leaf() {
        // S53 phase B — owner writes to their own namespace under a
        // `write=owner` policy. Decision must be Allow.
        let Some(url) = postgres_url() else {
            eprintln!("skip: AI_MEMORY_TEST_POSTGRES_URL not set");
            return;
        };
        crate::config::override_active_permissions_mode_for_test(
            crate::config::PermissionsMode::Enforce,
        );
        let store = PostgresStore::connect(&url).await.expect("connect");
        let pool = store.pool.clone();
        let owner = format!("ai:gov-owner-{}", uuid::Uuid::new_v4());
        let ns = format!("fa2a12-allow-{}", &uuid::Uuid::new_v4().to_string()[..8]);
        seed_governance_standard(
            &pool,
            &ns,
            &owner,
            serde_json::json!({"write": "owner", "promote": "any", "delete": "owner"}),
        )
        .await;

        let payload = serde_json::json!({"title": "owner write"});
        let decision = store
            .enforce_governance_action(
                crate::store::GovernedAction::Store,
                &ns,
                &owner,
                None,
                None,
                &payload,
            )
            .await
            .expect("enforce_governance_action");
        assert!(
            matches!(decision, crate::models::GovernanceDecision::Allow),
            "owner write to own ns must Allow; got {decision:?}"
        );

        cleanup_governance_ns(&pool, &ns).await;
    }

    #[tokio::test]
    async fn live_governance_deny_non_owner_inherited() {
        // S53/S60/S80 — a non-owner write to a deep child of a
        // `write=owner` parent must be Denied via the inheritance walk.
        let Some(url) = postgres_url() else {
            eprintln!("skip: AI_MEMORY_TEST_POSTGRES_URL not set");
            return;
        };
        crate::config::override_active_permissions_mode_for_test(
            crate::config::PermissionsMode::Enforce,
        );
        let store = PostgresStore::connect(&url).await.expect("connect");
        let pool = store.pool.clone();
        let owner = format!("ai:gov-owner-{}", uuid::Uuid::new_v4());
        let intruder = format!("ai:gov-intruder-{}", uuid::Uuid::new_v4());
        let parent = format!("fa2a12-deny-{}", &uuid::Uuid::new_v4().to_string()[..8]);
        let deep_child = format!("{parent}/sub/level/deep");
        seed_governance_standard(
            &pool,
            &parent,
            &owner,
            serde_json::json!({
                "write": "owner",
                "promote": "any",
                "delete": "owner",
                "inherit": true,
            }),
        )
        .await;

        let payload = serde_json::json!({"title": "intruder"});
        let decision = store
            .enforce_governance_action(
                crate::store::GovernedAction::Store,
                &deep_child,
                &intruder,
                None,
                None,
                &payload,
            )
            .await
            .expect("enforce_governance_action");
        match decision {
            crate::models::GovernanceDecision::Deny(refusal) => {
                assert!(
                    refusal.reason.contains("owner-only namespace")
                        || refusal.reason.to_lowercase().contains("owner"),
                    "deny reason should reference owner-only policy; got: {refusal:?}"
                );
                assert_eq!(
                    refusal.denied_level,
                    crate::models::GovernanceLevel::Owner,
                    "owner-level deny must carry GovernanceLevel::Owner; got {refusal:?}",
                );
            }
            other => panic!("intruder write to deep child must Deny; got {other:?}"),
        }

        // Owner write to the same deep child should Allow — owner walk
        // resolves leaf→root and finds the parent's standard owner.
        let owner_decision = store
            .enforce_governance_action(
                crate::store::GovernedAction::Store,
                &deep_child,
                &owner,
                None,
                None,
                &payload,
            )
            .await
            .expect("enforce_governance_action owner");
        assert!(
            matches!(owner_decision, crate::models::GovernanceDecision::Allow),
            "owner write to inherited deep child must Allow; got {owner_decision:?}"
        );

        cleanup_governance_ns(&pool, &parent).await;
    }

    #[tokio::test]
    async fn live_governance_pending_on_approve_level() {
        // S34 — a `write=approve` policy on a namespace must route
        // non-owner writes through Pending. The decision payload must
        // land a row in `pending_actions`.
        let Some(url) = postgres_url() else {
            eprintln!("skip: AI_MEMORY_TEST_POSTGRES_URL not set");
            return;
        };
        crate::config::override_active_permissions_mode_for_test(
            crate::config::PermissionsMode::Enforce,
        );
        let store = PostgresStore::connect(&url).await.expect("connect");
        let pool = store.pool.clone();
        let owner = format!("ai:gov-owner-{}", uuid::Uuid::new_v4());
        let requester = format!("ai:gov-requester-{}", uuid::Uuid::new_v4());
        let ns = format!("fa2a12-pending-{}", &uuid::Uuid::new_v4().to_string()[..8]);
        seed_governance_standard(
            &pool,
            &ns,
            &owner,
            serde_json::json!({"write": "approve", "promote": "any", "delete": "owner"}),
        )
        .await;

        let payload = serde_json::json!({"title": "needs approval"});
        let decision = store
            .enforce_governance_action(
                crate::store::GovernedAction::Store,
                &ns,
                &requester,
                None,
                None,
                &payload,
            )
            .await
            .expect("enforce_governance_action");
        let pending_id = match decision {
            crate::models::GovernanceDecision::Pending(id) => id,
            other => panic!("approve-level non-owner write must Pending; got {other:?}"),
        };
        assert!(!pending_id.is_empty(), "Pending id must be non-empty");

        let row: (String, String, String) = sqlx::query_as(
            "SELECT action_type, namespace, status FROM pending_actions WHERE id = $1",
        )
        .bind(&pending_id)
        .fetch_one(&pool)
        .await
        .expect("read pending_actions row");
        assert_eq!(row.0, "store", "action_type must be 'store'");
        assert_eq!(row.1, ns, "namespace must match");
        assert_eq!(row.2, "pending", "status must be 'pending'");

        cleanup_governance_ns(&pool, &ns).await;
    }

    #[tokio::test]
    async fn live_governance_inheritance_cap_at_five() {
        // F-A2A1.2 depth cap — a namespace at MAX_NAMESPACE_DEPTH (8
        // levels) under a `write=owner` parent at the root must still
        // resolve to Deny for a non-owner, because the cap retains the
        // most-specific 5 levels which include the policy-anchored
        // child path. Conversely, a policy seated at the root that's
        // OUTSIDE the cap (depth 8 child, policy at depth 1 root) is
        // expected NOT to apply — the cap is the explicit contract.
        //
        // This test pins the "most-specific kept" semantics by seating
        // the policy 2 levels above the leaf (well within the cap)
        // and verifying inheritance fires.
        let Some(url) = postgres_url() else {
            eprintln!("skip: AI_MEMORY_TEST_POSTGRES_URL not set");
            return;
        };
        crate::config::override_active_permissions_mode_for_test(
            crate::config::PermissionsMode::Enforce,
        );
        let store = PostgresStore::connect(&url).await.expect("connect");
        let pool = store.pool.clone();
        let owner = format!("ai:cap-owner-{}", uuid::Uuid::new_v4());
        let intruder = format!("ai:cap-intruder-{}", uuid::Uuid::new_v4());
        // Anchor the policy at a 4-segment namespace; the leaf is 6
        // segments — within the cap.
        let suffix = &uuid::Uuid::new_v4().to_string()[..6];
        let policy_ns = format!("fa2a12-cap-{suffix}/a/b/c");
        let leaf_ns = format!("{policy_ns}/d/e");
        seed_governance_standard(
            &pool,
            &policy_ns,
            &owner,
            serde_json::json!({
                "write": "owner",
                "promote": "any",
                "delete": "owner",
                "inherit": true,
            }),
        )
        .await;

        let payload = serde_json::json!({"leaf": leaf_ns});
        let decision = store
            .enforce_governance_action(
                crate::store::GovernedAction::Store,
                &leaf_ns,
                &intruder,
                None,
                None,
                &payload,
            )
            .await
            .expect("enforce_governance_action");
        match decision {
            crate::models::GovernanceDecision::Deny(_) => {}
            other => panic!(
                "policy at depth 4 must deny intruder write at depth 6 (within cap); got \
                 {other:?}"
            ),
        }

        cleanup_governance_ns(&pool, &format!("fa2a12-cap-{suffix}")).await;
    }

    // ---------------------------------------------------------------------
    // FX-C2 (ARCH-2 followup) — `get_links_for_anchor` parity coverage.
    //
    // Mirror of the SQLite-side tests in `src/store/sqlite.rs`. Pins
    // the per-anchor probe's wire shape across both backends: inbound +
    // outbound edges in one call, empty vec for unlinked anchors,
    // attest_level + temporal-validity columns round-trip via the
    // sqlx projection. Skips cleanly when AI_MEMORY_TEST_POSTGRES_URL
    // is unset so the default `cargo test` flow stays offline.
    // ---------------------------------------------------------------------

    async fn fxc2_seed_two_memories(store: &PostgresStore, ns: &str) -> (String, String) {
        let ctx = CallerContext::for_agent("ai:sal-test");
        let a_id = format!("fxc2-a-{}", uuid::Uuid::new_v4());
        let b_id = format!("fxc2-b-{}", uuid::Uuid::new_v4());
        let a = sample_memory(&a_id, ns, "fxc2-anchor", "anchor content here");
        let b = sample_memory(&b_id, ns, "fxc2-target", "target content here");
        store.store(&ctx, &a).await.expect("store anchor");
        store.store(&ctx, &b).await.expect("store target");
        (a_id, b_id)
    }

    #[tokio::test]
    async fn live_get_links_for_anchor_returns_inbound_and_outbound() {
        let Some(url) = postgres_url() else {
            eprintln!("skip: AI_MEMORY_TEST_POSTGRES_URL not set");
            return;
        };
        let store = PostgresStore::connect(&url).await.expect("connect");
        let ctx = CallerContext::for_agent("ai:sal-test");
        let ns = format!("fxc2-getlinks-{}", uuid::Uuid::new_v4());
        let (a_id, b_id) = fxc2_seed_two_memories(&store, &ns).await;
        // upstream memory C used as inbound-anchor probe source
        let c_id = format!("fxc2-c-{}", uuid::Uuid::new_v4());
        let c = sample_memory(&c_id, &ns, "fxc2-upstream", "upstream content");
        store.store(&ctx, &c).await.expect("store upstream");

        let now = chrono::Utc::now().to_rfc3339();
        // anchor -> target (outbound)
        store
            .link(
                &ctx,
                &MemoryLink {
                    source_id: a_id.clone(),
                    target_id: b_id.clone(),
                    relation: crate::models::MemoryLinkRelation::RelatedTo,
                    created_at: now.clone(),
                    valid_from: None,
                    valid_until: None,
                    observed_by: None,
                    signature: None,
                    attest_level: None,
                },
            )
            .await
            .expect("link a->b");
        // upstream -> anchor (inbound)
        store
            .link(
                &ctx,
                &MemoryLink {
                    source_id: c_id.clone(),
                    target_id: a_id.clone(),
                    relation: crate::models::MemoryLinkRelation::Contradicts,
                    created_at: now,
                    valid_from: None,
                    valid_until: None,
                    observed_by: None,
                    signature: None,
                    attest_level: None,
                },
            )
            .await
            .expect("link c->a");

        let edges = store
            .get_links_for_anchor(&a_id)
            .await
            .expect("get_links_for_anchor");
        assert!(
            edges
                .iter()
                .any(|l| l.source_id == a_id && l.target_id == b_id),
            "missing outbound edge in postgres parity"
        );
        assert!(
            edges
                .iter()
                .any(|l| l.source_id == c_id && l.target_id == a_id),
            "missing inbound edge in postgres parity"
        );
    }

    #[tokio::test]
    async fn live_get_links_for_anchor_empty_for_unlinked_id() {
        let Some(url) = postgres_url() else {
            eprintln!("skip: AI_MEMORY_TEST_POSTGRES_URL not set");
            return;
        };
        let store = PostgresStore::connect(&url).await.expect("connect");
        let ctx = CallerContext::for_agent("ai:sal-test");
        let ns = format!("fxc2-empty-{}", uuid::Uuid::new_v4());
        let alone_id = format!("fxc2-alone-{}", uuid::Uuid::new_v4());
        let alone = sample_memory(&alone_id, &ns, "fxc2-alone", "no edges here");
        store.store(&ctx, &alone).await.expect("store alone");
        let edges = store
            .get_links_for_anchor(&alone_id)
            .await
            .expect("get_links_for_anchor on unlinked id");
        assert!(
            edges.is_empty(),
            "unlinked id must yield empty vec across both backends"
        );
    }

    #[tokio::test]
    async fn live_get_links_for_anchor_projects_attest_level_and_temporal() {
        // FX-C2 wire-shape parity: the Postgres branch MUST project the
        // same `attest_level` + temporal-validity columns the SQLite
        // branch does. This test inserts a row with explicit
        // valid_from/valid_until/observed_by/attest_level via raw sqlx
        // and verifies the trait-routed read round-trips them.
        let Some(url) = postgres_url() else {
            eprintln!("skip: AI_MEMORY_TEST_POSTGRES_URL not set");
            return;
        };
        let store = PostgresStore::connect(&url).await.expect("connect");
        let ns = format!("fxc2-temporal-{}", uuid::Uuid::new_v4());
        let (a_id, b_id) = fxc2_seed_two_memories(&store, &ns).await;
        let vf = chrono::DateTime::parse_from_rfc3339("2026-01-01T00:00:00Z")
            .expect("parse vf")
            .with_timezone(&chrono::Utc);
        let vu = chrono::DateTime::parse_from_rfc3339("2026-12-31T23:59:59Z")
            .expect("parse vu")
            .with_timezone(&chrono::Utc);
        sqlx::query(
            "INSERT INTO memory_links
                (source_id, target_id, relation, created_at,
                 valid_from, valid_until, observed_by, attest_level)
             VALUES ($1, $2, $3, NOW(), $4, $5, $6, $7)",
        )
        .bind(&a_id)
        .bind(&b_id)
        .bind("related_to")
        .bind(vf)
        .bind(vu)
        .bind("ai:tester@host")
        .bind("unsigned")
        .execute(&store.pool)
        .await
        .expect("raw insert for temporal probe");

        let edges = store
            .get_links_for_anchor(&a_id)
            .await
            .expect("get_links_for_anchor");
        let row = edges
            .iter()
            .find(|l| l.source_id == a_id && l.target_id == b_id)
            .expect("just-inserted edge");
        assert_eq!(row.valid_from.as_deref(), Some("2026-01-01T00:00:00+00:00"));
        assert_eq!(
            row.valid_until.as_deref(),
            Some("2026-12-31T23:59:59+00:00")
        );
        assert_eq!(row.observed_by.as_deref(), Some("ai:tester@host"));
        assert_eq!(row.attest_level.as_deref(), Some("unsigned"));
    }

    // ============================================================
    // FX-C2-batch3 — Postgres live parity for read-only trait
    // additions (list_namespaces, get_taxonomy, list_agents,
    // list_pending_actions, entity_get_by_alias, health_check,
    // stats). Gated on AI_MEMORY_TEST_POSTGRES_URL.
    // ============================================================

    #[tokio::test]
    async fn live_list_namespaces_groups_by_count() {
        let Some(url) = postgres_url() else {
            eprintln!("skip: AI_MEMORY_TEST_POSTGRES_URL not set");
            return;
        };
        let store = PostgresStore::connect(&url).await.expect("connect");
        let ctx = CallerContext::for_agent("ai:sal-test");
        let unique = uuid::Uuid::new_v4();
        let ns_alpha = format!("fxc2-ns-alpha-{unique}");
        let ns_beta = format!("fxc2-ns-beta-{unique}");
        for i in 0..3 {
            let id = format!("a-{i}-{unique}");
            let mem = sample_memory(&id, &ns_alpha, &format!("t-{i}"), "body content");
            store.store(&ctx, &mem).await.expect("store alpha");
        }
        let mem = sample_memory(&format!("b-{unique}"), &ns_beta, "tb", "beta body content");
        store.store(&ctx, &mem).await.expect("store beta");
        let rows = store.list_namespaces().await.expect("list_namespaces");
        let alpha = rows
            .iter()
            .find(|r| r.namespace == ns_alpha)
            .expect("alpha namespace");
        let beta = rows
            .iter()
            .find(|r| r.namespace == ns_beta)
            .expect("beta namespace");
        assert_eq!(alpha.count, 3);
        assert_eq!(beta.count, 1);
    }

    #[tokio::test]
    async fn live_get_taxonomy_assembles_hierarchical_tree() {
        let Some(url) = postgres_url() else {
            eprintln!("skip: AI_MEMORY_TEST_POSTGRES_URL not set");
            return;
        };
        let store = PostgresStore::connect(&url).await.expect("connect");
        let ctx = CallerContext::for_agent("ai:sal-test");
        let unique = uuid::Uuid::new_v4();
        let root = format!("fxc2-tax-{unique}");
        let team = format!("{root}/team");
        let secrets = format!("{root}/team/secrets");
        let mem_root = sample_memory(&format!("root-{unique}"), &root, "rt", "root body content");
        store.store(&ctx, &mem_root).await.expect("store root");
        for i in 0..2 {
            let mem = sample_memory(
                &format!("team-{i}-{unique}"),
                &team,
                &format!("t-{i}"),
                "team body content",
            );
            store.store(&ctx, &mem).await.expect("store team");
        }
        let mem_sec = sample_memory(
            &format!("sec-{unique}"),
            &secrets,
            "ss",
            "secrets body content",
        );
        store.store(&ctx, &mem_sec).await.expect("store secrets");

        let tax = store
            .get_taxonomy(Some(&root), 8, 100)
            .await
            .expect("get_taxonomy");
        assert_eq!(tax.total_count, 4, "1 root + 2 team + 1 secrets = 4");
        assert_eq!(tax.tree.namespace, root);
        assert_eq!(tax.tree.subtree_count, 4);
        assert!(!tax.truncated);
    }

    #[tokio::test]
    async fn live_list_agents_roundtrip() {
        let Some(url) = postgres_url() else {
            eprintln!("skip: AI_MEMORY_TEST_POSTGRES_URL not set");
            return;
        };
        let store = PostgresStore::connect(&url).await.expect("connect");
        let ctx = CallerContext::for_agent("daemon");
        let unique = uuid::Uuid::new_v4();
        let agent_id = format!("ai:fxc2-tester-{unique}");
        let agent = AgentRegistration {
            agent_id: agent_id.clone(),
            agent_type: "test".to_string(),
            capabilities: vec!["recall".to_string()],
            registered_at: String::new(),
            last_seen_at: String::new(),
        };
        store
            .register_agent(&ctx, &agent)
            .await
            .expect("register_agent");
        let listed = store.list_agents().await.expect("list_agents");
        assert!(
            listed.iter().any(|r| r.agent_id == agent_id),
            "registered agent must surface in list_agents"
        );
    }

    #[tokio::test]
    async fn live_list_pending_actions_returns_seeded_row() {
        let Some(url) = postgres_url() else {
            eprintln!("skip: AI_MEMORY_TEST_POSTGRES_URL not set");
            return;
        };
        let store = PostgresStore::connect(&url).await.expect("connect");
        let unique = uuid::Uuid::new_v4();
        let ns = format!("fxc2-pa-{unique}");
        let pid = format!("pa-{unique}");
        // Seed a single pending row directly into the table.
        sqlx::query(
            "INSERT INTO pending_actions
                 (id, action_type, memory_id, namespace, payload, requested_by,
                  requested_at, status, approvals)
             VALUES ($1, $2, $3, $4, $5, $6, NOW(), $7, $8)",
        )
        .bind(&pid)
        .bind("Store")
        .bind(None::<String>)
        .bind(&ns)
        .bind(serde_json::json!({"title":"t","content":"c"}))
        .bind("alice")
        .bind("pending")
        .bind(serde_json::json!([]))
        .execute(&store.pool)
        .await
        .expect("seed pending_actions row");

        let rows =
            <PostgresStore as MemoryStore>::list_pending_actions(&store, Some("pending"), 100)
                .await
                .expect("list_pending_actions");
        let row = rows
            .iter()
            .find(|r| r.id == pid)
            .expect("seeded pending row must surface");
        assert_eq!(row.namespace, ns);
        assert_eq!(row.status, "pending");
        assert_eq!(row.requested_by, "alice");
    }

    #[tokio::test]
    async fn live_entity_get_by_alias_resolves_canonical_record() {
        let Some(url) = postgres_url() else {
            eprintln!("skip: AI_MEMORY_TEST_POSTGRES_URL not set");
            return;
        };
        let store = PostgresStore::connect(&url).await.expect("connect");
        let ctx = CallerContext::for_agent("ai:sal-test");
        let unique = uuid::Uuid::new_v4();
        let ns = format!("fxc2-ent-{unique}");
        let entity_id = format!("ent-{unique}");
        let mut mem = sample_memory(
            &entity_id,
            &ns,
            &format!("alphaone-co-{unique}"),
            "entity row body",
        );
        mem.metadata = serde_json::json!({
            "kind": "entity",
            "agent_id": "ai:sal-test",
        });
        store.store(&ctx, &mem).await.expect("store entity");
        let alias = format!("AlphaOne-{unique}");
        // Postgres `entity_aliases` is (entity_id, alias, created_at);
        // namespace is resolved via JOIN with `memories`.
        sqlx::query("INSERT INTO entity_aliases (entity_id, alias) VALUES ($1, $2)")
            .bind(&entity_id)
            .bind(&alias)
            .execute(&store.pool)
            .await
            .expect("insert alias");

        let rec = store
            .entity_get_by_alias(&alias, Some(&ns))
            .await
            .expect("entity_get_by_alias");
        let rec = rec.expect("entity must resolve");
        assert_eq!(rec.entity_id, entity_id);
        assert_eq!(rec.namespace, ns);
        assert!(rec.aliases.iter().any(|a| a == &alias));
    }

    #[tokio::test]
    async fn live_health_check_returns_true() {
        let Some(url) = postgres_url() else {
            eprintln!("skip: AI_MEMORY_TEST_POSTGRES_URL not set");
            return;
        };
        let store = PostgresStore::connect(&url).await.expect("connect");
        let ok = store.health_check().await.expect("health_check");
        assert!(ok);
    }

    #[tokio::test]
    async fn live_stats_projects_full_shape() {
        let Some(url) = postgres_url() else {
            eprintln!("skip: AI_MEMORY_TEST_POSTGRES_URL not set");
            return;
        };
        let store = PostgresStore::connect(&url).await.expect("connect");
        let ctx = CallerContext::for_agent("ai:sal-test");
        let unique = uuid::Uuid::new_v4();
        let ns = format!("fxc2-stats-{unique}");
        for i in 0..2 {
            let mem = sample_memory(
                &format!("stats-{i}-{unique}"),
                &ns,
                &format!("t-{i}"),
                "stats body content",
            );
            store.store(&ctx, &mem).await.expect("store");
        }
        let s = store.stats().await.expect("stats");
        let ns_row = s
            .by_namespace
            .iter()
            .find(|r| r.namespace == ns)
            .expect("ns must surface in stats");
        assert_eq!(ns_row.count, 2);
        assert!(s.total >= 2, "stats.total must include seeded rows");
        // db_size_bytes is best-effort on postgres; assert non-negative
        // shape — we already enforce non-negative via u64::try_from.
        let _ = s.db_size_bytes;
    }

    // ------------------------------------------------------------------
    // FX-C2 batch-4 — live-Postgres parity tests for the six new trait
    // methods (find_by_title_namespace, next_versioned_title,
    // find_contradictions, invalidate_link, check_duplicate_with_text,
    // update_embedding). Each test skips cleanly when
    // AI_MEMORY_TEST_POSTGRES_URL is unset.
    // ------------------------------------------------------------------

    #[tokio::test]
    async fn live_find_by_title_namespace_resolves_id() {
        let Some(url) = postgres_url() else {
            eprintln!("skip: AI_MEMORY_TEST_POSTGRES_URL not set");
            return;
        };
        let store = PostgresStore::connect(&url).await.expect("connect");
        let ctx = CallerContext::for_agent("ai:sal-test");
        let unique = uuid::Uuid::new_v4();
        let ns = format!("fxc2b4-find-{unique}");
        let mem = sample_memory(
            &format!("find-{unique}"),
            &ns,
            "find-target-title",
            "find_by_title body",
        );
        let id = store.store(&ctx, &mem).await.expect("store");
        let found = store
            .find_by_title_namespace("find-target-title", &ns)
            .await
            .expect("find_by_title_namespace");
        assert_eq!(found.as_deref(), Some(id.as_str()));
        let missing = store
            .find_by_title_namespace("nonexistent-title", &ns)
            .await
            .expect("find_by_title_namespace miss");
        assert!(missing.is_none());
    }

    #[tokio::test]
    async fn live_next_versioned_title_picks_suffix_on_collision() {
        let Some(url) = postgres_url() else {
            eprintln!("skip: AI_MEMORY_TEST_POSTGRES_URL not set");
            return;
        };
        let store = PostgresStore::connect(&url).await.expect("connect");
        let ctx = CallerContext::for_agent("ai:sal-test");
        let unique = uuid::Uuid::new_v4();
        let ns = format!("fxc2b4-version-{unique}");
        // First store claims the base title.
        let mem = sample_memory(
            &format!("ver-{unique}"),
            &ns,
            "version-base",
            "v1 body content",
        );
        store.store(&ctx, &mem).await.expect("store");
        let picked = store
            .next_versioned_title("version-base", &ns)
            .await
            .expect("next_versioned_title");
        assert_eq!(picked, "version-base (2)");
        // Fresh title is returned unchanged.
        let fresh = store
            .next_versioned_title("never-used-title", &ns)
            .await
            .expect("next_versioned_title fresh");
        assert_eq!(fresh, "never-used-title");
    }

    #[tokio::test]
    async fn live_find_contradictions_surfaces_fts_hits() {
        let Some(url) = postgres_url() else {
            eprintln!("skip: AI_MEMORY_TEST_POSTGRES_URL not set");
            return;
        };
        let store = PostgresStore::connect(&url).await.expect("connect");
        let ctx = CallerContext::for_agent("ai:sal-test");
        let unique = uuid::Uuid::new_v4();
        let ns = format!("fxc2b4-contradictions-{unique}");
        let m1 = sample_memory(
            &format!("c1-{unique}"),
            &ns,
            "rust borrow checker semantics",
            "rust language safety guarantees",
        );
        let m2 = sample_memory(
            &format!("c2-{unique}"),
            &ns,
            "completely separate cookbook",
            "fish stew recipe and instructions",
        );
        store.store(&ctx, &m1).await.expect("store m1");
        store.store(&ctx, &m2).await.expect("store m2");
        let hits = store
            .find_contradictions("rust borrow checker", &ns)
            .await
            .expect("find_contradictions");
        assert!(
            hits.iter().any(|m| m.title.contains("rust borrow")),
            "must surface rust row"
        );
        assert!(
            !hits.iter().any(|m| m.title.contains("cookbook")),
            "must not surface unrelated row"
        );
    }

    #[tokio::test]
    async fn live_invalidate_link_marks_found() {
        let Some(url) = postgres_url() else {
            eprintln!("skip: AI_MEMORY_TEST_POSTGRES_URL not set");
            return;
        };
        let store = PostgresStore::connect(&url).await.expect("connect");
        let ctx = CallerContext::for_agent("ai:sal-test");
        let unique = uuid::Uuid::new_v4();
        let ns = format!("fxc2b4-invalidate-{unique}");
        let src = sample_memory(
            &format!("src-{unique}"),
            &ns,
            "src-title",
            "src body content",
        );
        let dst = sample_memory(
            &format!("dst-{unique}"),
            &ns,
            "dst-title",
            "dst body content",
        );
        let src_id = store.store(&ctx, &src).await.expect("store src");
        let dst_id = store.store(&ctx, &dst).await.expect("store dst");
        let link = crate::models::MemoryLink {
            source_id: src_id.clone(),
            target_id: dst_id.clone(),
            relation: crate::models::MemoryLinkRelation::RelatedTo,
            created_at: chrono::Utc::now().to_rfc3339(),
            signature: None,
            observed_by: None,
            valid_from: None,
            valid_until: None,
            attest_level: None,
        };
        store.link(&ctx, &link).await.expect("create link");
        let row = store
            .invalidate_link(&src_id, &dst_id, "related_to", Some("2030-01-01T00:00:00Z"))
            .await
            .expect("invalidate_link");
        assert!(row.found, "link must be marked found");
        // valid_until is normalised on the postgres side; just assert
        // non-empty + timezone present.
        assert!(!row.valid_until.is_empty());
        // Calling again should surface the prior value.
        let row2 = store
            .invalidate_link(&src_id, &dst_id, "related_to", Some("2031-02-02T00:00:00Z"))
            .await
            .expect("re-invalidate");
        assert!(row2.found);
        assert!(row2.previous_valid_until.is_some());
    }

    /// #1568 (H1 residual) — the postgres SAL link path must run the
    /// same pre-link gates as the sqlite `db::create_link_signed`
    /// path. Pre-fix, `link_internal` performed FK pre-flight only, so
    /// a `reflects_on` edge that closes a reflection cycle landed
    /// ungoverned on postgres-backed daemons. Pins: cycle refusal with
    /// the canonical `LINK_CYCLE_ERR_PREFIX` message (the 409-class
    /// `StoreError::LinkRefused`), and that non-reflects_on relations
    /// are unaffected.
    #[tokio::test]
    async fn live_link_reflects_on_cycle_refused_1568() {
        let Some(url) = postgres_url() else {
            eprintln!("skip: AI_MEMORY_TEST_POSTGRES_URL not set");
            return;
        };
        let store = PostgresStore::connect(&url).await.expect("connect");
        let ctx = CallerContext::for_agent("ai:sal-test");
        let unique = uuid::Uuid::new_v4();
        let ns = format!("h1res-link-{unique}");
        let a = sample_memory(&format!("cyc-a-{unique}"), &ns, "cyc-a", "body a");
        let b = sample_memory(&format!("cyc-b-{unique}"), &ns, "cyc-b", "body b");
        let a_id = store.store(&ctx, &a).await.expect("store a");
        let b_id = store.store(&ctx, &b).await.expect("store b");

        let mk = |src: &str, dst: &str| crate::models::MemoryLink {
            source_id: src.to_string(),
            target_id: dst.to_string(),
            relation: crate::models::MemoryLinkRelation::ReflectsOn,
            created_at: chrono::Utc::now().to_rfc3339(),
            signature: None,
            observed_by: None,
            valid_from: None,
            valid_until: None,
            attest_level: None,
        };

        // a reflects_on b lands fine (no cycle yet).
        store.link(&ctx, &mk(&a_id, &b_id)).await.expect("a->b");
        // b reflects_on a would close the cycle — must be refused.
        let err = store
            .link(&ctx, &mk(&b_id, &a_id))
            .await
            .expect_err("cycle-closing reflects_on edge must be refused");
        assert!(
            matches!(err, StoreError::LinkRefused { .. }),
            "expected LinkRefused, got: {err:?}"
        );
        assert!(
            err.to_string()
                .starts_with(crate::storage::LINK_CYCLE_ERR_PREFIX),
            "wire message must carry the canonical cycle prefix, got: {err}"
        );
        // Direct self-link is refused too (walker's defensive arm).
        let err_self = store
            .link(&ctx, &mk(&a_id, &a_id))
            .await
            .expect_err("self reflects_on must be refused");
        assert!(matches!(err_self, StoreError::LinkRefused { .. }));
        // Non-reflects_on relations are unaffected (gate not over-broad).
        let mut rel = mk(&b_id, &a_id);
        rel.relation = crate::models::MemoryLinkRelation::RelatedTo;
        store
            .link(&ctx, &rel)
            .await
            .expect("related_to b->a must still land");
    }

    /// #1572 (M1 residual) — postgres parity for the recall-path
    /// confidence-decay touch. Pre-fix the `AI_MEMORY_CONFIDENCE_DECAY`
    /// opt-in only decayed on the sqlite adapter. Pins: a 30-day-old
    /// row (one `DEFAULT_HALF_LIFE_DAYS`) touched with decay enabled
    /// lands at ~0.5 confidence with `confidence_source = 'decayed'`
    /// and a fresh `confidence_decayed_at` stamp; with the env unset,
    /// the touch leaves confidence calibration untouched.
    #[tokio::test]
    async fn live_touch_after_recall_applies_decay_parity_1572() {
        let Some(url) = postgres_url() else {
            eprintln!("skip: AI_MEMORY_TEST_POSTGRES_URL not set");
            return;
        };
        let store = PostgresStore::connect(&url).await.expect("connect");
        let ctx = CallerContext::for_agent("ai:sal-test");
        let unique = uuid::Uuid::new_v4();
        let ns = format!("m1res-decay-{unique}");

        // Control row — decay disabled: calibration columns untouched.
        let control = sample_memory(&format!("decay-ctl-{unique}"), &ns, "decay-ctl", "body");
        let control_id = store.store(&ctx, &control).await.expect("store control");
        store
            .touch_after_recall(&[control_id.clone()])
            .await
            .expect("touch control");
        let got = store.get(&ctx, &control_id).await.expect("get control");
        assert_eq!(got.confidence_source, ConfidenceSource::CallerProvided);
        assert!(got.confidence_decayed_at.is_none());
        assert!((got.confidence - 1.0).abs() < f64::EPSILON);

        // Decay row — backdate created_at by one half-life, enable the
        // opt-in, touch, and expect the half-life collapse to ~0.5.
        let mem = sample_memory(&format!("decay-{unique}"), &ns, "decay-row", "body");
        let id = store.store(&ctx, &mem).await.expect("store");
        sqlx::query(
            "UPDATE memories SET created_at = NOW() - ($2 || ' days')::interval WHERE id = $1",
        )
        .bind(&id)
        .bind(crate::confidence::DEFAULT_HALF_LIFE_DAYS.to_string())
        .execute(&store.pool)
        .await
        .expect("backdate created_at");

        // SAFETY: env set/remove window scoped tightly around the
        // touch — same precedent as tests/form_5_confidence_calibration.rs.
        unsafe { std::env::set_var(crate::confidence::decay::ENV_DECAY, "1") };
        let touch_result = store.touch_after_recall(&[id.clone()]).await;
        unsafe { std::env::remove_var(crate::confidence::decay::ENV_DECAY) };
        touch_result.expect("touch with decay enabled");

        let got = store.get(&ctx, &id).await.expect("get decayed row");
        assert_eq!(
            got.confidence_source,
            ConfidenceSource::Decayed,
            "decay touch must flip provenance to 'decayed'"
        );
        assert!(
            got.confidence_decayed_at.is_some(),
            "decay touch must stamp confidence_decayed_at"
        );
        assert!(
            (got.confidence - 0.5).abs() < 0.02,
            "one half-life of age must collapse confidence to ~0.5, got {}",
            got.confidence
        );
    }

    /// #1608 — `store_with_embedding` (the postgres HTTP-create anchor
    /// hot path) must persist the FULL Form-4 / Form-5 / QW-2 column
    /// set. Pre-fix its INSERT listed 19 columns, so citations /
    /// source_uri / source_span / confidence_source /
    /// confidence_signals / confidence_decayed_at / entity_id /
    /// persona_version were silently dropped and the schema default
    /// `confidence_source = 'caller_provided'` contradicted the wire
    /// response (the #1588 DO-leg lived finding: anchor row lied while
    /// the federation receivers — fed via the #1029-fixed
    /// `apply_remote_memory` — were correct).
    #[tokio::test]
    async fn live_store_with_embedding_persists_full_provenance_1608() {
        let Some(url) = postgres_url() else {
            eprintln!("skip: AI_MEMORY_TEST_POSTGRES_URL not set");
            return;
        };
        let store = PostgresStore::connect(&url).await.expect("connect");
        let ctx = CallerContext::for_agent("ai:sal-test");
        let unique = uuid::Uuid::new_v4();
        let ns = format!("prov-1608-{unique}");

        let mut mem = sample_memory(&format!("prov-{unique}"), &ns, "prov-1608", "body");
        mem.confidence_source = ConfidenceSource::Default;
        mem.citations = vec![crate::models::Citation {
            uri: "doc:rerun-evidence".to_string(),
            accessed_at: "2026-06-11T00:00:00Z".to_string(),
            hash: None,
            span: None,
        }];
        mem.source_uri = Some("doc:1608-source".to_string());
        mem.entity_id = Some("entity-1608".to_string());
        mem.persona_version = Some(3);

        // Dim matches the test schema's `vector(384)` column (the
        // MiniLM default the AGE test harness provisions).
        let embedding = vec![0.5_f32; 384];
        let id = store
            .store_with_embedding(&ctx, &mem, Some(&embedding))
            .await
            .expect("store_with_embedding");

        let got = store.get(&ctx, &id).await.expect("get back");
        assert_eq!(
            got.confidence_source,
            ConfidenceSource::Default,
            "persisted confidence_source must match the handler-stamped value, \
             not the schema default (#1608)"
        );
        assert_eq!(got.citations.len(), 1, "citation must round-trip");
        assert_eq!(got.citations[0].uri, "doc:rerun-evidence");
        assert_eq!(got.source_uri.as_deref(), Some("doc:1608-source"));
        assert_eq!(got.entity_id.as_deref(), Some("entity-1608"));
        assert_eq!(got.persona_version, Some(3));

        // store() parity for the two QW-2 columns it previously dropped.
        let mut mem2 = sample_memory(&format!("prov2-{unique}"), &ns, "prov-1608-b", "body");
        mem2.entity_id = Some("entity-1608-b".to_string());
        mem2.persona_version = Some(7);
        let id2 = store.store(&ctx, &mem2).await.expect("plain store");
        let got2 = store.get(&ctx, &id2).await.expect("get back 2");
        assert_eq!(got2.entity_id.as_deref(), Some("entity-1608-b"));
        assert_eq!(got2.persona_version, Some(7));
    }

    /// #1607 — postgres twin of the sqlite #1596 touch-TTL extension
    /// FLOOR. Pre-fix `touch_after_recall` REPLACED `expires_at` with
    /// `NOW() + window`, so recalling a fresh mid-tier row pulled its
    /// +7d create-time backstop in to now+1d. Pins: a mid-tier row
    /// whose expiry is ~7 days out keeps that expiry across a touch
    /// (`GREATEST` floor), while a row whose expiry is nearer than the
    /// 1-day window is extended out to ~now+1d.
    #[tokio::test]
    async fn live_touch_after_recall_expiry_is_extension_floor_1607() {
        let Some(url) = postgres_url() else {
            eprintln!("skip: AI_MEMORY_TEST_POSTGRES_URL not set");
            return;
        };
        let store = PostgresStore::connect(&url).await.expect("connect");
        let ctx = CallerContext::for_agent("ai:sal-test");
        let unique = uuid::Uuid::new_v4();
        let ns = format!("floor-1607-{unique}");

        let expiry_secs = |id: &str| {
            let pool = store.pool.clone();
            let id = id.to_string();
            async move {
                let row: (Option<f64>,) = sqlx::query_as(
                    "SELECT EXTRACT(EPOCH FROM (expires_at - NOW()))::float8 \
                     FROM memories WHERE id = $1",
                )
                .bind(&id)
                .fetch_one(&pool)
                .await
                .expect("read expiry");
                row.0.expect("expires_at must be set")
            }
        };

        // Far-expiry row: +7d backstop must SURVIVE the touch.
        let mut far = sample_memory(&format!("floor-far-{unique}"), &ns, "floor-far", "body");
        far.tier = crate::models::Tier::Mid;
        let far_id = store.store(&ctx, &far).await.expect("store far");
        sqlx::query("UPDATE memories SET expires_at = NOW() + INTERVAL '7 days' WHERE id = $1")
            .bind(&far_id)
            .execute(&store.pool)
            .await
            .expect("set far expiry");
        store
            .touch_after_recall(&[far_id.clone()])
            .await
            .expect("touch far");
        let day_secs = f64::from(u32::try_from(crate::SECS_PER_DAY).expect("fits u32"));
        let far_secs = expiry_secs(&far_id).await;
        assert!(
            far_secs > 6.0 * day_secs,
            "touch must NOT pull a +7d expiry in (floor semantics, #1607); \
             remaining secs = {far_secs}"
        );

        // Near-expiry row: +1h remaining must be EXTENDED to ~now+1d.
        let mut near = sample_memory(&format!("floor-near-{unique}"), &ns, "floor-near", "body");
        near.tier = crate::models::Tier::Mid;
        let near_id = store.store(&ctx, &near).await.expect("store near");
        sqlx::query("UPDATE memories SET expires_at = NOW() + INTERVAL '1 hour' WHERE id = $1")
            .bind(&near_id)
            .execute(&store.pool)
            .await
            .expect("set near expiry");
        store
            .touch_after_recall(&[near_id.clone()])
            .await
            .expect("touch near");
        let near_secs = expiry_secs(&near_id).await;
        assert!(
            (near_secs - day_secs).abs() < 300.0,
            "touch must extend a near expiry out to ~now+1d; remaining secs = {near_secs}"
        );
    }

    /// #1542 — a failing AGE projection must NOT poison the link
    /// transaction. Reproduces the fleet posture: a NON-superuser role
    /// (PostgreSQL refuses `LOAD 'age'` for it, and it has no
    /// `ag_catalog` USAGE so the MERGE fails too) writes a link via
    /// `link_signed`. Pre-#1542 the aborted tx made the final COMMIT a
    /// silent ROLLBACK: the handler returned 201 while `memory_links`
    /// persisted nothing (lived on do-1461: 201 + linked:true + zero
    /// rows). Post-fix the projection rides a SAVEPOINT and the
    /// canonical relational row must be readable afterwards.
    #[tokio::test]
    async fn live_link_persists_when_age_projection_refused_1542() {
        let Some(url) = postgres_url() else {
            eprintln!("skip: AI_MEMORY_TEST_POSTGRES_URL not set");
            return;
        };
        let admin = PostgresStore::connect(&url).await.expect("connect admin");
        let ctx = CallerContext::for_agent("ai:sal-test");
        let unique = uuid::Uuid::new_v4().simple().to_string();
        let ns = format!("link-1542-{unique}");

        // Two anchor rows, written as the privileged test role.
        let a = sample_memory(&format!("l42a-{unique}"), &ns, "l42-a", "src");
        let b = sample_memory(&format!("l42b-{unique}"), &ns, "l42-b", "dst");
        let a_id = admin.store(&ctx, &a).await.expect("store a");
        let b_id = admin.store(&ctx, &b).await.expect("store b");

        // Provision a LOAD-refused role mirroring the fleet daemon
        // posture: full DML on the public schema, NO superuser, NO
        // ag_catalog access. Idempotent across runs.
        let role = format!("age_refused_1542_{unique}");
        let pw = uuid::Uuid::new_v4().simple().to_string();
        // Membership in the admin role confers object OWNERSHIP rights
        // (so `connect()`'s idempotent schema-init passes) WITHOUT the
        // SUPERUSER attribute — `LOAD` checks the current role's own
        // attribute, which is exactly the fleet daemon posture.
        let admin_role: String = sqlx::query_scalar("SELECT current_user")
            .fetch_one(&admin.pool)
            .await
            .expect("resolve admin role");
        for stmt in [
            format!("CREATE ROLE {role} LOGIN PASSWORD '{pw}'"),
            format!("GRANT {admin_role} TO {role}"),
        ] {
            // CONNECT grant references whatever db the URL names; the
            // ai_memory literal arm is best-effort for shared harness
            // DBs — failures here only matter if the final connect
            // fails, which the assert below surfaces.
            let _ = sqlx::query(&stmt).execute(&admin.pool).await;
        }
        let restricted_url = {
            // Splice the restricted credentials into the test URL.
            let rest = url
                .split_once('@')
                .map(|(_, tail)| tail.to_string())
                .expect("test URL must carry credentials");
            format!("postgres://{role}:{pw}@{rest}")
        };
        let restricted = match PostgresStore::connect(&restricted_url).await {
            Ok(s) => s,
            Err(e) => {
                // Local pg_hba may forbid password auth for ad-hoc
                // roles; that environment cannot exercise this pin.
                eprintln!("skip: restricted-role connect failed ({e})");
                return;
            }
        };

        // Precondition pin: LOAD 'age' must actually be REFUSED for
        // this role — otherwise the test silently stops exercising the
        // #1542 poisoned-tx path.
        let load_err = sqlx::query("LOAD 'age'").execute(&restricted.pool).await;
        assert!(
            load_err.is_err(),
            "test precondition: LOAD 'age' must be refused for the              non-superuser role (got Ok — role attributes drifted)"
        );

        let link = MemoryLink {
            source_id: a_id.clone(),
            target_id: b_id.clone(),
            relation: crate::models::MemoryLinkRelation::RelatedTo,
            created_at: String::new(),
            valid_from: None,
            valid_until: None,
            observed_by: None,
            signature: None,
            attest_level: None,
        };
        restricted
            .link_signed(&ctx, &link, None)
            .await
            .expect("link_signed must succeed for the restricted role");

        // THE pin: the canonical relational row must actually exist.
        let n: i64 = sqlx::query_scalar(
            "SELECT count(*) FROM memory_links WHERE source_id = $1 AND target_id = $2",
        )
        .bind(&a_id)
        .bind(&b_id)
        .fetch_one(&admin.pool)
        .await
        .expect("count link rows");
        assert_eq!(
            n, 1,
            "the relational memory_links row must persist even when the \
             AGE projection is refused for the writing role (#1542)"
        );
    }

    #[tokio::test]
    async fn live_invalidate_link_returns_not_found_for_unknown_triple() {
        let Some(url) = postgres_url() else {
            eprintln!("skip: AI_MEMORY_TEST_POSTGRES_URL not set");
            return;
        };
        let store = PostgresStore::connect(&url).await.expect("connect");
        let row = store
            .invalidate_link("nope-src", "nope-dst", "related_to", None)
            .await
            .expect("invalidate_link miss");
        assert!(!row.found);
        assert!(row.valid_until.is_empty());
    }

    #[tokio::test]
    async fn live_check_duplicate_with_text_hash_short_circuit() {
        let Some(url) = postgres_url() else {
            eprintln!("skip: AI_MEMORY_TEST_POSTGRES_URL not set");
            return;
        };
        let store = PostgresStore::connect(&url).await.expect("connect");
        let ctx = CallerContext::for_agent("ai:sal-test");
        let unique = uuid::Uuid::new_v4();
        let ns = format!("fxc2b4-dup-{unique}");
        let mem = sample_memory(
            &format!("dup-{unique}"),
            &ns,
            "dup-test-title",
            "dup-test body content",
        );
        store.store(&ctx, &mem).await.expect("store");
        let query_text = format!("{} {}", mem.title, mem.content);
        // Empty embedding — phase 1 hash short-circuit doesn't need
        // pgvector and must surface similarity=1.0 byte-equal.
        let check = store
            .check_duplicate_with_text(&[], &query_text, Some(&ns), 0.8)
            .await
            .expect("check_duplicate_with_text");
        assert!(
            check.is_duplicate,
            "byte-equal text must short-circuit as duplicate"
        );
        let n = check.nearest.expect("nearest must be populated");
        assert!((n.similarity - 1.0).abs() < f32::EPSILON);
    }

    #[tokio::test]
    async fn live_update_embedding_persists_vector() {
        let Some(url) = postgres_url() else {
            eprintln!("skip: AI_MEMORY_TEST_POSTGRES_URL not set");
            return;
        };
        let store = PostgresStore::connect(&url).await.expect("connect");
        let ctx = CallerContext::for_agent("ai:sal-test");
        let unique = uuid::Uuid::new_v4();
        let ns = format!("fxc2b4-update-emb-{unique}");
        let mem = sample_memory(
            &format!("emb-{unique}"),
            &ns,
            "emb-test",
            "embedding update body",
        );
        let id = store.store(&ctx, &mem).await.expect("store");
        // PostgresStore declares the embedding column as `vector(N)`
        // where N matches `EMBEDDING_DIM` (the connect-time selection).
        // To stay backend-agnostic in this test we read the current
        // column dim and craft a zero vector of that length.
        let dim = store
            .current_embedding_dim()
            .await
            .expect("current_embedding_dim");
        let dim_usize = usize::try_from(dim.unwrap_or(384)).unwrap_or(384);
        let vec = vec![0.0_f32; dim_usize];
        store
            .update_embedding(&ctx, &id, Some(&vec))
            .await
            .expect("update_embedding");
        // Re-fetch to verify the vector landed (column is non-NULL).
        let written: Option<i64> = sqlx::query_scalar(
            "SELECT 1::BIGINT FROM memories WHERE id = $1 AND embedding IS NOT NULL",
        )
        .bind(&id)
        .fetch_optional(&store.pool)
        .await
        .expect("verify embedding");
        assert!(written.is_some(), "embedding column must be non-NULL");
    }

    // ------------------------------------------------------------------
    // FX-C2-batch5 — parity tests for the final 6 trait methods.
    // Gated on AI_MEMORY_TEST_POSTGRES_URL; otherwise skipped cleanly.
    // ------------------------------------------------------------------

    #[tokio::test]
    async fn fx_c2_batch5_live_kg_query_trait_method_works() {
        let Some(url) = postgres_url() else {
            eprintln!("skip: AI_MEMORY_TEST_POSTGRES_URL not set");
            return;
        };
        let store = PostgresStore::connect(&url).await.expect("connect");
        let ctx = CallerContext::for_agent("ai:sal-test");
        let unique = uuid::Uuid::new_v4();
        let ns = format!("fxc2b5-kgq-{unique}");
        let src = sample_memory(&format!("src-{unique}"), &ns, "kg-query-src", "source body");
        let dst = sample_memory(&format!("dst-{unique}"), &ns, "kg-query-dst", "target body");
        let src_id = store.store(&ctx, &src).await.expect("store src");
        let dst_id = store.store(&ctx, &dst).await.expect("store dst");
        let link = crate::models::MemoryLink {
            source_id: src_id.clone(),
            target_id: dst_id.clone(),
            relation: crate::models::MemoryLinkRelation::RelatedTo,
            created_at: chrono::Utc::now().to_rfc3339(),
            signature: None,
            observed_by: None,
            valid_from: None,
            valid_until: None,
            attest_level: None,
        };
        store.link(&ctx, &link).await.expect("create link");
        // Call the SAL trait method (3-arg form) — verifies the trait
        // entry point reaches PostgresStore::kg_query_with_history.
        let rows = <PostgresStore as MemoryStore>::kg_query(&store, &src_id, 2, false)
            .await
            .expect("kg_query trait");
        assert!(
            rows.iter().any(|r| r.target_id == dst_id),
            "kg_query trait method must surface the linked neighbor"
        );
    }

    #[tokio::test]
    async fn fx_c2_batch5_live_kg_timeline_trait_method_works() {
        let Some(url) = postgres_url() else {
            eprintln!("skip: AI_MEMORY_TEST_POSTGRES_URL not set");
            return;
        };
        let store = PostgresStore::connect(&url).await.expect("connect");
        let ctx = CallerContext::for_agent("ai:sal-test");
        let unique = uuid::Uuid::new_v4();
        let ns = format!("fxc2b5-tl-{unique}");
        let src = sample_memory(&format!("tl-src-{unique}"), &ns, "tl-src", "src body");
        let dst = sample_memory(&format!("tl-dst-{unique}"), &ns, "tl-dst", "dst body");
        let src_id = store.store(&ctx, &src).await.expect("store src");
        let dst_id = store.store(&ctx, &dst).await.expect("store dst");
        // Insert a link with valid_from set so kg_timeline picks it up
        // (the SAL `link` trait method does not surface valid_from).
        sqlx::query(
            "INSERT INTO memory_links \
             (source_id, target_id, relation, created_at, valid_from, attest_level) \
             VALUES ($1, $2, 'related_to', NOW(), '2030-01-01 00:00:00+00', 'unsigned')",
        )
        .bind(&src_id)
        .bind(&dst_id)
        .execute(&store.pool)
        .await
        .expect("insert timeline link");
        let events = <PostgresStore as MemoryStore>::kg_timeline(&store, &src_id, None, None, None)
            .await
            .expect("kg_timeline trait");
        assert!(
            events.iter().any(|e| e.target_id == dst_id),
            "kg_timeline trait method must surface the assertion"
        );
    }

    #[tokio::test]
    async fn fx_c2_batch5_live_entity_register_creates_then_idempotent() {
        let Some(url) = postgres_url() else {
            eprintln!("skip: AI_MEMORY_TEST_POSTGRES_URL not set");
            return;
        };
        let store = PostgresStore::connect(&url).await.expect("connect");
        let ctx = CallerContext::for_agent("ai:sal-test");
        let unique = uuid::Uuid::new_v4();
        let ns = format!("fxc2b5-ent-{unique}");
        let first = store
            .entity_register(
                &ctx,
                "AlphaOne LLC",
                &ns,
                &["AlphaOne".to_string(), "AO".to_string()],
                &serde_json::json!({"website": "https://alphaone.example"}),
                Some("ai:sal-test"),
            )
            .await
            .expect("entity_register first");
        assert!(first.created, "first registration must create the row");
        assert_eq!(first.canonical_name, "AlphaOne LLC");
        assert!(first.aliases.iter().any(|a| a == "AlphaOne"));
        // Second call merges aliases without creating a new row.
        let second = store
            .entity_register(
                &ctx,
                "AlphaOne LLC",
                &ns,
                &["AO Inc".to_string()],
                &serde_json::json!({}),
                Some("ai:sal-test"),
            )
            .await
            .expect("entity_register second");
        assert!(!second.created, "re-register must not create");
        assert!(second.aliases.iter().any(|a| a == "AlphaOne"));
        assert!(second.aliases.iter().any(|a| a == "AO"));
        assert!(second.aliases.iter().any(|a| a == "AO Inc"));
    }

    #[tokio::test]
    async fn fx_c2_batch5_live_list_archived_trait_method_works() {
        let Some(url) = postgres_url() else {
            eprintln!("skip: AI_MEMORY_TEST_POSTGRES_URL not set");
            return;
        };
        let store = PostgresStore::connect(&url).await.expect("connect");
        // Use a unique namespace and ensure list returns an empty
        // result (no rows to archive in this scratch ns) plus that
        // the trait method dispatches to the inherent without an
        // ambiguity error.
        let unique = uuid::Uuid::new_v4();
        let ns = format!("fxc2b5-arch-{unique}");
        let listed = <PostgresStore as MemoryStore>::list_archived(&store, Some(&ns), 100, 0)
            .await
            .expect("list_archived trait");
        assert!(
            listed.is_empty(),
            "fresh namespace must have zero archived rows"
        );
    }

    #[tokio::test]
    async fn fx_c2_batch5_live_decide_pending_action_alias_works() {
        let Some(url) = postgres_url() else {
            eprintln!("skip: AI_MEMORY_TEST_POSTGRES_URL not set");
            return;
        };
        let store = PostgresStore::connect(&url).await.expect("connect");
        let ctx = CallerContext::for_agent("ai:sal-test");
        // Insert a pending row directly so we can drive the
        // decide_pending_action trait alias.
        let unique = uuid::Uuid::new_v4();
        let pid = format!("pending-{unique}");
        let ns = format!("fxc2b5-decide-{unique}");
        sqlx::query(
            "INSERT INTO pending_actions \
             (id, action_type, namespace, memory_id, requested_by, payload, status, requested_at, approvals) \
             VALUES ($1, 'store', $2, NULL, 'ai:sal-test', '{}'::jsonb, 'pending', NOW(), '[]'::jsonb)",
        )
        .bind(&pid)
        .bind(&ns)
        .execute(&store.pool)
        .await
        .expect("insert pending");
        let result = store
            .decide_pending_action(&ctx, &pid, false, "ai:sal-test")
            .await
            .expect("decide_pending_action");
        assert!(result, "first decide must return true");
        let second = store
            .decide_pending_action(&ctx, &pid, false, "ai:sal-test")
            .await
            .expect("decide_pending_action second");
        assert!(!second, "already-decided rows must return false");
    }

    #[tokio::test]
    async fn fx_c2_batch5_live_approve_with_approver_type_alias_works() {
        let Some(url) = postgres_url() else {
            eprintln!("skip: AI_MEMORY_TEST_POSTGRES_URL not set");
            return;
        };
        let store = PostgresStore::connect(&url).await.expect("connect");
        let ctx = CallerContext::for_agent("ai:sal-test");
        let unique = uuid::Uuid::new_v4();
        let pid = format!("pending-{unique}");
        let ns = format!("fxc2b5-approve-{unique}");
        sqlx::query(
            "INSERT INTO pending_actions \
             (id, action_type, namespace, memory_id, requested_by, payload, status, requested_at, approvals) \
             VALUES ($1, 'store', $2, NULL, 'ai:sal-test', '{}'::jsonb, 'pending', NOW(), '[]'::jsonb)",
        )
        .bind(&pid)
        .bind(&ns)
        .execute(&store.pool)
        .await
        .expect("insert pending");
        // approve_with_approver_type alias must produce the same outcome
        // as governance_approve_with_consensus for the Human approver
        // (no namespace policy ⇒ Human default).
        let outcome = store
            .approve_with_approver_type(&ctx, &pid, "ai:sal-test")
            .await
            .expect("approve_with_approver_type");
        assert!(matches!(outcome, crate::store::ApproveOutcome::Approved));
    }
}