areev-cal 1.9.3

CAL (Context Assembly Language) lexer, parser, and executor for Areev.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135
3136
3137
3138
3139
3140
3141
3142
3143
3144
3145
3146
3147
3148
3149
3150
3151
3152
3153
3154
3155
3156
3157
3158
3159
3160
3161
3162
3163
3164
3165
3166
3167
3168
3169
3170
3171
3172
3173
3174
3175
3176
3177
3178
3179
3180
3181
3182
3183
3184
3185
3186
3187
3188
3189
3190
3191
3192
3193
3194
3195
3196
3197
3198
3199
3200
3201
3202
3203
3204
3205
3206
3207
3208
3209
3210
3211
3212
3213
3214
3215
3216
3217
3218
3219
3220
3221
3222
3223
3224
3225
3226
3227
3228
3229
3230
3231
3232
3233
3234
3235
3236
3237
3238
3239
3240
3241
3242
3243
3244
3245
3246
3247
3248
3249
3250
3251
3252
3253
3254
3255
3256
3257
3258
3259
3260
3261
3262
3263
3264
3265
3266
3267
3268
3269
3270
3271
3272
3273
3274
3275
3276
3277
3278
3279
3280
3281
3282
3283
3284
3285
3286
3287
3288
3289
3290
3291
3292
3293
3294
3295
3296
3297
3298
3299
3300
3301
3302
3303
3304
3305
3306
3307
3308
3309
3310
3311
3312
3313
3314
3315
3316
3317
3318
3319
3320
3321
3322
3323
3324
3325
3326
3327
3328
3329
3330
3331
3332
3333
3334
3335
3336
3337
3338
3339
3340
3341
3342
3343
3344
3345
3346
3347
3348
3349
3350
3351
3352
3353
3354
3355
3356
3357
3358
3359
3360
3361
3362
3363
3364
3365
3366
3367
3368
3369
3370
3371
3372
3373
3374
3375
3376
3377
3378
3379
3380
3381
3382
3383
3384
3385
3386
3387
3388
3389
3390
3391
3392
3393
3394
3395
3396
3397
3398
3399
3400
3401
3402
3403
3404
3405
3406
3407
3408
3409
3410
3411
3412
3413
3414
3415
3416
3417
3418
3419
3420
3421
3422
3423
3424
3425
3426
3427
3428
3429
3430
3431
3432
3433
3434
3435
3436
3437
3438
3439
3440
3441
3442
3443
3444
3445
3446
3447
3448
3449
3450
3451
3452
3453
3454
3455
3456
3457
3458
3459
3460
3461
3462
3463
3464
3465
3466
3467
3468
3469
3470
3471
3472
3473
3474
3475
3476
3477
3478
3479
3480
3481
3482
3483
3484
3485
3486
3487
3488
3489
3490
3491
3492
3493
3494
3495
3496
3497
3498
3499
3500
3501
3502
3503
3504
3505
3506
3507
3508
3509
3510
3511
3512
3513
3514
3515
3516
3517
3518
3519
3520
3521
3522
3523
3524
3525
3526
3527
3528
3529
3530
3531
3532
3533
3534
3535
3536
3537
3538
3539
3540
3541
3542
3543
3544
3545
3546
3547
3548
3549
3550
3551
3552
3553
3554
3555
3556
3557
3558
3559
3560
3561
3562
3563
3564
3565
3566
3567
3568
3569
3570
3571
3572
3573
3574
3575
3576
3577
3578
3579
3580
3581
3582
3583
3584
3585
3586
3587
3588
3589
3590
3591
3592
3593
3594
3595
3596
3597
3598
3599
3600
3601
3602
3603
3604
3605
3606
3607
3608
3609
3610
3611
3612
3613
3614
3615
3616
3617
3618
3619
3620
3621
3622
3623
3624
3625
3626
3627
3628
3629
3630
3631
3632
3633
3634
3635
3636
3637
3638
3639
3640
3641
3642
3643
3644
3645
3646
3647
3648
3649
3650
3651
3652
3653
3654
3655
3656
3657
3658
3659
3660
3661
3662
3663
3664
3665
3666
3667
3668
3669
3670
3671
3672
3673
3674
3675
3676
3677
3678
3679
3680
3681
3682
3683
3684
3685
3686
3687
3688
3689
3690
3691
3692
3693
3694
3695
3696
3697
3698
3699
3700
3701
3702
3703
3704
3705
3706
3707
3708
3709
3710
3711
3712
3713
3714
3715
3716
3717
3718
3719
3720
3721
3722
3723
3724
3725
3726
3727
3728
3729
3730
3731
3732
3733
3734
3735
3736
3737
3738
3739
3740
3741
3742
3743
3744
3745
3746
3747
3748
3749
//! AreevFacade — CalStoreFacade over the embedded areev-store.
//!
//! Session-scoped: carries the capability defaults (namespace, user) that
//! CAL queries inherit when they don't specify one (§7.11 direction).
//!
//! M2 scope: structural recall only. Semantic (`query`) recall returns a
//! clear error until the FTS/vector legs land (M4).

use std::collections::{HashMap, HashSet};
use std::sync::Mutex;

use areev_core::authz::Verb;
use areev_core::error::{Hash, AreevError, Result};
use areev_core::ns::NsScope;
use areev_core::format::deserialize::DeserializedGrain;
use areev_core::format::serialize::serialize_grain;
use areev_core::types::{Fact, Grain, Observation, RelatedTo, State};
use areev_store::Areev;

use crate::ast::QueryParam;
use crate::errors::CalError;
use crate::facade::{
    AccumulateResult, AssemblyManifest, CalCapabilities, CalStoreFacade, FieldInfo, GrainTypeInfo,
    GrantRow, RerankType, TemplateInfo,
};
use crate::json_build::{build_grain_from_json, GrainSink};
use crate::queries::{PersistedQuery, QueryEntry, QueryListEntry, QueryRegistry};
use crate::store_types::{
    ConflictStatus, DiversityMethod, ForkGroupInfo, RecallParams, SearchHit, SupersessionStatus,
    VersionEntry,
};
use crate::templates::{PersistedTemplate, TemplateRegistry};

/// `meta` key prefixes for CAL host metadata. One row per entry, so recording
/// a last-run timestamp does not rewrite the whole set.
const QRY_PREFIX: &str = "qry:";
const TPL_PREFIX: &str = "tpl:";

/// Recursive ingress transform over a JSON value's string leaves.
fn ingress_value_tree(
    m: &mut Areev,
    ns: &str,
    v: &mut serde_json::Value,
) -> Result<()> {
    match v {
        serde_json::Value::String(s) => {
            if let Some(t) = m.ingress_transform_text(ns, s)? {
                *s = t;
            }
            Ok(())
        }
        serde_json::Value::Array(a) => {
            for item in a {
                ingress_value_tree(m, ns, item)?;
            }
            Ok(())
        }
        serde_json::Value::Object(o) => {
            for (k, item) in o.iter_mut() {
                if !matches!(k.as_str(), "namespace" | "session_id" | "run_id" | "parent") {
                    ingress_value_tree(m, ns, item)?;
                }
            }
            Ok(())
        }
        _ => Ok(()),
    }
}

fn now_secs() -> u64 {
    std::time::SystemTime::now()
        .duration_since(std::time::UNIX_EPOCH)
        .map(|d| d.as_secs())
        .unwrap_or(0)
}

fn now_ms() -> i64 {
    std::time::SystemTime::now()
        .duration_since(std::time::UNIX_EPOCH)
        .map(|d| d.as_millis() as i64)
        .unwrap_or(0)
}

/// A synthetic tool-call id for a host that did not supply one, so that two
/// executions of the same tool stay two records.
///
/// The `auto:` prefix is deliberate: it marks the id as minted here rather than
/// carried from a provider, so nothing downstream mistakes it for a real
/// `tool_call_id` it could correlate against an LLM transcript.
///
/// Uniqueness comes from the counter, which is monotonic within a process and
/// therefore holds even where the clock is coarse or steps backwards. The
/// timestamp and pid only separate *different* processes writing the same
/// memory in sequence — a clock tick alone would not, since a short-lived
/// process restarts the counter at zero.
///
/// This does make the record non-reproducible: recording the same call twice
/// writes two grains. That is the intended reading of an occurrence log — it
/// happened twice — and it is why the id is minted per call rather than derived
/// from the call's content, which would put us straight back into collapsing
/// retries.
fn occurrence_id() -> String {
    use std::sync::atomic::{AtomicU64, Ordering};
    static COUNTER: AtomicU64 = AtomicU64::new(0);
    let n = COUNTER.fetch_add(1, Ordering::Relaxed);
    format!(
        "auto:{}-{}-{}",
        std::process::id(),
        chrono::Utc::now()
            .timestamp_nanos_opt()
            .unwrap_or_else(|| now_ms().saturating_mul(1_000_000)),
        n
    )
}

/// Membership test for the `WHERE <field> IN (...)` filters. `None` is "no
/// filter"; an empty set never reaches here (the caller short-circuits, because
/// an empty `IN` selects nothing rather than everything).
fn set_contains(set: &Option<Vec<String>>, value: Option<&str>) -> bool {
    match set {
        None => true,
        Some(values) => value.is_some_and(|v| values.iter().any(|c| c == v)),
    }
}

/// A grain's structural tags.
///
/// `GrainCommon.tags` serializes under the LONG name `structural_tags` (it
/// compacts to the wire key `tags`, then expands back to `structural_tags`).
/// Reading `"tags"` here would find nothing and silently match everything,
/// which is the same class of failure #318 fixes.
fn grain_tags(g: &DeserializedGrain) -> Vec<&str> {
    g.fields
        .get("structural_tags")
        .and_then(|v| v.as_array())
        .map(|arr| arr.iter().filter_map(|t| t.as_str()).collect())
        .unwrap_or_default()
}

/// Does this grain pass the `tags INCLUDE […]` / `EXCLUDE […]` sets (#318)?
///
/// A grain passes when it carries EVERY member of `tags` and NONE of
/// `exclude_tags`. A grain with no tags therefore matches no `INCLUDE` and
/// every `EXCLUDE`, which is the reading an export receipt has to be able to
/// rely on.
///
/// Both fields parsed, were advertised as filterable by `DESCRIBE FIELDS`,
/// were marked consumed by push-down — and were read by nothing. So
/// `tags EXCLUDE ["label:restricted"]` returned exactly the grains it was
/// asked to exclude, and `areev corpus --select` wrote them into the JSONL
/// under an immutable manifest recording the exclusion. That is the failure
/// class #91 closed for every other field: pushed down, evaluated per grain,
/// or refused — never dropped.
fn tags_match(
    tags: &Option<Vec<String>>,
    exclude: &Option<Vec<String>>,
    g: &DeserializedGrain,
) -> bool {
    if tags.is_none() && exclude.is_none() {
        return true;
    }
    let have = grain_tags(g);
    if let Some(required) = tags {
        if !required.iter().all(|t| have.contains(&t.as_str())) {
            return false;
        }
    }
    if let Some(forbidden) = exclude {
        if forbidden.iter().any(|t| have.contains(&t.as_str())) {
            return false;
        }
    }
    true
}

/// "3 hours ago" for `WITH annotate_relative_time`. Coarse on purpose: the
/// point is freshness at a glance, and a model reading "2 weeks ago" needs no
/// more precision than that. Negative ages (a grain stamped in the future,
/// which import and clock skew both produce) read as "just now" rather than
/// wrapping into a nonsense past.
fn relative_time_label(age_ms: i64) -> String {
    const MIN: i64 = 60_000;
    const HOUR: i64 = 60 * MIN;
    const DAY: i64 = 24 * HOUR;
    let plural = |n: i64, unit: &str| {
        if n == 1 {
            format!("1 {unit} ago")
        } else {
            format!("{n} {unit}s ago")
        }
    };
    match age_ms {
        a if a < MIN => "just now".into(),
        a if a < HOUR => plural(a / MIN, "minute"),
        a if a < DAY => plural(a / HOUR, "hour"),
        a if a < 7 * DAY => plural(a / DAY, "day"),
        a if a < 30 * DAY => plural(a / (7 * DAY), "week"),
        a if a < 365 * DAY => plural(a / (30 * DAY), "month"),
        a => plural(a / (365 * DAY), "year"),
    }
}

/// CalStoreFacade implementation over an embedded `Areev` store.
pub struct AreevFacade {
    store: Mutex<Areev>,
    namespace: Option<String>,
    user: Option<String>,
    /// Read-only mounted memories (org/category replicas): alias → store.
    /// A recall with namespace "alias.inner" routes to the mount (§8).
    mounts: std::collections::HashMap<String, Mutex<Areev>>,
    /// Saved queries and custom templates are *host metadata* carried by the
    /// file (`meta` rows), not memories — they travel with the .db so the
    /// CLI, MCP and console all see the same set. Rehydrated on first use.
    queries: Mutex<Option<QueryRegistry>>,
    templates: Mutex<Option<TemplateRegistry>>,
    /// Entries the file carries that this process could not load — a template
    /// that outgrew the §10.8 body limit, a set past the per-file cap, a row
    /// written by a newer version. Reported alongside `Areev::open_warnings`
    /// so a silently smaller set of saved queries is something the operator
    /// sees rather than discovers.
    meta_warnings: Mutex<Vec<String>>,
    /// The session's resolved rights. Defaults to the owner session — a
    /// local open with no principal asserted is the implicit superuser
    /// (`root@localhost`), which is why the single-user path never meets
    /// authorization. `with_principal` replaces it with a fail-closed
    /// restricted set built from the file's own grant grains.
    ///
    /// Behind a lock so a host that serializes requests (the std server
    /// handles one connection at a time) can rebind per request
    /// ([`Self::bind_principal`]). Concurrent hosts bind once at open —
    /// rebinding under concurrent CAL execution would race sessions.
    authz: std::sync::RwLock<areev_core::authz::AuthzSet>,
}

impl AreevFacade {
    pub fn new(store: Areev) -> Self {
        Self::with_session(store, None, None)
    }

    /// Session-scoped facade: `namespace`/`user` become the capability
    /// defaults consulted by the executor.
    pub fn with_session(store: Areev, namespace: Option<String>, user: Option<String>) -> Self {
        AreevFacade {
            store: Mutex::new(store),
            namespace,
            user,
            mounts: std::collections::HashMap::new(),
            queries: Mutex::new(None),
            templates: Mutex::new(None),
            meta_warnings: Mutex::new(Vec::new()),
            authz: std::sync::RwLock::new(areev_core::authz::AuthzSet::owner("user:local")),
        }
    }

    /// Bind this facade to a principal: rights become exactly what the
    /// file's live grant grains cover (fail closed — a file with no grants
    /// for this principal allows nothing). Grants are read once here; a
    /// grant written later needs a rebind (the CAL `GRANT` path will
    /// refresh this itself when it lands).
    pub fn with_principal(self, principal: &str) -> areev_core::error::Result<Self> {
        self.bind_principal(principal)?;
        Ok(self)
    }

    /// Rebind this facade to a principal: rights become exactly what the
    /// file's live grant grains cover right now (fail closed). For hosts
    /// that serialize requests — the std server — this is the per-request
    /// seam: resolve the credential, bind, handle, then [`Self::bind`]
    /// the surface's default back.
    pub fn bind_principal(&self, principal: &str) -> areev_core::error::Result<()> {
        let grants = {
            let mut guard = self.store.lock().unwrap();
            guard.authz_grants(principal)?
        };
        self.bind(areev_core::authz::AuthzSet::restricted(principal, grants));
        Ok(())
    }

    /// Install a pre-built rights set (e.g. the anonymous baseline, or the
    /// owner default when restoring after a request).
    pub fn bind(&self, authz: areev_core::authz::AuthzSet) {
        *self.authz.write().expect("authz lock poisoned") = authz;
    }

    /// The session's resolved rights (owner unless a principal was bound).
    pub fn authz(&self) -> areev_core::authz::AuthzSet {
        self.authz.read().expect("authz lock poisoned").clone()
    }

    /// Make a principal's live grants EQUAL `desired`, in one pass (#309).
    ///
    /// Narrowing a packed grant had no atomic path at all: `REVOKE` refuses a
    /// scope narrower than the grant, so removing one namespace from
    /// `read ON deal.a,deal.b,deal.c` meant revoke-all-then-grant (a window
    /// with NO access) or the other order (a window with too much). A
    /// synchronizer projecting an external policy engine into a memory had to
    /// pause that principal's requests around its own lock to hide the
    /// window.
    ///
    /// Here, every live `mg:permits` head is either superseded in place into
    /// a desired grant or retired with the same `"revoked"` retraction record
    /// `REVOKE` writes, and what is missing is added. A concurrent bind
    /// therefore observes the old set or the new one — never an empty one,
    /// and never a third set that was true at no point.
    ///
    /// An equal set writes NOTHING, so a synchronizer can run on a timer
    /// without churning the audit trail.
    ///
    /// Gated by `admin ON *`, like `GRANT` and `REVOKE`.
    pub fn set_grants(
        &self,
        principal: &str,
        desired: &[areev_core::authz::Grant],
        because: &str,
    ) -> Result<GrantChange> {
        self.check_verb(Verb::Admin, "*")?;
        let want: Vec<String> = {
            let mut v: Vec<String> = desired.iter().map(|g| g.to_object_string()).collect();
            v.sort();
            v.dedup();
            v
        };
        let mut m = self.store.lock().unwrap();
        let live = m.recall(
            areev_core::authz::AUTHZ_NS,
            principal,
            Some(areev_core::authz::REL_PERMITS),
            areev_store::Areev::AUTHZ_GRANT_CAP,
        )?;
        let mut have: Vec<(Hash, String)> = Vec::new();
        for g in &live {
            let Some(obj) = g.get_str("object") else { continue };
            if areev_core::authz::Grant::from_object_string(obj).is_err() {
                continue; // retraction records carry no rights
            }
            have.push((g.hash, obj.to_string()));
        }
        let mut change = GrantChange::default();
        let mut unmatched_want: Vec<&String> =
            want.iter().filter(|w| !have.iter().any(|(_, o)| o == *w)).collect();
        let stale: Vec<(Hash, String)> = have
            .iter()
            .filter(|(_, o)| !want.contains(o))
            .cloned()
            .collect();
        let write = |m: &mut areev_store::Areev, old: &Hash, object: &str| -> Result<()> {
            let mut fact = areev_core::types::Fact::new(
                principal,
                areev_core::authz::REL_PERMITS,
                object,
            )
            .namespace(areev_core::authz::AUTHZ_NS)
            .created_at(now_epoch_ms());
            fact.common.context = Some(serde_json::json!({
                "grantor": self.session_principal(),
                "because": because,
                "set_grants": true,
            }));
            m.supersede(old, &mut fact)?;
            Ok(())
        };
        for (old, _) in &stale {
            match unmatched_want.pop() {
                // Supersede IN PLACE where a head can become a desired grant:
                // the principal never passes through a moment with fewer
                // rights than either the old or the new set gives.
                Some(object) => {
                    write(&mut m, old, object)?;
                    change.superseded += 1;
                }
                None => {
                    write(&mut m, old, "revoked")?;
                    change.retired += 1;
                }
            }
        }
        for object in unmatched_want {
            let mut fact = areev_core::types::Fact::new(
                principal,
                areev_core::authz::REL_PERMITS,
                object,
            )
            .namespace(areev_core::authz::AUTHZ_NS)
            .created_at(now_epoch_ms());
            fact.common.context = Some(serde_json::json!({
                "grantor": self.session_principal(),
                "because": because,
                "set_grants": true,
            }));
            m.add(&fact)?;
            change.added += 1;
        }
        Ok(change)
    }

    /// A value that changes whenever this memory's authorization policy does
    /// (#309) — a single indexed read a host caching bound sessions can make
    /// per request instead of re-resolving grants or evicting on a timer.
    ///
    /// A CHANGE DETECTOR: compare for equality, never for ordering.
    pub fn authz_epoch(&self) -> Result<i64> {
        self.store.lock().unwrap().authz_epoch()
    }

    /// A per-call, principal-scoped session over this facade — the
    /// rebind-race-free write path (governed-agents §6.8).
    ///
    /// [`Self::bind_principal`] swaps ONE process-wide slot and is documented
    /// as safe only for hosts that serialize requests. A runtime attributing
    /// journal writes to a run's triggering principal — or a second approver
    /// answering a HITL ask while the run's own writes continue — needs
    /// concurrent per-principal rights, which a shared slot cannot express
    /// without racing. A session resolves its fail-closed [`AuthzSet`] ONCE
    /// here (grants written later need a new session, same rule as rebind)
    /// and never touches the shared slot; any number of sessions run
    /// concurrently over the same store handle.
    ///
    /// Writes through a session are **attributed**: grains that do not set
    /// `author_did` get the session principal stamped in, so "who wrote this"
    /// is answerable from the grain itself, not from ambient state.
    pub fn principal_session(
        &self,
        principal: &str,
    ) -> Result<PrincipalSession<'_>> {
        Ok(self.session_with(self.resolve_rights(principal)?))
    }

    /// Resolve a principal's fail-closed rights from the file's grants (#324).
    ///
    /// The store read [`Self::principal_session`] does, split out so a host
    /// serving many principals can do it ONCE per principal and reuse the
    /// result. Pair it with [`Self::authz_epoch`] (#309): cache the set keyed
    /// by `(principal, epoch)`, and re-resolve when the epoch moves. Without
    /// this, every request paid a grant read under the store mutex, and the
    /// only cacheable thing was the epoch itself — a value that tells a host
    /// its cache is stale but gives it nothing to cache.
    ///
    /// The returned set is a SNAPSHOT: a `set_grants` after this call does not
    /// change it, which is the same rule `principal_session` has always had.
    pub fn resolve_rights(&self, principal: &str) -> Result<areev_core::authz::AuthzSet> {
        let grants = {
            let mut guard = self.store.lock().unwrap();
            guard.authz_grants(principal)?
        };
        Ok(areev_core::authz::AuthzSet::restricted(principal, grants))
    }

    /// Build a session over rights already resolved (#324) — free, no store
    /// read. The borrow is what keeps it safe to hold: a session cannot
    /// outlive the facade it authorizes against.
    ///
    /// Takes a RESTRICTED set only in practice: `resolve_rights` never returns
    /// an owner set, and handing this an [`AuthzSet::owner`] would silently
    /// promote a caller to the implicit superuser. It is not refused here
    /// because an owner-equivalent host legitimately builds one, but a host
    /// that accepts a principal name from a request must go through
    /// `resolve_rights`, never construct the set itself.
    pub fn session_with(&self, rights: areev_core::authz::AuthzSet) -> PrincipalSession<'_> {
        PrincipalSession {
            facade: self,
            authz: rights,
            namespace: None,
        }
    }

    /// The namespace a namespace-DEFAULTING read resolves to.
    ///
    /// The active session's, when one is bound on this thread; otherwise the
    /// facade's own. `RELATED`, `ENTITY … AT` and `NOVELTY` read exactly one
    /// namespace and take no operand for it, so a multi-principal host had
    /// no way to point them at the namespace the caller works in (#302).
    fn default_ns(&self) -> Option<String> {
        active_session_namespace(self).or_else(|| self.namespace.clone())
    }

    /// The rights ONE call is authorized against.
    ///
    /// The facade's shared slot, unless a [`PrincipalSession`] is active on
    /// this thread for this facade — then the session's own fail-closed set
    /// (#302).
    ///
    /// A THREAD-LOCAL override rather than a second slot, and that is the
    /// whole point. [`Self::bind_principal`] swaps one process-wide value,
    /// which is why its own documentation says it is safe only for hosts
    /// that serialize requests: two concurrent requests race, and the loser
    /// executes under the winner's rights. A thread-local cannot race by
    /// construction — CAL execution is synchronous on the calling thread (it
    /// serializes on `Mutex<Areev>` anyway), so a session's rights are
    /// visible exactly for the duration of its own call and to nobody else.
    ///
    /// Before this, `PrincipalSession` carried per-principal rights for
    /// WRITES only: every gated read went to the shared slot, so a host
    /// serving several signed-in people needed a facade per principal — and
    /// on the embedded backend, where a second handle is refused, that was
    /// not possible at all.
    fn rights(&self) -> areev_core::authz::AuthzSet {
        if let Some(set) = active_session_rights(self) {
            return set;
        }
        self.authz.read().expect("authz lock poisoned").clone()
    }

    /// The enforcement read used by every gated method.
    fn check_verb(&self, verb: Verb, ns: &str) -> Result<()> {
        self.rights().check(verb, ns)
    }

    /// This session's EFFECTIVE rights: an active [`PrincipalSession`]'s when
    /// one is on this thread, else the facade's bound set.
    ///
    /// [`Self::authz`] returns the bound set only, so a host that gates on it
    /// while a session is active enforces the wrong principal. Host surfaces
    /// that need to check several namespaces in one call — a `RELATED` walk
    /// over a namespace list, a change feed filtered to what the caller may
    /// read — should ask this, not `authz()`.
    pub fn effective_authz(&self) -> areev_core::authz::AuthzSet {
        self.rights()
    }

    fn session_is_owner(&self) -> bool {
        self.rights().is_owner()
    }

    fn session_principal(&self) -> String {
        self.rights().principal().to_string()
    }

    /// Write the Tier-2 audit Observation (CAL 1.3 §8.14): every destructive
    /// execution records the session principal, the verb, the target, the
    /// reason, and how many grains it removed. It is a grain — it syncs with
    /// the file and is RECALLable — and it rides the reserved authz
    /// namespace next to the grants. Audit records are *occurrences*, so
    /// each carries a unique frame id: two identical erasures must stay two
    /// records (the #66 lesson).
    /// Record that a destruction went ahead over a legal hold (#278).
    ///
    /// The Tier-2 record names the hold — its namespace, who placed it, and
    /// why — so the audit says WHAT was overridden, not merely that
    /// something was.
    fn audit_hold_override(
        &self,
        verb: &str,
        target: &str,
        because: &str,
        count: usize,
        hold: &areev_store::HoldRecord,
    ) -> Result<()> {
        let mut obs = areev_core::authz::audit_observation(
            &self.session_principal(),
            verb,
            target,
            Some(because),
            count,
            now_epoch_ms(),
        );
        if let Some(serde_json::Value::Object(map)) = obs.common.context.as_mut() {
            map.insert(
                "hold_overridden".into(),
                serde_json::json!({
                    "ns": hold.ns,
                    "placed_by": hold.placed_by,
                    "because": hold.because,
                }),
            );
        }
        self.store.lock().unwrap().append_audit(&mut obs).map(|_| ())
    }

    /// A REFUSED destruction is recorded too (#278).
    ///
    /// The record a controller needs to answer an Art. 17 request on an
    /// Art. 17(3) ground: the request was made, and here is the obligation
    /// that deferred it. `grains_erased: 0` says nothing was destroyed.
    fn audit_hold_refusal(&self, verb: &str, target: &str, detail: &str) {
        let mut obs = areev_core::authz::audit_observation(
            &self.session_principal(),
            &format!("{verb}.refused"),
            target,
            Some(detail),
            0,
            now_epoch_ms(),
        );
        let _ = self.store.lock().unwrap().append_audit(&mut obs);
    }

    fn audit_tier2(
        &self,
        verb: &str,
        target: &str,
        because: Option<&str>,
        count: usize,
        stale_exports: &[areev_store::CorpusExportRegistry],
    ) -> Result<()> {
        // One builder for every surface (areev_core::authz) so the CLI's
        // host-level erasures and CAL's produce identical audit shapes.
        let mut obs = areev_core::authz::audit_observation(
            &self.session_principal(),
            verb,
            target,
            because,
            count,
            now_epoch_ms(),
        );
        if !stale_exports.is_empty() {
            let mut context = obs
                .common
                .context
                .take()
                .and_then(|value| value.as_object().cloned())
                .unwrap_or_default();
            context.insert(
                "stale_corpora".into(),
                serde_json::to_value(stale_exports).unwrap_or_else(|_| serde_json::json!([])),
            );
            // One provenance hop further (parity with the CLI's erasure
            // notice): adapters trained on a stale corpus are stale too —
            // `areev tune` writes `derived_from` = the export manifest.
            let mut stale_adapters = Vec::new();
            {
                let mut store = self.store.lock().unwrap();
                for export in stale_exports {
                    let Ok(h) = areev_core::Hash::from_hex(&export.manifest_hash) else {
                        continue;
                    };
                    for g in store.grains_derived_from(&h).unwrap_or_default() {
                        if g.get_str("relation") != Some("mg:adapter") {
                            continue;
                        }
                        stale_adapters.push(serde_json::json!({
                            "subject": g.get_str("subject"),
                            "grain_hash": g.hash.to_hex(),
                            "export_id": export.export_id,
                        }));
                    }
                }
            }
            if !stale_adapters.is_empty() {
                context.insert("stale_adapters".into(), serde_json::json!(stale_adapters));
            }
            obs.common.context = Some(serde_json::Value::Object(context));
        }
        // One chain per memory (#280), shared with the CLI writers.
        self.store.lock().unwrap().append_audit(&mut obs).map(|_| ())
    }

    /// The namespace a JSON-built write lands in: the explicit `namespace`
    /// field, else the session default, else `"shared"` (the store default).
    /// This is the resource every write-verb check runs against.
    fn write_ns<'a>(&'a self, fields: &'a serde_json::Map<String, serde_json::Value>) -> &'a str {
        fields
            .get("namespace")
            .and_then(|v| v.as_str())
            .or(self.namespace.as_deref())
            .unwrap_or("shared")
    }

    /// Mount a read-only memory (an org/category replica) under an alias.
    /// CAL reaches it with `WHERE namespace = "<alias>.<inner-ns>"` — which
    /// is what makes single-statement ASSEMBLE span user + org files.
    pub fn mount(&mut self, alias: &str, store: Areev) {
        self.mounts.insert(alias.to_string(), Mutex::new(store));
    }

    pub fn into_inner(self) -> Areev {
        self.store.into_inner().unwrap_or_else(|p| p.into_inner())
    }

    /// Run a closure against the underlying store — the escape hatch for
    /// implementation-level operations CAL structurally excludes (forget,
    /// bundle, stats). Host-surface only; never reachable from CAL text.
    /// The session's capability namespace, if scoped.
    pub fn session_namespace(&self) -> Option<&str> {
        self.namespace.as_deref()
    }

    /// Recall over-fetch multiplier: `recall_hybrid` is asked for
    /// `limit × RECALL_OVERFETCH` candidates before post-filtering.
    pub const RECALL_OVERFETCH: usize = 4;

    /// How many first-pass results seed `WITH multi_hop`. The top few name the
    /// entities worth following; taking every result would fan out over the
    /// long tail of a weak match.
    pub const MULTI_HOP_SEED: usize = 8;

    /// Candidates pulled per entity per hop. Small on purpose — a hop is a
    /// widening heuristic, and the candidate pool is capped anyway.
    pub const MULTI_HOP_FANOUT: usize = 8;

    /// Aliases of read-only mounted stores (ASSEMBLE cross-file sources).
    pub fn mount_aliases(&self) -> Vec<String> {
        let mut a: Vec<String> = self.mounts.keys().cloned().collect();
        a.sort();
        a
    }

    /// Raw, **unauthorized** store access.
    ///
    /// This applies no `AuthzSet` check: the closure sees the whole memory
    /// regardless of what the session's principal was granted. That is
    /// correct for a host acting under its own authority (the runtime
    /// journalling its own run, a trigger evaluating its own cadence) and
    /// WRONG for anything reachable by a caller whose rights are narrower
    /// than the file's — which is every method a principal-bound binding or
    /// MCP session exposes.
    ///
    /// Use [`Self::store_read`] / [`Self::store_write`] / [`Self::store_as`]
    /// on any surface a bound principal can reach. GHSA-rmrx-26f6-f97w was
    /// exactly this: typed reads on the Python/Node bindings and two MCP
    /// tools reached the store through here, so `principal=` restricted CAL
    /// and nothing else.
    pub fn with_store<R>(&self, f: impl FnOnce(&mut Areev) -> R) -> R {
        let mut guard = self.store.lock().unwrap();
        f(&mut guard)
    }

    /// Store access gated on `verb` over `ns`, checked against the session's
    /// EFFECTIVE rights — an active [`PrincipalSession`] when there is one,
    /// else the facade's bound `AuthzSet`. The owner session passes
    /// everything, so gating a call site changes nothing for an unbound
    /// handle and fails closed for a bound one.
    ///
    /// `ns` follows the convention the gated CAL methods already use:
    /// the namespace read or written, or `"*"` for a memory-wide operation.
    pub fn store_as<R>(
        &self,
        verb: Verb,
        ns: &str,
        f: impl FnOnce(&mut Areev) -> R,
    ) -> Result<R> {
        self.check_verb(verb, ns)?;
        Ok(self.with_store(f))
    }

    /// [`Self::store_as`] for the usual case — a closure that is itself a
    /// store call returning `Result` — flattening the two so a gated call
    /// site reads exactly like the ungated one it replaces.
    pub fn store_checked<T>(
        &self,
        verb: Verb,
        ns: &str,
        f: impl FnOnce(&mut Areev) -> Result<T>,
    ) -> Result<T> {
        self.store_as(verb, ns, f)?
    }

    /// [`Self::store_checked`] with `Verb::Read`.
    pub fn store_read<T>(
        &self,
        ns: &str,
        f: impl FnOnce(&mut Areev) -> Result<T>,
    ) -> Result<T> {
        self.store_checked(Verb::Read, ns, f)
    }

    /// [`Self::store_checked`] with `Verb::Write`.
    pub fn store_write<T>(
        &self,
        ns: &str,
        f: impl FnOnce(&mut Areev) -> Result<T>,
    ) -> Result<T> {
        self.store_checked(Verb::Write, ns, f)
    }

    /// Ingress boundary for the structured write path (proposal §4.2):
    /// identity fields whole-value as `person`, other string leaves through
    /// detection. `Ok(None)` = no ingress policy covers the write namespace
    /// (the overwhelmingly common case — one store probe). Runtime journal
    /// writes (`record_tool_call`, `record_run_manifest`) are deliberately
    /// exempt, the write-side mirror of the `run_grains` egress exemption.
    fn ingress_fields(
        &self,
        fields: &serde_json::Map<String, serde_json::Value>,
    ) -> Result<Option<serde_json::Map<String, serde_json::Value>>> {
        const IDENTITY: &[&str] = &["subject", "user_id", "observer"];
        const SKIP: &[&str] = &[
            "namespace", "session_id", "run_id", "node_id", "parent", "relation",
            "derived_from", "supersedes", "author_did",
        ];
        let ns = self.write_ns(fields).to_string();
        let mut guard = self.store.lock().unwrap();
        if !guard.ingress_active(&ns)? {
            return Ok(None);
        }
        let mut out = fields.clone();
        for (k, v) in out.iter_mut() {
            if SKIP.contains(&k.as_str()) {
                continue;
            }
            if IDENTITY.contains(&k.as_str()) {
                if let serde_json::Value::String(sv) = v {
                    if let Some(t) = guard.ingress_transform_identity(&ns, sv)? {
                        *sv = t;
                    }
                }
                continue;
            }
            ingress_value_tree(&mut guard, &ns, v)?;
        }
        Ok(Some(out))
    }

    /// Reverse-lookup placeholder tokens (proposal D9, REQ-ANON-3): the
    /// privileged, audited act. Requires the `admin` verb on `ns`; every
    /// execution writes a Tier-2 Observation in `agent:authz` carrying the
    /// revealed values' *fingerprints*, never the identities. Returns JSON
    /// `{"revealed": {token: value | null}}`.
    pub fn reveal_tokens(&self, ns: &str, tokens: &[String]) -> Result<String> {
        self.check_verb(Verb::Admin, ns)?;
        let mut revealed = serde_json::Map::new();
        let mut fingerprints: Vec<String> = Vec::new();
        self.with_store(|m| -> Result<()> {
            for token in tokens {
                match m.anon_reveal(ns, token)? {
                    Some(value) => {
                        fingerprints.push(areev_core::authz::subject_fingerprint(&value));
                        revealed.insert(token.clone(), serde_json::json!(value));
                    }
                    None => {
                        revealed.insert(token.clone(), serde_json::Value::Null);
                    }
                }
            }
            Ok(())
        })?;
        // Tier-2 audit: the reveal IS the record — fingerprints only, so the
        // immutable, replicating audit grain cannot re-identify by itself.
        let mut obs = areev_core::authz::audit_observation(
            &self.session_principal(),
            "reveal",
            ns,
            None,
            fingerprints.len(),
            now_ms(),
        );
        if !fingerprints.is_empty() {
            let ctx = obs.common.context.get_or_insert_with(|| serde_json::json!({}));
            if let Some(o) = ctx.as_object_mut() {
                o.insert("revealed_fingerprints".into(), serde_json::json!(fingerprints));
            }
        }
        // The reveal is a Tier-2 record like an erasure, so it rides the
        // same chain (#280).
        self.with_store(|m| m.append_audit(&mut obs))?;
        serde_json::to_string(&serde_json::json!({"revealed": revealed}))
            .map_err(|e| AreevError::Internal(e.to_string()))
    }

    // ---- text anonymization (docs/anonymization-proposal.md, P0) ----------
    //
    // Text in, JSON out — no store WRITES, but reads the store's
    // known-identity table for the facade's default namespace (issue #32):
    // a subject already interned by an intake step (grain egress) is
    // detectable in free text too, the same propagation table, one
    // matcher. `policy_json` is still supplied explicitly by the caller
    // (P0's contract; the declared `anon:<ns>` policy row is not
    // auto-loaded here) and may carry its own `known` entries for
    // identities the caller holds but never interned as a grain subject.

    /// The facade's default namespace's accumulated known-identity list —
    /// same table `egress_grains` builds for grain reads (issue #32). Empty
    /// when the facade has no default namespace (bare `AreevFacade::new`).
    fn known_identities(&self) -> Vec<String> {
        match &self.namespace {
            Some(ns) => self.with_store(|m| m.anon_known_identities(ns)),
            None => Vec::new(),
        }
    }

    /// Run the Tier-0 detector chain over `text`. Returns JSON
    /// `{"text": <nfc text>, "detections": [{start, end, category,
    /// confidence, detector}]}` — offsets are UTF-8 bytes into the returned
    /// (NFC-normalized) text.
    pub fn scan_text(&self, text: &str, policy_json: Option<&str>) -> Result<String> {
        let policy = match policy_json {
            Some(j) => areev_core::anon::AnonPolicy::from_json(j)?,
            None => areev_core::anon::AnonPolicy::default(),
        };
        let out = areev_core::anon::scan(text, &policy, &self.known_identities())?;
        serde_json::to_string(&out).map_err(|e| AreevError::Internal(e.to_string()))
    }

    /// Pseudonymize `text` under the policy (default policy when `None`).
    /// Returns JSON `{"text", "mapping", "mapping_id", "replaced"}`. Only
    /// `pseudonym` spans enter the mapping — `mask`/`redact` are one-way.
    /// `key_hex` keys the `mapping_id` derivation (D11); without it the id
    /// must not be shipped anywhere the mapping doesn't also travel.
    pub fn anonymize_text(
        &self,
        text: &str,
        policy_json: Option<&str>,
        key_hex: Option<&str>,
    ) -> Result<String> {
        let policy = match policy_json {
            Some(j) => areev_core::anon::AnonPolicy::from_json(j)?,
            None => areev_core::anon::AnonPolicy::default(),
        };
        let key = match key_hex {
            Some(h) => Some(hex::decode(h).map_err(|e| {
                AreevError::Validation(format!("anonymize key must be hex: {e}"))
            })?),
            None => None,
        };
        let out =
            areev_core::anon::anonymize(text, &policy, &self.known_identities(), key.as_deref())?;
        serde_json::to_string(&out).map_err(|e| AreevError::Internal(e.to_string()))
    }

    /// Replace placeholder tokens in `text` with their originals from
    /// `mapping_json` (a JSON object of placeholder → value). Returns JSON
    /// `{"text", "replaced", "unmatched"}`; unmatched tokens are left intact
    /// and reported, never guessed.
    pub fn rehydrate_text(&self, text: &str, mapping_json: &str) -> Result<String> {
        let mapping = areev_core::anon::mapping_from_json(mapping_json)?;
        let out = areev_core::anon::rehydrate(text, &mapping)?;
        serde_json::to_string(&out).map_err(|e| AreevError::Internal(e.to_string()))
    }

    /// Preflight the governed-corpus registry write. Exporting reads the
    /// selected namespaces, but recording its immutable lineage additionally
    /// requires `write ON agent:harness`.
    pub fn authorize_corpus_export(&self) -> Result<()> {
        self.check_verb(Verb::Write, areev_core::authz::HARNESS_NS)
    }

    #[allow(clippy::too_many_arguments)]
    pub fn record_corpus_export(
        &self,
        selector: &str,
        destination: &str,
        recipient: Option<&str>,
        exported_at_ms: i64,
        subject_fingerprints: &[String],
        source_hashes: &[String],
    ) -> Result<Hash> {
        self.authorize_corpus_export()?;
        self.with_store(|store| {
            store.record_corpus_export(
                selector,
                destination,
                recipient,
                exported_at_ms,
                subject_fingerprints,
                source_hashes,
            )
        })
    }

    /// Value-level idempotent add (see [`Areev::add_if_novel`]). Returns the
    /// grain hash and whether a new grain was written (`false` = the value was
    /// already the current head). Bindings expose this as an `idempotent` flag.
    pub fn cal_add_if_novel(
        &self,
        grain_type: &str,
        fields: &serde_json::Map<String, serde_json::Value>,
    ) -> Result<(Hash, bool)> {
        self.check_verb(Verb::Write, self.write_ns(fields))?;
        let ingressed = self.ingress_fields(fields)?;
        let fields = ingressed.as_ref().unwrap_or(fields);
        let mut m = self.store.lock().unwrap();
        build_grain_from_json(grain_type, fields, AddIfNovelSink { m: &mut m })
    }

    /// Record one tool execution. The single implementation behind
    /// `record_tool_call` on every binding, so Python and Node cannot drift.
    ///
    /// Each call is stamped with an identity, which is what makes this record an
    /// *occurrence* rather than a value. Without one they collapsed: grains are
    /// content-addressed over the whole blob and `created_at` has millisecond
    /// resolution, so byte-identical calls recorded inside one millisecond hash
    /// to a single address, and since 1.1.1 a duplicate add is a silent no-op.
    /// An agent retrying a failing tool in a tight loop is precisely that
    /// workload — and "how many times did this fail" is the entire input to
    /// `loop.tool_failure`, so the flagship analyzer lost its signal exactly
    /// where it is meant to fire. The documented five-failure example stored one
    /// grain and produced no recommendation at all (#66).
    ///
    /// `call_id` is the host's invocation id (an LLM `tool_call_id`), stored as
    /// the grain's `tool_call_id` and queryable as such — the correlation key
    /// back to the provider transcript. Absent one, `occurrence_id` mints a
    /// synthetic id.
    ///
    /// It is not a de-duplication key: replaying the same `call_id` later writes
    /// a second grain, since `created_at` is part of the content address too.
    /// Recording is append-only, and a host replaying a tool log owns not
    /// replaying it twice.
    // This signature is mirrored by the CLI, MCP, Python, and Node surfaces;
    // grouping fields would make those scalar-in APIs diverge.
    //
    // The Wave-0 extension (governed-agents proposal §8): the async lifecycle
    // vocabulary (`status`/`failure_cause`/`executor_kind`/`correlation_id`),
    // the run↔plan join (`workflow_hash` + `node_id` → an `mg:step_action`
    // link), and the run-correlation key (`run_id`) were typed Tool fields
    // unreachable from every non-Rust surface — the execution-record READ
    // APIs existed everywhere while only Rust code could produce the records.
    // All values route through `build_grain_from_json`, so enum strings and
    // link shapes get the same strict validation as `add()`.
    #[allow(clippy::too_many_arguments)]
    pub fn record_tool_call(
        &self,
        ns: &str,
        tool_name: &str,
        input: Option<&str>,
        result: &str,
        is_error: bool,
        thread: Option<&str>,
        call_id: Option<&str>,
        run_id: Option<&str>,
        workflow_hash: Option<&str>,
        node_id: Option<&str>,
        status: Option<&str>,
        failure_cause: Option<&str>,
        executor_kind: Option<&str>,
        correlation_id: Option<&str>,
    ) -> Result<Hash> {
        let fields = build_tool_call_fields(
            ns,
            tool_name,
            input,
            result,
            is_error,
            thread,
            call_id,
            run_id,
            workflow_hash,
            node_id,
            status,
            failure_cause,
            executor_kind,
            correlation_id,
        )?;
        self.cal_add("tool", &fields)
    }

    /// Record the immutable configuration for a run and link the run id to it.
    /// The State is timestamped at epoch zero deliberately: it is a value-level
    /// configuration artifact, so identical JSON must have one content address
    /// even when observed by different runs at different wall-clock times.
    pub fn record_run_manifest(&self, run_id: &str, config_json: &str) -> Result<(Hash, Hash)> {
        self.check_verb(Verb::Write, areev_core::authz::HARNESS_NS)?;
        // Same contract as every other run_id write surface (§2 item 3).
        areev_core::types::validate_run_id(run_id)?;
        let config: serde_json::Value = serde_json::from_str(config_json).map_err(|e| {
            AreevError::Validation(format!("run manifest config must be valid JSON: {e}"))
        })?;
        if !config.is_object() {
            return Err(AreevError::Validation(
                "run manifest config must be a JSON object".into(),
            ));
        }

        let state = State::new(config)
            .namespace(areev_core::authz::HARNESS_NS)
            .created_at(0);
        let (_, config_hash) = serialize_grain(&state)?;
        let link = Fact::new(
            &format!("run:{run_id}"),
            "mg:harness",
            &config_hash.to_hex(),
        )
        .namespace(areev_core::authz::HARNESS_NS);
        let mut store = self.store.lock().unwrap();
        let hashes = store.add_batch(&[&state, &link])?;
        Ok((hashes[0], hashes[1]))
    }

    /// Register a host-trained adapter (the tuning seam's `areev tune`).
    /// Validates the trainer's reply tuple, embeds the Rule E1 evalset pin
    /// and the corpus-manifest lineage into the object JSON (the single-read
    /// contract the `adapter_intake` analyzer depends on), and writes ONE
    /// `mg:adapter` Fact in `agent:harness` whose `derived_from` names the
    /// corpus export manifest — so `areev provenance <manifest>` and CAL
    /// `DERIVED FROM` walk from the corpus to every adapter trained on it.
    /// A hard validation error writes nothing.
    ///
    /// Unlike `record_run_manifest`'s epoch-zero value collapse, an adapter
    /// registration is an *event*: `recorded_at_ms` is the real clock.
    pub fn record_adapter(
        &self,
        reply_json: &str,
        manifest_hash: &str,
        evalset_hash: &str,
        recorded_at_ms: i64,
    ) -> Result<Hash> {
        self.check_verb(Verb::Write, areev_core::authz::HARNESS_NS)?;
        let mut reply: serde_json::Map<String, serde_json::Value> =
            serde_json::from_str(reply_json).map_err(|e| {
                AreevError::Validation(format!("trainer reply must be a JSON object: {e}"))
            })?;
        let need_str = |v: Option<&serde_json::Value>, what: &str| -> Result<String> {
            v.and_then(|x| x.as_str())
                .map(str::trim)
                .filter(|x| !x.is_empty())
                .map(str::to_string)
                .ok_or_else(|| {
                    AreevError::Validation(format!(
                        "trainer reply is missing required field {what}"
                    ))
                })
        };
        let adapter = reply
            .get("adapter")
            .and_then(|a| a.as_object())
            .cloned()
            .ok_or_else(|| {
                AreevError::Validation(
                    "trainer reply is missing required object \"adapter\"".into(),
                )
            })?;
        need_str(adapter.get("uri"), "adapter.uri")?;
        need_str(adapter.get("sha256"), "adapter.sha256")?;
        need_str(reply.get("base_model"), "base_model")?;
        // The subject becomes the promotion target `model:<serves_as>` —
        // TargetRef's only opaque constraint is non-empty, checked here so a
        // malformed name fails at tune time, not at draft time.
        let serves_as = need_str(reply.get("serves_as"), "serves_as")?;
        let manifest = Hash::from_hex(manifest_hash).map_err(|_| {
            AreevError::Validation(format!(
                "corpus manifest {manifest_hash:?} is not a grain hash"
            ))
        })?;
        {
            let mut store = self.store.lock().unwrap();
            let grain = store.get(&manifest).map_err(|_| {
                AreevError::Validation(format!(
                    "corpus manifest {manifest_hash} not found in this memory"
                ))
            })?;
            // Lineage anchors to a REAL export manifest, not any grain a
            // caller names: the corpus-export Observation is the only shape
            // the erasure walk and the registry reader recognize.
            if grain.get_str("observer_type") != Some("corpus_export") {
                return Err(AreevError::Validation(format!(
                    "{manifest_hash} is not a corpus export manifest — use the \
                     hash from `areev corpus` / record_corpus_export"
                )));
            }
        }
        if evalset_hash.trim().is_empty() {
            return Err(AreevError::Validation(
                "an adapter registration requires the evalset pin (Rule E1)".into(),
            ));
        }
        reply.insert("evalset_hash".into(), serde_json::json!(evalset_hash));
        reply.insert("corpus_manifest".into(), serde_json::json!(manifest.to_hex()));
        let object = serde_json::Value::Object(reply).to_string();

        let mut fact = Fact::new(&format!("model:{serves_as}"), "mg:adapter", &object)
            .namespace(areev_core::authz::HARNESS_NS)
            .created_at(recorded_at_ms);
        fact.common.derived_from = Some(manifest.to_hex());
        fact.common
            .extra_fields
            .insert("evalset_hash".into(), serde_json::json!(evalset_hash));
        let mut store = self.store.lock().unwrap();
        store.add(&fact)
    }

    /// Add many grains in one store transaction. Each entry is the same
    /// `(grain_type, fields)` pair [`cal_add`](CalStoreFacade::cal_add) takes,
    /// validated identically — the batching is in the write, not the parsing,
    /// so a malformed entry fails the whole call and writes nothing.
    ///
    /// Worth roughly 1.6x over the same grains added one at a time (244 ->
    /// 148 us/grain, measured at 2k grains), saturating around a batch of 10.
    /// Note this only helps with the BM25 text index **off**: with it on, the
    /// per-row index cost dominates so completely that batch size makes no
    /// difference at all (~17ms/grain at every size) — see
    /// `defer_text_index` and tursodatabase/turso#8170.
    pub fn cal_add_batch(
        &self,
        entries: &[(String, serde_json::Map<String, serde_json::Value>)],
    ) -> Result<Vec<Hash>> {
        // Every entry's namespace is checked before anything is written —
        // a batch is all-or-nothing for authorization like it is for
        // validation.
        for (_, fields) in entries {
            self.check_verb(Verb::Write, self.write_ns(fields))?;
        }
        // Build every grain first so a bad entry is rejected before anything
        // is written, then hand the whole set to the store as one batch.
        let mut built: Vec<Box<dyn areev_store::AddableDyn>> = Vec::with_capacity(entries.len());
        for (grain_type, fields) in entries {
            let ingressed = self.ingress_fields(fields)?;
            let fields = ingressed.as_ref().unwrap_or(fields);
            build_grain_from_json(grain_type, fields, CollectSink { out: &mut built })?;
        }
        let refs: Vec<&dyn areev_store::AddableDyn> = built.iter().map(|b| b.as_ref()).collect();
        let mut m = self.store.lock().unwrap();
        m.add_batch(&refs)
    }

    fn hit(grain: DeserializedGrain) -> SearchHit {
        let hash = grain.hash;
        SearchHit {
            grain,
            score: 1.0,
            hash,
            score_breakdown: None,
            explanation: None,
            scope_depth: None,
            source_namespace: None,
            relative_time: None,
            conflict_status: None,
            supersession_status: None,
            superseded_by_hash: None,
            recall_source: None,
        }
    }
}

/// Sink that keeps the built grain instead of writing it, so a whole batch
/// can be validated up front and then written in one transaction.
struct CollectSink<'a> {
    out: &'a mut Vec<Box<dyn areev_store::AddableDyn>>,
}
impl GrainSink for CollectSink<'_> {
    type Out = ();
    fn consume<G: Grain + Clone + 'static>(self, grain: &G) -> Result<()> {
        self.out.push(Box::new(grain.clone()));
        Ok(())
    }
}

/// The one field-builder behind `record_tool_call` on the facade AND on
/// [`PrincipalSession`] — two entry points, one validation path, so the
/// attributed and unattributed surfaces cannot drift.
#[allow(clippy::too_many_arguments)]
fn build_tool_call_fields(
    ns: &str,
    tool_name: &str,
    input: Option<&str>,
    result: &str,
    is_error: bool,
    thread: Option<&str>,
    call_id: Option<&str>,
    run_id: Option<&str>,
    workflow_hash: Option<&str>,
    node_id: Option<&str>,
    status: Option<&str>,
    failure_cause: Option<&str>,
    executor_kind: Option<&str>,
    correlation_id: Option<&str>,
) -> Result<serde_json::Map<String, serde_json::Value>> {
    let mut fields = serde_json::Map::new();
    fields.insert("tool_name".into(), serde_json::json!(tool_name));
    if let Some(input) = input {
        let input = serde_json::from_str(input).map_err(|e| {
            AreevError::Validation(format!("record_tool_call input must be valid JSON: {e}"))
        })?;
        fields.insert("input".into(), input);
    }
    fields.insert("content".into(), serde_json::json!(result));
    fields.insert("is_error".into(), serde_json::json!(is_error));
    fields.insert("namespace".into(), serde_json::json!(ns));
    if let Some(t) = thread {
        fields.insert("session_id".into(), serde_json::json!(t));
    }
    fields.insert(
        "tool_call_id".into(),
        serde_json::json!(match call_id {
            Some(id) => id.to_string(),
            None => occurrence_id(),
        }),
    );
    if let Some(r) = run_id {
        fields.insert("run_id".into(), serde_json::json!(r));
    }
    // The step_action link is a pair: a hash with no node names no execution
    // record, a node with no plan links nothing. Both or neither — half a
    // join is refused, not guessed at.
    match (workflow_hash, node_id) {
        (Some(wf), Some(node)) => {
            fields.insert(
                "related_to".into(),
                serde_json::json!([{
                    "hash": wf,
                    "relation_type": areev_core::types::step_action_relation(node),
                }]),
            );
        }
        (None, None) => {}
        _ => {
            return Err(AreevError::Validation(
                "record_tool_call takes workflow_hash and node_id together \
                 (both or neither) — half an mg:step_action link is meaningless"
                    .into(),
            ))
        }
    }
    if let Some(s) = status {
        fields.insert("status".into(), serde_json::json!(s));
    }
    if let Some(fc) = failure_cause {
        fields.insert("failure_cause".into(), serde_json::json!(fc));
    }
    if let Some(ek) = executor_kind {
        fields.insert("executor_kind".into(), serde_json::json!(ek));
    }
    if let Some(cid) = correlation_id {
        fields.insert("correlation_id".into(), serde_json::json!(cid));
    }
    Ok(fields)
}

/// A principal-scoped, rebind-race-free write session — see
/// [`AreevFacade::principal_session`]. Holds its own fail-closed rights;
/// never reads or writes the facade's shared authz slot. Reads still go
/// through the facade's normal surface — this type exists for **attributed
/// writes** (a run journaling as its triggering principal, a responder
/// answering a HITL ask), where "who" must be per-call, not ambient.
pub struct PrincipalSession<'f> {
    facade: &'f AreevFacade,
    authz: areev_core::authz::AuthzSet,
    /// This session's default namespace (#302). `None` inherits the
    /// facade's, which is fixed at construction — so without this a
    /// multi-principal host could not point `RELATED`, `ENTITY … AT` or
    /// `NOVELTY` at the namespace the CALLER works in.
    namespace: Option<String>,
}

thread_local! {
    /// The session stack active on THIS thread, keyed by facade identity so
    /// one facade's session can never authorize another facade's call.
    ///
    /// A stack rather than a slot because a session's own call may re-enter
    /// the facade; the innermost is the one that applies.
    static ACTIVE_SESSIONS: std::cell::RefCell<
        Vec<(usize, areev_core::authz::AuthzSet, Option<String>)>,
    > = const { std::cell::RefCell::new(Vec::new()) };
}

/// The rights of the innermost session active on this thread for `facade`.
fn active_session_rights(facade: &AreevFacade) -> Option<areev_core::authz::AuthzSet> {
    let key = facade as *const AreevFacade as usize;
    ACTIVE_SESSIONS.with(|s| {
        s.borrow()
            .iter()
            .rev()
            .find(|(k, _, _)| *k == key)
            .map(|(_, a, _)| a.clone())
    })
}

/// The default namespace of the innermost session active on this thread.
fn active_session_namespace(facade: &AreevFacade) -> Option<String> {
    let key = facade as *const AreevFacade as usize;
    ACTIVE_SESSIONS.with(|s| {
        s.borrow()
            .iter()
            .rev()
            .find(|(k, _, _)| *k == key)
            .and_then(|(_, _, ns)| ns.clone())
    })
}

/// Pops the session off the thread's stack on drop, so a panic inside a
/// gated method cannot leave one principal's rights installed for the next
/// call on this thread.
pub struct SessionScope {
    _private: (),
}

impl Drop for SessionScope {
    fn drop(&mut self) {
        ACTIVE_SESSIONS.with(|s| {
            s.borrow_mut().pop();
        });
    }
}

impl PrincipalSession<'_> {
    pub fn principal(&self) -> &str {
        self.authz.principal()
    }

    pub fn authz(&self) -> &areev_core::authz::AuthzSet {
        &self.authz
    }

    /// Point this session's namespace-defaulting reads — `RELATED`,
    /// `ENTITY … AT`, `NOVELTY`, and any `RECALL` with no explicit
    /// namespace — at `ns` (#302).
    pub fn in_namespace(mut self, ns: impl Into<String>) -> Self {
        self.namespace = Some(ns.into());
        self
    }

    /// Install this session's rights for the duration of one call.
    fn enter(&self) -> SessionScope {
        let key = self.facade as *const AreevFacade as usize;
        ACTIVE_SESSIONS.with(|s| {
            s.borrow_mut()
                .push((key, self.authz.clone(), self.namespace.clone()))
        });
        SessionScope { _private: () }
    }

    /// The namespace a write lands in (mirrors the facade's default rule).
    fn write_ns<'a>(&'a self, fields: &'a serde_json::Map<String, serde_json::Value>) -> &'a str {
        fields
            .get("namespace")
            .and_then(|v| v.as_str())
            .or(self.facade.namespace.as_deref())
            .unwrap_or("default")
    }

    /// Add a TYPED grain, checked and attributed exactly as [`Self::cal_add`]
    /// does — `write` on the grain's namespace, `author_did` stamped when the
    /// grain does not set one (#324).
    ///
    /// The session's only write used to be the stringly-typed `cal_add`, so a
    /// Rust host writing an attributed `Fact` built a JSON field map by hand
    /// (`"valid_from"`, `"created_at"`, `"namespace"`) and learned about a
    /// misspelled field at runtime, from a validation error — while the very
    /// same host's unattributed writes went through the grain builders
    /// `Areev::add` takes. This is that path, under a principal.
    ///
    /// Namespace resolution matches `cal_add`: the grain's own, else the
    /// facade's session namespace, else `"default"`.
    ///
    /// **Refuses under an anonymization ingress policy.** `cal_add` routes its
    /// field map through the ingress boundary; a typed grain has no field map
    /// to route, and quietly writing raw identifiers into a namespace whose
    /// policy exists to pseudonymize them would be a privacy regression
    /// introduced by a new API. Use `cal_add` there.
    pub fn add<G: Grain + Clone + 'static>(&self, grain: &G) -> Result<Hash> {
        let ns = grain
            .common()
            .namespace
            .clone()
            .or_else(|| self.facade.namespace.clone())
            .unwrap_or_else(|| "default".to_string());
        self.authz.check(areev_core::authz::Verb::Write, &ns)?;

        let mut m = self.facade.store.lock().unwrap();
        if m.ingress_active(&ns)? {
            return Err(AreevError::Validation(format!(
                "namespace {ns:?} has an anonymization ingress policy, which applies to the \
                 structured write path — use cal_add() so the write passes the ingress \
                 boundary, or clear the policy"
            )));
        }

        let mut g = grain.clone();
        if g.common().namespace.is_none() {
            g.common_mut().namespace = Some(ns);
        }
        if g.common().author_did.is_none() {
            g.common_mut().author_did = Some(self.authz.principal().to_string());
        }
        m.add(&g)
    }

    /// Add a grain, checked against THIS session's rights and attributed to
    /// its principal: grains that do not set `author_did` get it stamped.
    pub fn cal_add(
        &self,
        grain_type: &str,
        fields: &serde_json::Map<String, serde_json::Value>,
    ) -> Result<Hash> {
        self.authz
            .check(areev_core::authz::Verb::Write, self.write_ns(fields))?;
        let mut attributed;
        let fields = if fields.contains_key("author_did") {
            fields
        } else {
            attributed = fields.clone();
            attributed.insert(
                "author_did".into(),
                serde_json::json!(self.authz.principal()),
            );
            &attributed
        };
        let ingressed = self.facade.ingress_fields(fields)?;
        let fields = ingressed.as_ref().unwrap_or(fields);
        let mut m = self.facade.store.lock().unwrap();
        build_grain_from_json(grain_type, fields, AddSink { m: &mut m })
    }

    /// The attributed twin of [`AreevFacade::record_tool_call`] — one
    /// field-builder ([`build_tool_call_fields`]), two authorization roots.
    #[allow(clippy::too_many_arguments)]
    pub fn record_tool_call(
        &self,
        ns: &str,
        tool_name: &str,
        input: Option<&str>,
        result: &str,
        is_error: bool,
        thread: Option<&str>,
        call_id: Option<&str>,
        run_id: Option<&str>,
        workflow_hash: Option<&str>,
        node_id: Option<&str>,
        status: Option<&str>,
        failure_cause: Option<&str>,
        executor_kind: Option<&str>,
        correlation_id: Option<&str>,
    ) -> Result<Hash> {
        let fields = build_tool_call_fields(
            ns,
            tool_name,
            input,
            result,
            is_error,
            thread,
            call_id,
            run_id,
            workflow_hash,
            node_id,
            status,
            failure_cause,
            executor_kind,
            correlation_id,
        )?;
        self.cal_add("tool", &fields)
    }
}

struct AddSink<'a> {
    m: &'a mut Areev,
}
impl GrainSink for AddSink<'_> {
    type Out = Hash;
    fn consume<G: Grain + Clone + 'static>(self, grain: &G) -> Result<Hash> {
        self.m.add(grain)
    }
}

struct AddIfNovelSink<'a> {
    m: &'a mut Areev,
}
impl GrainSink for AddIfNovelSink<'_> {
    type Out = (Hash, bool);
    fn consume<G: Grain + Clone + 'static>(self, grain: &G) -> Result<(Hash, bool)> {
        self.m.add_if_novel(grain)
    }
}

struct SupersedeSink<'a> {
    m: &'a mut Areev,
    old: Hash,
}
impl GrainSink for SupersedeSink<'_> {
    type Out = Hash;
    fn consume<G: Grain + Clone + 'static>(self, grain: &G) -> Result<Hash> {
        let mut g = grain.clone();
        self.m.supersede(&self.old, &mut g)
    }
}

impl AreevFacade {
    /// Note an entry the file carries that this process could not load.
    ///
    /// Skipping is deliberate — one unloadable row must not make the whole
    /// memory unusable — but skipping *silently* is not: a saved query that
    /// vanishes without a word looks like it was never written.
    fn note_meta_warning(&self, kind: &str, name: &str, why: impl std::fmt::Display) {
        self.meta_warnings
            .lock()
            .expect("meta warnings poisoned")
            .push(format!(
                "{kind} \"{name}\" is in the file but could not be loaded ({why}); \
                 it is not available in this process and will be lost if you overwrite it"
            ));
    }

    /// Saved queries and templates the file carries that this process could not
    /// load. Empty when everything in the file is usable here.
    pub fn meta_warnings(&self) -> Vec<String> {
        self.meta_warnings
            .lock()
            .expect("meta warnings poisoned")
            .clone()
    }

    /// Run `f` against the saved-query registry, rehydrating it from the
    /// file's `meta` rows on first use. A row that fails to parse or register
    /// is skipped rather than failing the whole open — one bad entry must not
    /// make the memory unusable — but it is recorded in [`Self::meta_warnings`].
    fn with_queries<R>(&self, f: impl FnOnce(&mut QueryRegistry) -> R) -> R {
        let mut guard = self.queries.lock().expect("query registry poisoned");
        if guard.is_none() {
            let mut reg = QueryRegistry::new();
            match self.with_store(|m| m.meta_scan(QRY_PREFIX)) {
                Ok(rows) => {
                    for (name, json) in rows {
                        match serde_json::from_str::<PersistedQuery>(&json) {
                            Ok(p) => {
                                if let Err(e) = reg.register_full(
                                    &name,
                                    &p.body,
                                    &p.description,
                                    &p.params,
                                    p.last_run_at,
                                    p.updated_at,
                                ) {
                                    self.note_meta_warning("saved query", &name, e);
                                }
                            }
                            Err(e) => self.note_meta_warning("saved query", &name, e),
                        }
                    }
                }
                Err(e) => self.note_meta_warning("saved queries", "*", e),
            }
            *guard = Some(reg);
        }
        f(guard.as_mut().expect("initialised directly above"))
    }

    /// Same for custom templates.
    fn with_templates<R>(&self, f: impl FnOnce(&mut TemplateRegistry) -> R) -> R {
        let mut guard = self.templates.lock().expect("template registry poisoned");
        if guard.is_none() {
            let mut reg = TemplateRegistry::new();
            match self.with_store(|m| m.meta_scan(TPL_PREFIX)) {
                Ok(rows) => {
                    for (name, json) in rows {
                        match serde_json::from_str::<PersistedTemplate>(&json) {
                            Ok(p) => {
                                match reg.register(
                                    &name,
                                    &p.source,
                                    &p.description,
                                    p.parent.as_deref(),
                                ) {
                                    Ok(()) => {
                                        reg.restore_timestamps(&name, p.last_run_at, p.updated_at);
                                        // The FOR clause lives on the statement,
                                        // not in the body, so it only survives a
                                        // reload if it is put back explicitly.
                                        reg.set_grain_types(&name, &p.grain_types);
                                    }
                                    Err(e) => self.note_meta_warning("template", &name, e),
                                }
                            }
                            Err(e) => self.note_meta_warning("template", &name, e),
                        }
                    }
                }
                Err(e) => self.note_meta_warning("templates", "*", e),
            }
            *guard = Some(reg);
        }
        f(guard.as_mut().expect("initialised directly above"))
    }

    fn persist_query(&self, name: &str, p: &PersistedQuery) -> Result<()> {
        let json = serde_json::to_string(p)
            .map_err(|e| AreevError::Validation(format!("saved query \"{name}\": {e}")))?;
        self.with_store(|m| m.meta_put(&format!("{QRY_PREFIX}{name}"), &json))
    }

    fn snapshot_query(&self, name: &str) -> Option<PersistedQuery> {
        self.with_queries(|reg| {
            reg.get(name).map(|e| PersistedQuery {
                body: e.body.clone(),
                description: e.description.clone(),
                params: e.params.clone(),
                last_run_at: e.last_run_at,
                updated_at: e.updated_at,
            })
        })
    }

    fn snapshot_template(&self, name: &str) -> Option<PersistedTemplate> {
        self.with_templates(|reg| {
            reg.get(name).filter(|e| !e.builtin).map(|e| PersistedTemplate {
                source: e.template.source().to_string(),
                description: e.description.clone(),
                parent: e.parent.clone(),
                grain_types: e.grain_types.clone(),
                last_run_at: e.last_run_at,
                updated_at: e.updated_at,
            })
        })
    }
}

impl CalStoreFacade for AreevFacade {
    fn as_any(&self) -> Option<&dyn std::any::Any> {
        Some(self)
    }

    /// Record one assembly-budget sample into the telemetry sidecar (feeds the
    /// `budget_pressure` analyzer). Best-effort: telemetry never fails a query.
    fn note_assembly_budget(&self, overflow: bool) {
        let _ = self.with_store(|m| m.telemetry_note_budget(overflow));
    }

    /// The egress payload flag (proposal §4.1): active when any namespace
    /// declares an egress policy or the host installed the floor. Carries
    /// mapping *ids* only — the mapping itself stays in process (D5).
    fn anon_egress_report(&self) -> Option<serde_json::Value> {
        self.with_store(|m| {
            let declared = m.anon_declared();
            let floor = m.anonymize_egress_floor();
            let egress_ns: Vec<String> = declared
                .iter()
                .filter(|(_, mode)| mode == "egress")
                .map(|(ns, _)| ns.clone())
                .collect();
            if egress_ns.is_empty() && !floor {
                return None;
            }
            let mappings: Vec<serde_json::Value> = m
                .anon_mappings()
                .unwrap_or_default()
                .into_iter()
                .map(|(ns, id, _)| serde_json::json!({"ns": ns, "mapping_id": id}))
                .collect();
            Some(serde_json::json!({
                "namespaces": egress_ns,
                "floor": floor,
                "mappings": mappings,
            }))
        })
    }

    fn note_assembly_manifest(&self, manifest: &AssemblyManifest) {
        // A read-only principal must not acquire a write through telemetry.
        if !self
            .authz()
            .allows(Verb::Write, areev_core::authz::HARNESS_NS)
        {
            return;
        }
        use std::sync::atomic::{AtomicU64, Ordering};
        static SEQ: AtomicU64 = AtomicU64::new(0);
        let now = now_ms();
        let mut obs = Observation::new("areev:assemble", "system")
            .namespace(areev_core::authz::HARNESS_NS)
            .subject(&manifest.rendered_sha256)
            .object("assembly_manifest")
            .created_at(now);
        obs.frame_id = Some(format!(
            "assembly:{now}:{}",
            SEQ.fetch_add(1, Ordering::Relaxed)
        ));
        obs.common.extra_fields.insert(
            "manifest".into(),
            serde_json::to_value(manifest).unwrap_or(serde_json::Value::Null),
        );
        obs.common.related_to = manifest
            .included_hashes
            .iter()
            .map(|hash| RelatedTo {
                hash: hash.clone(),
                relation_type: "mg:assembly_input".into(),
                weight: None,
            })
            .collect();
        // Off the recall measurement and best-effort: a manifest failure does
        // not change the successful ASSEMBLE result.
        let _ = self.with_store(|m| m.add(&obs));
    }

    // ── CAL host metadata: saved queries and custom templates ───────────
    //
    // The registry owns the rules (name shape, per-namespace cap, body size,
    // parameter count), so every write validates in memory first and only
    // then touches the file. If the file write fails the in-memory entry is
    // rolled back, so the registry never runs ahead of what is persisted.

    fn define_query(
        &self,
        name: &str,
        body: &str,
        description: Option<&str>,
        params: &[QueryParam],
    ) -> Result<()> {
        // Saved queries and templates are the host-config surface: admin.
        self.check_verb(Verb::Admin, "*")?;
        let existing = self.snapshot_query(name);
        self.with_queries(|reg| reg.register(name, body, description.unwrap_or(""), params))
            .map_err(AreevError::Validation)?;
        let Some(p) = self.snapshot_query(name) else {
            return Err(AreevError::Internal(format!(
                "saved query \"{name}\" vanished after registration"
            )));
        };
        if let Err(e) = self.persist_query(name, &p) {
            // Roll the registry back to whatever was there before.
            self.with_queries(|reg| {
                let _ = reg.delete(name);
                if let Some(prev) = &existing {
                    let _ = reg.register_full(
                        name,
                        &prev.body,
                        &prev.description,
                        &prev.params,
                        prev.last_run_at,
                        prev.updated_at,
                    );
                }
            });
            return Err(e);
        }
        Ok(())
    }

    fn drop_query(&self, name: &str) -> Result<()> {
        self.check_verb(Verb::Admin, "*")?;
        // Snapshot before deleting: if the file write fails the registry has to
        // go back, or the entry is gone here and still on disk — it would
        // reappear on the next open, which reads as the drop never happening.
        let existing = self.snapshot_query(name);
        self.with_queries(|reg| reg.delete(name))
            .map_err(AreevError::Validation)?;
        if let Err(e) = self.with_store(|m| m.meta_delete(&format!("{QRY_PREFIX}{name}"))) {
            if let Some(prev) = &existing {
                self.with_queries(|reg| {
                    let _ = reg.register_full(
                        name,
                        &prev.body,
                        &prev.description,
                        &prev.params,
                        prev.last_run_at,
                        prev.updated_at,
                    );
                });
            }
            return Err(e);
        }
        Ok(())
    }

    fn list_queries(&self) -> Vec<QueryListEntry> {
        self.with_queries(|reg| reg.list())
    }

    fn get_query(&self, name: &str) -> Option<QueryEntry> {
        self.with_queries(|reg| reg.get(name).cloned())
    }

    fn update_query_last_run(&self, name: &str) -> Result<()> {
        let now = now_secs();
        let updated = self.with_queries(|reg| {
            let e = reg.get(name)?;
            // Built-ins are not persisted, and a re-run within the same second
            // cannot change the one-second-resolution timestamp — so it would
            // be a write transaction that rewrites the row with what it
            // already holds.
            if e.builtin || e.last_run_at == Some(now) {
                return None;
            }
            let (body, description, params, updated_at) = (
                e.body.clone(),
                e.description.clone(),
                e.params.clone(),
                e.updated_at,
            );
            reg.register_full(
                name,
                &body,
                &description,
                &params,
                Some(now),
                updated_at,
            )
            .ok()?;
            Some(PersistedQuery {
                body,
                description,
                params,
                last_run_at: Some(now),
                updated_at,
            })
        });
        match updated {
            Some(p) => self.persist_query(name, &p),
            None => Ok(()),
        }
    }

    fn define_template(
        &self,
        name: &str,
        source: &str,
        description: Option<&str>,
        parent: Option<&str>,
        grain_types: &[String],
    ) -> Result<()> {
        self.check_verb(Verb::Admin, "*")?;
        let existing = self.snapshot_template(name);
        self.with_templates(|reg| {
            reg.register(name, source, description.unwrap_or(""), parent)?;
            // The FOR clause rides the statement, not the body — set it on the
            // entry too, so the in-memory and persisted views agree.
            reg.set_grain_types(name, grain_types);
            Ok(())
        })
        .map_err(|e: CalError| AreevError::Validation(e.to_string()))?;
        let p = PersistedTemplate {
            source: source.to_string(),
            description: description.unwrap_or("").to_string(),
            parent: parent.map(str::to_string),
            grain_types: grain_types.to_vec(),
            last_run_at: None,
            updated_at: Some(now_secs()),
        };
        let json = serde_json::to_string(&p)
            .map_err(|e| AreevError::Validation(format!("template \"{name}\": {e}")))?;
        if let Err(e) = self.with_store(|m| m.meta_put(&format!("{TPL_PREFIX}{name}"), &json)) {
            // Roll the registry back to whatever was there before, so it never
            // runs ahead of what is persisted.
            self.with_templates(|reg| {
                let _ = reg.delete(name);
                if let Some(prev) = &existing {
                    if reg
                        .register(name, &prev.source, &prev.description, prev.parent.as_deref())
                        .is_ok()
                    {
                        reg.restore_timestamps(name, prev.last_run_at, prev.updated_at);
                        reg.set_grain_types(name, &prev.grain_types);
                    }
                }
            });
            return Err(e);
        }
        Ok(())
    }

    fn drop_template(&self, name: &str) -> Result<()> {
        self.check_verb(Verb::Admin, "*")?;
        let existing = self.snapshot_template(name);
        self.with_templates(|reg| reg.delete(name))
            .map_err(|e| AreevError::Validation(e.to_string()))?;
        if let Err(e) = self.with_store(|m| m.meta_delete(&format!("{TPL_PREFIX}{name}"))) {
            if let Some(prev) = &existing {
                self.with_templates(|reg| {
                    if reg
                        .register(name, &prev.source, &prev.description, prev.parent.as_deref())
                        .is_ok()
                    {
                        reg.restore_timestamps(name, prev.last_run_at, prev.updated_at);
                        reg.set_grain_types(name, &prev.grain_types);
                    }
                });
            }
            return Err(e);
        }
        Ok(())
    }

    fn list_templates(&self) -> Vec<TemplateInfo> {
        self.with_templates(|reg| reg.list())
    }

    fn get_template(&self, name: &str) -> Option<TemplateInfo> {
        // Direct lookup, not `list().find()`: this runs on the FORMAT render
        // path, and building the whole list (every source string cloned) to
        // throw all but one away is work proportional to the registry on every
        // rendered query.
        self.with_templates(|reg| {
            reg.get(name).map(|e| TemplateInfo {
                name: name.to_string(),
                description: e.description.clone(),
                builtin: e.builtin,
                parent: e.parent.clone(),
                grain_types: e.grain_types.clone(),
                source: e.template.source().to_string(),
                last_run_at: e.last_run_at,
                updated_at: e.updated_at,
            })
        })
    }

    fn record_template_run(&self, name: &str) {
        let persisted = self.with_templates(|reg| {
            let before = reg.get(name).and_then(|e| e.last_run_at);
            reg.record_run(name);
            let entry = reg.get(name)?;
            // `last_run_at` has one-second resolution, so a second render in
            // the same second cannot change what is on disk. Skipping that
            // write matters: this runs on the FORMAT path, and a rendered
            // recall should not cost a write transaction per call.
            if entry.builtin || entry.last_run_at == before {
                return None;
            }
            Some(PersistedTemplate {
                source: entry.template.source().to_string(),
                description: entry.description.clone(),
                parent: entry.parent.clone(),
                grain_types: entry.grain_types.clone(),
                last_run_at: entry.last_run_at,
                updated_at: entry.updated_at,
            })
        });
        if let Some(p) = persisted {
            if let Ok(json) = serde_json::to_string(&p) {
                let _ = self.with_store(|m| m.meta_put(&format!("{TPL_PREFIX}{name}"), &json));
            }
        }
    }

    fn recall(&self, params: &RecallParams) -> Result<Vec<SearchHit>> {
        // `WHERE <field> IN (...)` with nothing in it selects nothing. This is
        // the sharp edge of the whole `IN` family: `LET $friends = …` binding to
        // the empty set is the *natural* "this user has no friends yet"
        // outcome, and treating an empty filter as no filter answered with the
        // entire table. Fail closed, before any leg runs.
        for empty in [&params.subject_in, &params.relation_in, &params.object_in] {
            if empty.as_ref().is_some_and(|v| v.is_empty()) {
                return Ok(Vec::new());
            }
        }

        // ---- namespace scope resolution --------------------------------
        // The requested scope terms: an explicit `namespace IN (…)` set wins,
        // else the single namespace filter, else the session default. Each
        // term may be an exact name, a `"org.*"` prefix pattern (parent +
        // descendants), or mount-routed `alias.inner` (the inner part may
        // itself be a pattern).
        let requested_terms: Vec<String> = match &params.namespaces {
            Some(set) => set.clone(),
            None => match params.namespace.as_deref().or(self.namespace.as_deref()) {
                Some(one) => vec![one.to_string()],
                None => Vec::new(),
            },
        };
        // A session with no namespace scope keeps the historical contract:
        // the read gate checks `*`, the recall runs in the store default.
        if requested_terms.is_empty() {
            self.check_verb(Verb::Read, "*")?;
        }
        // Mount-route every term; one RECALL reads one store, so a set that
        // spans mounts (or mixes a mount with the session store) refuses with
        // a pointer at ASSEMBLE, which exists for exactly that.
        let mut mount_alias: Option<String> = None;
        let mut inner_scopes: Vec<(String, NsScope)> = Vec::with_capacity(requested_terms.len());
        for (i, full) in requested_terms.iter().enumerate() {
            let (alias, inner) = match full.split_once('.') {
                Some((a, rest)) if self.mounts.contains_key(a) => {
                    (Some(a.to_string()), rest.to_string())
                }
                _ => (None, full.clone()),
            };
            if i == 0 {
                mount_alias = alias;
            } else if mount_alias != alias {
                return Err(AreevError::Validation(
                    "a namespace set cannot span mounted memories in one RECALL — query each \
                     store separately, or ASSEMBLE with one source per store"
                        .into(),
                ));
            }
            inner_scopes.push((inner.clone(), NsScope::parse(&inner)?));
        }
        // Exact terms pass the read gate as themselves — the caller named
        // them, so the refusal may too. (Unknown names stay in the scope and
        // recall as empty; existence is not checked here.)
        for (term, scope) in &inner_scopes {
            if matches!(scope, NsScope::Exact(_)) {
                self.check_verb(Verb::Read, term)?;
            }
        }
        let mut m = match &mount_alias {
            Some(a) => self.mounts.get(a).unwrap().lock().unwrap(),
            None => self.store.lock().unwrap(),
        };
        // Resolve prefix scopes against the target store's namespace
        // registry, gating each DISCOVERED namespace on the session's read
        // grants — fail closed, and without naming what the caller could not
        // already know: in a multi-tenant file, a refusal that names a
        // sibling tenant's namespace would itself be a disclosure, so it
        // names the pattern the caller typed instead.
        let owner = self.session_is_owner();
        let mut ns_set: std::collections::BTreeSet<String> = std::collections::BTreeSet::new();
        for (term, scope) in &inner_scopes {
            match scope {
                NsScope::Exact(e) => {
                    ns_set.insert(e.clone());
                }
                NsScope::Prefix { .. } => {
                    for cand in m.namespaces_in_scope(scope)? {
                        if !owner && self.check_verb(Verb::Read, &cand).is_err() {
                            return Err(AreevError::AuthzDenied(format!(
                                "principal {} lacks read on part of scope {term:?} — the \
                                 prefix covers a namespace outside this session's grants",
                                self.session_principal()
                            )));
                        }
                        ns_set.insert(cand);
                    }
                }
            }
        }
        // A scope of nothing selects nothing: all-pattern terms that matched
        // no namespace answer empty, honestly — but only when the caller
        // actually named a scope (the no-scope session default is below).
        if ns_set.is_empty() && !requested_terms.is_empty() {
            return Ok(Vec::new());
        }
        if ns_set.is_empty() {
            ns_set.insert("shared".to_string()); // the no-scope store default
        }
        let ns_list: Vec<String> = ns_set.into_iter().collect();
        // `scoped` = the result set can span namespaces; the single exact
        // namespace — the common case and the voice path — keeps every
        // single-namespace fast path below.
        let scoped = ns_list.len() > 1;
        let ns = ns_list[0].as_str();
        let k = params.limit.unwrap_or(16).min(1000);

        // M4: hybrid recall — structural leg + BM25 leg fused with RRF.
        // A query alone, a subject alone, or both are all valid.
        //
        // With neither a subject nor a free-text query there is no leg to hang
        // ranking on, so fall back to a bounded recent-by-type scan (newest
        // first). This is the "reflect over recent experience" path — e.g.
        // `RECALL events RECENT 20`, `RECALL observations WHERE session_id = X`
        // — whose WHERE conditions (session_id, observer_id, object, …) are
        // applied as post-filters below and by the executor. Bare `RECALL *`
        // (no grain type) with no anchor is still rejected as too broad.
        // Which leg ran matters below: `recent` takes no structural predicates
        // and does not know about supersession, so this path has to reapply
        // both itself.
        //
        // `WHERE subject IN (a, b, c)` anchors just as well as `subject = a` —
        // it is a union of anchored legs, one per value. Treating it as
        // unanchored dropped the query into the recent-by-type scan, where the
        // filter was never applied at all (it lives in `RecallParams` and
        // nothing downstream read it), so the documented
        // `LET $friends = SUBJECTS OF (…)` pattern answered with *everybody's*
        // preferences instead of the friends'. Anchoring per value also means
        // the scan is bounded by the subjects asked for rather than by
        // `default_limit` — a post-filter over the newest 50 would miss a
        // named subject whose grains are older than that.
        let anchors: Vec<String> = match (&params.subject, &params.subject_in) {
            (Some(s), _) => vec![s.clone()],
            (None, Some(values)) => values.clone(),
            (None, None) => Vec::new(),
        };
        let unanchored = anchors.is_empty() && params.query.is_none();
        // `WITH superseded` — the caller is asking about the past, so every leg
        // widens from the heads to the whole supersession chain.
        let include_superseded = params.exclude_superseded == Some(false);
        // `WHERE session_id = "…"` with nothing else to anchor on: read the
        // thread index instead of a page of the namespace. Without this, the
        // `unanchored` arm below scans `recent`/`recent_live` newest-first
        // across the WHOLE namespace and the session filter is applied
        // afterwards, so on a busy namespace the tail of one conversation can
        // sit entirely outside the scanned page and the query answers
        // "nothing" — the single most common read a chat/voice agent makes,
        // silently wrong. `idx_thread(ns, session, seq)` bounds the scan by the
        // session, so k here means k turns of THIS conversation.
        //
        // A session IS an anchor, so this branch also lifts the "RECALL needs a
        // subject filter, a free-text query, or a specific grain type" refusal
        // for the typed-less form: `RECALL WHERE session_id = "…"` is bounded.
        //
        // Only on the unanchored path: with a subject or a free-text query the
        // hybrid leg is already bounded by that anchor (a far tighter bound
        // than a namespace page), and the post-filter finishes the job. Kept as
        // its own branch rather than nested inside the unanchored arm so the
        // recent-by-type match below stays exactly as it was.
        let raw = if let Some(session) = params.session_id.as_deref().filter(|_| unanchored) {
            let n = k.saturating_mul(Self::RECALL_OVERFETCH);
            if scoped {
                m.recent_in_session_scoped(&ns_list, session, params.grain_type, n, !include_superseded)?
            } else {
                m.recent_in_session(ns, session, params.grain_type, n, !include_superseded)?
            }
        } else if let Some(order) = params.order_by.as_ref().and_then(|k| {
            // `created_at` is the one sort key the `grains` table carries as a
            // column, so it is the one ORDER BY that can be served from the
            // scan instead of re-sorting a page afterwards. The executor only
            // sets `order_by` for it; anything else it ranks itself over a
            // widened scan (see `RecallParams::order_by`).
            // `params.grain_type.is_some()` matters: ORDER BY is not an
            // anchor, so without a type this must still fall through to the
            // "RECALL needs a subject filter, a free-text query, or a specific
            // grain type" refusal below rather than scanning the namespace.
            (unanchored && params.grain_type.is_some() && k.field == "created_at").then_some(
                if k.descending {
                    areev_store::RecentOrder::CreatedAtDesc
                } else {
                    areev_store::RecentOrder::CreatedAtAsc
                },
            )
        }) {
            let n = k.min(1000);
            if scoped {
                m.recent_ordered_scoped(&ns_list, params.grain_type, n, !include_superseded, order)?
            } else {
                m.recent_ordered(ns, params.grain_type, n, !include_superseded, order)?
            }
        } else if unanchored {
            match params.grain_type {
                // Heads only, unless `WITH superseded` asked otherwise. The
                // anchored leg already serves heads; this one read the grains
                // table straight through, so a superseded value came back
                // alongside the head that replaced it and recall reported both
                // as current. Supersession is index-layer state, so the
                // distinction has to be made in the query, not after it.
                Some(_) if !include_superseded => {
                    if scoped {
                        m.recent_live_scoped(
                            &ns_list,
                            params.grain_type,
                            k.saturating_mul(Self::RECALL_OVERFETCH),
                        )?
                    } else {
                        m.recent_live(ns, params.grain_type, k.saturating_mul(Self::RECALL_OVERFETCH))?
                    }
                }
                Some(_) => {
                    if scoped {
                        m.recent_scoped(
                            &ns_list,
                            params.grain_type,
                            k.saturating_mul(Self::RECALL_OVERFETCH),
                        )?
                    } else {
                        m.recent(ns, params.grain_type, k.saturating_mul(Self::RECALL_OVERFETCH))?
                    }
                }
                None => {
                    return Err(AreevError::Validation(
                        "RECALL needs a subject filter, a free-text (LIKE) query, \
                         or a specific grain type with RECENT/LIMIT"
                            .into(),
                    ))
                }
            }
        } else {
            // Translate the recall flags the executor set from `WITH` options
            // (diversity / rerank / query_expansion) into engine tuning. MMR is
            // the only diversity method wired in-engine; the threshold variant
            // is not reachable from CAL's `WITH diversity`.
            let tuning = areev_store::RecallTuning {
                query_expansion: params.query_expansion == Some(true),
                rerank: params.rerank.is_some(),
                diversity_lambda: params.diversity.as_ref().and_then(|d| match d.method {
                    DiversityMethod::Mmr { lambda } => Some(lambda),
                    DiversityMethod::Threshold(_) => None,
                }),
                include_superseded,
            };
            let budget = k.saturating_mul(Self::RECALL_OVERFETCH);
            match anchors.len() {
                // The common case, and the voice hot path: one anchored leg.
                0 | 1 if !scoped => m.recall_hybrid_tuned(
                    ns,
                    anchors.first().map(String::as_str),
                    params.relation.as_deref(),
                    params.query.as_deref(),
                    budget,
                    None,
                    tuning,
                )?,
                // Same leg over a resolved namespace set (`IN` / a prefix
                // scope that expanded to more than one namespace).
                0 | 1 => m.recall_hybrid_scoped(
                    &ns_list,
                    anchors.first().map(String::as_str),
                    params.relation.as_deref(),
                    params.query.as_deref(),
                    budget,
                    None,
                    tuning,
                )?,
                // `subject IN (a, b, …)`: one anchored leg per value, unioned.
                // Each leg gets the full budget so a subject with many grains
                // cannot starve the others out of the result set; the union is
                // deduped by content address and the caller's LIMIT is applied
                // below, as it is on every other path.
                _ => {
                    let mut seen: HashSet<Hash> = HashSet::new();
                    let mut union = Vec::new();
                    for anchor in &anchors {
                        let leg = if scoped {
                            m.recall_hybrid_scoped(
                                &ns_list,
                                Some(anchor.as_str()),
                                params.relation.as_deref(),
                                params.query.as_deref(),
                                budget,
                                None,
                                tuning,
                            )?
                        } else {
                            m.recall_hybrid_tuned(
                                ns,
                                Some(anchor.as_str()),
                                params.relation.as_deref(),
                                params.query.as_deref(),
                                budget,
                                None,
                                tuning,
                            )?
                        };
                        for g in leg {
                            if seen.insert(g.hash) {
                                union.push(g);
                            }
                        }
                    }
                    // Newest first, matching what a single anchored leg returns.
                    union.sort_by(|a, b| {
                        b.get_i64("created_at")
                            .unwrap_or(0)
                            .cmp(&a.get_i64("created_at").unwrap_or(0))
                    });
                    union
                }
            }
        };

        // `WITH multi_hop(n)` — entity-graph expansion.
        //
        // Take the entities the first pass surfaced (its results' subject and
        // object terms), anchor a fresh recall on each, and add what comes back
        // to the candidate pool. Repeat `n` times, following the graph outward.
        //
        // Both directions: an entity is followed as a subject (what does X point
        // at) *and* as an object (what points at X). Forward-only expansion made
        // "who else works here" — the archetypal one-hop question — return
        // nothing, since entities are harvested from the `object` field but were
        // only ever re-anchored as subjects. The reverse leg reads the OSP index,
        // so it sees the relations the file declares as entity relations; that is
        // the same rule every other reverse traversal in the engine follows.
        //
        // Expansion happens here, before the post-filters and the `LIMIT` below,
        // so hops *compete* for the k slots the caller asked for rather than
        // extending past them. Appended after the first pass, so a direct match
        // always outranks something reached by association.
        //
        // Fail-open, like every other recall refinement: a hop that errors is
        // skipped rather than failing the query.
        let mut raw = raw;
        if let Some(hops) = params.multi_hop.filter(|h| *h > 0) {
            let mut seen: HashSet<Hash> = raw.iter().map(|g| g.hash).collect();
            let mut visited: HashSet<String> = HashSet::new();
            let mut frontier: Vec<String> = Vec::new();
            let push_entities = |g: &DeserializedGrain,
                                     visited: &mut HashSet<String>,
                                     out: &mut Vec<String>| {
                for field in ["subject", "object"] {
                    if let Some(v) = g.get_str(field) {
                        if !v.is_empty() && visited.insert(v.to_string()) {
                            out.push(v.to_string());
                        }
                    }
                }
            };
            for g in raw.iter().take(Self::MULTI_HOP_SEED) {
                push_entities(g, &mut visited, &mut frontier);
            }

            let budget = k.saturating_mul(Self::RECALL_OVERFETCH);
            'hops: for _ in 0..hops {
                let mut next: Vec<String> = Vec::new();
                for entity in std::mem::take(&mut frontier) {
                    if raw.len() >= budget {
                        break 'hops;
                    }
                    // Hops stay inside the resolved scope: a graph walk must
                    // not escape the namespaces the query (and its authz
                    // sweep) selected.
                    let forward = if scoped {
                        m.recall_hybrid_scoped(
                            &ns_list,
                            Some(&entity),
                            None,
                            params.query.as_deref(),
                            Self::MULTI_HOP_FANOUT,
                            None,
                            areev_store::RecallTuning::default(),
                        )
                        .unwrap_or_default()
                    } else {
                        m.recall_hybrid(
                            ns,
                            Some(&entity),
                            None,
                            params.query.as_deref(),
                            Self::MULTI_HOP_FANOUT,
                            None,
                        )
                        .unwrap_or_default()
                    };
                    let reverse: Vec<DeserializedGrain> = ns_list
                        .iter()
                        .flat_map(|hop_ns| {
                            m.grains_by_object(hop_ns, &entity, Self::MULTI_HOP_FANOUT)
                                .unwrap_or_default()
                        })
                        .collect();
                    for g in forward.into_iter().chain(reverse) {
                        if seen.insert(g.hash) {
                            push_entities(&g, &mut visited, &mut next);
                            raw.push(g);
                        }
                    }
                }
                if next.is_empty() {
                    break;
                }
                frontier = next;
            }
        }
        drop(m);

        // Defense in depth for scoped recalls: every leg is already
        // namespace-bounded in SQL, but a future leg that forgets the bound
        // would silently WIDEN a result set — the worst failure shape here —
        // so membership is re-asserted per grain when the scope is a set.
        let ns_filter: HashSet<&str> = ns_list.iter().map(String::as_str).collect();
        // ONE predicate for "recency re-ranking is active", read by both the
        // widened `take` below and the re-rank block after it. They used to
        // test it differently — `is_some()` for the widening, `> 0.0` for the
        // re-rank — so `WITH recency_weight(0)` widened the scan and then
        // never truncated it back, and a `RECENT 3` answered with
        // `3 * RECALL_OVERFETCH` grains. A weight of zero means "no recency
        // component", which is the SAME answer as no option at all; so does a
        // negative or NaN weight, and all three now take the unwidened path.
        let recency_weight = params.recency_weight.filter(|w| *w > 0.0);
        let mut hits: Vec<SearchHit> = raw
            .into_iter()
            .filter(|g| {
                !scoped || ns_filter.contains(g.get_str("namespace").unwrap_or("shared"))
            })
            // `relation` reaches the anchored leg as a store-side predicate,
            // but `recent` takes no predicates at all — so on that path the
            // filter was simply dropped and `RECALL facts WHERE relation = "x"`
            // answered with every grain of that type. Silently returning more
            // than was asked for is worse than returning nothing.
            .filter(|g| {
                !unanchored
                    || match &params.relation {
                        Some(r) => g.get_str("relation") == Some(r.as_str()),
                        None => true,
                    }
            })
            .filter(|g| match &params.object {
                Some(o) => g.get_str("object") == Some(o.as_str()),
                None => true,
            })
            // The `IN` family. `subject_in` already anchored the legs above, but
            // an anchored leg on "jane" can still surface grains where jane is
            // the *object*, so all three are re-applied here as membership
            // tests. Before this, nothing in the engine read these three fields
            // at all: the executor set them and the query returned every row the
            // rest of the WHERE matched, with no error and no warning.
            .filter(|g| set_contains(&params.subject_in, g.get_str("subject")))
            .filter(|g| set_contains(&params.relation_in, g.get_str("relation")))
            .filter(|g| set_contains(&params.object_in, g.get_str("object")))
            // #318: the tag sets, applied here for exactly the reason the
            // three above are.
            .filter(|g| tags_match(&params.tags, &params.exclude_tags, g))
            .filter(|g| match params.grain_type {
                Some(gt) => g.grain_type == gt,
                None => true,
            })
            .filter(|g| {
                let ca = g.get_i64("created_at").unwrap_or(0);
                params.time_start.is_none_or(|t| ca >= t)
                    && params.time_end.is_none_or(|t| ca <= t)
            })
            .filter(|g| match params.confidence_threshold {
                Some(c) => g.get_f64("confidence").unwrap_or(0.0) >= c,
                None => true,
            })
            // `WITH recency_weight(w)` re-ranks the CANDIDATES, so it has to
            // see them before this bound — ranking a set already cut to k is
            // the same truncated-window mistake ORDER BY made. Without the
            // option the take stays exactly where it was, so the hot path is
            // unchanged.
            .take(if recency_weight.is_some() { usize::MAX } else { k })
            .map(Self::hit)
            .collect();

        // ── `WITH recency_weight(w)` ─────────────────────────────────────
        //
        // Parsed since 1.0, stored on RecallParams, and read by NOTHING — ten
        // of the built-in saved queries in `queries.rs` pass it, so ten shipped
        // queries were quietly not doing what they said. Implemented to the
        // formula the field has always documented:
        //
        //     final = (1 - w) * relevance + w * freshness
        //     freshness = 1 / (1 + age_hours)
        //
        // `relevance` comes from FUSION ORDER, not `hit.score`: every hit
        // leaves `Self::hit` with score 1.0, so the ranking a recall carries is
        // positional (RRF/structural order), not numeric. Rank i of n therefore
        // scores `1 - i/n` — order-preserving, and identical to the current
        // order when w = 0.
        //
        // State facts are exempt, as documented: "lives in Berlin" does not
        // become less true with age, so decaying it would push a current fact
        // below a stale event.
        if let Some(w) = recency_weight {
            let w = w.clamp(0.0, 1.0);
            let now = std::time::SystemTime::now()
                .duration_since(std::time::UNIX_EPOCH)
                .map(|d| d.as_millis() as i64)
                .unwrap_or(0);
            let n = hits.len().max(1) as f64;
            for (i, h) in hits.iter_mut().enumerate() {
                let relevance = 1.0 - (i as f64) / n;
                let is_state = h.grain.get_str("temporal_type") == Some("state");
                h.score = if is_state {
                    relevance
                } else {
                    let age_hours =
                        ((now - h.grain.get_i64("created_at").unwrap_or(now)).max(0) as f64)
                            / 3_600_000.0;
                    let freshness = 1.0 / (1.0 + age_hours);
                    (1.0 - w) * relevance + w * freshness
                };
            }
            // Stable, so equal scores keep fusion order.
            hits.sort_by(|a, b| b.score.partial_cmp(&a.score).unwrap_or(std::cmp::Ordering::Equal));
            hits.truncate(k);
        }

        // Label the history. A widened recall returns stale versions next to the
        // heads that replaced them, and nothing in an immutable blob says which
        // is which — unlabeled, `WITH superseded` would quietly feed a model
        // outdated values that read as current. Renderers and the RF-2
        // context rule key off these two fields, so stamping them is what makes
        // the widened result honest rather than merely bigger.
        if include_superseded && !hits.is_empty() {
            let hashes: Vec<Hash> = hits.iter().map(|h| h.hash).collect();
            let mut m = match &mount_alias {
                Some(a) => self.mounts.get(a).unwrap().lock().unwrap(),
                None => self.store.lock().unwrap(),
            };
            // Fail-open, like every other recall refinement: an unlabeled result
            // is worse than a labeled one but far better than a failed query.
            if let Ok(map) = m.supersession_map(&hashes) {
                drop(m);
                for hit in &mut hits {
                    hit.supersession_status = Some(match map.get(&hit.hash) {
                        Some(_) => SupersessionStatus::Superseded,
                        None => SupersessionStatus::Current,
                    });
                    hit.superseded_by_hash = map.get(&hit.hash).copied();
                }
            }
        }

        // `WITH conflict_resolution` — keep only the newest grain per
        // (subject, relation). Documented in §5 and advertised by DESCRIBE, but
        // the implementation lived on the ASSEMBLE post-merge path only, which
        // a RECALL payload never reaches — so a caller specifically trying to
        // avoid feeding two contradictory values into a model's context got
        // both, with no signal. Ties break on the later hash so the choice is
        // deterministic across nodes rather than dependent on scan order.
        if params.conflict_resolution == Some(true) {
            let mut newest: HashMap<(String, String), (i64, Hash)> = HashMap::new();
            for h in &hits {
                let (Some(s), Some(r)) = (h.grain.get_str("subject"), h.grain.get_str("relation"))
                else {
                    continue;
                };
                let created = h.grain.get_i64("created_at").unwrap_or(0);
                let key = (s.to_string(), r.to_string());
                let better = match newest.get(&key) {
                    None => true,
                    Some((best, best_hash)) => {
                        (created, h.hash.as_bytes()) > (*best, best_hash.as_bytes())
                    }
                };
                if better {
                    newest.insert(key, (created, h.hash));
                }
            }
            for h in &mut hits {
                let keep = match (h.grain.get_str("subject"), h.grain.get_str("relation")) {
                    // A grain with no (subject, relation) key has nothing to
                    // conflict with, so it is never the loser of a comparison.
                    (Some(s), Some(r)) => newest
                        .get(&(s.to_string(), r.to_string()))
                        .is_none_or(|(_, hash)| *hash == h.hash),
                    _ => true,
                };
                h.conflict_status = Some(if keep {
                    ConflictStatus::Current
                } else {
                    ConflictStatus::Outdated
                });
            }
            hits.retain(|h| h.conflict_status != Some(ConflictStatus::Outdated));
        }

        // `WITH annotate_relative_time` — "3 hours ago" beside the epoch
        // milliseconds, so a model reading the context does not have to do
        // date arithmetic to know whether a memory is fresh.
        if params.annotate_relative_time == Some(true) {
            let now = now_ms();
            for h in &mut hits {
                h.relative_time = h
                    .grain
                    .get_i64("created_at")
                    .map(|created| relative_time_label(now - created));
            }
        }

        // `WITH explanation` — why this grain came back. Template-based and
        // derived entirely from the predicates that ran (the field's contract:
        // no LLM, suitable for EU AI Act Art. 86 disclosure).
        if params.explanation == Some(true) {
            for h in &mut hits {
                let mut why: Vec<String> = Vec::new();
                if !anchors.is_empty() {
                    if let Some(s) = h.grain.get_str("subject") {
                        if anchors.iter().any(|a| a == s) {
                            why.push(format!("anchored on subject \"{s}\""));
                        }
                    }
                }
                if let Some(q) = &params.query {
                    why.push(format!("matched the free-text query \"{q}\""));
                }
                if let Some(r) = params.relation.as_deref().or_else(|| {
                    params.relation_in.as_ref().and_then(|_| h.grain.get_str("relation"))
                }) {
                    why.push(format!("relation is \"{r}\""));
                }
                if why.is_empty() {
                    why.push(match params.grain_type {
                        Some(gt) => format!("recent {} in this namespace", gt.as_str()),
                        None => "recent grain in this namespace".into(),
                    });
                }
                if h.supersession_status == Some(SupersessionStatus::Superseded) {
                    why.push("included as history by WITH superseded".into());
                }
                h.explanation = Some(why.join("; "));
            }
        }

        Ok(hits)
    }

    fn exists(&self, hash: &Hash) -> Result<bool> {
        if self.session_is_owner() {
            return self.store.lock().unwrap().has(hash);
        }
        // An existence bit is a read, and a hash names no namespace — so a
        // restricted session resolves the grain first and answers only for
        // namespaces its grants can read.
        let fetched = self.store.lock().unwrap().get(hash);
        match fetched {
            Ok(g) => {
                self.check_verb(Verb::Read, g.get_str("namespace").unwrap_or("shared"))?;
                Ok(true)
            }
            Err(AreevError::NotFound(_)) => Ok(false),
            Err(e) => Err(e),
        }
    }

    fn get(&self, hash: &Hash) -> Result<DeserializedGrain> {
        let g = self.store.lock().unwrap().get(hash)?;
        self.check_verb(Verb::Read, g.get_str("namespace").unwrap_or("shared"))?;
        Ok(g)
    }

    fn count(&self) -> Result<usize> {
        // A store-wide count spans every namespace.
        self.check_verb(Verb::Read, "*")?;
        self.store.lock().unwrap().count()
    }

    fn get_history(&self, namespace: &str, subject: &str, relation: &str) -> Result<Vec<VersionEntry>> {
        self.check_verb(Verb::Read, namespace)?;
        let entries = self.store.lock().unwrap().history(namespace, subject, relation)?;
        Ok(entries
            .into_iter()
            .map(|e| VersionEntry {
                hash: e.hash,
                object: e.object,
                created_at: e.created_at,
                confidence: e.confidence,
                superseded_by: e.superseded_by,
            })
            .collect())
    }

    fn open_forks(&self) -> Result<Vec<ForkGroupInfo>> {
        // The fork listing spans every namespace.
        self.check_verb(Verb::Read, "*")?;
        let groups = self.with_store(|m| m.open_forks())?;
        Ok(groups
            .into_iter()
            .map(|f| ForkGroupInfo {
                namespace: f.namespace,
                subject: f.subject,
                relation: f.relation,
                // `Areev::heads` orders `created_at DESC, hash DESC` — the same
                // tuple the provisional-head election uses — so tip 0 is the
                // value recall serves. Preserve that order; CONTRADICTIONS
                // reports every other tip as a peer of it.
                heads: f.heads.iter().map(|h| h.to_hex()).collect(),
            })
            .collect())
    }

    fn default_namespace(&self) -> Option<&str> {
        self.namespace.as_deref()
    }

    fn active_user(&self) -> Option<&str> {
        self.user.as_deref()
    }

    fn cal_add(
        &self,
        grain_type: &str,
        fields: &serde_json::Map<String, serde_json::Value>,
    ) -> Result<Hash> {
        self.check_verb(Verb::Write, self.write_ns(fields))?;
        let ingressed = self.ingress_fields(fields)?;
        let fields = ingressed.as_ref().unwrap_or(fields);
        let mut m = self.store.lock().unwrap();
        build_grain_from_json(grain_type, fields, AddSink { m: &mut m })
    }

    fn cal_supersede(
        &self,
        old_hash: &Hash,
        grain_type: &str,
        fields: &serde_json::Map<String, serde_json::Value>,
    ) -> Result<Hash> {
        if !self.session_is_owner() {
            // Authorize against the TARGET's namespace, the way `cal_delete`
            // does — that is the grain this statement actually rewrites out
            // of live recall. `SET namespace` names where the *replacement*
            // lands, so checking only that lets a caller supersede a grain in
            // a namespace it holds no supersede grant on simply by naming one
            // it does.
            let old_ns = {
                let g = self.store.lock().unwrap().get(old_hash)?;
                g.get_str("namespace").unwrap_or("shared").to_string()
            };
            self.check_verb(Verb::Supersede, &old_ns)?;
            // A supersession that moves the value to another namespace also
            // writes there, so that namespace needs the grant too.
            let new_ns = self.write_ns(fields);
            if new_ns != old_ns {
                self.check_verb(Verb::Supersede, new_ns)?;
            }
        }
        let ingressed = self.ingress_fields(fields)?;
        let fields = ingressed.as_ref().unwrap_or(fields);
        let mut m = self.store.lock().unwrap();
        build_grain_from_json(
            grain_type,
            fields,
            SupersedeSink {
                m: &mut m,
                old: *old_hash,
            },
        )
    }

    /// `FORGET <hash>` — tombstone a single grain by content address. Only
    /// ever hits the session store; mounts are read-only by construction.
    /// Capped upstream by `CalExecutorConfig::allow_destructive_ops`; the
    /// session's `delete` grant on the grain's own namespace is the
    /// authorization.
    fn cal_delete(&self, hash: &Hash, because: Option<&str>) -> Result<()> {
        if !self.session_is_owner() {
            let ns = {
                let g = self.store.lock().unwrap().get(hash)?;
                g.get_str("namespace").unwrap_or("shared").to_string()
            };
            self.check_verb(Verb::Delete, &ns)?;
        }
        let target = format!("hash:{}", hash.to_hex());
        // Bind the outcome so the MutexGuard drops HERE. An `if let` holds its
        // scrutinee's temporaries for the whole construct, so locking inline
        // kept the store locked through the arm — and `audit_hold_refusal`
        // locks it again, deadlocking the process on a std Mutex, which is not
        // reentrant. A legal-hold refusal therefore HUNG instead of refusing.
        let outcome = self.store.lock().unwrap().forget(hash);
        if let Err(e) = outcome {
            if e.code() == "STO-E009" {
                // #278: a deferral is evidence, not silence.
                self.audit_hold_refusal("delete", &target, &e.to_string());
            }
            return Err(e);
        }
        self.audit_tier2("delete", &target, because, 1, &[])
    }

    /// `FORGET <hash> WITH override_hold BECAUSE "…"` (#278).
    ///
    /// `admin` on the namespace ON TOP of `delete`, the way `reveal_tokens`
    /// gates re-identification: a principal who may erase is not
    /// automatically one who may override a records-retention hold.
    fn cal_delete_overriding(&self, hash: &Hash, because: &str) -> Result<()> {
        let ns = {
            let g = self.store.lock().unwrap().get(hash)?;
            g.get_str("namespace").unwrap_or("shared").to_string()
        };
        if !self.session_is_owner() {
            self.check_verb(Verb::Delete, &ns)?;
            self.check_verb(Verb::Admin, &ns)?;
        }
        let over = areev_store::HoldOverride::new(self.session_principal(), because)?;
        let target = format!("hash:{}", hash.to_hex());
        let overridden = self.store.lock().unwrap().forget_overriding(hash, &over)?;
        match overridden {
            Some(hold) => self.audit_hold_override("delete", &target, because, 1, &hold),
            None => self.audit_tier2("delete", &target, Some(because), 1, &[]),
        }
    }

    /// `MERGE` — the resolved value supersedes every open tip; the merge
    /// grain records all parents. `supersede` is the authorization (it is
    /// a head rewrite, however principled), and the reason rides the
    /// grain's supersession justification.
    fn cal_merge(
        &self,
        subject: &str,
        relation: &str,
        object: &str,
        confidence: f64,
        because: &str,
    ) -> Result<Hash> {
        let ns = self.default_ns().unwrap_or_else(|| "shared".to_string());
        self.check_verb(Verb::Supersede, &ns)?;
        let mut merged = areev_core::types::Fact::new(subject, relation, object)
            .namespace(&ns)
            .confidence(confidence)
            .created_at(now_epoch_ms());
        merged.common.supersession_justification = Some(because.to_string());
        self.store.lock().unwrap().merge_heads(&ns, subject, relation, &mut merged)
    }

    /// `RELATED` — the bounded k-hop walk in the session namespace.
    fn cal_related_scoped(
        &self,
        namespaces: &[String],
        start: &str,
        relations: &[&str],
        direction: &str,
        depth: usize,
        limit: usize,
    ) -> Result<Vec<String>> {
        if namespaces.is_empty() {
            return self.cal_related(start, relations, direction, depth, limit);
        }
        // EVERY named namespace is read-checked as itself before anything is
        // read (#303), the rule `recall` applies to exact terms. One
        // ungranted term refuses the whole statement rather than narrowing
        // the walk — a walk that quietly covered less than it was asked to
        // is an answer that means something different from what it says.
        for ns in namespaces {
            self.check_verb(Verb::Read, ns)?;
        }
        let dir = match direction {
            "in" => areev_store::Direction::In,
            "both" => areev_store::Direction::Both,
            _ => areev_store::Direction::Out,
        };
        self.store.lock().unwrap().related_scoped(
            namespaces,
            start,
            relations,
            dir,
            depth.clamp(1, 4),
            limit.min(256),
        )
    }

    fn cal_entity_at_scoped(
        &self,
        namespaces: &[String],
        subject: &str,
        relation: &str,
        at_ms: i64,
        axis: &str,
    ) -> Result<Vec<(String, serde_json::Value)>> {
        if namespaces.is_empty() {
            return Ok(self
                .cal_entity_at(subject, relation, at_ms, axis)?
                .into_iter()
                .map(|g| (String::new(), g))
                .collect());
        }
        for ns in namespaces {
            self.check_verb(Verb::Read, ns)?;
        }
        let axis = match axis {
            "knowledge" => areev_store::Axis::Knowledge,
            _ => areev_store::Axis::World,
        };
        let rows = self
            .store
            .lock()
            .unwrap()
            .entity_at_scoped(namespaces, subject, relation, at_ms, axis)?;
        Ok(rows.into_iter().map(|(ns, g)| (ns, grain_json(&g))).collect())
    }

    fn cal_related(
        &self,
        start: &str,
        relations: &[&str],
        direction: &str,
        depth: usize,
        limit: usize,
    ) -> Result<Vec<String>> {
        let ns = self.default_ns().unwrap_or_else(|| "shared".to_string());
        self.check_verb(Verb::Read, &ns)?;
        let dir = match direction {
            "in" => areev_store::Direction::In,
            "both" => areev_store::Direction::Both,
            _ => areev_store::Direction::Out,
        };
        self.store
            .lock()
            .unwrap()
            .related(&ns, start, relations, dir, depth.clamp(1, 4), limit.min(256))
    }

    /// `NOVELTY` — nearest existing grains; requires a host embedder.
    ///
    /// **Does not cross a mount, by design and by limitation.** Unlike
    /// `cal_recall`, which routes `"alias.inner"` to the mounted store, this
    /// always reads `self.store`. Two things would have to change first: the
    /// mount router here, and the embedder — `--embed-cmd` installs one on the
    /// PRIMARY memory only, so a mounted store's vector leg has no model to
    /// embed the query with and would answer empty even if routed. Routing
    /// alone would therefore trade one wrong answer for another, so the
    /// limitation is documented instead (`docs/cal-reference.md`, "Mounts and
    /// the vector leg") rather than half-fixed. A session whose namespace is
    /// an alias gets the session store's answer, which is the honest reading
    /// of "novel to THIS memory".
    fn cal_novelty(
        &self,
        text: &str,
        subject: Option<&str>,
        relation: Option<&str>,
        k: usize,
    ) -> Result<Vec<(String, f64)>> {
        let ns = self.default_ns().unwrap_or_else(|| "shared".to_string());
        self.check_verb(Verb::Read, &ns)?;
        let rows = self
            .store
            .lock()
            .unwrap()
            .nearest_semantic(&ns, subject, relation, text, k.clamp(1, 64))?;
        Ok(rows.into_iter().map(|(h, sim)| (h.to_hex(), sim as f64)).collect())
    }

    fn cal_entity_at(
        &self,
        subject: &str,
        relation: &str,
        at_ms: i64,
        axis: &str,
    ) -> Result<Option<serde_json::Value>> {
        let ns = self.default_ns().unwrap_or_else(|| "shared".to_string());
        self.check_verb(Verb::Read, &ns)?;
        let axis = match axis {
            "knowledge" => areev_store::Axis::Knowledge,
            _ => areev_store::Axis::World,
        };
        let g = self
            .store
            .lock()
            .unwrap()
            .entity_at(&ns, subject, relation, at_ms, axis)?;
        Ok(g.as_ref().map(grain_json))
    }

    fn cal_run_trace(&self, run_id: &str, limit: usize) -> Result<serde_json::Value> {
        let ns = self.default_ns().unwrap_or_else(|| "shared".to_string());
        self.check_verb(Verb::Read, &ns)?;
        let mut m = self.store.lock().unwrap();
        let recorded: Vec<_> = m.run_trace(&ns, run_id, limit)?.iter().map(grain_json).collect();
        let produced: Vec<_> = m.run_yield(&ns, run_id, limit)?.iter().map(grain_json).collect();
        Ok(serde_json::json!({ "recorded": recorded, "produced": produced }))
    }

    fn cal_runs_touching(&self, hash: &Hash, depth: usize) -> Result<Vec<String>> {
        let ns = self.default_ns().unwrap_or_else(|| "shared".to_string());
        self.check_verb(Verb::Read, &ns)?;
        self.store.lock().unwrap().runs_touching(&ns, hash, depth)
    }

    fn cal_derived_from(&self, hash: &Hash) -> Result<Vec<serde_json::Value>> {
        // Provenance spans namespaces, so an owner session — and any session
        // holding `read ON *` — answers the whole index, unchanged.
        //
        // Every other session used to be refused outright (#304), which made
        // `read ON *` the only way to let a person ask "what was built from
        // this" — and the two places a host actually uses reverse provenance
        // are corrections and lineage, both of which people with exact
        // namespace grants do. The fallback was a service principal holding
        // `read ON *` with the host post-filtering its results, which moves
        // the authorization decision out of the engine entirely.
        if self.session_is_owner() || self.check_verb(Verb::Read, "*").is_ok() {
            let grains = self.store.lock().unwrap().grains_derived_from(hash)?;
            return Ok(grains.iter().map(grain_json).collect());
        }
        // Otherwise: the PARENT must be readable by this session, under the
        // same rule `get` applies — you may ask what was derived from a grain
        // you can read, and nothing else.
        let parent = self.store.lock().unwrap().get(hash)?;
        self.check_verb(Verb::Read, parent.get_str("namespace").unwrap_or("shared"))?;
        let grains = self.store.lock().unwrap().grains_derived_from(hash)?;
        // Keep only children this session may read. Deliberately NO count of
        // what was withheld: a count would disclose that ANOTHER namespace
        // derived something from this grain, which is exactly what `recall`
        // declines to reveal when it refuses without naming a sibling
        // namespace. Narrowing rather than refusing is the non-disclosing
        // option, and it is the one that makes the read usable at all.
        Ok(grains
            .iter()
            .filter(|g| {
                self.check_verb(Verb::Read, g.get_str("namespace").unwrap_or("shared"))
                    .is_ok()
            })
            .map(grain_json)
            .collect())
    }

    fn cal_stats(&self) -> Result<serde_json::Value> {
        self.check_verb(Verb::Read, "*")?;
        let s = self.store.lock().unwrap().stats()?;
        Ok(serde_json::json!({
            "grains": s.grains,
            "current": s.current,
            "triples": s.triples,
            "terms": s.terms,
            "ops": s.ops,
            "events_indexed": s.events_indexed,
        }))
    }

    fn cal_verify(&self) -> Result<serde_json::Value> {
        self.check_verb(Verb::Read, "*")?;
        let r = self.store.lock().unwrap().verify()?;
        Ok(serde_json::json!({
            "integrity": r.integrity,
            "fts_notes": r.fts_notes,
            "grains": r.grains,
            "hash_mismatches": r.hash_mismatches,
            "undecodable": r.undecodable,
        }))
    }

    /// `REMEMBER` (CAL 1.3) — capture into the session namespace via the
    /// same store path as `areev remember` and the bindings' `capture`. The
    /// observer is the bound principal; a `write` grant is the
    /// authorization.
    fn cal_remember(
        &self,
        content: &str,
        session_id: Option<&str>,
        role: Option<&str>,
        run_id: Option<&str>,
    ) -> Result<Hash> {
        let ns = self.default_ns().unwrap_or_else(|| "shared".to_string());
        self.check_verb(Verb::Write, &ns)?;
        let observer = self.session_principal();
        self.store.lock().unwrap().capture(
            &ns,
            content,
            &areev_store::Capture {
                observer: Some(&observer),
                session_id,
                role,
                run_id,
            },
        )
    }

    /// `GRANT` (CAL 1.3 §8.15) — writes the grant grain: a Fact in the
    /// reserved `agent:authz` namespace, subject = grantee, relation =
    /// `mg:permits`, object = the canonical grant string, grantor + reason
    /// in `context`. Authorized by `admin`. A session's own rights are
    /// fixed at bind — a grant to the current principal applies to
    /// sessions bound after it, like a new database connection.
    fn cal_grant(
        &self,
        principal: &str,
        verbs: &[String],
        namespaces: &[String],
        because: Option<&str>,
    ) -> Result<Hash> {
        self.check_verb(Verb::Admin, "*")?;
        let grant = parse_grant_parts(principal, verbs, namespaces)?;
        let mut fact = areev_core::types::Fact::new(
            principal,
            areev_core::authz::REL_PERMITS,
            &grant.to_object_string(),
        )
        .namespace(areev_core::authz::AUTHZ_NS)
        .created_at(now_epoch_ms());
        fact.common.context = Some(serde_json::json!({
            "grantor": self.session_principal(),
            "because": because.unwrap_or(""),
        }));
        self.store.lock().unwrap().add(&fact)
    }

    /// `REVOKE` (CAL 1.3 §8.15) — retraction by supersession. Each live
    /// grant whose namespace scope is covered by the revoke loses the
    /// revoked verbs: reduced grants supersede in place; a grant with
    /// nothing left is superseded by a `revoked` retraction record. A grant
    /// with a WIDER scope than the revoke is refused by name — no silent
    /// splitting; revoke at the grant's own scope.
    fn cal_revoke(
        &self,
        principal: &str,
        verbs: &[String],
        namespaces: &[String],
        because: Option<&str>,
    ) -> Result<usize> {
        self.check_verb(Verb::Admin, "*")?;
        let revoke = parse_grant_parts(principal, verbs, namespaces)?;
        let revoke_all_ns = revoke.namespaces.iter().any(|n| n == "*");

        let mut m = self.store.lock().unwrap();
        let grains = m.recall(
            areev_core::authz::AUTHZ_NS,
            principal,
            Some(areev_core::authz::REL_PERMITS),
            256,
        )?;
        let mut touched = 0usize;
        for g in &grains {
            let Some(obj) = g.get_str("object") else { continue };
            let Ok(existing) = areev_core::authz::Grant::from_object_string(obj) else {
                continue; // retraction records and junk never carry rights
            };
            if !existing.verbs.iter().any(|v| revoke.verbs.contains(v)) {
                continue;
            }
            let covered = revoke_all_ns
                || existing
                    .namespaces
                    .iter()
                    .all(|n| revoke.namespaces.contains(n));
            if !covered {
                return Err(AreevError::Validation(format!(
                    "grant {obj:?} for {principal} spans more namespaces than the \
                     revoke — revoke at the grant's own scope"
                )));
            }
            let remaining: Vec<_> = existing
                .verbs
                .iter()
                .copied()
                .filter(|v| !revoke.verbs.contains(v))
                .collect();
            let object = if remaining.is_empty() {
                // Nothing left: a retraction record. `authz_grants` skips it
                // (it is not a parseable grant), so it conveys no rights —
                // and the history stays append-only.
                "revoked".to_string()
            } else {
                areev_core::authz::Grant {
                    verbs: remaining,
                    namespaces: existing.namespaces.clone(),
                }
                .to_object_string()
            };
            let mut replacement = areev_core::types::Fact::new(
                principal,
                areev_core::authz::REL_PERMITS,
                &object,
            )
            .namespace(areev_core::authz::AUTHZ_NS)
            .created_at(now_epoch_ms());
            replacement.common.context = Some(serde_json::json!({
                "grantor": self.session_principal(),
                "because": because.unwrap_or(""),
                "revoked": revoke.to_object_string(),
            }));
            m.supersede(&g.hash, &mut replacement)?;
            touched += 1;
        }
        Ok(touched)
    }

    /// `SHOW GRANTS` — the live grant rows. Reading the authz namespace
    /// requires `read` on it (or the owner session).
    fn cal_show_grants(&self, principal: Option<&str>) -> Result<Vec<crate::facade::GrantRow>> {
        self.check_verb(Verb::Read, areev_core::authz::AUTHZ_NS)?;
        let mut m = self.store.lock().unwrap();
        let grains = match principal {
            Some(p) => m.recall(
                areev_core::authz::AUTHZ_NS,
                p,
                Some(areev_core::authz::REL_PERMITS),
                256,
            )?,
            None => m.recent(
                areev_core::authz::AUTHZ_NS,
                Some(areev_core::types::GrainType::Fact),
                1000,
            )?,
        };
        let mut rows = Vec::new();
        for g in &grains {
            if g.get_str("relation") != Some(areev_core::authz::REL_PERMITS) {
                continue;
            }
            let (Some(subject), Some(obj)) = (g.get_str("subject"), g.get_str("object")) else {
                continue;
            };
            // Only parseable grants convey rights; retraction records and
            // junk are history, not ACL.
            if areev_core::authz::Grant::from_object_string(obj).is_err() {
                continue;
            }
            rows.push(crate::facade::GrantRow {
                principal: subject.to_string(),
                object: obj.to_string(),
                hash: g.hash.to_hex(),
            });
        }
        Ok(rows)
    }

    /// `FORGET SUBJECT` — identity-scoped erasure in the session namespace
    /// (CAL 1.3 §8.14): every grain referencing the identity, its partition
    /// keys, history, and dictionary entries; `text_mentions` extends it to
    /// indexed-text mentions. Authorized by `erase` on that namespace.
    fn cal_forget_user(
        &self,
        user_id: &str,
        text_mentions: bool,
        because: &str,
    ) -> Result<crate::store_types::ErasureProof> {
        let ns = self.default_ns().unwrap_or_else(|| "shared".to_string());
        self.check_verb(Verb::Erase, &ns)?;
        let fp = areev_core::authz::subject_fingerprint(user_id);
        // Bind the outcome so the MutexGuard drops HERE — see `cal_delete`:
        // a `match` holds its scrutinee's temporaries across every arm, so the
        // refusal arm's `audit_hold_refusal` deadlocked on the same lock.
        let outcome = self.store.lock().unwrap().forget_subject_with(
            &ns,
            user_id,
            areev_store::ErasureOptions { text_mentions },
        );
        let report = match outcome {
            Ok(r) => r,
            Err(e) => {
                if e.code() == "STO-E009" {
                    // #278: the subject stays a FINGERPRINT even in a
                    // refusal — an immutable, replicating grain naming the
                    // subject would undo the erasure it records
                    // (REQ-ERASE-5).
                    self.audit_hold_refusal(
                        "erase",
                        &format!("subject:{fp} ns:{ns}"),
                        &e.to_string(),
                    );
                }
                return Err(e);
            }
        };
        let stale_exports = self
            .store
            .lock()
            .unwrap()
            .corpus_exports_touching_subject(user_id)
            .unwrap_or_default();
        // The audit target carries a FINGERPRINT, never the identity: an
        // immutable, replicating audit grain naming the erased subject
        // would put the reference straight back into the file (and every
        // bundle and archive made from it). See
        // `areev_core::authz::subject_fingerprint`.
        self.audit_tier2(
            "erase",
            &format!(
                "subject:{} ns:{ns}",
                areev_core::authz::subject_fingerprint(user_id)
            ),
            Some(because),
            report.grains_erased,
            &stale_exports,
        )?;
        Ok(crate::store_types::ErasureProof {
            user_id: user_id.to_string(),
            count: report.grains_erased as u64,
            // Tombstone + index erasure, not key destruction — there is no
            // key fingerprint to report on this path.
            key_fingerprint: String::new(),
            timestamp: now_epoch_ms(),
            user_record_deleted: report.grains_erased > 0,
        })
    }

    /// `FORGET SUBJECT "<id>" WITH override_hold BECAUSE "…"` (#278).
    fn cal_forget_user_overriding(
        &self,
        user_id: &str,
        text_mentions: bool,
        because: &str,
    ) -> Result<crate::store_types::ErasureProof> {
        let ns = self.default_ns().unwrap_or_else(|| "shared".to_string());
        self.check_verb(Verb::Erase, &ns)?;
        if !self.session_is_owner() {
            self.check_verb(Verb::Admin, &ns)?;
        }
        let over = areev_store::HoldOverride::new(self.session_principal(), because)?;
        let (report, overridden) = self.store.lock().unwrap().forget_subject_overriding(
            &ns,
            user_id,
            areev_store::ErasureOptions { text_mentions },
            &over,
        )?;
        let target = format!(
            "subject:{} ns:{ns}",
            areev_core::authz::subject_fingerprint(user_id)
        );
        match overridden {
            Some(hold) => {
                self.audit_hold_override("erase", &target, because, report.grains_erased, &hold)?
            }
            None => self.audit_tier2("erase", &target, Some(because), report.grains_erased, &[])?,
        }
        Ok(crate::store_types::ErasureProof {
            user_id: user_id.to_string(),
            count: report.grains_erased as u64,
            key_fingerprint: String::new(),
            timestamp: now_epoch_ms(),
            user_record_deleted: report.grains_erased > 0,
        })
    }

    /// `REPORT SUBJECT` — the read-only DSAR selection (OMS 1.6 draft):
    /// the SAME selector `cal_forget_user` erases with, hydrated instead.
    /// Session-namespace-scoped like the erasure form; authorized by
    /// `read` — it is a pure read and writes no audit grain (the audit
    /// obligation is on destruction, not access).
    fn cal_subject_report(
        &self,
        subject_id: &str,
        text_mentions: bool,
    ) -> Result<crate::store_types::SubjectReportResult> {
        let ns = self.default_ns().unwrap_or_else(|| "shared".to_string());
        self.check_verb(Verb::Read, &ns)?;
        let report = self.store.lock().unwrap().subject_report_with(
            &ns,
            subject_id,
            areev_store::ErasureOptions { text_mentions },
        )?;
        Ok(crate::store_types::SubjectReportResult {
            identity_names: report.identity_names,
            grains: report.grains.iter().map(grain_json).collect(),
        })
    }

    /// `PURGE OLDER THAN` — the retention sweep (CAL 1.3 §8.14), scoped to
    /// one namespace (the statement's `IN`, else the session's, else
    /// "shared" — never an implicit all-namespace sweep from CAL).
    /// Authorized by `erase` on that namespace.
    fn cal_purge_stale(
        &self,
        min_age_days: f64,
        namespace: Option<&str>,
        batch_limit: usize,
        grain_type: Option<&str>,
        because: &str,
    ) -> Result<usize> {
        let ns = namespace
            .or(self.namespace.as_deref())
            .unwrap_or("shared")
            .to_string();
        self.check_verb(Verb::Erase, &ns)?;
        let gtype = match grain_type {
            None => None,
            Some(t) => Some(areev_core::types::GrainType::from_str(t).ok_or_else(|| {
                AreevError::Validation(format!("unknown grain type for PURGE: {t:?}"))
            })?),
        };
        let cutoff_ms = now_epoch_ms() - (min_age_days * 86_400_000.0) as i64;
        // `LIMIT n` bounds the sweep to the oldest n matches — the operator
        // asked for a reviewable batch, not the namespace.
        let exports = self.store.lock().unwrap().corpus_exports().unwrap_or_default();
        let report = self.store.lock().unwrap().forget_older_than_capped(
            Some(&ns),
            cutoff_ms,
            gtype,
            Some(batch_limit),
        )?;
        let stale_exports =
            areev_store::exports_touching_hashes(&exports, &report.erased_hashes);
        self.audit_tier2(
            "erase",
            &format!(
                "older_than:{min_age_days}d ns:{ns}{}",
                grain_type.map(|t| format!(" type:{t}")).unwrap_or_default()
            ),
            Some(because),
            report.grains_erased,
            &stale_exports,
        )?;
        Ok(report.grains_erased)
    }
}

/// Validate DCL parts into a canonical [`areev_core::authz::Grant`]: every
/// verb must be in the verb registry, the principal non-empty, namespaces
/// non-empty strings. Fail-closed — one bad part refuses the whole
/// statement.
fn parse_grant_parts(
    principal: &str,
    verbs: &[String],
    namespaces: &[String],
) -> Result<areev_core::authz::Grant> {
    if principal.trim().is_empty() {
        return Err(AreevError::Validation("empty principal".into()));
    }
    if verbs.is_empty() {
        return Err(AreevError::Validation("no verbs named".into()));
    }
    let mut parsed = Vec::new();
    for v in verbs {
        let v = areev_core::authz::Verb::parse(v)?;
        if !parsed.contains(&v) {
            parsed.push(v);
        }
    }
    let namespaces: Vec<String> = if namespaces.is_empty() {
        vec!["*".to_string()]
    } else {
        namespaces.to_vec()
    };
    for n in &namespaces {
        if n.trim().is_empty() {
            return Err(AreevError::Validation("empty namespace".into()));
        }
        // Grants match namespaces EXACTLY (or `*` for all) — a prefix
        // pattern here would silently grant nothing today and a family
        // tomorrow, so `"org.*"` refuses with the rule spelled out rather
        // than becoming a grant on a namespace literally named "org.*".
        if n != "*" && NsScope::is_pattern(n) {
            return Err(AreevError::Validation(format!(
                "grants take exact namespaces or `*` (got {n:?}): prefix patterns are a \
                 recall scope, not a grant scope — grant each namespace, or `*`"
            )));
        }
    }
    Ok(areev_core::authz::Grant { verbs: parsed, namespaces })
}

/// The grain-as-JSON shape shared by the Wave-2 reads:
/// `{hash, type, fields}` — the same shape the MCP tools speak.
fn grain_json(g: &DeserializedGrain) -> serde_json::Value {
    serde_json::json!({
        "hash": g.hash.to_hex(),
        "type": g.grain_type.as_str(),
        "fields": g.fields.clone().into_iter().collect::<serde_json::Map<_, _>>(),
    })
}

/// Wall-clock epoch ms for audit stamps and PURGE cutoffs — host-side time,
/// deliberately outside the executor (which stays clock-free).
fn now_epoch_ms() -> i64 {
    std::time::SystemTime::now()
        .duration_since(std::time::UNIX_EPOCH)
        .map(|d| d.as_millis() as i64)
        .unwrap_or(0)
}

/// What [`AreevFacade::set_grants`] did (#309).
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, serde::Serialize)]
pub struct GrantChange {
    /// Grants that did not exist before.
    pub added: usize,
    /// Live heads rewritten in place into a desired grant.
    pub superseded: usize,
    /// Live heads retired with a `"revoked"` retraction record.
    pub retired: usize,
}

impl GrantChange {
    /// Whether anything was written. An equal set writes nothing.
    pub fn is_empty(&self) -> bool {
        self.added == 0 && self.superseded == 0 && self.retired == 0
    }
}

/// A [`PrincipalSession`] IS a CAL facade (#302).
///
/// `CalExecutor::execute(cal, &session)` therefore runs ANY statement — read
/// or write — under the session's own fail-closed rights, instead of only
/// its writes. Every method installs the session for the duration of the
/// call and delegates to the facade, so there is ONE validation path and a
/// method added to the facade later cannot silently keep reading the shared
/// slot: it would not compile here without a delegation.
///
/// `bind_principal` stays for hosts that serialize requests.
impl crate::facade::CalStoreFacade for PrincipalSession<'_> {
    fn recall(&self, params: &RecallParams) -> Result<Vec<SearchHit>> {
        let _scope = self.enter();
        self.facade.recall(params)
    }
    fn exists(&self, hash: &Hash) -> Result<bool> {
        let _scope = self.enter();
        self.facade.exists(hash)
    }
    fn get(&self, hash: &Hash) -> Result<DeserializedGrain> {
        let _scope = self.enter();
        self.facade.get(hash)
    }
    fn count(&self) -> Result<usize> {
        let _scope = self.enter();
        self.facade.count()
    }
    fn get_history(&self, namespace: &str, subject: &str, relation: &str,) -> Result<Vec<VersionEntry>> {
        let _scope = self.enter();
        self.facade.get_history(namespace, subject, relation)
    }
    /// The SESSION's namespace when it set one, else the facade's — so a
    /// host serving several people can point each caller's namespace-
    /// defaulting reads at the namespace they work in (#302).
    fn default_namespace(&self) -> Option<&str> {
        self.namespace.as_deref().or(self.facade.default_namespace())
    }
    fn active_user(&self) -> Option<&str> {
        let _scope = self.enter();
        self.facade.active_user()
    }
    fn cal_add(&self, grain_type: &str, fields: &serde_json::Map<String, serde_json::Value>,) -> Result<Hash> {
        let _scope = self.enter();
        self.facade.cal_add(grain_type, fields)
    }
    fn cal_add_with_options(&self, grain_type: &str, fields: &serde_json::Map<String, serde_json::Value>, options: crate::store_types::AddOptions,) -> Result<crate::store_types::AddResult> {
        let _scope = self.enter();
        self.facade.cal_add_with_options(grain_type, fields, options)
    }
    fn cal_supersede(&self, old_hash: &Hash, grain_type: &str, fields: &serde_json::Map<String, serde_json::Value>,) -> Result<Hash> {
        let _scope = self.enter();
        self.facade.cal_supersede(old_hash, grain_type, fields)
    }
    fn cal_accumulate(&self, grain_type: &str, target: &super::ast::AccumulateTarget, add_ops: &[(String, f64)], set_ops: &serde_json::Map<String, serde_json::Value>, reason: &str,) -> Result<AccumulateResult> {
        let _scope = self.enter();
        self.facade.cal_accumulate(grain_type, target, add_ops, set_ops, reason)
    }
    fn describe_capabilities(&self) -> CalCapabilities {
        let _scope = self.enter();
        self.facade.describe_capabilities()
    }
    fn describe_grain_types(&self) -> Vec<GrainTypeInfo> {
        let _scope = self.enter();
        self.facade.describe_grain_types()
    }
    fn describe_fields(&self, _grain_type: Option<areev_core::types::GrainType>) -> Vec<FieldInfo> {
        let _scope = self.enter();
        self.facade.describe_fields(_grain_type)
    }
    fn note_assembly_budget(&self, overflow: bool) {
        let _scope = self.enter();
        self.facade.note_assembly_budget(overflow)
    }
    fn anon_egress_report(&self) -> Option<serde_json::Value> {
        let _scope = self.enter();
        self.facade.anon_egress_report()
    }
    fn note_assembly_manifest(&self, manifest: &AssemblyManifest) {
        let _scope = self.enter();
        self.facade.note_assembly_manifest(manifest)
    }
    fn define_template(
        &self,
        name: &str,
        source: &str,
        description: Option<&str>,
        parent: Option<&str>,
        grain_types: &[String],
    ) -> Result<()> {
        let _scope = self.enter();
        self.facade
            .define_template(name, source, description, parent, grain_types)
    }
    fn drop_template(&self, _name: &str) -> Result<()> {
        let _scope = self.enter();
        self.facade.drop_template(_name)
    }
    fn open_forks(&self) -> Result<Vec<ForkGroupInfo>> {
        let _scope = self.enter();
        self.facade.open_forks()
    }
    fn rerank_passages(&self, _query: &str, _passages: &[&str], _rerank_type: RerankType, _model: Option<&str>, _user_id: Option<&str>,) -> Result<Vec<usize>> {
        let _scope = self.enter();
        self.facade.rerank_passages(_query, _passages, _rerank_type, _model, _user_id)
    }
    fn cal_delete(&self, _hash: &Hash, _because: Option<&str>) -> Result<()> {
        let _scope = self.enter();
        self.facade.cal_delete(_hash, _because)
    }
    fn cal_delete_overriding(&self, hash: &Hash, because: &str) -> Result<()> {
        let _scope = self.enter();
        self.facade.cal_delete_overriding(hash, because)
    }
    fn cal_forget_user_overriding(
        &self,
        user_id: &str,
        text_mentions: bool,
        because: &str,
    ) -> Result<crate::store_types::ErasureProof> {
        let _scope = self.enter();
        self.facade
            .cal_forget_user_overriding(user_id, text_mentions, because)
    }
    fn cal_forget_user(&self, _user_id: &str, _text_mentions: bool, _because: &str,) -> Result<crate::store_types::ErasureProof> {
        let _scope = self.enter();
        self.facade.cal_forget_user(_user_id, _text_mentions, _because)
    }
    fn cal_forget_scope(&self, scope: &str) -> Result<crate::store_types::ErasureProof> {
        let _guard = self.enter();
        self.facade.cal_forget_scope(scope)
    }
    fn cal_subject_report(&self, _subject_id: &str, _text_mentions: bool,) -> Result<crate::store_types::SubjectReportResult> {
        let _scope = self.enter();
        self.facade.cal_subject_report(_subject_id, _text_mentions)
    }
    fn as_any(&self) -> Option<&dyn std::any::Any> {
        // Deliberately None: a downcast to `AreevFacade` would hand the
        // caller the UNSCOPED facade and let it read past this session's
        // grants — which is the whole thing this type exists to prevent.
        None
    }
    fn cal_merge(&self, _subject: &str, _relation: &str, _object: &str, _confidence: f64, _because: &str,) -> Result<Hash> {
        let _scope = self.enter();
        self.facade.cal_merge(_subject, _relation, _object, _confidence, _because)
    }
    fn cal_related_scoped(
        &self,
        namespaces: &[String],
        start: &str,
        relations: &[&str],
        direction: &str,
        depth: usize,
        limit: usize,
    ) -> Result<Vec<String>> {
        let _scope = self.enter();
        self.facade
            .cal_related_scoped(namespaces, start, relations, direction, depth, limit)
    }
    fn cal_entity_at_scoped(
        &self,
        namespaces: &[String],
        subject: &str,
        relation: &str,
        at_ms: i64,
        axis: &str,
    ) -> Result<Vec<(String, serde_json::Value)>> {
        let _scope = self.enter();
        self.facade
            .cal_entity_at_scoped(namespaces, subject, relation, at_ms, axis)
    }
    fn cal_related(&self, _start: &str, _relations: &[&str], _direction: &str, _depth: usize, _limit: usize,) -> Result<Vec<String>> {
        let _scope = self.enter();
        self.facade.cal_related(_start, _relations, _direction, _depth, _limit)
    }
    fn cal_novelty(&self, _text: &str, _subject: Option<&str>, _relation: Option<&str>, _k: usize,) -> Result<Vec<(String, f64)>> {
        let _scope = self.enter();
        self.facade.cal_novelty(_text, _subject, _relation, _k)
    }
    fn cal_entity_at(&self, _subject: &str, _relation: &str, _at_ms: i64, _axis: &str,) -> Result<Option<serde_json::Value>> {
        let _scope = self.enter();
        self.facade.cal_entity_at(_subject, _relation, _at_ms, _axis)
    }
    fn cal_run_trace(&self, _run_id: &str, _limit: usize) -> Result<serde_json::Value> {
        let _scope = self.enter();
        self.facade.cal_run_trace(_run_id, _limit)
    }
    fn cal_runs_touching(&self, _hash: &Hash, _depth: usize) -> Result<Vec<String>> {
        let _scope = self.enter();
        self.facade.cal_runs_touching(_hash, _depth)
    }
    fn cal_derived_from(&self, _hash: &Hash) -> Result<Vec<serde_json::Value>> {
        let _scope = self.enter();
        self.facade.cal_derived_from(_hash)
    }
    fn cal_stats(&self) -> Result<serde_json::Value> {
        let _scope = self.enter();
        self.facade.cal_stats()
    }
    fn cal_verify(&self) -> Result<serde_json::Value> {
        let _scope = self.enter();
        self.facade.cal_verify()
    }
    fn cal_remember(&self, _content: &str, _session_id: Option<&str>, _role: Option<&str>, _run_id: Option<&str>,) -> Result<Hash> {
        let _scope = self.enter();
        self.facade.cal_remember(_content, _session_id, _role, _run_id)
    }
    fn cal_grant(&self, _principal: &str, _verbs: &[String], _namespaces: &[String], _because: Option<&str>,) -> Result<Hash> {
        let _scope = self.enter();
        self.facade.cal_grant(_principal, _verbs, _namespaces, _because)
    }
    fn cal_revoke(&self, _principal: &str, _verbs: &[String], _namespaces: &[String], _because: Option<&str>,) -> Result<usize> {
        let _scope = self.enter();
        self.facade.cal_revoke(_principal, _verbs, _namespaces, _because)
    }
    fn cal_show_grants(&self, _principal: Option<&str>) -> Result<Vec<GrantRow>> {
        let _scope = self.enter();
        self.facade.cal_show_grants(_principal)
    }
    fn cal_purge_stale(&self, _min_age_days: f64, _namespace: Option<&str>, _batch_limit: usize, _grain_type: Option<&str>, _because: &str,) -> Result<usize> {
        let _scope = self.enter();
        self.facade.cal_purge_stale(_min_age_days, _namespace, _batch_limit, _grain_type, _because)
    }
    fn list_templates(&self) -> Vec<TemplateInfo> {
        let _scope = self.enter();
        self.facade.list_templates()
    }
    fn get_template(&self, _name: &str) -> Option<TemplateInfo> {
        let _scope = self.enter();
        self.facade.get_template(_name)
    }
    fn record_template_run(&self, name: &str) {
        let _scope = self.enter();
        self.facade.record_template_run(name)
    }
    fn define_query(
        &self,
        name: &str,
        body: &str,
        description: Option<&str>,
        params: &[crate::ast::QueryParam],
    ) -> Result<()> {
        let _scope = self.enter();
        self.facade.define_query(name, body, description, params)
    }
    fn drop_query(&self, _name: &str) -> Result<()> {
        let _scope = self.enter();
        self.facade.drop_query(_name)
    }
    fn list_queries(&self) -> Vec<crate::queries::QueryListEntry> {
        let _scope = self.enter();
        self.facade.list_queries()
    }
    fn get_query(&self, _name: &str) -> Option<crate::queries::QueryEntry> {
        let _scope = self.enter();
        self.facade.get_query(_name)
    }
    fn update_query_last_run(&self, _name: &str) -> Result<()> {
        let _scope = self.enter();
        self.facade.update_query_last_run(_name)
    }
}