ijima-server 0.2.3

HTTP daemon and store backends for the Ijima centralized agentic memory backend
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
// Copyright (C) 2026 Industrial Algebra
// SPDX-License-Identifier: Apache-2.0

//! HTTP/JSON API surface — the REST endpoints harnesses speak.
//!
//! Maps the core [`Store`] trait methods onto axum routes, each guarded
//! by a Schubert capability check via [`AuthPrincipal`]. Every request
//! is scoped to the authenticated principal's personal namespace
//! (`ns_<principal>_private`); shared/global namespaces land with the
//! `memory_promote` endpoint.
//!
//! ## Routes
//!
//! | Method | Path | Capability | Store method |
//! |---|---|---|---|
//! | GET | `/health` | (none) | — |
//! | POST | `/memories` | `memory:write` | `store_memory` |
//! | GET | `/memories/:id` | `memory:read` | `recall_memory` |
//! | DELETE | `/memories/:id` | `memory:write` | `delete_memory` |
//! | POST | `/memories/search` | `memory:read` | `search_memories` |
//! | POST | `/sessions/:session_id/turns` | `session:ingest` | `ingest_turn` |
//! | GET | `/sessions/:session_id/turns` | `memory:read` | `session_turns` |
//! | POST | `/sessions` | `session:ingest` | `create_session` |
//! | GET | `/sessions` | `memory:read` | `list_sessions` |
//! | POST | `/sessions/:session_id/end` | `session:ingest` | `end_session` |
//! | GET | `/mining/queue` | `mining:review` | `list_pending` |
//! | POST | `/mining/queue/:id/accept` | `mining:review` | `accept_extraction` |
//! | POST | `/mining/queue/:id/reject` | `mining:review` | `reject_extraction` |
//! | POST | `/sessions/:session_id/mine` | `mining:trigger` | `trigger_mine` (feature `mining`) |

use std::sync::Arc;

use axum::{
    Extension, Json, Router,
    extract::{Path, Query},
    http::StatusCode,
    response::{IntoResponse, Response},
    routing::{get, post},
};
use serde::{Deserialize, Serialize};

#[cfg(feature = "mining")]
use ijima_core::capabilities::MINING_TRIGGER;
use ijima_core::{
    AcceptedExtraction, DiaryEntry, Embedder, EntityId, KnowledgeGraph, Memory, MemoryId,
    NamespaceCount, NamespaceId, PalaceGraph, ProjectTaxon, QueuedExtraction, RepoDirectory, Room,
    SearchHit, Session, SessionId, SessionTurn, Store, TokenRevocation, TunnelTraversal,
    capabilities::{
        ADMIN, KNOWLEDGE_READ, MEMORY_READ, MEMORY_WRITE, MINING_REVIEW, SESSION_INGEST,
        TRUST_PROMOTE,
    },
    harness::Harness,
    memory::MemorySource,
};

use crate::extractor::AuthPrincipal;
use crate::redaction::Redactor;

#[cfg(feature = "federation")]
use ijima_core::federation::{
    AuthoritativeScope, ConflictSignal, FederationState, InstanceFederationConfig, RoutedWrite,
    RoutedWriteReceipt,
};

/// Builds the Ijima HTTP application router.
///
/// `auth` and `store` are shared via axum's [`Extension`] layer; the
/// [`AuthPrincipal`] extractor reads `auth` to verify bearer tokens.
pub fn app(
    auth: Arc<crate::IjimaAuth>,
    store: Arc<dyn Store>,
    kg: Arc<dyn KnowledgeGraph>,
    embedder: Option<Arc<dyn Embedder>>,
    redactor: Arc<Redactor>,
    #[cfg(feature = "rate-limit")] rate_limiter: Option<crate::rate_limit::RateLimitState>,
    #[cfg(feature = "federation")] federation_config: Arc<InstanceFederationConfig>,
) -> Router {
    let router = Router::new()
        .route("/health", get(health))
        .route("/status", get(status))
        .route("/memories", get(browse_memories).post(store_memory))
        .route("/memories/check", post(check_duplicate))
        .route("/memories/search", post(search_memories))
        .route("/memories/stats", get(memory_stats))
        .route("/memories/{id}", get(recall_memory).delete(delete_memory))
        .route("/memories/{id}/promote", post(promote_memory))
        .route("/rooms", get(list_rooms))
        .route("/taxonomy", get(taxonomy))
        .route("/palace/graph", get(palace_graph))
        .route("/palace/tunnel", get(traverse_tunnel))
        .route("/diaries", post(write_diary))
        .route("/diaries/{agent}", get(read_diary))
        .route("/repos", get(list_repos).post(register_repo))
        .route("/repos/resolve", get(resolve_repo))
        .route("/tokens/revoke", post(revoke_token_route))
        .route("/tokens/revocations", get(list_token_revocations))
        .route("/namespaces/grant", post(grant_ns_membership))
        .route("/namespaces/revoke", post(revoke_ns_membership))
        .route("/namespaces/members", get(list_ns_members))
        .route("/doctrine", post(ingest_doctrine))
        .route("/wakeup", get(wakeup))
        .route("/kg/triples", post(add_triple).get(find_triples))
        .route("/kg/entities/{id}", get(query_entity))
        .route("/kg/triples/{id}/invalidate", post(invalidate_triple))
        .route("/kg/timeline", get(kg_timeline))
        .route("/kg/stats", get(kg_stats))
        .route(
            "/sessions/{session_id}/turns",
            post(ingest_turn).get(session_turns),
        )
        .route("/sessions", post(create_session).get(list_sessions))
        .route("/sessions/{session_id}/end", post(end_session))
        .route("/mining/queue", get(list_pending))
        .route("/mining/queue/{id}/accept", post(accept_extraction))
        .route("/mining/queue/{id}/reject", post(reject_extraction));
    #[cfg(feature = "mining")]
    let router = router.route("/sessions/{session_id}/mine", post(trigger_mine));

    #[cfg(feature = "federation")]
    let router = router
        .route("/federation/state", get(federation_state))
        .route("/federation/routed-write", post(routed_write))
        .route("/federation/conflict-signal", post(conflict_signal));
    let router = router
        .layer(Extension(auth))
        .layer(Extension(store))
        .layer(Extension(kg))
        .layer(Extension(embedder))
        .layer(Extension(redactor));

    #[cfg(feature = "federation")]
    let router = router.layer(Extension(federation_config));

    #[cfg(feature = "rate-limit")]
    let router = match rate_limiter {
        Some(rl) => router.layer(Extension(rl)),
        None => router,
    };
    #[cfg(not(feature = "rate-limit"))]
    let router = router;

    router
}

// ---------- errors ----------

/// API-level error mapping to HTTP status codes.
#[derive(Debug)]
pub enum ApiError {
    /// Capability check failed (principal's token lacks the required cap).
    Forbidden,
    /// Resource absent (or in a different namespace).
    NotFound,
    /// Malformed request body or parameters.
    BadRequest(String),
    /// Duplicate content (content-hash dedup) — 409.
    Conflict(String),
    /// Store / internal failure.
    Internal(String),
}

impl IntoResponse for ApiError {
    fn into_response(self) -> Response {
        let (status, msg): (StatusCode, String) = match self {
            ApiError::Forbidden => (StatusCode::FORBIDDEN, "forbidden".into()),
            ApiError::NotFound => (StatusCode::NOT_FOUND, "not found".into()),
            ApiError::BadRequest(m) => (StatusCode::BAD_REQUEST, m),
            ApiError::Conflict(m) => (StatusCode::CONFLICT, m),
            ApiError::Internal(m) => (StatusCode::INTERNAL_SERVER_ERROR, m),
        };
        (status, msg).into_response()
    }
}

fn internal(e: ijima_core::IjimaError) -> ApiError {
    match e {
        ijima_core::IjimaError::Duplicate { detail } => ApiError::Conflict(detail),
        other => ApiError::Internal(other.to_string()),
    }
}

/// Query params carrying an optional namespace override + limit.
#[derive(Deserialize, Default)]
struct NsQuery {
    /// Override the default personal namespace. Personal namespaces
    /// (`ns_<name>_private`) belonging to *other* principals are
    /// rejected with 403; shared/global namespaces are allowed.
    namespace: Option<String>,
    limit: Option<usize>,
}

/// Resolves the effective namespace for a request: the caller's
/// personal namespace by default, or the requested one if authorized.
///
/// Authorization (WS3 org walls, in check order):
/// - `ns_<this_principal>_private` → allowed (own personal).
/// - any other `*_private` → **403** (someone else's personal).
/// - `global`, `ns_doctrine` (doctrine), `ns_import_*` (staging) → open
///   to any authenticated principal (the commons/read-everyone tiers).
/// - anything else (shared org namespaces, e.g. `ns_ia_shared`) →
///   **membership-gated**: the store's membership table must contain the
///   principal, or the grant must carry `admin` (operator bypass).
async fn resolve_ns(
    principal: &AuthPrincipal,
    store: &dyn Store,
    requested: Option<&str>,
) -> Result<ijima_core::NamespaceId, ApiError> {
    let own = format!("ns_{}_private", principal.0.principal.as_str());
    let requested = match requested {
        None => return Ok(ijima_core::NamespaceId::new(own)),
        Some(ns) => ns,
    };
    if requested == own {
        return Ok(ijima_core::NamespaceId::new(requested));
    }
    if requested.ends_with("_private") {
        return Err(ApiError::Forbidden);
    }
    let open = requested == "global"
        || requested == ijima_core::namespace::DOCTRINE_NAMESPACE
        || requested.starts_with("ns_import_");
    if !open && !principal.0.may(ADMIN) {
        let ns = ijima_core::NamespaceId::new(requested);
        let member = store
            .is_namespace_member(&ns, principal.0.principal.as_str())
            .await
            .map_err(internal)?;
        if !member {
            return Err(ApiError::Forbidden);
        }
    }
    Ok(ijima_core::NamespaceId::new(requested))
}

// ---------- handlers ----------

async fn health() -> impl IntoResponse {
    Json(serde_json::json!({ "status": "ok" }))
}

/// Process start marker — captured once, when `/status` is first hit
/// (equivalently: daemon boot, since the router is built at boot).
static STARTED_AT: std::sync::OnceLock<std::time::SystemTime> = std::sync::OnceLock::new();

#[derive(Serialize)]
struct StatusResponse {
    memories: usize,
    namespaces: Vec<NamespaceCount>,
    entities: usize,
    triples: usize,
    /// Server version (crate version at compile time).
    version: &'static str,
    /// Wall-clock process start (unix seconds).
    started_at_unix: u64,
    /// Seconds since process start.
    uptime_secs: u64,
}

/// Global store statistics across all namespaces. Admin-gated (it spans
/// every principal's data). Per-namespace KG counts are available via
/// `GET /kg/stats?namespace=...`.
async fn status(
    principal: AuthPrincipal,
    Extension(store): Extension<Arc<dyn Store>>,
    Extension(kg): Extension<Arc<dyn KnowledgeGraph>>,
) -> Result<Json<StatusResponse>, ApiError> {
    if !principal.0.may(ijima_core::capabilities::ADMIN) {
        return Err(ApiError::Forbidden);
    }
    let store_stats = store.store_stats().await.map_err(internal)?;
    let kg_stats = kg.kg_global_stats().await.map_err(internal)?;
    let started = *STARTED_AT.get_or_init(std::time::SystemTime::now);
    let uptime_secs = started.elapsed().map(|d| d.as_secs()).unwrap_or(0);
    let started_at_unix = started
        .duration_since(std::time::UNIX_EPOCH)
        .map(|d| d.as_secs())
        .unwrap_or(0);
    Ok(Json(StatusResponse {
        memories: store_stats.total_memories,
        namespaces: store_stats.namespaces,
        entities: kg_stats.entities,
        triples: kg_stats.triples,
        version: env!("CARGO_PKG_VERSION"),
        started_at_unix,
        uptime_secs,
    }))
}

// ===== Token revocation (WS1b — grant kill-switch) =====

/// Body for `POST /tokens/revoke`.
#[derive(Deserialize)]
struct RevokeRequest {
    /// The bearer token to revoke (the raw string; only its SHA-256 is
    /// persisted).
    token: String,
    /// Optional operator note (e.g. `"leaked in CI log"`).
    reason: Option<String>,
}

/// Revokes a grant token: persists the hash (survives restarts) and adds
/// it to the live rejection set. Auth: `admin`. Idempotent.
async fn revoke_token_route(
    principal: AuthPrincipal,
    Extension(store): Extension<Arc<dyn Store>>,
    Extension(auth): Extension<Arc<crate::IjimaAuth>>,
    Json(req): Json<RevokeRequest>,
) -> Result<StatusCode, ApiError> {
    if !principal.0.may(ADMIN) {
        return Err(ApiError::Forbidden);
    }
    let revocation = TokenRevocation {
        token_hash: crate::auth::bearer_hash(&req.token),
        revoked_at_unix: std::time::SystemTime::now()
            .duration_since(std::time::UNIX_EPOCH)
            .map(|d| d.as_secs())
            .unwrap_or(0),
        reason: req.reason,
    };
    // Persist first, then arm the in-memory check: a crash between the two
    // re-arms at boot (store is source of truth).
    store
        .revoke_token(revocation.clone())
        .await
        .map_err(internal)?;
    auth.revoke(&revocation.token_hash);
    Ok(StatusCode::NO_CONTENT)
}

// ---------- namespace membership (WS3 org walls) ----------

#[derive(Deserialize)]
struct NsMembershipRequest {
    /// The shared namespace (e.g. `ns_ia_shared`).
    namespace: String,
    /// The principal to grant/revoke.
    principal: String,
}

/// Grants namespace membership (upsert). Auth: `admin`. Powers
/// `ijima namespace grant`.
async fn grant_ns_membership(
    principal: AuthPrincipal,
    Extension(store): Extension<Arc<dyn Store>>,
    Json(req): Json<NsMembershipRequest>,
) -> Result<Json<serde_json::Value>, ApiError> {
    if !principal.0.may(ADMIN) {
        return Err(ApiError::Forbidden);
    }
    let membership = ijima_core::NamespaceMembership {
        namespace: req.namespace.clone(),
        principal: req.principal.clone(),
        granted_at_unix: std::time::SystemTime::now()
            .duration_since(std::time::UNIX_EPOCH)
            .map(|d| d.as_secs())
            .unwrap_or(0),
        granted_by: principal.0.principal.as_str().to_string(),
    };
    store
        .grant_namespace_membership(membership)
        .await
        .map_err(internal)?;
    Ok(Json(
        serde_json::json!({ "granted": true, "namespace": req.namespace, "principal": req.principal }),
    ))
}

/// Revokes namespace membership (idempotent). Auth: `admin`.
async fn revoke_ns_membership(
    principal: AuthPrincipal,
    Extension(store): Extension<Arc<dyn Store>>,
    Json(req): Json<NsMembershipRequest>,
) -> Result<StatusCode, ApiError> {
    if !principal.0.may(ADMIN) {
        return Err(ApiError::Forbidden);
    }
    store
        .revoke_namespace_membership(&NamespaceId::new(&req.namespace), &req.principal)
        .await
        .map_err(internal)?;
    Ok(StatusCode::NO_CONTENT)
}

/// Lists a namespace's members, oldest grant first. Auth: `admin`.
async fn list_ns_members(
    principal: AuthPrincipal,
    Extension(store): Extension<Arc<dyn Store>>,
    Query(q): Query<NsQuery>,
) -> Result<Json<Vec<ijima_core::NamespaceMembership>>, ApiError> {
    if !principal.0.may(ADMIN) {
        return Err(ApiError::Forbidden);
    }
    let ns = q.namespace.as_deref().ok_or(ApiError::BadRequest(
        "?namespace=<ns> is required".to_string(),
    ))?;
    let members = store
        .list_namespace_members(&NamespaceId::new(ns))
        .await
        .map_err(internal)?;
    Ok(Json(members))
}

/// Lists every recorded revocation, oldest first. Auth: `admin`.
async fn list_token_revocations(
    principal: AuthPrincipal,
    Extension(store): Extension<Arc<dyn Store>>,
) -> Result<Json<Vec<TokenRevocation>>, ApiError> {
    if !principal.0.may(ADMIN) {
        return Err(ApiError::Forbidden);
    }
    Ok(Json(store.list_revocations().await.map_err(internal)?))
}

#[derive(Serialize)]
struct IdResponse {
    id: String,
}

async fn store_memory(
    principal: AuthPrincipal,
    Extension(store): Extension<Arc<dyn Store>>,
    Query(q): Query<NsQuery>,
    Json(memory): Json<Memory>,
) -> Result<Json<IdResponse>, ApiError> {
    if !principal.0.may(MEMORY_WRITE) {
        return Err(ApiError::Forbidden);
    }
    // WS2: `?namespace=` routes the write into a shared/import namespace
    // (grant-checked by resolve_ns — another principal's `_private` is
    // still forbidden); without it, the caller's personal namespace.
    let ns = resolve_ns(&principal, store.as_ref(), q.namespace.as_deref()).await?;
    let mut memory = memory;
    if memory.created_at.is_empty() {
        memory.created_at = std::time::SystemTime::now()
            .duration_since(std::time::UNIX_EPOCH)
            .map(|d| d.as_secs().to_string())
            .unwrap_or_default();
    }
    let id = store.store_memory(&ns, memory).await.map_err(internal)?;
    Ok(Json(IdResponse { id: id.0 }))
}

#[derive(Deserialize)]
struct CheckDuplicateRequest {
    content: String,
}

#[derive(Serialize)]
struct CheckDuplicateResponse {
    /// The id of an existing memory with identical content, if any.
    duplicate: Option<String>,
}

/// Pre-check for content-hash dedup (`POST /memories/check`). Returns
/// the existing memory id if identical content is already stored in the
/// caller's (effective) namespace.
async fn check_duplicate(
    principal: AuthPrincipal,
    Extension(store): Extension<Arc<dyn Store>>,
    Query(q): Query<NsQuery>,
    Json(req): Json<CheckDuplicateRequest>,
) -> Result<Json<CheckDuplicateResponse>, ApiError> {
    if !principal.0.may(MEMORY_READ) {
        return Err(ApiError::Forbidden);
    }
    let ns = resolve_ns(&principal, store.as_ref(), q.namespace.as_deref()).await?;
    let dup = store
        .check_duplicate(&ns, &req.content)
        .await
        .map_err(internal)?;
    Ok(Json(CheckDuplicateResponse {
        duplicate: dup.map(|id| id.0),
    }))
}

async fn recall_memory(
    principal: AuthPrincipal,
    Extension(store): Extension<Arc<dyn Store>>,
    Path(id): Path<String>,
    Query(q): Query<NsQuery>,
) -> Result<Json<Memory>, ApiError> {
    if !principal.0.may(MEMORY_READ) {
        return Err(ApiError::Forbidden);
    }
    let ns = resolve_ns(&principal, store.as_ref(), q.namespace.as_deref()).await?;
    match store
        .recall_memory(&ns, &MemoryId(id))
        .await
        .map_err(internal)?
    {
        Some(memory) => Ok(Json(memory)),
        None => Err(ApiError::NotFound),
    }
}

async fn delete_memory(
    principal: AuthPrincipal,
    Extension(store): Extension<Arc<dyn Store>>,
    Path(id): Path<String>,
    Query(q): Query<NsQuery>,
) -> Result<StatusCode, ApiError> {
    if !principal.0.may(MEMORY_WRITE) {
        return Err(ApiError::Forbidden);
    }
    let ns = resolve_ns(&principal, store.as_ref(), q.namespace.as_deref()).await?;
    store
        .delete_memory(&ns, &MemoryId(id))
        .await
        .map_err(internal)?;
    Ok(StatusCode::NO_CONTENT)
}

#[derive(Deserialize)]
struct SearchRequest {
    /// The query text. The daemon embeds this centrally with its own
    /// embedder (D9 §5: "the service owns the model"), guaranteeing
    /// vector compatibility with stored memories.
    text: String,
    limit: Option<usize>,
    /// Search scope: `personal` (default — the resolved namespace only) or
    /// `visible` (the principal's readable world: own private + `global`
    /// commons + open `ns_import_*` staging + member org walls, merged by
    /// similarity). The pi integration uses `visible` for parity
    /// with pi-mempalace's global search.
    scope: Option<String>,
}

#[derive(Serialize)]
struct SearchResponse {
    memories: Vec<SearchHit>,
}

async fn search_memories(
    principal: AuthPrincipal,
    Extension(store): Extension<Arc<dyn Store>>,
    Extension(embedder): Extension<Option<Arc<dyn Embedder>>>,
    Query(q): Query<NsQuery>,
    Json(req): Json<SearchRequest>,
) -> Result<Json<SearchResponse>, ApiError> {
    if !principal.0.may(MEMORY_READ) {
        return Err(ApiError::Forbidden);
    }
    let embedder = embedder
        .ok_or_else(|| ApiError::Internal("search unavailable: daemon has no embedder".into()))?;
    let query = embedder.embed(&req.text).map_err(internal)?;
    let limit = req.limit.unwrap_or(10);

    // `visible` scope: the principal's readable world — own private
    // namespace + the `global` commons + open `ns_import_*` staging +
    // every org wall they hold membership in (WS3) — merged and ranked
    // by similarity across all of them (pi-mempalace parity; the "empty
    // brain" incident: the pre-WS2 definition only merged private +
    // global, so freshly-imported corpora were invisible).
    let hits = if req.scope.as_deref() == Some("visible") {
        let own_ns = principal.0.personal_namespace();
        let mut namespaces = vec![own_ns.clone(), NamespaceId::new("global")];
        for ns in store
            .list_namespaces_for_principal(principal.0.principal.as_str())
            .await
            .map_err(internal)?
        {
            namespaces.push(ns);
        }
        let stats = store.store_stats().await.map_err(internal)?;
        for ns_count in &stats.namespaces {
            if ns_count.namespace.starts_with("ns_import_") {
                namespaces.push(NamespaceId::new(ns_count.namespace.clone()));
            }
        }
        namespaces.sort_by(|a, b| a.as_str().cmp(b.as_str()));
        namespaces.dedup_by(|a, b| a.as_str() == b.as_str());
        let mut merged: Vec<SearchHit> = Vec::new();
        for ns in namespaces {
            let hits = store
                .search_memories(&ns, &query, limit)
                .await
                .map_err(internal)?;
            merged = merge_search_hits(merged, hits, limit);
        }
        merged
    } else {
        let ns = resolve_ns(&principal, store.as_ref(), q.namespace.as_deref()).await?;
        store
            .search_memories(&ns, &query, limit)
            .await
            .map_err(internal)?
    };
    Ok(Json(SearchResponse { memories: hits }))
}

/// Merges two scored hit lists by similarity (desc), deduplicating by memory
/// id (the highest-similarity instance wins — NOT `dedup_by`, which only
/// drops adjacent dups) and truncating to `limit`. Pure — the `scope=visible`
/// path uses this to combine private + global results.
fn merge_search_hits(a: Vec<SearchHit>, b: Vec<SearchHit>, limit: usize) -> Vec<SearchHit> {
    use std::collections::HashSet;
    let mut all: Vec<SearchHit> = a.into_iter().chain(b).collect();
    all.sort_by(|x, y| {
        y.similarity
            .partial_cmp(&x.similarity)
            .unwrap_or(std::cmp::Ordering::Equal)
    });
    // Keep the first (highest-similarity, post-sort) instance of each id.
    let mut seen: HashSet<String> = HashSet::new();
    all.retain(|h| seen.insert(h.memory.id.0.clone()));
    all.truncate(limit);
    all
}

// ---------- promotion (personal → shared, D9 §2) ----------

#[derive(Deserialize)]
struct PromoteRequest {
    /// The shared/team namespace to promote into
    /// (e.g. `ns_team_default`).
    target_namespace: String,
    /// Optional id for the promoted copy. Defaults to
    /// `<original_id>__shared`.
    new_id: Option<String>,
}

#[derive(Serialize)]
struct PromoteResponse {
    id: String,
    original_id: String,
    target_namespace: String,
    redactions: Vec<crate::redaction::Redaction>,
}

/// Promotes a memory from the caller's personal namespace to a shared
/// namespace, running the [redaction filter](crate::redaction) at the
/// boundary. The original stays verbatim in personal scope; a scrubbed
/// copy lands in the target namespace.
async fn promote_memory(
    principal: AuthPrincipal,
    Extension(store): Extension<Arc<dyn Store>>,
    Extension(redactor): Extension<Arc<Redactor>>,
    Path(id): Path<String>,
    Json(req): Json<PromoteRequest>,
) -> Result<Json<PromoteResponse>, ApiError> {
    if !principal.0.may(TRUST_PROMOTE) {
        return Err(ApiError::Forbidden);
    }
    let personal_ns = principal.0.personal_namespace();

    // Read from the caller's personal namespace.
    let memory = store
        .recall_memory(&personal_ns, &MemoryId(id.clone()))
        .await
        .map_err(internal)?
        .ok_or(ApiError::NotFound)?;

    // Scrub at the boundary (D9 §2 — the one place filtering happens).
    let scrubbed = redactor.redact(&memory.content);

    // Write the redacted copy to the shared namespace.
    let new_id = req
        .new_id
        .clone()
        .unwrap_or_else(|| format!("{id}__shared"));
    let promoted = Memory {
        id: MemoryId(new_id.clone()),
        content: scrubbed.text,
        project: memory.project,
        topic: memory.topic,
        source: ijima_core::memory::MemorySource::Explicit,
        harness: memory.harness,
        // Provenance back-reference to the original personal memory.
        session_id: Some(id.clone()),
        // Promotion preserves the origin/authority provenance of the source.
        origin: memory.origin.clone(),
        authority: memory.authority.clone(),
        importance: memory.importance,
        created_at: memory.created_at.clone(),
    };
    let target_ns = ijima_core::NamespaceId::new(&req.target_namespace);
    // WS3: the promotion target goes through the same org-wall rule as
    // every other write — membership for shared namespaces (admin
    // bypasses); import staging is not a valid promotion target.
    {
        let target = req.target_namespace.as_str();
        if target.ends_with("_private") && target != personal_ns.as_str() {
            return Err(ApiError::Forbidden);
        }
        let open = target == "global"
            || target == ijima_core::namespace::DOCTRINE_NAMESPACE
            || target == personal_ns.as_str();
        if target.starts_with("ns_import_") {
            return Err(ApiError::BadRequest(
                "import staging namespaces are not promotion targets".to_string(),
            ));
        }
        if !open && !principal.0.may(ADMIN) {
            let member = store
                .is_namespace_member(&target_ns, principal.0.principal.as_str())
                .await
                .map_err(internal)?;
            if !member {
                return Err(ApiError::Forbidden);
            }
        }
    }
    store
        .store_memory(&target_ns, promoted)
        .await
        .map_err(internal)?;

    Ok(Json(PromoteResponse {
        id: new_id,
        original_id: id,
        target_namespace: req.target_namespace,
        redactions: scrubbed.redactions,
    }))
}

// ---------- doctrine ingest (D9) ----------

#[derive(Deserialize)]
struct DoctrineRequest {
    id: String,
    content: String,
    project: String,
    topic: String,
}

/// Ingests a curated doctrine entry into the global `ns_doctrine`
/// namespace. Admin-gated — doctrine is PR-reviewed in Git and never
/// written by agents. Idempotent (delete-then-store) so re-ingests
/// upsert cleanly. No redaction (doctrine is pre-reviewed).
async fn ingest_doctrine(
    principal: AuthPrincipal,
    Extension(store): Extension<Arc<dyn Store>>,
    Json(req): Json<DoctrineRequest>,
) -> Result<Json<IdResponse>, ApiError> {
    if !principal.0.may(ijima_core::capabilities::ADMIN) {
        return Err(ApiError::Forbidden);
    }
    let ns = ijima_core::NamespaceId::new(ijima_core::namespace::DOCTRINE_NAMESPACE);
    // Idempotent upsert: remove any existing entry, then store.
    store
        .delete_memory(&ns, &MemoryId(req.id.clone()))
        .await
        .map_err(internal)?;
    let memory = Memory {
        id: MemoryId(req.id.clone()),
        content: req.content,
        project: req.project,
        topic: req.topic,
        source: ijima_core::memory::MemorySource::Doctrine,
        harness: ijima_core::harness::Harness::Other,
        session_id: None,
        // Doctrine is the curated local tier — authoritative on this instance.
        origin: ijima_core::InstanceId::local(),
        authority: ijima_core::AuthorityScope::local(),
        importance: 1.0,
        created_at: std::time::SystemTime::now()
            .duration_since(std::time::UNIX_EPOCH)
            .map(|d| d.as_secs().to_string())
            .unwrap_or_default(),
    };
    store.store_memory(&ns, memory).await.map_err(internal)?;
    Ok(Json(IdResponse { id: req.id }))
}

// ---------- wake-up composition (D9 §4) ----------

/// How many personal essentials to include in a wake-up response.
const WAKEUP_PERSONAL_LIMIT: usize = 20;
/// How many doctrine entries to include.
const WAKEUP_DOCTRINE_LIMIT: usize = 50;

#[derive(Serialize)]
struct WakeupResponse {
    /// L0: the authenticated principal's identity.
    identity: serde_json::Value,
    /// L1a: the caller's personal essentials (top-N by importance + recency).
    personal_essentials: Vec<Memory>,
    /// L1b: the shared team doctrine baseline (identical across the team).
    doctrine: Vec<Memory>,
}

/// Composes the session-start context: L0 identity + L1a personal
/// essentials + L1b team doctrine. This is the "shared brain" — L1b is
/// identical across the team, L1a is the individual's personal brain.
async fn wakeup(
    principal: AuthPrincipal,
    Extension(store): Extension<Arc<dyn Store>>,
) -> Result<Json<WakeupResponse>, ApiError> {
    if !principal.0.may(MEMORY_READ) {
        return Err(ApiError::Forbidden);
    }
    let personal_ns = principal.0.personal_namespace();
    let doctrine_ns = ijima_core::NamespaceId::new(ijima_core::namespace::DOCTRINE_NAMESPACE);

    let (personal_essentials, doctrine) = tokio::join!(
        store.list_memories(&personal_ns, WAKEUP_PERSONAL_LIMIT),
        store.list_memories(&doctrine_ns, WAKEUP_DOCTRINE_LIMIT),
    );

    Ok(Json(WakeupResponse {
        identity: serde_json::json!({ "principal": principal.0.principal.as_str() }),
        personal_essentials: personal_essentials.map_err(internal)?,
        doctrine: doctrine.map_err(internal)?,
    }))
}

// ---------- knowledge graph ----------

#[derive(Deserialize)]
struct AddTripleRequest {
    subject: String,
    predicate: String,
    object: String,
    valid_from: Option<String>,
    confidence: Option<f32>,
    source_memory_id: Option<String>,
}

async fn add_triple(
    principal: AuthPrincipal,
    Extension(kg): Extension<Arc<dyn KnowledgeGraph>>,
    Extension(store): Extension<Arc<dyn Store>>,
    Query(q): Query<NsQuery>,
    Json(req): Json<AddTripleRequest>,
) -> Result<Json<ijima_core::Triple>, ApiError> {
    if !principal.0.may(ijima_core::capabilities::KNOWLEDGE_WRITE) {
        return Err(ApiError::Forbidden);
    }
    let ns = resolve_ns(&principal, store.as_ref(), q.namespace.as_deref()).await?;
    let triple = kg
        .add_triple(
            &ns,
            EntityId::new(req.subject),
            &req.predicate,
            EntityId::new(req.object),
            req.valid_from.as_deref(),
            req.confidence.unwrap_or(1.0),
            req.source_memory_id.as_deref(),
        )
        .await
        .map_err(internal)?;
    // Touch `store` so the Extension is consumed.
    let _ = store;
    Ok(Json(triple))
}

async fn query_entity(
    principal: AuthPrincipal,
    Extension(store): Extension<Arc<dyn Store>>,
    Extension(kg): Extension<Arc<dyn KnowledgeGraph>>,
    Path(id): Path<String>,
    Query(q): Query<NsQuery>,
) -> Result<Json<ijima_core::EntityRecord>, ApiError> {
    if !principal.0.may(KNOWLEDGE_READ) {
        return Err(ApiError::Forbidden);
    }
    let ns = resolve_ns(&principal, store.as_ref(), q.namespace.as_deref()).await?;
    let rec = kg
        .query_entity(&ns, &EntityId::new(id))
        .await
        .map_err(internal)?;
    Ok(Json(rec))
}

async fn invalidate_triple(
    principal: AuthPrincipal,
    Extension(store): Extension<Arc<dyn Store>>,
    Extension(kg): Extension<Arc<dyn KnowledgeGraph>>,
    Path(id): Path<String>,
    Query(q): Query<NsQuery>,
) -> Result<StatusCode, ApiError> {
    if !principal.0.may(ijima_core::capabilities::KNOWLEDGE_WRITE) {
        return Err(ApiError::Forbidden);
    }
    let ns = resolve_ns(&principal, store.as_ref(), q.namespace.as_deref()).await?;
    kg.invalidate_triple(&ns, &id).await.map_err(internal)?;
    Ok(StatusCode::NO_CONTENT)
}

#[derive(Deserialize, Default)]
struct FindTriplesQuery {
    namespace: Option<String>,
    subject: Option<String>,
    predicate: Option<String>,
    object: Option<String>,
}

async fn find_triples(
    principal: AuthPrincipal,
    Extension(store): Extension<Arc<dyn Store>>,
    Extension(kg): Extension<Arc<dyn KnowledgeGraph>>,
    Query(q): Query<FindTriplesQuery>,
) -> Result<Json<Vec<ijima_core::Triple>>, ApiError> {
    if !principal.0.may(KNOWLEDGE_READ) {
        return Err(ApiError::Forbidden);
    }
    let ns = resolve_ns(&principal, store.as_ref(), q.namespace.as_deref()).await?;
    let triples = kg
        .find_triples(
            &ns,
            q.subject.as_deref().map(EntityId::new).as_ref(),
            q.predicate.as_deref(),
            q.object.as_deref().map(EntityId::new).as_ref(),
        )
        .await
        .map_err(internal)?;
    Ok(Json(triples))
}

async fn kg_timeline(
    principal: AuthPrincipal,
    Extension(store): Extension<Arc<dyn Store>>,
    Extension(kg): Extension<Arc<dyn KnowledgeGraph>>,
    Query(q): Query<NsQuery>,
) -> Result<Json<Vec<ijima_core::Triple>>, ApiError> {
    if !principal.0.may(KNOWLEDGE_READ) {
        return Err(ApiError::Forbidden);
    }
    let ns = resolve_ns(&principal, store.as_ref(), q.namespace.as_deref()).await?;
    let triples = kg
        .kg_timeline(&ns, q.limit.unwrap_or(50))
        .await
        .map_err(internal)?;
    Ok(Json(triples))
}

async fn kg_stats(
    principal: AuthPrincipal,
    Extension(store): Extension<Arc<dyn Store>>,
    Extension(kg): Extension<Arc<dyn KnowledgeGraph>>,
    Query(q): Query<NsQuery>,
) -> Result<Json<ijima_core::KgStats>, ApiError> {
    if !principal.0.may(KNOWLEDGE_READ) {
        return Err(ApiError::Forbidden);
    }
    let ns = resolve_ns(&principal, store.as_ref(), q.namespace.as_deref()).await?;
    let stats = kg.knowledge_stats(&ns).await.map_err(internal)?;
    Ok(Json(stats))
}

async fn ingest_turn(
    principal: AuthPrincipal,
    Extension(store): Extension<Arc<dyn Store>>,
    Path(session_id): Path<String>,
    Json(mut turn): Json<SessionTurn>,
) -> Result<StatusCode, ApiError> {
    if !principal.0.may(SESSION_INGEST) {
        return Err(ApiError::Forbidden);
    }
    let ns = principal.0.personal_namespace();
    turn.session_id = SessionId::new(session_id);
    store.ingest_turn(&ns, turn).await.map_err(internal)?;
    Ok(StatusCode::NO_CONTENT)
}

// TurnsQuery is unified into NsQuery above.

#[derive(Serialize)]
struct TurnsResponse {
    turns: Vec<SessionTurn>,
}

async fn session_turns(
    principal: AuthPrincipal,
    Extension(store): Extension<Arc<dyn Store>>,
    Path(session_id): Path<String>,
    Query(q): Query<NsQuery>,
) -> Result<Json<TurnsResponse>, ApiError> {
    if !principal.0.may(MEMORY_READ) {
        return Err(ApiError::Forbidden);
    }
    let ns = resolve_ns(&principal, store.as_ref(), q.namespace.as_deref()).await?;
    let turns = store
        .session_turns(&ns, &SessionId::new(session_id), q.limit.unwrap_or(50))
        .await
        .map_err(internal)?;
    Ok(Json(TurnsResponse { turns }))
}

/// Creates (or upserts) a session's metadata. `ended_at` is forced to
/// `None` on create — use `POST /sessions/:id/end` to close a session.
/// Auth: `session:ingest`. The session is stored in the caller's
/// personal namespace (matching turn ingest).
async fn create_session(
    principal: AuthPrincipal,
    Extension(store): Extension<Arc<dyn Store>>,
    Json(mut session): Json<Session>,
) -> Result<Json<IdResponse>, ApiError> {
    if !principal.0.may(SESSION_INGEST) {
        return Err(ApiError::Forbidden);
    }
    let ns = principal.0.personal_namespace();
    if session.started_at.is_empty() {
        session.started_at = std::time::SystemTime::now()
            .duration_since(std::time::UNIX_EPOCH)
            .map(|d| d.as_secs().to_string())
            .unwrap_or_default();
    }
    session.ended_at = None;
    let id = store.create_session(&ns, session).await.map_err(internal)?;
    Ok(Json(IdResponse { id: id.0 }))
}

#[derive(Deserialize)]
struct SessionListQuery {
    namespace: Option<String>,
    /// Optional harness filter (wire string, e.g. `pi`).
    harness: Option<String>,
    limit: Option<usize>,
}

/// Lists sessions in the effective namespace, newest first, optionally
/// filtered by harness. Auth: `memory:read` (session metadata is
/// read via the same capability as memory palace reads).
async fn list_sessions(
    principal: AuthPrincipal,
    Extension(store): Extension<Arc<dyn Store>>,
    Query(q): Query<SessionListQuery>,
) -> Result<Json<Vec<Session>>, ApiError> {
    if !principal.0.may(MEMORY_READ) {
        return Err(ApiError::Forbidden);
    }
    let ns = resolve_ns(&principal, store.as_ref(), q.namespace.as_deref()).await?;
    let harness = q.harness.as_deref().map(Harness::from_wire_str);
    let limit = q.limit.unwrap_or(50).min(500);
    let sessions = store
        .list_sessions(&ns, harness.as_ref(), limit)
        .await
        .map_err(internal)?;
    Ok(Json(sessions))
}

#[derive(Deserialize)]
struct EndSessionRequest {
    ended_at: String,
}

/// Marks a session as ended. Scoped to the caller's personal namespace.
/// Auth: `session:ingest`.
async fn end_session(
    principal: AuthPrincipal,
    Extension(store): Extension<Arc<dyn Store>>,
    Path(session_id): Path<String>,
    Json(req): Json<EndSessionRequest>,
) -> Result<StatusCode, ApiError> {
    if !principal.0.may(SESSION_INGEST) {
        return Err(ApiError::Forbidden);
    }
    let ns = principal.0.personal_namespace();
    store
        .end_session(&ns, &SessionId::new(session_id), req.ended_at)
        .await
        .map_err(internal)?;
    Ok(StatusCode::NO_CONTENT)
}

// ---------- mining review queue (ADR M2, M3) ----------

/// Lists pending mining extractions in the effective namespace, newest
/// first. Auth: `mining:review`.
async fn list_pending(
    principal: AuthPrincipal,
    Extension(store): Extension<Arc<dyn Store>>,
    Query(q): Query<NsQuery>,
) -> Result<Json<Vec<QueuedExtraction>>, ApiError> {
    if !principal.0.may(MINING_REVIEW) {
        return Err(ApiError::Forbidden);
    }
    let ns = resolve_ns(&principal, store.as_ref(), q.namespace.as_deref()).await?;
    let limit = q.limit.unwrap_or(50).min(500);
    let pending = store.list_pending(&ns, limit).await.map_err(internal)?;
    Ok(Json(pending))
}

/// Accepts a queued extraction: promotes it to the palace and removes it
/// from the queue. Auth: `mining:review`.
async fn accept_extraction(
    principal: AuthPrincipal,
    Extension(store): Extension<Arc<dyn Store>>,
    Path(id): Path<String>,
) -> Result<Json<AcceptedExtraction>, ApiError> {
    if !principal.0.may(MINING_REVIEW) {
        return Err(ApiError::Forbidden);
    }
    let ns = principal.0.personal_namespace();
    let accepted = store.accept_extraction(&ns, &id).await.map_err(internal)?;
    Ok(Json(accepted))
}

/// Rejects a queued extraction: drops it without promoting. Auth:
/// `mining:review`. Returns 204.
async fn reject_extraction(
    principal: AuthPrincipal,
    Extension(store): Extension<Arc<dyn Store>>,
    Path(id): Path<String>,
) -> Result<StatusCode, ApiError> {
    if !principal.0.may(MINING_REVIEW) {
        return Err(ApiError::Forbidden);
    }
    let ns = principal.0.personal_namespace();
    store.reject_extraction(&ns, &id).await.map_err(internal)?;
    Ok(StatusCode::NO_CONTENT)
}

// ---------- mining trigger (ADR M1, M3, M7) ----------

/// Triggers an extraction pass over a session's turns: runs the rules tier
/// (always) plus the llm tier when `IJIMA_LLM_*` is configured, merges +
/// content-dedups, then ingests — `Auto` extractions archive to the palace,
/// `PendingReview` stage in the review queue. Auth: `mining:trigger`.
///
/// The llm agent's `HttpAgent::respond` blocks on its own tokio runtime, so
/// the synchronous `mine_all` pass runs on a blocking thread (via
/// [`tokio::task::spawn_blocking`]) to avoid a runtime-in-runtime panic
/// inside this async handler. The concrete [`HttpAgent`] is `Send`; the
/// `&mut dyn Agent` coercion happens *inside* the closure, so it never
/// crosses the spawn boundary as an unsized non-`Send` trait object.
#[cfg(feature = "mining")]
async fn trigger_mine(
    principal: AuthPrincipal,
    Extension(store): Extension<Arc<dyn Store>>,
    Path(session_id): Path<String>,
    Query(q): Query<NsQuery>,
) -> Result<Json<crate::mining_pipeline::MiningReport>, ApiError> {
    use proserpina_agent::http::HttpAgent;

    if !principal.0.may(MINING_TRIGGER) {
        return Err(ApiError::Forbidden);
    }
    let ns = resolve_ns(&principal, store.as_ref(), q.namespace.as_deref()).await?;

    // Fetch the session's turns (a generous limit — v0 mines the whole session).
    let turns = store
        .session_turns(&ns, &SessionId::new(session_id.clone()), 10_000)
        .await
        .map_err(internal)?;
    let turn_texts: Vec<String> = turns.into_iter().map(|t| t.content).collect();
    let ctx = crate::mining_pipeline::mining_context(&session_id, "general", Harness::Other);

    // The extraction pass is synchronous (ADR M1); the llm agent bridges to
    // async HTTP internally via its own runtime + `block_on`. Run it on a
    // blocking thread so that `block_on` is legal (we are outside any async
    // executor here). `build_mining_agent` returns a concrete `Option<HttpAgent>`
    // — kept as the concrete type (not a trait object) so it stays `Send` for
    // the move into the spawned task.
    let extractions = tokio::task::spawn_blocking(move || {
        let mut agent: Option<HttpAgent> = build_mining_agent();
        let agent_dyn: Option<&mut dyn proserpina_agent::Agent> = agent
            .as_mut()
            .map(|a| a as &mut dyn proserpina_agent::Agent);
        ijima_miner::mine_all(&turn_texts, &ctx, agent_dyn)
    })
    .await
    .map_err(|e| {
        internal(ijima_core::IjimaError::Mining {
            detail: format!("extraction task failed: {e}"),
        })
    })?
    .map_err(internal)?;

    let report = crate::mining_pipeline::ingest_extractions(store.as_ref(), &ns, extractions)
        .await
        .map_err(internal)?;
    Ok(Json(report))
}

/// Constructs the llm extraction agent from `IJIMA_LLM_*` env config, or
/// `None` when mining should run rules-only (no `IJIMA_LLM_MODEL` /
/// `IJIMA_LLM_API_KEY` set). `mine_all(None)` then skips the llm tier.
///
/// Defaults `IJIMA_LLM_BASE_URL` to the DeepSeek endpoint. The agent uses a
/// single "Session Mining Extractor" persona covering both fact and pattern
/// extraction; v0 does not vary the agent persona per role (ADR M5,
/// single-shot). Returns a concrete [`HttpAgent`] (not a trait object) so it
/// remains `Send` for the blocking-thread move.
#[cfg(feature = "mining")]
fn build_mining_agent() -> Option<proserpina_agent::http::HttpAgent> {
    use proserpina_agent::{
        AgentId, Persona,
        http::{HttpAgent, HttpConfig},
    };

    let base_url = std::env::var("IJIMA_LLM_BASE_URL")
        .unwrap_or_else(|_| "https://api.deepseek.com/v1".to_string());
    let model = std::env::var("IJIMA_LLM_MODEL").ok()?;
    let api_key = std::env::var("IJIMA_LLM_API_KEY").ok()?;

    let persona = Persona::new("Session Mining Extractor")
        .with_framing(
            "You mine session transcripts for durable facts and recurring \
             patterns. Output one JSON object per line, each \
             {\"content\",\"project\",\"topic\",\"confidence\"}. Omit all \
             preamble. If nothing worth extracting, output nothing.",
        )
        .with_focus(
            "decisions, chosen tools, stated constraints, measurements, recurring workflows",
        );

    Some(HttpAgent::new(
        AgentId::new("ijima-miner"),
        persona,
        HttpConfig {
            base_url,
            model,
            api_key,
        },
    ))
}

// ===== Palace organization (memory:read) =====

#[derive(Deserialize)]
struct NamespaceQuery {
    namespace: Option<String>,
}

#[derive(Deserialize)]
struct RoomsQuery {
    namespace: Option<String>,
    project: Option<String>,
    limit: Option<usize>,
}

#[derive(Deserialize)]
struct TunnelQuery {
    namespace: Option<String>,
    topic: String,
    project_a: String,
    project_b: String,
    limit: Option<usize>,
}

#[derive(Deserialize)]
struct DiaryQuery {
    namespace: Option<String>,
    limit: Option<usize>,
}

#[derive(Deserialize)]
struct MemoryBrowseQuery {
    namespace: Option<String>,
    project: Option<String>,
    topic: Option<String>,
    limit: Option<usize>,
}

#[derive(Deserialize)]
struct ResolveRepoQuery {
    cwd: String,
}

/// Lists rooms (topic cells), optionally filtered to a project. Auth: `memory:read`.
async fn list_rooms(
    principal: AuthPrincipal,
    Extension(store): Extension<Arc<dyn Store>>,
    Query(q): Query<RoomsQuery>,
) -> Result<Json<Vec<Room>>, ApiError> {
    if !principal.0.may(MEMORY_READ) {
        return Err(ApiError::Forbidden);
    }
    let ns = resolve_ns(&principal, store.as_ref(), q.namespace.as_deref()).await?;
    let limit = q.limit.unwrap_or(50).min(500);
    let rooms = store
        .list_rooms(&ns, q.project.as_deref(), limit)
        .await
        .map_err(internal)?;
    Ok(Json(rooms))
}

/// Full project → topic → count taxonomy. Auth: `memory:read`.
async fn taxonomy(
    principal: AuthPrincipal,
    Extension(store): Extension<Arc<dyn Store>>,
    Query(q): Query<NamespaceQuery>,
) -> Result<Json<Vec<ProjectTaxon>>, ApiError> {
    if !principal.0.may(MEMORY_READ) {
        return Err(ApiError::Forbidden);
    }
    let ns = resolve_ns(&principal, store.as_ref(), q.namespace.as_deref()).await?;
    Ok(Json(store.taxonomy(&ns).await.map_err(internal)?))
}

/// The palace graph: projects as nodes, shared-topic tunnels as edges. Auth: `memory:read`.
async fn palace_graph(
    principal: AuthPrincipal,
    Extension(store): Extension<Arc<dyn Store>>,
    Query(q): Query<NamespaceQuery>,
) -> Result<Json<PalaceGraph>, ApiError> {
    if !principal.0.may(MEMORY_READ) {
        return Err(ApiError::Forbidden);
    }
    let ns = resolve_ns(&principal, store.as_ref(), q.namespace.as_deref()).await?;
    Ok(Json(store.palace_graph(&ns).await.map_err(internal)?))
}

/// Traverses a tunnel — the memories from both projects on a shared topic. Auth: `memory:read`.
async fn traverse_tunnel(
    principal: AuthPrincipal,
    Extension(store): Extension<Arc<dyn Store>>,
    Query(q): Query<TunnelQuery>,
) -> Result<Json<TunnelTraversal>, ApiError> {
    if !principal.0.may(MEMORY_READ) {
        return Err(ApiError::Forbidden);
    }
    let ns = resolve_ns(&principal, store.as_ref(), q.namespace.as_deref()).await?;
    let limit = q.limit.unwrap_or(50).min(500);
    Ok(Json(
        store
            .traverse_tunnel(&ns, &q.topic, &q.project_a, &q.project_b, limit)
            .await
            .map_err(internal)?,
    ))
}

/// Appends a diary entry to the caller's namespace. Auth: `memory:write`.
async fn write_diary(
    principal: AuthPrincipal,
    Extension(store): Extension<Arc<dyn Store>>,
    Json(entry): Json<DiaryEntry>,
) -> Result<StatusCode, ApiError> {
    if !principal.0.may(MEMORY_WRITE) {
        return Err(ApiError::Forbidden);
    }
    let ns = principal.0.personal_namespace();
    store.write_diary(&ns, entry).await.map_err(internal)?;
    Ok(StatusCode::NO_CONTENT)
}

/// Reads `agent`'s diary in the caller's namespace. Auth: `memory:read`.
async fn read_diary(
    principal: AuthPrincipal,
    Extension(store): Extension<Arc<dyn Store>>,
    Path(agent): Path<String>,
    Query(q): Query<DiaryQuery>,
) -> Result<Json<Vec<DiaryEntry>>, ApiError> {
    if !principal.0.may(MEMORY_READ) {
        return Err(ApiError::Forbidden);
    }
    let ns = resolve_ns(&principal, store.as_ref(), q.namespace.as_deref()).await?;
    let limit = q.limit.unwrap_or(50).min(500);
    Ok(Json(
        store
            .read_diary(&ns, &agent, limit)
            .await
            .map_err(internal)?,
    ))
}

/// Browses memories (the `memory_recall` path), optionally filtered to
/// project/topic — distinct from the importance-ranked wake-up feed. Auth: `memory:read`.
async fn browse_memories(
    principal: AuthPrincipal,
    Extension(store): Extension<Arc<dyn Store>>,
    Query(q): Query<MemoryBrowseQuery>,
) -> Result<Json<Vec<Memory>>, ApiError> {
    if !principal.0.may(MEMORY_READ) {
        return Err(ApiError::Forbidden);
    }
    let ns = resolve_ns(&principal, store.as_ref(), q.namespace.as_deref()).await?;
    let limit = q.limit.unwrap_or(50).min(500);
    Ok(Json(
        store
            .list_memories_filtered(&ns, q.project.as_deref(), q.topic.as_deref(), limit)
            .await
            .map_err(internal)?,
    ))
}

#[derive(Serialize)]
struct NamespaceStats {
    total: usize,
    projects: Vec<ProjectCount>,
}

#[derive(Serialize)]
struct ProjectCount {
    project: String,
    count: usize,
}

/// Read-accessible namespace stats (derived from room counts; unlike
/// `/status` which is admin-gated). Auth: `memory:read`.
async fn memory_stats(
    principal: AuthPrincipal,
    Extension(store): Extension<Arc<dyn Store>>,
    Query(q): Query<NamespaceQuery>,
) -> Result<Json<NamespaceStats>, ApiError> {
    if !principal.0.may(MEMORY_READ) {
        return Err(ApiError::Forbidden);
    }
    let ns = resolve_ns(&principal, store.as_ref(), q.namespace.as_deref()).await?;
    let rooms = store.list_rooms(&ns, None, 1000).await.map_err(internal)?;
    let total: usize = rooms.iter().map(|r| r.count).sum();
    let mut by_project: std::collections::BTreeMap<String, usize> =
        std::collections::BTreeMap::new();
    for r in &rooms {
        *by_project.entry(r.project.clone()).or_default() += r.count;
    }
    let projects = by_project
        .into_iter()
        .map(|(project, count)| ProjectCount { project, count })
        .collect();
    Ok(Json(NamespaceStats { total, projects }))
}

// ===== Repo directory (global registry — Context Mapper) =====

/// Registers/upserts a repo in the global registry (operator action). Auth: `admin`.
async fn register_repo(
    principal: AuthPrincipal,
    Extension(store): Extension<Arc<dyn Store>>,
    Json(repo): Json<RepoDirectory>,
) -> Result<StatusCode, ApiError> {
    if !principal.0.may(ADMIN) {
        return Err(ApiError::Forbidden);
    }
    store.register_repo(repo).await.map_err(internal)?;
    Ok(StatusCode::NO_CONTENT)
}

/// Lists every registered repo (the ecosystem roster). Auth: `memory:read`.
async fn list_repos(
    principal: AuthPrincipal,
    Extension(store): Extension<Arc<dyn Store>>,
) -> Result<Json<Vec<RepoDirectory>>, ApiError> {
    if !principal.0.may(MEMORY_READ) {
        return Err(ApiError::Forbidden);
    }
    Ok(Json(store.list_repos().await.map_err(internal)?))
}

/// Reverse-resolves a working directory to its registered repo. Auth: `memory:read`.
async fn resolve_repo(
    principal: AuthPrincipal,
    Extension(store): Extension<Arc<dyn Store>>,
    Query(q): Query<ResolveRepoQuery>,
) -> Result<Json<RepoDirectory>, ApiError> {
    if !principal.0.may(MEMORY_READ) {
        return Err(ApiError::Forbidden);
    }
    match store.resolve_repo(&q.cwd).await.map_err(internal)? {
        Some(repo) => Ok(Json(repo)),
        None => Err(ApiError::NotFound),
    }
}

// ---------- federation control API (scaffold; feature `federation`) ----------

/// `GET /federation/state` — the instance's federated self-description.
#[cfg(feature = "federation")]
async fn federation_state(
    Extension(cfg): Extension<Arc<InstanceFederationConfig>>,
) -> Json<FederationState> {
    Json(cfg.to_state())
}

/// `POST /federation/routed-write` — apply a write under an authoritative scope.
///
/// Scaffold: applies the write locally with provenance stamping (origin =
/// this instance, authority = the scope) but performs **no** boundary
/// enforcement — no trust-tier egress filtering, scope/airgap deny, or
/// boundary transformation. Ijima's non-bypassable safety floor is the
/// follow-on (ADR `federation-control-api` §Deferred).
#[cfg(feature = "federation")]
async fn routed_write(
    principal: AuthPrincipal,
    Extension(store): Extension<Arc<dyn Store>>,
    Extension(cfg): Extension<Arc<InstanceFederationConfig>>,
    Json(write): Json<RoutedWrite>,
) -> Result<Json<RoutedWriteReceipt>, ApiError> {
    if !principal.0.may(MEMORY_WRITE) {
        return Err(ApiError::Forbidden);
    }
    let RoutedWrite {
        target: _,
        scope,
        operation: _,
        payload,
    } = write;

    // === Boundary enforcement (non-bypassable; the federation ingress path) ===
    // (1) Airgap: a sovereign instance rejects all federation writes.
    if cfg.role == ijima_core::federation::InstanceRole::Airgapped {
        return Err(ApiError::Forbidden);
    }
    // (2) Scope filter: accept only writes for scopes this instance is
    //     authoritative for (default-deny for sovereignty).
    if !cfg.accepts_scope(&scope) {
        return Err(ApiError::BadRequest(format!(
            "out of authoritative scope: {}/{}",
            scope.namespace, scope.project
        )));
    }

    let mut memory: Memory = serde_json::from_value(payload)
        .map_err(|e| ApiError::BadRequest(format!("payload is not a Memory: {e}")))?;
    // Stamp federation provenance: this instance applied it; the routed scope
    // is the source-of-truth authority for the record.
    memory.origin = ijima_core::provenance::InstanceId::local();
    memory.authority =
        ijima_core::provenance::AuthorityScope(format!("{}/{}", scope.namespace, scope.project));
    if memory.created_at.is_empty() {
        memory.created_at = std::time::SystemTime::now()
            .duration_since(std::time::UNIX_EPOCH)
            .map(|d| d.as_secs().to_string())
            .unwrap_or_default();
    }
    let ns = principal.0.personal_namespace();

    // (3) Trust-tier ingress: doctrine arriving via federation is never
    //     auto-trusted — stage it as PendingReview (never auto-promoted).
    //     Lower tiers (Explicit/Mined/AutoCapture) cross as-is.
    let (commit, mut warnings) = if memory.source == MemorySource::Doctrine {
        let pending = store
            .enqueue_extraction(&ns, memory, 0.5)
            .await
            .map_err(internal)?;
        (
            pending,
            vec!["doctrine downgraded to PendingReview (trust-tier ingress rule)".into()],
        )
    } else {
        let id = store.store_memory(&ns, memory).await.map_err(internal)?;
        (id.0, Vec::new())
    };
    warnings.push("boundary enforcement: scope + airgap + doctrine-downgrade applied".into());
    Ok(Json(RoutedWriteReceipt {
        accepted: true,
        instance: cfg.instance_id.clone(),
        scope,
        commit: Some(commit),
        warnings,
    }))
}

/// `POST /federation/conflict-signal` — poll for a conflict on a scope.
///
/// Scaffold: no conflict detection yet. Returns `404` (no active conflict);
/// the single-instance deployment has no peer to conflict with.
#[cfg(feature = "federation")]
async fn conflict_signal(
    Json(_scope): Json<AuthoritativeScope>,
) -> Result<Json<ConflictSignal>, ApiError> {
    Err(ApiError::NotFound)
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::IjimaAuth;
    use axum::body::Body;
    use axum::http::{Request, StatusCode};
    use ijima_core::{harness::Harness, memory::MemorySource};
    use tower::ServiceExt;

    async fn app_with_store() -> (Router, Arc<IjimaAuth>) {
        let auth = Arc::new(IjimaAuth::from_embedded_policy().expect("policy"));
        let store_inner = Arc::new(crate::SurrealStore::open_embedded().await.expect("open"));
        let store: Arc<dyn Store> = store_inner.clone();
        let kg: Arc<dyn KnowledgeGraph> = store_inner;
        (
            app(
                auth.clone(),
                store,
                kg,
                None,
                Arc::new(crate::redaction::Redactor::new()),
                #[cfg(feature = "rate-limit")]
                None,
                #[cfg(feature = "federation")]
                Arc::new(InstanceFederationConfig::default()),
            ),
            auth,
        )
    }

    /// Like [`app_with_store`] but with a custom federation config — for
    /// boundary-enforcement tests (airgap, out-of-scope).
    #[cfg(feature = "federation")]
    async fn app_with_federation_config(
        config: InstanceFederationConfig,
    ) -> (Router, Arc<IjimaAuth>) {
        let auth = Arc::new(IjimaAuth::from_embedded_policy().expect("policy"));
        let store_inner = Arc::new(crate::SurrealStore::open_embedded().await.expect("open"));
        let store: Arc<dyn Store> = store_inner.clone();
        let kg: Arc<dyn KnowledgeGraph> = store_inner;
        (
            app(
                auth.clone(),
                store,
                kg,
                None,
                Arc::new(crate::redaction::Redactor::new()),
                #[cfg(feature = "rate-limit")]
                None,
                Arc::new(config),
            ),
            auth,
        )
    }

    fn bearer(auth: &IjimaAuth, principal: &str, cap: &str) -> String {
        format!(
            "Bearer {}",
            auth.issue_bearer(principal, cap).expect("issue")
        )
    }

    #[cfg(feature = "federation")]
    #[tokio::test]
    async fn federation_state_returns_local_config() {
        let (app, _auth) = app_with_store().await;
        let res = app
            .oneshot(
                Request::builder()
                    .uri("/federation/state")
                    .body(Body::empty())
                    .unwrap(),
            )
            .await
            .unwrap();
        assert_eq!(res.status(), StatusCode::OK);
        let state = body_json(res).await;
        assert_eq!(state["instance_id"], "local");
        assert_eq!(state["role"], "Unifying");
    }

    #[cfg(feature = "federation")]
    #[tokio::test]
    async fn routed_write_applies_a_memory() {
        let (app, auth) = app_with_store().await;
        let write = bearer(&auth, "elliott", MEMORY_WRITE);
        let body = serde_json::json!({
            "target": "local",
            "scope": {"namespace": "local", "project": "Dominic"},
            "operation": "Create",
            "payload": {
                "id": "mem_fed_test",
                "content": "federated hello",
                "project": "Dominic",
                "topic": "federated",
                "source": "Explicit",
                "harness": "Dominic"
            }
        })
        .to_string();
        let res = app
            .oneshot(
                Request::builder()
                    .method("POST")
                    .uri("/federation/routed-write")
                    .header("authorization", &write)
                    .header("content-type", "application/json")
                    .body(Body::from(body))
                    .unwrap(),
            )
            .await
            .unwrap();
        assert_eq!(res.status(), StatusCode::OK);
        let receipt = body_json(res).await;
        assert_eq!(receipt["accepted"], true);
        assert!(receipt["commit"].as_str().is_some());
        assert_eq!(
            receipt["warnings"][0],
            "boundary enforcement: scope + airgap + doctrine-downgrade applied"
        );
    }

    #[cfg(feature = "federation")]
    #[tokio::test]
    async fn routed_write_requires_memory_write() {
        let (app, auth) = app_with_store().await;
        let read = bearer(&auth, "elliott", MEMORY_READ); // read cap, not write
        let body = serde_json::json!({
            "target": "local",
            "scope": {"namespace": "local", "project": "Dominic"},
            "operation": "Create",
            "payload": {
                "id": "x", "content": "c", "project": "p",
                "topic": "t", "source": "Explicit", "harness": "Dominic"
            }
        })
        .to_string();
        let res = app
            .oneshot(
                Request::builder()
                    .method("POST")
                    .uri("/federation/routed-write")
                    .header("authorization", &read)
                    .header("content-type", "application/json")
                    .body(Body::from(body))
                    .unwrap(),
            )
            .await
            .unwrap();
        assert_eq!(res.status(), StatusCode::FORBIDDEN);
    }

    #[cfg(feature = "federation")]
    #[tokio::test]
    async fn routed_write_rejects_out_of_scope() {
        let (app, auth) = app_with_store().await;
        let write = bearer(&auth, "elliott", MEMORY_WRITE);
        // default config is authoritative for {local, *}; {shared, ...} is out of scope
        let body = serde_json::json!({
            "target": "local",
            "scope": {"namespace": "shared", "project": "Dominic"},
            "operation": "Create",
            "payload": {
                "id": "x", "content": "c", "project": "p",
                "topic": "t", "source": "Explicit", "harness": "Dominic"
            }
        })
        .to_string();
        let res = app
            .oneshot(
                Request::builder()
                    .method("POST")
                    .uri("/federation/routed-write")
                    .header("authorization", &write)
                    .header("content-type", "application/json")
                    .body(Body::from(body))
                    .unwrap(),
            )
            .await
            .unwrap();
        assert_eq!(res.status(), StatusCode::BAD_REQUEST);
    }

    #[cfg(feature = "federation")]
    #[tokio::test]
    async fn routed_write_rejects_when_airgapped() {
        let cfg = InstanceFederationConfig {
            role: ijima_core::federation::InstanceRole::Airgapped,
            ..InstanceFederationConfig::default()
        };
        let (app, auth) = app_with_federation_config(cfg).await;
        let write = bearer(&auth, "elliott", MEMORY_WRITE);
        let body = serde_json::json!({
            "target": "local",
            "scope": {"namespace": "local", "project": "Dominic"},
            "operation": "Create",
            "payload": {
                "id": "x", "content": "c", "project": "p",
                "topic": "t", "source": "Explicit", "harness": "Dominic"
            }
        })
        .to_string();
        let res = app
            .oneshot(
                Request::builder()
                    .method("POST")
                    .uri("/federation/routed-write")
                    .header("authorization", &write)
                    .header("content-type", "application/json")
                    .body(Body::from(body))
                    .unwrap(),
            )
            .await
            .unwrap();
        assert_eq!(res.status(), StatusCode::FORBIDDEN);
    }

    #[cfg(feature = "federation")]
    #[tokio::test]
    async fn routed_write_downgrades_doctrine_to_pending() {
        let (app, auth) = app_with_store().await;
        let write = bearer(&auth, "elliott", MEMORY_WRITE);
        let body = serde_json::json!({
            "target": "local",
            "scope": {"namespace": "local", "project": "Dominic"},
            "operation": "Create",
            "payload": {
                "id": "mem_doctrine",
                "content": "peer-claimed doctrine",
                "project": "Dominic",
                "topic": "federated",
                "source": "Doctrine",
                "harness": "Dominic"
            }
        })
        .to_string();
        let res = app
            .oneshot(
                Request::builder()
                    .method("POST")
                    .uri("/federation/routed-write")
                    .header("authorization", &write)
                    .header("content-type", "application/json")
                    .body(Body::from(body))
                    .unwrap(),
            )
            .await
            .unwrap();
        assert_eq!(res.status(), StatusCode::OK);
        let receipt = body_json(res).await;
        assert_eq!(receipt["accepted"], true);
        assert_eq!(
            receipt["warnings"][0],
            "doctrine downgraded to PendingReview (trust-tier ingress rule)"
        );
    }

    #[cfg(feature = "federation")]
    #[tokio::test]
    async fn conflict_signal_returns_404_when_none() {
        let (app, _auth) = app_with_store().await;
        let body = serde_json::json!({"namespace": "shared", "project": "Dominic"}).to_string();
        let res = app
            .oneshot(
                Request::builder()
                    .method("POST")
                    .uri("/federation/conflict-signal")
                    .header("content-type", "application/json")
                    .body(Body::from(body))
                    .unwrap(),
            )
            .await
            .unwrap();
        assert_eq!(res.status(), StatusCode::NOT_FOUND);
    }

    fn sample_memory_json(id: &str) -> String {
        serde_json::json!({
            "id": id,
            "content": "decided to wire the daemon",
            "project": "ijima",
            "topic": "api",
            "source": "Explicit",
            "harness": "Pi",
            "session_id": "sess_1",
            "importance": 0.5,
            "created_at": "0",
        })
        .to_string()
    }

    #[tokio::test]
    async fn health_is_public() {
        let (app, _) = app_with_store().await;
        let res = app
            .oneshot(
                Request::builder()
                    .uri("/health")
                    .body(Body::empty())
                    .unwrap(),
            )
            .await
            .unwrap();
        assert_eq!(res.status(), StatusCode::OK);
    }

    #[tokio::test]
    async fn recall_without_auth_is_401() {
        let (app, _) = app_with_store().await;
        let res = app
            .oneshot(
                Request::builder()
                    .uri("/memories/mem_1")
                    .body(Body::empty())
                    .unwrap(),
            )
            .await
            .unwrap();
        assert_eq!(res.status(), StatusCode::UNAUTHORIZED);
    }

    #[tokio::test]
    async fn store_then_recall_round_trips() {
        let (app, auth) = app_with_store().await;
        let write = bearer(&auth, "elliott", MEMORY_WRITE);
        let read = bearer(&auth, "elliott", MEMORY_READ);

        // POST /memories
        let res = app
            .clone()
            .oneshot(
                Request::builder()
                    .method("POST")
                    .uri("/memories")
                    .header("authorization", &write)
                    .header("content-type", "application/json")
                    .body(Body::from(sample_memory_json("mem_1")))
                    .unwrap(),
            )
            .await
            .unwrap();
        assert_eq!(res.status(), StatusCode::OK);

        // GET /memories/mem_1
        let res = app
            .oneshot(
                Request::builder()
                    .uri("/memories/mem_1")
                    .header("authorization", &read)
                    .body(Body::empty())
                    .unwrap(),
            )
            .await
            .unwrap();
        assert_eq!(res.status(), StatusCode::OK);
        let body = axum::body::to_bytes(res.into_body(), usize::MAX)
            .await
            .unwrap();
        let mem: Memory = serde_json::from_slice(&body).unwrap();
        assert_eq!(mem.content, "decided to wire the daemon");
        assert_eq!(mem.harness, Harness::Pi);
        assert_eq!(mem.source, MemorySource::Explicit);
    }

    #[tokio::test]
    async fn store_with_read_only_token_is_403() {
        let (app, auth) = app_with_store().await;
        let read = bearer(&auth, "elliott", MEMORY_READ);
        let res = app
            .oneshot(
                Request::builder()
                    .method("POST")
                    .uri("/memories")
                    .header("authorization", &read)
                    .header("content-type", "application/json")
                    .body(Body::from(sample_memory_json("mem_x")))
                    .unwrap(),
            )
            .await
            .unwrap();
        assert_eq!(res.status(), StatusCode::FORBIDDEN);
    }

    #[tokio::test]
    async fn namespace_isolation_across_principals() {
        let (app, auth) = app_with_store().await;
        // alice stores
        let alice_write = bearer(&auth, "alice", MEMORY_WRITE);
        let _ = app
            .clone()
            .oneshot(
                Request::builder()
                    .method("POST")
                    .uri("/memories")
                    .header("authorization", &alice_write)
                    .header("content-type", "application/json")
                    .body(Body::from(sample_memory_json("mem_a")))
                    .unwrap(),
            )
            .await
            .unwrap();
        // bob cannot recall alice's memory
        let bob_read = bearer(&auth, "bob", MEMORY_READ);
        let res = app
            .oneshot(
                Request::builder()
                    .uri("/memories/mem_a")
                    .header("authorization", &bob_read)
                    .body(Body::empty())
                    .unwrap(),
            )
            .await
            .unwrap();
        assert_eq!(res.status(), StatusCode::NOT_FOUND);
    }

    #[tokio::test]
    async fn promote_redacts_secrets_and_leaves_original_intact() {
        let (app, auth) = app_with_store().await;
        let write = bearer(&auth, "elliott", MEMORY_WRITE);
        let read = bearer(&auth, "elliott", MEMORY_READ);
        let promote = bearer(&auth, "elliott", TRUST_PROMOTE);

        // WS3: elliott must be a member of the promotion target's org
        // wall — grant via the admin route (full-stack setup).
        let admin = bearer(&auth, "root", ADMIN);
        let res = app
            .clone()
            .oneshot(
                Request::builder()
                    .method("POST")
                    .uri("/namespaces/grant")
                    .header("authorization", &admin)
                    .header("content-type", "application/json")
                    .body(Body::from(
                        serde_json::json!({
                            "namespace": "ns_team_shared",
                            "principal": "elliott"
                        })
                        .to_string(),
                    ))
                    .unwrap(),
            )
            .await
            .unwrap();
        assert_eq!(res.status(), StatusCode::OK, "membership grant");

        // Store a personal memory containing a secret.
        let body = serde_json::json!({
            "id": "mem_secret",
            "content": "deploy key sk-abcdefghijklmnopqrstuvwxyz1234567890 contact ops@test.com",
            "project": "ijima",
            "topic": "ops",
            "source": "Explicit",
            "harness": "Pi",
        })
        .to_string();
        let res = app
            .clone()
            .oneshot(
                Request::builder()
                    .method("POST")
                    .uri("/memories")
                    .header("authorization", &write)
                    .header("content-type", "application/json")
                    .body(Body::from(body))
                    .unwrap(),
            )
            .await
            .unwrap();
        assert_eq!(res.status(), StatusCode::OK);

        // Promote to a shared namespace.
        let promote_body = serde_json::json!({
            "target_namespace": "ns_team_shared",
        })
        .to_string();
        let res = app
            .clone()
            .oneshot(
                Request::builder()
                    .method("POST")
                    .uri("/memories/mem_secret/promote")
                    .header("authorization", &promote)
                    .header("content-type", "application/json")
                    .body(Body::from(promote_body))
                    .unwrap(),
            )
            .await
            .unwrap();
        assert_eq!(res.status(), StatusCode::OK);
        let resp: serde_json::Value = serde_json::from_slice(
            &axum::body::to_bytes(res.into_body(), usize::MAX)
                .await
                .unwrap(),
        )
        .unwrap();
        let new_id = resp["id"].as_str().unwrap();
        assert_eq!(new_id, "mem_secret__shared");
        let cats: Vec<&str> = resp["redactions"]
            .as_array()
            .unwrap()
            .iter()
            .map(|r| r["category"].as_str().unwrap())
            .collect();
        assert!(cats.contains(&"api_key"));
        assert!(cats.contains(&"email"));

        // The original personal memory is untouched (verbatim).
        let res = app
            .clone()
            .oneshot(
                Request::builder()
                    .uri("/memories/mem_secret")
                    .header("authorization", &read)
                    .body(Body::empty())
                    .unwrap(),
            )
            .await
            .unwrap();
        let orig: Memory = serde_json::from_slice(
            &axum::body::to_bytes(res.into_body(), usize::MAX)
                .await
                .unwrap(),
        )
        .unwrap();
        assert!(orig.content.contains("sk-abcdef"));
        assert!(orig.content.contains("ops@test.com"));

        // The promoted shared copy is readable via ?namespace= and has
        // secrets scrubbed.
        let res = app
            .oneshot(
                Request::builder()
                    .uri("/memories/mem_secret__shared?namespace=ns_team_shared")
                    .header("authorization", &read)
                    .body(Body::empty())
                    .unwrap(),
            )
            .await
            .unwrap();
        assert_eq!(res.status(), StatusCode::OK);
        let shared: Memory = serde_json::from_slice(
            &axum::body::to_bytes(res.into_body(), usize::MAX)
                .await
                .unwrap(),
        )
        .unwrap();
        assert!(shared.content.contains("[REDACTED:api_key]"));
        assert!(shared.content.contains("[REDACTED:email]"));
        assert!(!shared.content.contains("sk-abcdef"));
        assert!(!shared.content.contains("ops@test.com"));
        // Provenance back-reference.
        assert_eq!(shared.session_id.as_deref(), Some("mem_secret"));
    }

    #[tokio::test]
    async fn promote_requires_trust_promote_not_memory_write() {
        // ADR provenance-tier: raising trust is costlier than writing at a
        // tier, so promote_memory requires trust:promote (codim 4), not
        // memory:write (codim 2). A memory:write-only token gets 403.
        let (app, auth) = app_with_store().await;
        let write = bearer(&auth, "elliott", MEMORY_WRITE);
        let body = serde_json::json!({
            "id": "mem_p",
            "content": "provenance tier test",
            "project": "ijima",
            "topic": "t",
            "source": "Explicit",
            "harness": "Pi",
        })
        .to_string();
        // Store succeeds with memory:write.
        let res = app
            .clone()
            .oneshot(
                Request::builder()
                    .method("POST")
                    .uri("/memories")
                    .header("authorization", &write)
                    .header("content-type", "application/json")
                    .body(Body::from(body))
                    .unwrap(),
            )
            .await
            .unwrap();
        assert_eq!(res.status(), StatusCode::OK);

        // Promote is forbidden with only memory:write.
        let promote_body = serde_json::json!({ "target_namespace": "ns_team_shared" }).to_string();
        let res = app
            .clone()
            .oneshot(
                Request::builder()
                    .method("POST")
                    .uri("/memories/mem_p/promote")
                    .header("authorization", &write)
                    .header("content-type", "application/json")
                    .body(Body::from(promote_body))
                    .unwrap(),
            )
            .await
            .unwrap();
        assert_eq!(res.status(), StatusCode::FORBIDDEN);

        // WS3: the promotion target is membership-gated — grant elliott
        // into ns_team_shared via the admin route, then the trust:promote
        // holder succeeds.
        let admin = bearer(&auth, "root", ADMIN);
        let res = app
            .clone()
            .oneshot(
                Request::builder()
                    .method("POST")
                    .uri("/namespaces/grant")
                    .header("authorization", &admin)
                    .header("content-type", "application/json")
                    .body(Body::from(
                        serde_json::json!({
                            "namespace": "ns_team_shared",
                            "principal": "elliott"
                        })
                        .to_string(),
                    ))
                    .unwrap(),
            )
            .await
            .unwrap();
        assert_eq!(res.status(), StatusCode::OK, "membership grant");

        let promote = bearer(&auth, "elliott", TRUST_PROMOTE);
        let promote_body = serde_json::json!({ "target_namespace": "ns_team_shared" }).to_string();
        let res = app
            .oneshot(
                Request::builder()
                    .method("POST")
                    .uri("/memories/mem_p/promote")
                    .header("authorization", &promote)
                    .header("content-type", "application/json")
                    .body(Body::from(promote_body))
                    .unwrap(),
            )
            .await
            .unwrap();
        assert_eq!(res.status(), StatusCode::OK);
    }

    // ---------- WS3 org walls ----------

    /// The full wall lifecycle: non-member 403 → admin grants → member
    /// 200 → revoke → 403 again. Also pins the admin bypass.
    #[tokio::test]
    async fn shared_namespace_membership_lifecycle() {
        let (app, auth) = app_with_store().await;
        let rw = bearer(&auth, "elliott", MEMORY_WRITE);
        let admin = bearer(&auth, "root", ADMIN);

        let write_into = |app: Router, token: String, n: u8| async move {
            app.oneshot(
                Request::builder()
                    .method("POST")
                    .uri("/memories?namespace=ns_ia_shared")
                    .header("authorization", token)
                    .header("content-type", "application/json")
                    .body(Body::from(
                        serde_json::json!({
                            "id": format!("mem_wall_{n}"),
                            "content": format!("org-wall probe {n}"),
                            "project": "ijima",
                            "topic": "ws3",
                            "source": "Explicit",
                            "harness": "Pi",
                            "importance": 0.5,
                            "created_at": "0",
                        })
                        .to_string(),
                    ))
                    .unwrap(),
            )
            .await
            .unwrap()
        };

        // 1. Non-member is walled out.
        let res = write_into(app.clone(), rw.clone(), 1).await;
        assert_eq!(
            res.status(),
            StatusCode::FORBIDDEN,
            "non-member must be walled"
        );

        // 2. Admin bypasses without membership.
        let res = write_into(app.clone(), admin.clone(), 2).await;
        assert_eq!(res.status(), StatusCode::OK, "admin bypass");

        // 3. Non-admin cannot grant.
        let res = app
            .clone()
            .oneshot(
                Request::builder()
                    .method("POST")
                    .uri("/namespaces/grant")
                    .header("authorization", rw.clone())
                    .header("content-type", "application/json")
                    .body(Body::from(
                        serde_json::json!({ "namespace": "ns_ia_shared", "principal": "elliott" })
                            .to_string(),
                    ))
                    .unwrap(),
            )
            .await
            .unwrap();
        assert_eq!(res.status(), StatusCode::FORBIDDEN, "grant requires admin");

        // 4. Admin grants → member writes fine.
        let res = app
            .clone()
            .oneshot(
                Request::builder()
                    .method("POST")
                    .uri("/namespaces/grant")
                    .header("authorization", admin.clone())
                    .header("content-type", "application/json")
                    .body(Body::from(
                        serde_json::json!({ "namespace": "ns_ia_shared", "principal": "elliott" })
                            .to_string(),
                    ))
                    .unwrap(),
            )
            .await
            .unwrap();
        assert_eq!(res.status(), StatusCode::OK);
        let res = write_into(app.clone(), rw.clone(), 3).await;
        assert_eq!(res.status(), StatusCode::OK, "member passes");

        // 5. Members listing (admin) shows the grant.
        let res = app
            .clone()
            .oneshot(
                Request::builder()
                    .uri("/namespaces/members?namespace=ns_ia_shared")
                    .header("authorization", admin.clone())
                    .body(Body::empty())
                    .unwrap(),
            )
            .await
            .unwrap();
        assert_eq!(res.status(), StatusCode::OK);
        let members = body_json(res).await;
        assert_eq!(members[0]["principal"].as_str(), Some("elliott"));
        assert_eq!(members[0]["granted_by"].as_str(), Some("root"));

        // 6. Revoke → walled again.
        let res = app
            .clone()
            .oneshot(
                Request::builder()
                    .method("POST")
                    .uri("/namespaces/revoke")
                    .header("authorization", admin.clone())
                    .header("content-type", "application/json")
                    .body(Body::from(
                        serde_json::json!({ "namespace": "ns_ia_shared", "principal": "elliott" })
                            .to_string(),
                    ))
                    .unwrap(),
            )
            .await
            .unwrap();
        assert_eq!(res.status(), StatusCode::NO_CONTENT);
        let res = write_into(app, rw, 4).await;
        assert_eq!(
            res.status(),
            StatusCode::FORBIDDEN,
            "revoked member is walled"
        );
    }

    /// Open namespaces stay open: doctrine and import staging need no
    /// membership.
    #[tokio::test]
    async fn doctrine_and_import_namespaces_stay_open() {
        let (app, auth) = app_with_store().await;
        let read = bearer(&auth, "elliott", MEMORY_READ);

        let res = app
            .clone()
            .oneshot(
                Request::builder()
                    .uri("/memories?namespace=ns_doctrine&limit=5")
                    .header("authorization", read.clone())
                    .body(Body::empty())
                    .unwrap(),
            )
            .await
            .unwrap();
        assert_eq!(res.status(), StatusCode::OK, "doctrine is readable by all");

        let res = app
            .clone()
            .oneshot(
                Request::builder()
                    .uri("/memories?namespace=ns_import_probe&limit=5")
                    .header("authorization", read)
                    .body(Body::empty())
                    .unwrap(),
            )
            .await
            .unwrap();
        assert_eq!(res.status(), StatusCode::OK, "import staging is open");
    }

    #[tokio::test]
    async fn cross_principal_personal_namespace_is_forbidden() {
        let (app, auth) = app_with_store().await;
        // Alice stores a memory.
        let alice_write = bearer(&auth, "alice", MEMORY_WRITE);
        let _ = app
            .clone()
            .oneshot(
                Request::builder()
                    .method("POST")
                    .uri("/memories")
                    .header("authorization", &alice_write)
                    .header("content-type", "application/json")
                    .body(Body::from(
                        serde_json::json!({
                            "id": "mem_a",
                            "content": "alice only",
                            "project": "x",
                            "topic": "x",
                            "source": "Explicit",
                            "harness": "Pi",
                        })
                        .to_string(),
                    ))
                    .unwrap(),
            )
            .await
            .unwrap();

        // Bob tries to read alice's personal namespace explicitly.
        let bob_read = bearer(&auth, "bob", MEMORY_READ);
        let res = app
            .oneshot(
                Request::builder()
                    .uri("/memories/mem_a?namespace=ns_alice_private")
                    .header("authorization", &bob_read)
                    .body(Body::empty())
                    .unwrap(),
            )
            .await
            .unwrap();
        assert_eq!(res.status(), StatusCode::FORBIDDEN);
    }

    #[tokio::test]
    async fn doctrine_ingest_requires_admin_and_is_readable_shared() {
        let (app, auth) = app_with_store().await;
        let admin = bearer(&auth, "ci", "admin");
        let read = bearer(&auth, "anyone", MEMORY_READ);

        // Non-admin cannot ingest doctrine.
        let res = app
            .clone()
            .oneshot(
                Request::builder()
                    .method("POST")
                    .uri("/doctrine")
                    .header("authorization", &read)
                    .header("content-type", "application/json")
                    .body(Body::from(
                        serde_json::json!({
                            "id": "d1",
                            "content": "doctrine body",
                            "project": "ijima",
                            "topic": "arch",
                        })
                        .to_string(),
                    ))
                    .unwrap(),
            )
            .await
            .unwrap();
        assert_eq!(res.status(), StatusCode::FORBIDDEN);

        // Admin ingests.
        let res = app
            .clone()
            .oneshot(
                Request::builder()
                    .method("POST")
                    .uri("/doctrine")
                    .header("authorization", &admin)
                    .header("content-type", "application/json")
                    .body(Body::from(
                        serde_json::json!({
                            "id": "d1",
                            "content": "doctrine body",
                            "project": "ijima",
                            "topic": "arch",
                        })
                        .to_string(),
                    ))
                    .unwrap(),
            )
            .await
            .unwrap();
        assert_eq!(res.status(), StatusCode::OK);

        // Any read-capable principal can recall doctrine from ns_doctrine.
        let res = app
            .oneshot(
                Request::builder()
                    .uri("/memories/d1?namespace=ns_doctrine")
                    .header("authorization", &read)
                    .body(Body::empty())
                    .unwrap(),
            )
            .await
            .unwrap();
        assert_eq!(res.status(), StatusCode::OK);
        let mem: Memory = serde_json::from_slice(
            &axum::body::to_bytes(res.into_body(), usize::MAX)
                .await
                .unwrap(),
        )
        .unwrap();
        assert_eq!(mem.content, "doctrine body");
        assert_eq!(mem.source, ijima_core::memory::MemorySource::Doctrine);
    }

    #[cfg(feature = "backend-surreal")]
    #[tokio::test]
    async fn visible_scope_searches_the_principals_readable_world() {
        // The "empty brain" regression: scope=visible used to merge only
        // private + global, so imported corpora and org-wall content were
        // invisible to the pi integration. Visible must span private +
        // global + open ns_import_* staging + member walls — and NOT walls
        // the principal is absent from.
        use ijima_core::HashEmbedder;
        let auth = Arc::new(IjimaAuth::from_embedded_policy().expect("policy"));
        let embedder: Arc<dyn ijima_core::Embedder> = Arc::new(HashEmbedder::default());
        let store_inner = Arc::new(
            crate::SurrealStore::open_embedded_with(embedder.clone())
                .await
                .expect("open"),
        );
        let store: Arc<dyn Store> = store_inner.clone();
        let kg: Arc<dyn KnowledgeGraph> = store_inner;
        let app = app(
            auth.clone(),
            store.clone(),
            kg,
            Some(embedder),
            Arc::new(crate::redaction::Redactor::new()),
            #[cfg(feature = "rate-limit")]
            None,
            #[cfg(feature = "federation")]
            Arc::new(InstanceFederationConfig::default()),
        );
        let read = bearer(&auth, "elliott", "memory:read");

        // Seed one distinct memory per tier.
        let seed = |ns: &'static str, id: &'static str, content: String| {
            let store = store.clone();
            async move {
                store
                    .store_memory(
                        &NamespaceId::new(ns),
                        Memory {
                            id: MemoryId(id.into()),
                            content,
                            project: "ijima".into(),
                            topic: "test".into(),
                            source: MemorySource::AutoCapture,
                            harness: Harness::Pi,
                            session_id: None,
                            origin: ijima_core::InstanceId::local(),
                            authority: ijima_core::AuthorityScope::local(),
                            importance: 0.5,
                            created_at: "0".into(),
                        },
                    )
                    .await
                    .expect("seed")
            }
        };
        seed("global", "mem_vis_global", "global commons row".into()).await;
        seed(
            "ns_import_probe",
            "mem_vis_import",
            "import staging row".into(),
        )
        .await;
        seed("ns_wall_member", "mem_vis_wall", "member wall row".into()).await;
        seed("ns_wall_other", "mem_vis_other", "foreign wall row".into()).await;
        store
            .grant_namespace_membership(ijima_core::NamespaceMembership {
                namespace: "ns_wall_member".into(),
                principal: "elliott".into(),
                granted_at_unix: 0,
                granted_by: "root".into(),
            })
            .await
            .expect("grant");

        let res = app
            .clone()
            .oneshot(
                Request::builder()
                    .method("POST")
                    .uri("/memories/search")
                    .header("authorization", &read)
                    .header("content-type", "application/json")
                    .body(Body::from(
                        serde_json::json!({
                            "text": "import staging row",
                            "limit": 50,
                            "scope": "visible"
                        })
                        .to_string(),
                    ))
                    .unwrap(),
            )
            .await
            .unwrap();
        assert_eq!(res.status(), StatusCode::OK);
        let body: serde_json::Value = serde_json::from_slice(
            &axum::body::to_bytes(res.into_body(), usize::MAX)
                .await
                .unwrap(),
        )
        .unwrap();
        let hits = body["memories"].as_array().unwrap().clone();
        let ids: Vec<&str> = hits
            .iter()
            .map(|h| h["memory"]["id"].as_str().unwrap())
            .collect();
        assert!(ids.contains(&"mem_vis_import"), "staging must be visible");
        assert!(ids.contains(&"mem_vis_global"), "global must be visible");
        assert!(ids.contains(&"mem_vis_wall"), "member wall must be visible");
        assert!(
            !ids.contains(&"mem_vis_other"),
            "a wall the principal is absent from must stay invisible"
        );
    }

    #[tokio::test]
    async fn wakeup_composes_personal_and_doctrine() {
        let (app, auth) = app_with_store().await;
        let write = bearer(&auth, "elliott", MEMORY_WRITE);
        let admin = bearer(&auth, "ci", "admin");
        let read = bearer(&auth, "elliott", MEMORY_READ);

        // Store a personal memory.
        let _ = app
            .clone()
            .oneshot(
                Request::builder()
                    .method("POST")
                    .uri("/memories")
                    .header("authorization", &write)
                    .header("content-type", "application/json")
                    .body(Body::from(
                        serde_json::json!({
                            "id": "mem_p",
                            "content": "personal essential",
                            "project": "ijima",
                            "topic": "x",
                            "source": "Explicit",
                            "harness": "Pi",
                        })
                        .to_string(),
                    ))
                    .unwrap(),
            )
            .await
            .unwrap();

        // Ingest doctrine.
        let _ = app
            .clone()
            .oneshot(
                Request::builder()
                    .method("POST")
                    .uri("/doctrine")
                    .header("authorization", &admin)
                    .header("content-type", "application/json")
                    .body(Body::from(
                        serde_json::json!({
                            "id": "doc_1",
                            "content": "doctrine baseline",
                            "project": "ijima",
                            "topic": "arch",
                        })
                        .to_string(),
                    ))
                    .unwrap(),
            )
            .await
            .unwrap();

        // Wake-up composes both.
        let res = app
            .oneshot(
                Request::builder()
                    .uri("/wakeup")
                    .header("authorization", &read)
                    .body(Body::empty())
                    .unwrap(),
            )
            .await
            .unwrap();
        assert_eq!(res.status(), StatusCode::OK);
        let body: serde_json::Value = serde_json::from_slice(
            &axum::body::to_bytes(res.into_body(), usize::MAX)
                .await
                .unwrap(),
        )
        .unwrap();
        assert_eq!(body["identity"]["principal"], "elliott");
        assert_eq!(body["personal_essentials"].as_array().unwrap().len(), 1);
        assert_eq!(
            body["personal_essentials"][0]["content"],
            "personal essential"
        );
        assert_eq!(body["doctrine"].as_array().unwrap().len(), 1);
        assert_eq!(body["doctrine"][0]["content"], "doctrine baseline");
        assert_eq!(body["doctrine"][0]["source"], "Doctrine");
    }

    #[cfg(feature = "rate-limit")]
    #[tokio::test(flavor = "multi_thread", worker_threads = 2)]
    async fn import_memories_backs_off_through_rate_limit() {
        // Regression (production, 2026-08-21): the first 14k-row import lost
        // 13.6k memories because 429s were counted as skips. The client now
        // retries with backoff, so the same import completes — slowly —
        // through a tiny rate bucket. Real socket, real client.
        let auth = Arc::new(IjimaAuth::from_embedded_policy().expect("policy"));
        let store_inner = Arc::new(crate::SurrealStore::open_embedded().await.expect("open"));
        let store: Arc<dyn Store> = store_inner.clone();
        let kg: Arc<dyn KnowledgeGraph> = store_inner;
        let app = app(
            auth.clone(),
            store,
            kg,
            None,
            Arc::new(crate::redaction::Redactor::new()),
            Some(crate::rate_limit::make_rate_limiter(1.0, 1.0)),
            #[cfg(feature = "federation")]
            Arc::new(InstanceFederationConfig::default()),
        );
        let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap();
        let addr = listener.local_addr().unwrap();
        tokio::spawn(async move {
            axum::serve(listener, app).await.unwrap();
        });

        // One multi-capability grant: check (read) + store (write).
        let token = auth
            .issue_grant_bearer("elliott", &[MEMORY_READ, MEMORY_WRITE])
            .expect("issue");
        let client = ijima_client::Client::new(
            ijima_client::ClientConfig::new(format!("http://{addr}"), Harness::Pi)
                .with_token(token),
        );
        let ns = format!("ns_import_ratelimit_{}", std::process::id());
        let memories: Vec<Memory> = (0..5)
            .map(|i| Memory {
                id: MemoryId(format!("mem_backoff_{i}")),
                content: format!("backoff corpus row {i} for rate-limit regression"),
                project: "ijima".into(),
                topic: "test".into(),
                source: ijima_core::memory::MemorySource::AutoCapture,
                harness: Harness::Pi,
                session_id: None,
                origin: ijima_core::InstanceId::local(),
                authority: ijima_core::AuthorityScope::local(),
                importance: 0.5,
                created_at: "0".into(),
            })
            .collect();
        let counts = client.import_memories(&ns, memories).await.expect("import");
        assert_eq!(counts.attempted, 5);
        assert_eq!(counts.added, 5, "no memory may be lost to 429s");
        assert_eq!(counts.skipped, 0);
    }

    #[tokio::test]
    async fn knowledge_graph_add_honors_namespace_param() {
        let (app, auth) = app_with_store().await;
        let write = bearer(&auth, "elliott", "knowledge:write");
        let read = bearer(&auth, "elliott", "knowledge:read");

        // Add a triple into the open staging namespace via ?namespace=.
        let res = app
            .clone()
            .oneshot(
                Request::builder()
                    .method("POST")
                    .uri("/kg/triples?namespace=ns_import_stage")
                    .header("authorization", &write)
                    .header("content-type", "application/json")
                    .body(Body::from(
                        serde_json::json!({
                            "subject": "Ijima",
                            "predicate": "depends_on",
                            "object": "Schubert",
                        })
                        .to_string(),
                    ))
                    .unwrap(),
            )
            .await
            .unwrap();
        assert_eq!(res.status(), StatusCode::OK);

        // Default (personal) namespace stays empty …
        let res = app
            .clone()
            .oneshot(
                Request::builder()
                    .uri("/kg/stats")
                    .header("authorization", &read)
                    .body(Body::empty())
                    .unwrap(),
            )
            .await
            .unwrap();
        let personal: serde_json::Value = serde_json::from_slice(
            &axum::body::to_bytes(res.into_body(), usize::MAX)
                .await
                .unwrap(),
        )
        .unwrap();
        assert_eq!(personal["triples"], 0);

        // … and the staging namespace reports the edge.
        let res = app
            .clone()
            .oneshot(
                Request::builder()
                    .uri("/kg/stats?namespace=ns_import_stage")
                    .header("authorization", &read)
                    .body(Body::empty())
                    .unwrap(),
            )
            .await
            .unwrap();
        let staged: serde_json::Value = serde_json::from_slice(
            &axum::body::to_bytes(res.into_body(), usize::MAX)
                .await
                .unwrap(),
        )
        .unwrap();
        assert_eq!(staged["triples"], 1);
    }

    #[tokio::test]
    async fn knowledge_graph_add_query_invalidate() {
        let (app, auth) = app_with_store().await;
        let write = bearer(&auth, "elliott", "knowledge:write");
        let read = bearer(&auth, "elliott", "knowledge:read");

        // Add a triple.
        let res = app
            .clone()
            .oneshot(
                Request::builder()
                    .method("POST")
                    .uri("/kg/triples")
                    .header("authorization", &write)
                    .header("content-type", "application/json")
                    .body(Body::from(
                        serde_json::json!({
                            "subject": "Ijima",
                            "predicate": "depends_on",
                            "object": "SurrealDB",
                            "confidence": 1.0,
                        })
                        .to_string(),
                    ))
                    .unwrap(),
            )
            .await
            .unwrap();
        assert_eq!(res.status(), StatusCode::OK);

        // Query the entity — outgoing edge present.
        let res = app
            .clone()
            .oneshot(
                Request::builder()
                    .uri("/kg/entities/Ijima")
                    .header("authorization", &read)
                    .body(Body::empty())
                    .unwrap(),
            )
            .await
            .unwrap();
        assert_eq!(res.status(), StatusCode::OK);
        let body: serde_json::Value = serde_json::from_slice(
            &axum::body::to_bytes(res.into_body(), usize::MAX)
                .await
                .unwrap(),
        )
        .unwrap();
        assert_eq!(body["outgoing"].as_array().unwrap().len(), 1);
        assert_eq!(body["outgoing"][0]["object"], "SurrealDB");
        assert!(body["incoming"].as_array().unwrap().is_empty());

        // Stats.
        let res = app
            .clone()
            .oneshot(
                Request::builder()
                    .uri("/kg/stats")
                    .header("authorization", &read)
                    .body(Body::empty())
                    .unwrap(),
            )
            .await
            .unwrap();
        let body: serde_json::Value = serde_json::from_slice(
            &axum::body::to_bytes(res.into_body(), usize::MAX)
                .await
                .unwrap(),
        )
        .unwrap();
        assert_eq!(body["entities"], 2);
        assert_eq!(body["triples"], 1);

        // Invalidate.
        let res = app
            .oneshot(
                Request::builder()
                    .method("POST")
                    .uri("/kg/triples/Ijima:depends_on:SurrealDB/invalidate")
                    .header("authorization", &write)
                    .body(Body::empty())
                    .unwrap(),
            )
            .await
            .unwrap();
        assert_eq!(res.status(), StatusCode::NO_CONTENT);
    }

    #[tokio::test]
    async fn status_requires_admin_and_reports_counts() {
        let (app, auth) = app_with_store().await;
        let admin = bearer(&auth, "op", "admin");
        let read = bearer(&auth, "user", MEMORY_READ);

        // Store a memory + a triple so counts are non-zero.
        let _ = app
            .clone()
            .oneshot(
                Request::builder()
                    .method("POST")
                    .uri("/memories")
                    .header("authorization", &admin)
                    .header("content-type", "application/json")
                    .body(Body::from(
                        serde_json::json!({
                            "id": "m1",
                            "content": "stat test",
                            "project": "x",
                            "topic": "x",
                            "source": "Explicit",
                            "harness": "Pi",
                        })
                        .to_string(),
                    ))
                    .unwrap(),
            )
            .await
            .unwrap();

        // Non-admin is forbidden.
        let res = app
            .clone()
            .oneshot(
                Request::builder()
                    .uri("/status")
                    .header("authorization", &read)
                    .body(Body::empty())
                    .unwrap(),
            )
            .await
            .unwrap();
        assert_eq!(res.status(), StatusCode::FORBIDDEN);

        // Admin sees global counts.
        let res = app
            .oneshot(
                Request::builder()
                    .uri("/status")
                    .header("authorization", &admin)
                    .body(Body::empty())
                    .unwrap(),
            )
            .await
            .unwrap();
        assert_eq!(res.status(), StatusCode::OK);
        let body: serde_json::Value = serde_json::from_slice(
            &axum::body::to_bytes(res.into_body(), usize::MAX)
                .await
                .unwrap(),
        )
        .unwrap();
        assert_eq!(body["memories"], 1);
        // Deploy-kit fields: version pinned to the crate version, sane
        // uptime, real start time.
        assert_eq!(body["version"], env!("CARGO_PKG_VERSION"));
        let uptime = body["uptime_secs"].as_u64().expect("uptime is u64");
        assert!(uptime < 60, "fresh test app should have tiny uptime");
        assert!(
            body["started_at_unix"].as_u64().expect("started_at is u64") > 1_000_000_000,
            "started_at looks like a unix timestamp"
        );
        assert!(!body["namespaces"].as_array().unwrap().is_empty());
    }

    #[tokio::test]
    async fn sessions_create_list_end_via_http() {
        let (app, auth) = app_with_store().await;
        let ingest = bearer(&auth, "op", SESSION_INGEST);
        let read = bearer(&auth, "op", MEMORY_READ);

        // Create two sessions.
        for (id, harness) in [("sess_a", "Pi"), ("sess_b", "Sakamoto")] {
            let res = app
                .clone()
                .oneshot(
                    Request::builder()
                        .method("POST")
                        .uri("/sessions")
                        .header("authorization", &ingest)
                        .header("content-type", "application/json")
                        .body(Body::from(
                            serde_json::json!({
                                "id": id,
                                "harness": harness,
                                "channel": "thread-1",
                                "started_at": "2026-07-05T10:00:00Z",
                            })
                            .to_string(),
                        ))
                        .unwrap(),
                )
                .await
                .unwrap();
            assert_eq!(res.status(), StatusCode::OK);
        }

        // List — both present.
        let res = app
            .clone()
            .oneshot(
                Request::builder()
                    .uri("/sessions")
                    .header("authorization", &read)
                    .body(Body::empty())
                    .unwrap(),
            )
            .await
            .unwrap();
        assert_eq!(res.status(), StatusCode::OK);
        let body: serde_json::Value = serde_json::from_slice(
            &axum::body::to_bytes(res.into_body(), usize::MAX)
                .await
                .unwrap(),
        )
        .unwrap();
        let arr = body.as_array().unwrap();
        assert_eq!(arr.len(), 2);

        // Filter by harness=pi.
        let res = app
            .clone()
            .oneshot(
                Request::builder()
                    .uri("/sessions?harness=pi")
                    .header("authorization", &read)
                    .body(Body::empty())
                    .unwrap(),
            )
            .await
            .unwrap();
        let body: serde_json::Value = serde_json::from_slice(
            &axum::body::to_bytes(res.into_body(), usize::MAX)
                .await
                .unwrap(),
        )
        .unwrap();
        assert_eq!(body.as_array().unwrap().len(), 1);
        assert_eq!(body[0]["harness"], "Pi");

        // End sess_a.
        let res = app
            .clone()
            .oneshot(
                Request::builder()
                    .method("POST")
                    .uri("/sessions/sess_a/end")
                    .header("authorization", &ingest)
                    .header("content-type", "application/json")
                    .body(Body::from(
                        serde_json::json!({ "ended_at": "2026-07-05T11:00:00Z" }).to_string(),
                    ))
                    .unwrap(),
            )
            .await
            .unwrap();
        assert_eq!(res.status(), StatusCode::NO_CONTENT);

        // Verify ended_at is persisted.
        let res = app
            .oneshot(
                Request::builder()
                    .uri("/sessions?harness=pi")
                    .header("authorization", &read)
                    .body(Body::empty())
                    .unwrap(),
            )
            .await
            .unwrap();
        let body: serde_json::Value = serde_json::from_slice(
            &axum::body::to_bytes(res.into_body(), usize::MAX)
                .await
                .unwrap(),
        )
        .unwrap();
        assert_eq!(body[0]["ended_at"], "2026-07-05T11:00:00Z");
    }

    #[tokio::test]
    async fn mining_queue_requires_review_capability() {
        let (app, auth) = app_with_store().await;
        let reviewer = bearer(&auth, "op", MINING_REVIEW);
        let reader = bearer(&auth, "op", MEMORY_READ);

        // A memory:read holder cannot list the queue.
        let res = app
            .clone()
            .oneshot(
                Request::builder()
                    .uri("/mining/queue")
                    .header("authorization", &reader)
                    .body(Body::empty())
                    .unwrap(),
            )
            .await
            .unwrap();
        assert_eq!(res.status(), StatusCode::FORBIDDEN);

        // A mining:review holder can list (empty queue).
        let res = app
            .oneshot(
                Request::builder()
                    .uri("/mining/queue")
                    .header("authorization", &reviewer)
                    .body(Body::empty())
                    .unwrap(),
            )
            .await
            .unwrap();
        assert_eq!(res.status(), StatusCode::OK);
        let body: serde_json::Value = serde_json::from_slice(
            &axum::body::to_bytes(res.into_body(), usize::MAX)
                .await
                .unwrap(),
        )
        .unwrap();
        assert!(body.as_array().unwrap().is_empty());
    }

    fn hit_mem(id: &str, sim: f32) -> SearchHit {
        SearchHit {
            memory: Memory {
                id: MemoryId(id.into()),
                content: id.into(),
                project: "p".into(),
                topic: "t".into(),
                source: ijima_core::MemorySource::Explicit,
                harness: ijima_core::harness::Harness::Pi,
                session_id: None,
                origin: ijima_core::InstanceId::local(),
                authority: ijima_core::AuthorityScope::local(),
                importance: 0.5,
                created_at: "0".into(),
            },
            similarity: sim,
        }
    }

    #[test]
    fn merge_search_hits_ranks_desc_dedups_and_truncates() {
        // scope=visible merge: two ranked lists combine by similarity, dedup
        // by memory id (first wins), truncate to limit.
        let a = vec![hit_mem("a", 0.9), hit_mem("b", 0.5)];
        let b = vec![hit_mem("c", 0.8), hit_mem("a", 0.7)]; // 'a' dup, lower sim
        let merged = merge_search_hits(a, b, 3);
        // Sorted by similarity desc: a(0.9), c(0.8), b(0.5) — the dup a(0.7)
        // is dropped (first wins).
        assert_eq!(merged.len(), 3);
        assert_eq!(merged[0].memory.id.0, "a");
        assert_eq!((merged[0].similarity * 10.0).round() as i32, 9);
        assert_eq!(merged[1].memory.id.0, "c");
        assert_eq!(merged[2].memory.id.0, "b");
    }

    #[test]
    fn merge_search_hits_respects_limit() {
        let a = vec![hit_mem("a", 0.9), hit_mem("b", 0.8)];
        let b = vec![hit_mem("c", 0.7), hit_mem("d", 0.6)];
        let merged = merge_search_hits(a, b, 2);
        assert_eq!(merged.len(), 2);
        assert_eq!(merged[0].memory.id.0, "a");
        assert_eq!(merged[1].memory.id.0, "b");
    }

    #[cfg(feature = "mining")]
    #[tokio::test]
    async fn trigger_requires_mining_trigger_capability() {
        let (app, auth) = app_with_store().await;
        // A memory:write holder cannot trigger mining.
        let write = bearer(&auth, "elliott", MEMORY_WRITE);
        let res = app
            .oneshot(
                Request::builder()
                    .method("POST")
                    .uri("/sessions/sess_x/mine")
                    .header("authorization", &write)
                    .body(Body::empty())
                    .unwrap(),
            )
            .await
            .unwrap();
        assert_eq!(res.status(), StatusCode::FORBIDDEN);
    }

    #[cfg(feature = "mining")]
    #[tokio::test]
    async fn trigger_mines_decision_and_archives() {
        // Rules-only: assumes no IJIMA_LLM_* env is set (CI is clean). When
        // env is unset, `build_mining_agent` returns None and `mine_all` runs
        // the deterministic rules tier.
        let (app, auth) = app_with_store().await;
        let ingest = bearer(&auth, "elliott", SESSION_INGEST);
        let trigger = bearer(&auth, "elliott", MINING_TRIGGER);

        // Ingest a decision-bearing turn into elliott's personal namespace.
        let turn = serde_json::json!({
            "session_id": "sess_mine",
            "turn_index": 0,
            "role": "User",
            "content": "We decided to use SurrealDB for storage.",
            "timestamp": "0",
        });
        let res = app
            .clone()
            .oneshot(
                Request::builder()
                    .method("POST")
                    .uri("/sessions/sess_mine/turns")
                    .header("authorization", &ingest)
                    .header("content-type", "application/json")
                    .body(Body::from(turn.to_string()))
                    .unwrap(),
            )
            .await
            .unwrap();
        assert_eq!(res.status(), StatusCode::NO_CONTENT);

        // Trigger mining (rules-only: no IJIMA_LLM_* env in tests).
        let res = app
            .oneshot(
                Request::builder()
                    .method("POST")
                    .uri("/sessions/sess_mine/mine")
                    .header("authorization", &trigger)
                    .body(Body::empty())
                    .unwrap(),
            )
            .await
            .unwrap();
        assert_eq!(res.status(), StatusCode::OK);
        let body = axum::body::to_bytes(res.into_body(), usize::MAX)
            .await
            .unwrap();
        let report: crate::mining_pipeline::MiningReport = serde_json::from_slice(&body).unwrap();
        assert!(
            report.archived >= 1,
            "rules tier should archive the decision: {report:?}"
        );
    }

    // ===== Palace / diary / repo route tests (Phase B) =====

    async fn body_json(res: axum::response::Response) -> serde_json::Value {
        let body = axum::body::to_bytes(res.into_body(), usize::MAX)
            .await
            .unwrap();
        serde_json::from_slice(&body).unwrap()
    }

    async fn seed_memory(app: &Router, auth: &IjimaAuth, id: &str, project: &str, topic: &str) {
        let body = serde_json::json!({
            "id": id,
            "content": format!("{project}/{topic} note"),
            "project": project,
            "topic": topic,
            "source": "Explicit",
            "harness": "Pi",
            "session_id": "sess_1",
            "importance": 0.5,
            "created_at": "0",
        })
        .to_string();
        let res = app
            .clone()
            .oneshot(
                Request::builder()
                    .method("POST")
                    .uri("/memories")
                    .header("authorization", bearer(auth, "elliott", MEMORY_WRITE))
                    .header("content-type", "application/json")
                    .body(Body::from(body))
                    .unwrap(),
            )
            .await
            .unwrap();
        assert_eq!(res.status(), StatusCode::OK, "seed {id} failed");
    }

    #[tokio::test]
    async fn store_memory_honors_namespace_query() {
        let (app, auth) = app_with_store().await;
        let body = serde_json::json!({
            "id": "mem_nsimp",
            "content": "imported via namespace query",
            "project": "ijima",
            "topic": "import",
            "source": "AutoCapture",
            "harness": "Pi",
            "importance": 0.5,
            "created_at": "0",
        })
        .to_string();
        let res = app
            .clone()
            .oneshot(
                Request::builder()
                    .method("POST")
                    .uri("/memories?namespace=ns_import_testbox")
                    .header("authorization", bearer(&auth, "elliott", MEMORY_WRITE))
                    .header("content-type", "application/json")
                    .body(Body::from(body))
                    .unwrap(),
            )
            .await
            .unwrap();
        assert_eq!(res.status(), StatusCode::OK);

        // Dedup check in that namespace finds it; the caller's personal
        // namespace does not (isolation held).
        let read_token = bearer(&auth, "elliott", MEMORY_READ);
        let check = |uri: &str| {
            let uri = uri.to_string();
            let app = app.clone();
            let body = serde_json::json!({
                "content": "imported via namespace query"
            })
            .to_string();
            let auth_header = read_token.clone();
            async move {
                app.oneshot(
                    Request::builder()
                        .method("POST")
                        .uri(uri)
                        .header("authorization", auth_header)
                        .header("content-type", "application/json")
                        .body(Body::from(body))
                        .unwrap(),
                )
                .await
                .unwrap()
            }
        };
        let res = check("/memories/check?namespace=ns_import_testbox").await;
        assert_eq!(res.status(), StatusCode::OK);
        let found = body_json(res).await;
        assert_eq!(
            found["duplicate"].as_str(),
            Some("mem_nsimp"),
            "same-namespace dedup check must find the import"
        );
        let res = check("/memories/check").await;
        assert_eq!(res.status(), StatusCode::OK);
        let personal = body_json(res).await;
        assert_eq!(
            personal["duplicate"].as_str(),
            None,
            "personal namespace must not see the import"
        );
    }

    #[tokio::test]
    async fn store_memory_rejects_foreign_private_namespace() {
        let (app, auth) = app_with_store().await;
        let body = serde_json::json!({
            "id": "mem_sneaky",
            "content": "cross-tenant write attempt",
            "project": "ijima",
            "topic": "security",
            "source": "Explicit",
            "harness": "Pi",
            "importance": 0.5,
            "created_at": "0",
        })
        .to_string();
        let res = app
            .oneshot(
                Request::builder()
                    .method("POST")
                    .uri("/memories?namespace=ns_bob_private")
                    .header("authorization", bearer(&auth, "elliott", MEMORY_WRITE))
                    .header("content-type", "application/json")
                    .body(Body::from(body))
                    .unwrap(),
            )
            .await
            .unwrap();
        assert_eq!(res.status(), StatusCode::FORBIDDEN);
    }

    #[tokio::test]
    async fn rooms_taxonomy_stats_reflect_seeded_memories() {
        let (app, auth) = app_with_store().await;
        seed_memory(&app, &auth, "mem_a", "ijima", "api").await;
        seed_memory(&app, &auth, "mem_b", "ijima", "auth").await;
        let read = bearer(&auth, "elliott", MEMORY_READ);

        // /rooms
        let res = app
            .clone()
            .oneshot(
                Request::builder()
                    .uri("/rooms")
                    .header("authorization", &read)
                    .body(Body::empty())
                    .unwrap(),
            )
            .await
            .unwrap();
        assert_eq!(res.status(), StatusCode::OK);
        let rooms = body_json(res).await;
        let topics: std::collections::HashSet<&str> = rooms
            .as_array()
            .unwrap()
            .iter()
            .map(|r| r["topic"].as_str().unwrap())
            .collect();
        assert!(
            topics.contains("api") && topics.contains("auth"),
            "rooms: {rooms}"
        );

        // /memories/stats
        let res = app
            .clone()
            .oneshot(
                Request::builder()
                    .uri("/memories/stats")
                    .header("authorization", &read)
                    .body(Body::empty())
                    .unwrap(),
            )
            .await
            .unwrap();
        assert_eq!(res.status(), StatusCode::OK);
        let stats = body_json(res).await;
        assert_eq!(stats["total"], 2, "stats: {stats}");
        assert_eq!(stats["projects"][0]["project"], "ijima");
        assert_eq!(stats["projects"][0]["count"], 2);
    }

    #[tokio::test]
    async fn browse_memories_filters_by_project() {
        let (app, auth) = app_with_store().await;
        seed_memory(&app, &auth, "mem_a", "ijima", "api").await;
        seed_memory(&app, &auth, "mem_b", "possum", "efficiency").await;
        let read = bearer(&auth, "elliott", MEMORY_READ);

        let res = app
            .clone()
            .oneshot(
                Request::builder()
                    .uri("/memories?project=possum")
                    .header("authorization", &read)
                    .body(Body::empty())
                    .unwrap(),
            )
            .await
            .unwrap();
        assert_eq!(res.status(), StatusCode::OK);
        let mems = body_json(res).await;
        let arr = mems.as_array().unwrap();
        assert_eq!(arr.len(), 1);
        assert_eq!(arr[0]["project"], "possum");
    }

    #[tokio::test]
    async fn palace_graph_and_tunnel_link_shared_topic() {
        let (app, auth) = app_with_store().await;
        seed_memory(&app, &auth, "mem_a", "ijima", "efficiency").await;
        seed_memory(&app, &auth, "mem_b", "possum", "efficiency").await;
        let read = bearer(&auth, "elliott", MEMORY_READ);

        let res = app
            .clone()
            .oneshot(
                Request::builder()
                    .uri("/palace/graph")
                    .header("authorization", &read)
                    .body(Body::empty())
                    .unwrap(),
            )
            .await
            .unwrap();
        assert_eq!(res.status(), StatusCode::OK);
        let graph = body_json(res).await;
        let projects: std::collections::HashSet<&str> = graph["projects"]
            .as_array()
            .unwrap()
            .iter()
            .map(|p| p.as_str().unwrap())
            .collect();
        assert!(
            projects.contains("ijima") && projects.contains("possum"),
            "graph: {graph}"
        );

        let res = app
            .clone()
            .oneshot(
                Request::builder()
                    .uri("/palace/tunnel?topic=efficiency&project_a=ijima&project_b=possum")
                    .header("authorization", &read)
                    .body(Body::empty())
                    .unwrap(),
            )
            .await
            .unwrap();
        assert_eq!(res.status(), StatusCode::OK);
        let trav = body_json(res).await;
        assert_eq!(trav["memories_a"].as_array().unwrap().len(), 1);
        assert_eq!(trav["memories_b"].as_array().unwrap().len(), 1);
    }

    #[tokio::test]
    async fn diary_write_then_read_round_trips() {
        let (app, auth) = app_with_store().await;
        let write = bearer(&auth, "elliott", MEMORY_WRITE);
        let read = bearer(&auth, "elliott", MEMORY_READ);

        let body = serde_json::json!({
            "agent": "pi",
            "content": "shipped the routes",
            "topic": "ijima",
            "timestamp": "2026-08-09T12:00:00Z"
        })
        .to_string();
        let res = app
            .clone()
            .oneshot(
                Request::builder()
                    .method("POST")
                    .uri("/diaries")
                    .header("authorization", &write)
                    .header("content-type", "application/json")
                    .body(Body::from(body))
                    .unwrap(),
            )
            .await
            .unwrap();
        assert_eq!(res.status(), StatusCode::NO_CONTENT);

        let res = app
            .clone()
            .oneshot(
                Request::builder()
                    .uri("/diaries/pi")
                    .header("authorization", &read)
                    .body(Body::empty())
                    .unwrap(),
            )
            .await
            .unwrap();
        assert_eq!(res.status(), StatusCode::OK);
        let entries = body_json(res).await;
        let arr = entries.as_array().unwrap();
        assert_eq!(arr.len(), 1);
        assert_eq!(arr[0]["content"], "shipped the routes");
    }

    #[tokio::test]
    async fn diary_write_requires_memory_write_not_read() {
        let (app, auth) = app_with_store().await;
        let read = bearer(&auth, "elliott", MEMORY_READ);
        let body = serde_json::json!({"agent": "pi", "content": "x", "timestamp": "t"}).to_string();
        let res = app
            .clone()
            .oneshot(
                Request::builder()
                    .method("POST")
                    .uri("/diaries")
                    .header("authorization", &read)
                    .header("content-type", "application/json")
                    .body(Body::from(body))
                    .unwrap(),
            )
            .await
            .unwrap();
        assert_eq!(res.status(), StatusCode::FORBIDDEN);
    }

    #[tokio::test]
    async fn repo_list_on_fresh_store_is_empty_not_error() {
        // Regression (field, v0.2.2): `repo_directory` was missing from the
        // open-time DDL — a SELECT from a never-written table hard-errors on
        // surrealdb 3, so every fresh deployment's `GET /repos` returned 500
        // "table does not exist". The round-trip test below masked it: its
        // register-first upsert materializes the table implicitly. List
        // FIRST on a fresh store must return an empty 200.
        let (app, auth) = app_with_store().await;
        let read = bearer(&auth, "elliott", MEMORY_READ);
        let res = app
            .oneshot(
                Request::builder()
                    .uri("/repos")
                    .header("authorization", &read)
                    .body(Body::empty())
                    .unwrap(),
            )
            .await
            .unwrap();
        assert_eq!(res.status(), StatusCode::OK);
        let body: serde_json::Value = serde_json::from_slice(
            &axum::body::to_bytes(res.into_body(), usize::MAX)
                .await
                .unwrap(),
        )
        .unwrap();
        assert_eq!(body.as_array().map(Vec::len), Some(0));
    }

    #[tokio::test]
    async fn repo_register_list_resolve_round_trips() {
        let (app, auth) = app_with_store().await;
        let admin = bearer(&auth, "elliott", ADMIN);
        let read = bearer(&auth, "elliott", MEMORY_READ);

        // register a repo (admin)
        let body = serde_json::json!({
            "name": "Ijima",
            "path": "/home/x/Ijima",
            "remote_url": "git@github.com:Industrial-Algebra/Ijima.git",
            "role": "memory-service"
        })
        .to_string();
        let res = app
            .clone()
            .oneshot(
                Request::builder()
                    .method("POST")
                    .uri("/repos")
                    .header("authorization", &admin)
                    .header("content-type", "application/json")
                    .body(Body::from(body))
                    .unwrap(),
            )
            .await
            .unwrap();
        assert_eq!(res.status(), StatusCode::NO_CONTENT);

        // list (memory:read)
        let res = app
            .clone()
            .oneshot(
                Request::builder()
                    .uri("/repos")
                    .header("authorization", &read)
                    .body(Body::empty())
                    .unwrap(),
            )
            .await
            .unwrap();
        assert_eq!(res.status(), StatusCode::OK);
        let repos = body_json(res).await;
        assert_eq!(repos[0]["name"], "Ijima");
        assert_eq!(repos[0]["path"], "/home/x/Ijima");

        // resolve a cwd inside the repo (memory:read)
        let res = app
            .clone()
            .oneshot(
                Request::builder()
                    .uri("/repos/resolve?cwd=/home/x/Ijima/src")
                    .header("authorization", &read)
                    .body(Body::empty())
                    .unwrap(),
            )
            .await
            .unwrap();
        assert_eq!(res.status(), StatusCode::OK);
        let repo = body_json(res).await;
        assert_eq!(repo["name"], "Ijima");

        // resolve a cwd in no registered repo → 404
        let res = app
            .clone()
            .oneshot(
                Request::builder()
                    .uri("/repos/resolve?cwd=/nowhere/here")
                    .header("authorization", &read)
                    .body(Body::empty())
                    .unwrap(),
            )
            .await
            .unwrap();
        assert_eq!(res.status(), StatusCode::NOT_FOUND);
    }

    #[tokio::test]
    async fn repo_register_requires_admin() {
        let (app, auth) = app_with_store().await;
        let read = bearer(&auth, "elliott", MEMORY_READ);
        let body = serde_json::json!({
            "name": "X", "path": "/x", "remote_url": "u", "role": "r"
        })
        .to_string();
        let res = app
            .clone()
            .oneshot(
                Request::builder()
                    .method("POST")
                    .uri("/repos")
                    .header("authorization", &read)
                    .header("content-type", "application/json")
                    .body(Body::from(body))
                    .unwrap(),
            )
            .await
            .unwrap();
        assert_eq!(res.status(), StatusCode::FORBIDDEN);
    }

    #[tokio::test]
    async fn token_revocation_kills_the_bearer_immediately() {
        let (app, auth) = app_with_store().await;
        let admin = bearer(&auth, "op", ADMIN);
        let victim = bearer(&auth, "victim", MEMORY_READ);

        // Victim can read before revocation.
        let res = app
            .clone()
            .oneshot(
                Request::builder()
                    .uri("/memories")
                    .header("authorization", &victim)
                    .body(Body::empty())
                    .unwrap(),
            )
            .await
            .unwrap();
        assert_eq!(res.status(), StatusCode::OK);

        // Non-admin cannot revoke.
        let res = app
            .clone()
            .oneshot(
                Request::builder()
                    .method("POST")
                    .uri("/tokens/revoke")
                    .header("authorization", &victim)
                    .header("content-type", "application/json")
                    .body(Body::from(
                        serde_json::json!({ "token": victim, "reason": "test" }).to_string(),
                    ))
                    .unwrap(),
            )
            .await
            .unwrap();
        assert_eq!(res.status(), StatusCode::FORBIDDEN);

        // Admin revokes the victim's bearer.
        let res = app
            .clone()
            .oneshot(
                Request::builder()
                    .method("POST")
                    .uri("/tokens/revoke")
                    .header("authorization", &admin)
                    .header("content-type", "application/json")
                    .body(Body::from(
                        serde_json::json!({ "token": victim, "reason": "leaked in test" })
                            .to_string(),
                    ))
                    .unwrap(),
            )
            .await
            .unwrap();
        assert_eq!(res.status(), StatusCode::NO_CONTENT);

        // The same bearer is now exactly as dead as a bad signature.
        let res = app
            .clone()
            .oneshot(
                Request::builder()
                    .uri("/memories")
                    .header("authorization", &victim)
                    .body(Body::empty())
                    .unwrap(),
            )
            .await
            .unwrap();
        assert_eq!(res.status(), StatusCode::UNAUTHORIZED);

        // Admin can list the revocation — hash only, never the bearer.
        let res = app
            .clone()
            .oneshot(
                Request::builder()
                    .uri("/tokens/revocations")
                    .header("authorization", &admin)
                    .body(Body::empty())
                    .unwrap(),
            )
            .await
            .unwrap();
        assert_eq!(res.status(), StatusCode::OK);
        let body: serde_json::Value = serde_json::from_slice(
            &axum::body::to_bytes(res.into_body(), usize::MAX)
                .await
                .unwrap(),
        )
        .unwrap();
        let revs = body.as_array().expect("list response");
        assert_eq!(revs.len(), 1);
        assert_eq!(revs[0]["reason"], "leaked in test");
        assert_eq!(
            revs[0]["token_hash"].as_str().expect("hash"),
            crate::auth::bearer_hash(&victim)
        );
        assert!(!revs[0].to_string().contains(&victim), "no raw bearer");

        // Revocation survives restart-by-rehydration: a fresh auth over
        // the same store re-arms (simulated via hydrate from the store).
        let listed: Vec<TokenRevocation> =
            serde_json::from_value(body).expect("deserializes as TokenRevocation");
        auth.hydrate_revocations(&listed);
        assert!(auth.is_revoked(&victim));
    }
}