areev 1.10.0

Command-line interface for Areev, the embedded memory engine for AI agents.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135
3136
3137
3138
3139
3140
3141
3142
3143
3144
3145
3146
3147
3148
3149
3150
3151
3152
3153
3154
3155
3156
3157
3158
3159
3160
3161
3162
3163
3164
3165
3166
3167
3168
3169
3170
3171
3172
3173
3174
3175
3176
3177
3178
3179
3180
3181
3182
3183
3184
3185
3186
3187
3188
3189
3190
3191
3192
3193
3194
3195
3196
3197
3198
3199
3200
3201
3202
3203
3204
3205
3206
3207
3208
3209
3210
3211
3212
3213
3214
3215
3216
3217
3218
3219
3220
3221
3222
3223
3224
3225
3226
3227
3228
3229
3230
3231
3232
3233
3234
3235
3236
3237
3238
3239
3240
3241
3242
3243
3244
3245
3246
3247
3248
3249
3250
3251
3252
3253
3254
3255
3256
3257
3258
3259
3260
3261
3262
3263
3264
3265
3266
3267
3268
3269
3270
3271
3272
3273
3274
3275
3276
3277
3278
3279
3280
3281
3282
3283
3284
3285
3286
3287
3288
3289
3290
3291
3292
3293
3294
3295
3296
3297
3298
3299
3300
3301
3302
3303
3304
3305
3306
3307
3308
3309
3310
3311
3312
3313
3314
3315
3316
3317
3318
3319
3320
3321
3322
3323
3324
3325
3326
3327
3328
3329
3330
3331
3332
3333
3334
3335
3336
3337
3338
3339
3340
3341
3342
3343
3344
3345
3346
3347
3348
3349
3350
3351
3352
3353
3354
3355
3356
3357
3358
3359
3360
3361
3362
3363
3364
3365
3366
3367
3368
3369
3370
3371
3372
3373
3374
3375
3376
3377
3378
3379
3380
3381
3382
3383
3384
3385
3386
3387
3388
3389
3390
3391
3392
3393
3394
3395
3396
3397
3398
3399
3400
3401
3402
3403
3404
3405
3406
3407
3408
3409
3410
3411
3412
3413
3414
3415
3416
3417
3418
3419
3420
3421
3422
3423
3424
3425
3426
3427
3428
3429
3430
3431
3432
3433
3434
3435
3436
3437
3438
3439
3440
3441
3442
3443
3444
3445
3446
3447
3448
3449
3450
3451
3452
3453
3454
3455
3456
3457
3458
3459
3460
3461
3462
3463
3464
3465
3466
3467
3468
3469
3470
3471
3472
3473
3474
3475
3476
3477
3478
3479
3480
3481
3482
3483
3484
3485
3486
3487
3488
3489
3490
3491
3492
3493
3494
3495
3496
3497
3498
3499
3500
3501
3502
3503
3504
3505
3506
3507
3508
3509
3510
3511
3512
3513
3514
3515
3516
3517
3518
3519
3520
3521
3522
3523
3524
3525
3526
3527
3528
3529
3530
3531
3532
3533
3534
3535
3536
3537
3538
3539
3540
3541
3542
3543
3544
3545
3546
3547
3548
3549
3550
3551
3552
3553
3554
3555
3556
3557
3558
3559
3560
3561
3562
3563
3564
3565
3566
3567
3568
3569
3570
3571
3572
3573
3574
3575
3576
3577
3578
3579
3580
3581
3582
3583
3584
3585
3586
3587
3588
3589
3590
3591
3592
3593
3594
3595
3596
3597
3598
3599
3600
3601
3602
3603
3604
3605
3606
3607
3608
3609
3610
3611
3612
3613
3614
3615
3616
3617
3618
3619
3620
3621
3622
3623
3624
3625
3626
3627
3628
3629
3630
3631
3632
3633
3634
3635
3636
3637
3638
3639
3640
3641
3642
3643
3644
3645
3646
3647
3648
3649
3650
3651
3652
3653
3654
3655
3656
3657
3658
3659
3660
3661
3662
3663
3664
3665
3666
3667
3668
3669
3670
3671
3672
3673
3674
3675
3676
3677
3678
3679
3680
3681
3682
3683
3684
3685
3686
3687
3688
3689
3690
3691
3692
3693
3694
3695
3696
3697
3698
3699
3700
3701
3702
3703
3704
3705
3706
3707
3708
3709
3710
3711
3712
3713
3714
3715
3716
3717
3718
3719
3720
3721
3722
3723
3724
3725
3726
3727
3728
3729
3730
3731
3732
3733
3734
3735
3736
3737
3738
3739
3740
3741
3742
3743
3744
3745
3746
3747
3748
3749
3750
3751
3752
3753
3754
3755
3756
3757
3758
3759
3760
3761
3762
3763
3764
3765
3766
3767
3768
3769
3770
3771
3772
3773
3774
3775
3776
3777
3778
3779
3780
3781
3782
3783
3784
3785
3786
3787
3788
3789
3790
3791
3792
3793
3794
3795
3796
3797
3798
3799
3800
3801
3802
3803
3804
3805
3806
3807
3808
3809
3810
3811
3812
3813
3814
3815
3816
3817
3818
3819
3820
3821
3822
3823
3824
3825
3826
3827
3828
3829
3830
3831
3832
3833
3834
3835
3836
3837
3838
3839
3840
3841
3842
3843
3844
3845
3846
3847
3848
3849
3850
3851
3852
3853
3854
3855
3856
3857
3858
3859
3860
3861
3862
3863
3864
3865
3866
3867
3868
3869
3870
3871
3872
3873
3874
3875
3876
3877
3878
3879
3880
3881
3882
3883
3884
3885
3886
3887
3888
3889
3890
3891
3892
3893
3894
3895
3896
3897
3898
3899
3900
3901
3902
3903
3904
3905
3906
3907
3908
3909
3910
3911
3912
3913
3914
3915
3916
3917
3918
3919
3920
3921
3922
3923
3924
3925
3926
3927
3928
3929
3930
3931
3932
3933
3934
3935
3936
3937
3938
3939
3940
3941
3942
3943
3944
3945
3946
3947
3948
3949
3950
3951
3952
3953
3954
3955
3956
3957
3958
3959
3960
3961
3962
3963
3964
3965
3966
3967
3968
3969
3970
3971
3972
3973
3974
3975
3976
3977
3978
3979
3980
3981
3982
3983
3984
3985
3986
3987
3988
3989
3990
3991
3992
3993
3994
3995
3996
3997
3998
3999
4000
4001
4002
4003
4004
4005
4006
4007
4008
4009
4010
4011
4012
4013
4014
4015
4016
4017
4018
4019
4020
4021
4022
4023
4024
4025
4026
4027
4028
4029
4030
4031
4032
4033
4034
4035
4036
4037
4038
4039
4040
4041
4042
4043
4044
4045
4046
4047
4048
4049
4050
4051
4052
4053
4054
4055
4056
4057
4058
4059
4060
4061
4062
4063
4064
4065
4066
4067
4068
4069
4070
4071
4072
4073
4074
4075
4076
4077
4078
4079
4080
4081
4082
4083
4084
4085
4086
4087
4088
4089
4090
4091
4092
4093
4094
4095
4096
4097
4098
4099
4100
4101
4102
4103
4104
4105
4106
4107
4108
4109
4110
4111
4112
4113
4114
4115
4116
4117
4118
4119
4120
4121
4122
4123
4124
4125
4126
4127
4128
4129
4130
4131
4132
4133
4134
4135
4136
4137
4138
4139
4140
4141
4142
4143
4144
4145
4146
4147
4148
4149
4150
4151
4152
4153
4154
4155
4156
4157
4158
4159
4160
4161
4162
4163
4164
4165
4166
4167
4168
4169
4170
4171
4172
4173
4174
4175
4176
4177
4178
4179
4180
4181
4182
4183
4184
4185
4186
4187
4188
4189
4190
4191
4192
4193
4194
4195
4196
4197
4198
4199
4200
4201
4202
4203
4204
4205
4206
4207
4208
4209
4210
4211
4212
4213
4214
4215
4216
4217
4218
4219
4220
4221
4222
4223
4224
4225
4226
4227
4228
4229
4230
4231
4232
4233
4234
4235
4236
4237
4238
4239
4240
4241
4242
4243
4244
4245
4246
4247
4248
4249
4250
4251
4252
4253
4254
4255
4256
4257
4258
4259
4260
4261
4262
4263
4264
4265
4266
4267
4268
4269
4270
4271
4272
4273
4274
4275
4276
4277
4278
4279
4280
4281
4282
4283
4284
4285
4286
4287
4288
4289
4290
4291
4292
4293
4294
4295
4296
4297
4298
4299
4300
4301
4302
4303
4304
4305
4306
4307
4308
4309
4310
4311
4312
4313
4314
4315
4316
4317
4318
4319
4320
4321
4322
4323
4324
4325
4326
4327
4328
4329
4330
4331
4332
4333
4334
4335
4336
4337
4338
4339
4340
4341
4342
4343
4344
4345
4346
4347
4348
4349
4350
4351
4352
4353
4354
4355
4356
4357
4358
4359
4360
4361
4362
4363
4364
4365
4366
4367
4368
4369
4370
4371
4372
4373
4374
4375
4376
4377
4378
4379
4380
4381
4382
4383
4384
4385
4386
4387
4388
4389
4390
4391
4392
4393
4394
4395
4396
4397
4398
4399
4400
4401
4402
4403
4404
4405
4406
4407
4408
4409
4410
4411
4412
4413
4414
4415
4416
4417
4418
4419
4420
4421
4422
4423
4424
4425
4426
4427
4428
4429
4430
4431
4432
4433
4434
4435
4436
4437
4438
4439
4440
4441
4442
4443
4444
4445
4446
4447
4448
4449
4450
4451
4452
4453
4454
4455
4456
4457
4458
4459
4460
4461
4462
4463
4464
4465
4466
4467
4468
4469
4470
4471
4472
4473
4474
4475
4476
4477
4478
4479
4480
4481
4482
4483
4484
4485
4486
4487
4488
4489
4490
4491
4492
4493
4494
4495
4496
4497
4498
4499
4500
4501
4502
4503
4504
4505
4506
4507
4508
4509
4510
4511
4512
4513
4514
4515
4516
4517
4518
4519
4520
4521
4522
4523
4524
4525
4526
4527
4528
4529
4530
4531
4532
4533
4534
4535
4536
4537
4538
4539
4540
4541
4542
4543
4544
4545
4546
4547
4548
4549
4550
4551
4552
4553
4554
4555
4556
4557
4558
4559
4560
4561
4562
4563
4564
4565
4566
4567
4568
4569
4570
4571
4572
4573
4574
4575
4576
4577
4578
4579
4580
4581
4582
4583
4584
4585
4586
4587
4588
4589
4590
4591
4592
4593
4594
4595
4596
4597
4598
4599
4600
4601
4602
4603
4604
4605
4606
4607
4608
4609
4610
4611
4612
4613
4614
4615
4616
4617
4618
4619
4620
4621
4622
4623
4624
4625
4626
4627
4628
4629
4630
4631
4632
4633
4634
4635
4636
4637
4638
4639
4640
4641
4642
4643
4644
4645
4646
4647
4648
4649
4650
4651
4652
4653
4654
4655
4656
4657
4658
4659
4660
4661
4662
4663
4664
4665
4666
4667
4668
4669
4670
4671
4672
4673
4674
4675
4676
4677
4678
4679
4680
4681
4682
4683
4684
4685
4686
4687
4688
4689
4690
4691
4692
4693
4694
4695
4696
4697
4698
4699
4700
4701
4702
4703
4704
4705
4706
4707
4708
4709
4710
4711
4712
4713
4714
4715
4716
4717
4718
4719
4720
4721
4722
4723
4724
4725
4726
4727
4728
4729
4730
4731
4732
4733
4734
4735
4736
4737
4738
4739
4740
4741
4742
4743
4744
4745
4746
4747
4748
4749
4750
4751
4752
4753
4754
4755
4756
4757
4758
4759
4760
4761
4762
4763
4764
4765
4766
4767
4768
4769
4770
4771
4772
4773
4774
4775
4776
4777
4778
4779
4780
4781
4782
4783
4784
4785
4786
4787
4788
4789
4790
4791
4792
4793
4794
4795
4796
4797
4798
4799
4800
4801
4802
4803
4804
4805
4806
4807
4808
4809
4810
4811
4812
4813
4814
4815
4816
4817
4818
4819
4820
4821
4822
4823
4824
4825
4826
4827
4828
4829
4830
4831
4832
4833
4834
4835
4836
4837
4838
4839
4840
4841
4842
4843
4844
4845
4846
4847
4848
4849
4850
4851
4852
4853
4854
4855
4856
4857
4858
4859
4860
4861
4862
4863
4864
4865
4866
4867
4868
4869
4870
4871
4872
4873
4874
4875
4876
4877
4878
4879
4880
4881
4882
4883
4884
4885
4886
4887
4888
4889
4890
4891
4892
4893
4894
4895
4896
4897
4898
4899
4900
4901
4902
4903
4904
4905
4906
4907
4908
4909
4910
4911
4912
4913
4914
4915
4916
4917
4918
4919
4920
4921
4922
4923
4924
4925
4926
4927
4928
4929
4930
4931
4932
4933
4934
4935
4936
4937
4938
4939
4940
4941
4942
4943
4944
4945
4946
4947
4948
4949
4950
4951
4952
4953
4954
4955
4956
4957
4958
4959
4960
4961
4962
4963
4964
4965
4966
4967
4968
4969
4970
4971
4972
4973
4974
4975
4976
4977
4978
4979
4980
4981
4982
4983
4984
4985
4986
4987
4988
4989
4990
4991
4992
4993
4994
4995
4996
4997
4998
4999
5000
5001
5002
5003
5004
5005
5006
5007
5008
5009
5010
5011
5012
5013
5014
5015
5016
5017
5018
5019
5020
5021
5022
5023
5024
5025
5026
5027
5028
5029
5030
5031
5032
5033
5034
5035
5036
5037
5038
5039
5040
5041
5042
5043
5044
5045
5046
5047
5048
5049
5050
5051
5052
5053
5054
5055
5056
5057
5058
5059
5060
5061
5062
5063
5064
5065
5066
5067
5068
5069
5070
5071
5072
5073
5074
5075
5076
5077
5078
5079
5080
5081
5082
5083
5084
5085
5086
5087
5088
5089
5090
5091
5092
5093
5094
5095
5096
5097
5098
5099
5100
5101
5102
5103
5104
5105
5106
5107
5108
5109
5110
5111
5112
5113
5114
5115
5116
5117
5118
5119
5120
5121
5122
5123
5124
5125
5126
5127
5128
5129
5130
5131
5132
5133
5134
5135
5136
5137
5138
5139
5140
5141
5142
5143
5144
5145
5146
5147
5148
5149
5150
5151
5152
5153
5154
5155
5156
5157
5158
5159
5160
5161
5162
5163
5164
5165
5166
5167
5168
5169
5170
5171
5172
5173
5174
5175
5176
5177
5178
5179
5180
5181
5182
5183
5184
5185
5186
5187
5188
5189
5190
5191
5192
5193
5194
5195
5196
5197
5198
5199
5200
5201
5202
5203
5204
5205
5206
5207
5208
5209
5210
5211
5212
5213
5214
5215
5216
5217
5218
5219
5220
5221
5222
5223
5224
5225
5226
5227
5228
5229
5230
5231
5232
5233
5234
5235
5236
5237
5238
5239
5240
5241
5242
5243
5244
5245
5246
5247
5248
5249
5250
5251
5252
5253
5254
5255
5256
5257
5258
5259
5260
5261
5262
5263
5264
5265
5266
5267
5268
5269
5270
5271
5272
5273
5274
5275
5276
5277
5278
5279
5280
5281
5282
5283
5284
5285
5286
5287
5288
5289
5290
5291
5292
5293
5294
5295
5296
5297
5298
5299
5300
5301
5302
5303
5304
5305
5306
5307
5308
5309
5310
5311
5312
5313
5314
5315
5316
5317
5318
5319
5320
5321
5322
5323
5324
5325
5326
5327
5328
5329
5330
5331
5332
5333
5334
5335
5336
5337
5338
5339
5340
5341
5342
5343
5344
5345
5346
5347
5348
5349
5350
5351
5352
5353
5354
5355
5356
5357
5358
5359
5360
5361
5362
5363
5364
5365
5366
5367
5368
5369
5370
5371
5372
5373
5374
5375
5376
5377
5378
5379
5380
5381
5382
5383
5384
5385
5386
5387
5388
5389
5390
5391
5392
5393
5394
5395
5396
5397
5398
5399
5400
5401
5402
5403
5404
5405
5406
5407
5408
5409
5410
5411
5412
5413
5414
5415
5416
5417
5418
5419
5420
5421
5422
5423
5424
5425
5426
5427
5428
5429
5430
5431
5432
5433
5434
5435
5436
5437
5438
5439
5440
5441
5442
5443
5444
5445
5446
5447
5448
5449
5450
5451
5452
5453
5454
5455
5456
5457
5458
5459
5460
5461
5462
5463
5464
5465
5466
5467
5468
5469
5470
5471
5472
5473
5474
5475
5476
5477
5478
5479
5480
5481
5482
5483
5484
5485
5486
5487
5488
5489
5490
5491
5492
5493
5494
5495
5496
5497
5498
5499
5500
5501
5502
5503
5504
5505
5506
5507
5508
5509
5510
5511
5512
5513
5514
5515
5516
5517
5518
5519
5520
5521
5522
5523
5524
5525
5526
5527
5528
5529
5530
5531
5532
5533
5534
5535
5536
5537
5538
5539
5540
5541
5542
5543
5544
5545
5546
5547
5548
5549
5550
5551
5552
5553
5554
5555
5556
5557
5558
5559
5560
5561
5562
5563
5564
5565
5566
5567
5568
5569
5570
5571
5572
5573
5574
5575
5576
5577
5578
5579
5580
5581
5582
5583
5584
5585
5586
5587
5588
5589
5590
5591
5592
5593
5594
5595
5596
5597
5598
5599
5600
5601
5602
5603
5604
5605
5606
5607
5608
5609
5610
5611
5612
5613
5614
5615
5616
5617
5618
5619
5620
5621
5622
5623
5624
5625
5626
5627
5628
5629
5630
5631
5632
5633
5634
5635
5636
5637
5638
5639
5640
5641
5642
5643
5644
5645
5646
5647
5648
5649
5650
5651
5652
5653
5654
5655
5656
5657
5658
5659
5660
5661
5662
5663
5664
5665
5666
5667
5668
5669
5670
5671
5672
5673
5674
5675
5676
5677
5678
5679
5680
5681
5682
5683
5684
5685
5686
5687
5688
5689
5690
5691
5692
5693
5694
5695
5696
5697
5698
5699
5700
5701
5702
5703
5704
5705
5706
5707
5708
5709
5710
5711
5712
5713
5714
5715
5716
5717
5718
5719
5720
5721
5722
5723
5724
5725
5726
5727
5728
5729
5730
5731
5732
5733
5734
5735
5736
5737
5738
5739
5740
5741
5742
5743
5744
5745
5746
5747
5748
5749
5750
5751
5752
5753
5754
5755
5756
5757
5758
5759
5760
5761
5762
5763
5764
5765
5766
5767
5768
5769
5770
5771
5772
5773
5774
5775
5776
5777
5778
5779
5780
5781
5782
5783
5784
5785
5786
5787
5788
5789
5790
5791
5792
5793
5794
5795
5796
5797
5798
5799
5800
5801
5802
5803
5804
5805
5806
5807
5808
5809
5810
5811
5812
5813
5814
5815
5816
5817
5818
5819
5820
5821
5822
5823
5824
5825
5826
5827
5828
5829
5830
5831
5832
5833
5834
5835
5836
5837
5838
5839
5840
5841
5842
5843
5844
5845
5846
5847
5848
5849
5850
5851
5852
5853
5854
5855
5856
5857
5858
5859
5860
5861
5862
5863
5864
5865
5866
5867
5868
5869
5870
5871
5872
5873
5874
5875
5876
5877
5878
5879
5880
5881
5882
5883
5884
5885
5886
5887
5888
5889
5890
5891
5892
5893
5894
5895
5896
5897
5898
5899
5900
5901
5902
5903
5904
5905
5906
5907
5908
5909
5910
5911
5912
5913
5914
5915
5916
5917
5918
5919
5920
5921
5922
5923
5924
5925
5926
5927
5928
5929
5930
5931
5932
5933
5934
5935
5936
5937
5938
5939
5940
5941
5942
5943
5944
5945
5946
5947
5948
5949
5950
5951
5952
5953
5954
5955
5956
5957
5958
5959
5960
5961
5962
5963
5964
5965
5966
5967
5968
5969
5970
5971
5972
5973
5974
5975
5976
5977
5978
5979
5980
5981
5982
5983
5984
5985
5986
5987
5988
5989
5990
5991
5992
5993
5994
5995
5996
5997
5998
5999
6000
6001
6002
6003
6004
6005
6006
6007
6008
6009
6010
6011
6012
6013
6014
6015
6016
6017
6018
6019
6020
6021
6022
6023
6024
6025
6026
6027
6028
6029
6030
6031
6032
6033
6034
6035
6036
6037
6038
6039
6040
6041
6042
6043
6044
6045
6046
6047
6048
6049
6050
6051
6052
6053
6054
6055
6056
6057
6058
6059
6060
6061
6062
6063
6064
6065
6066
6067
6068
6069
6070
6071
6072
6073
6074
6075
6076
6077
6078
6079
6080
6081
6082
6083
6084
6085
6086
6087
6088
6089
6090
6091
6092
6093
6094
6095
6096
6097
6098
6099
6100
6101
6102
6103
6104
6105
6106
6107
6108
6109
6110
6111
6112
6113
6114
6115
6116
6117
6118
6119
6120
6121
6122
6123
6124
6125
6126
6127
6128
6129
6130
6131
6132
6133
6134
6135
6136
6137
6138
6139
6140
6141
6142
6143
6144
6145
6146
6147
6148
6149
6150
6151
6152
6153
6154
6155
6156
6157
6158
6159
6160
6161
6162
6163
6164
6165
6166
6167
6168
6169
6170
6171
6172
6173
6174
6175
6176
6177
6178
6179
6180
6181
6182
6183
6184
6185
6186
6187
6188
6189
6190
6191
6192
6193
6194
6195
6196
6197
6198
6199
6200
6201
6202
6203
6204
6205
6206
6207
6208
6209
6210
6211
6212
6213
6214
6215
6216
6217
6218
6219
6220
6221
6222
6223
6224
6225
6226
6227
6228
6229
6230
6231
6232
6233
6234
6235
6236
6237
6238
6239
6240
6241
6242
6243
6244
6245
6246
6247
6248
6249
6250
6251
6252
6253
6254
6255
6256
6257
6258
6259
6260
6261
6262
6263
6264
6265
6266
6267
6268
6269
6270
6271
6272
6273
6274
6275
6276
6277
6278
6279
6280
6281
6282
6283
6284
6285
6286
6287
6288
6289
6290
6291
6292
6293
6294
6295
6296
6297
6298
6299
6300
6301
6302
6303
6304
6305
6306
6307
6308
6309
6310
6311
6312
6313
6314
6315
6316
6317
6318
6319
6320
6321
6322
6323
6324
6325
6326
6327
6328
6329
6330
6331
6332
6333
6334
6335
6336
6337
6338
6339
6340
6341
6342
6343
6344
6345
6346
6347
6348
6349
6350
6351
6352
6353
6354
6355
6356
6357
6358
6359
6360
6361
6362
6363
6364
6365
6366
6367
6368
6369
6370
6371
6372
6373
6374
6375
6376
6377
6378
6379
6380
6381
6382
6383
6384
6385
6386
6387
6388
6389
6390
6391
6392
6393
6394
6395
6396
6397
6398
6399
6400
6401
6402
6403
6404
6405
6406
6407
6408
6409
6410
6411
6412
6413
6414
6415
6416
6417
6418
6419
6420
6421
6422
6423
6424
6425
6426
6427
6428
6429
6430
6431
6432
6433
6434
6435
6436
6437
6438
6439
6440
6441
6442
6443
6444
6445
6446
6447
6448
6449
6450
6451
6452
6453
6454
6455
6456
6457
6458
6459
6460
6461
6462
6463
6464
6465
6466
6467
6468
6469
6470
6471
6472
6473
6474
6475
6476
6477
6478
6479
6480
6481
6482
6483
6484
6485
6486
6487
6488
6489
6490
6491
6492
6493
6494
6495
6496
6497
6498
6499
6500
6501
6502
6503
6504
6505
6506
6507
6508
6509
6510
6511
6512
6513
6514
6515
6516
6517
6518
6519
6520
6521
6522
6523
6524
6525
6526
6527
6528
6529
6530
6531
6532
6533
6534
6535
6536
6537
6538
6539
6540
6541
6542
6543
6544
6545
6546
6547
6548
6549
6550
6551
6552
6553
6554
6555
6556
6557
6558
6559
6560
6561
6562
6563
6564
6565
6566
6567
6568
6569
6570
6571
6572
6573
6574
6575
6576
6577
6578
6579
6580
6581
6582
6583
6584
6585
6586
6587
6588
6589
6590
6591
6592
6593
6594
6595
6596
6597
6598
6599
6600
6601
6602
6603
6604
6605
6606
6607
6608
6609
6610
6611
6612
6613
6614
6615
6616
6617
6618
6619
6620
6621
6622
6623
6624
6625
6626
6627
6628
6629
6630
6631
6632
6633
6634
6635
6636
6637
6638
6639
6640
6641
6642
6643
6644
6645
6646
6647
6648
6649
6650
6651
6652
6653
6654
6655
6656
6657
6658
6659
6660
6661
6662
6663
6664
6665
6666
6667
6668
6669
6670
6671
6672
6673
6674
6675
6676
6677
6678
6679
6680
6681
6682
6683
6684
6685
6686
6687
6688
6689
6690
6691
6692
6693
6694
6695
6696
6697
6698
6699
6700
6701
6702
6703
6704
6705
6706
6707
6708
6709
6710
6711
6712
6713
6714
6715
6716
6717
6718
6719
6720
6721
6722
6723
6724
6725
6726
6727
6728
6729
6730
6731
6732
6733
6734
6735
6736
6737
6738
6739
6740
6741
6742
6743
6744
6745
6746
6747
6748
6749
6750
6751
6752
6753
6754
6755
6756
6757
6758
6759
6760
6761
6762
6763
6764
6765
6766
6767
6768
6769
6770
6771
6772
6773
6774
6775
6776
6777
6778
6779
6780
6781
6782
6783
6784
6785
6786
6787
6788
6789
6790
6791
6792
6793
6794
6795
6796
6797
6798
6799
6800
6801
6802
6803
6804
6805
6806
6807
6808
6809
6810
6811
6812
6813
6814
6815
6816
6817
6818
6819
6820
6821
6822
6823
6824
6825
6826
6827
6828
6829
6830
6831
6832
6833
6834
6835
6836
6837
6838
6839
6840
6841
6842
6843
6844
6845
6846
6847
6848
6849
6850
6851
6852
6853
6854
6855
6856
6857
6858
6859
6860
6861
6862
6863
6864
6865
6866
6867
6868
6869
6870
6871
6872
6873
6874
6875
6876
6877
6878
6879
6880
6881
6882
6883
6884
6885
6886
6887
6888
6889
6890
6891
6892
6893
6894
6895
6896
6897
6898
6899
6900
6901
6902
6903
6904
6905
6906
6907
6908
6909
6910
6911
6912
6913
6914
6915
6916
6917
6918
6919
6920
6921
6922
6923
6924
6925
6926
6927
6928
6929
6930
6931
6932
6933
6934
6935
6936
6937
6938
6939
6940
6941
6942
6943
6944
6945
6946
6947
6948
6949
6950
6951
6952
6953
6954
6955
6956
6957
6958
6959
6960
6961
6962
6963
6964
6965
6966
6967
6968
6969
6970
6971
6972
6973
6974
6975
6976
6977
6978
6979
6980
6981
6982
6983
6984
6985
6986
6987
6988
6989
6990
6991
6992
6993
6994
6995
6996
6997
6998
6999
7000
7001
7002
7003
7004
7005
7006
7007
7008
7009
7010
7011
7012
7013
7014
7015
7016
7017
7018
7019
7020
7021
7022
7023
7024
7025
7026
7027
7028
7029
7030
7031
7032
7033
7034
7035
7036
7037
7038
7039
7040
7041
7042
7043
7044
7045
7046
7047
7048
7049
7050
7051
7052
7053
7054
7055
7056
7057
7058
7059
7060
7061
7062
7063
7064
7065
7066
7067
7068
7069
7070
7071
7072
7073
7074
7075
7076
7077
7078
7079
7080
7081
7082
7083
7084
7085
7086
7087
7088
7089
7090
7091
7092
7093
7094
7095
7096
7097
7098
7099
7100
7101
7102
7103
7104
7105
7106
7107
7108
7109
7110
7111
7112
7113
7114
7115
7116
7117
7118
7119
7120
7121
7122
7123
7124
7125
7126
7127
7128
7129
7130
7131
7132
7133
7134
7135
7136
7137
7138
7139
7140
7141
7142
7143
7144
7145
7146
7147
7148
7149
7150
7151
7152
7153
7154
7155
7156
7157
7158
7159
7160
7161
7162
7163
7164
7165
7166
7167
7168
7169
7170
7171
7172
7173
7174
7175
7176
7177
7178
7179
7180
7181
7182
7183
7184
7185
7186
7187
7188
7189
7190
7191
7192
7193
7194
7195
7196
7197
7198
7199
7200
7201
7202
7203
7204
7205
7206
7207
7208
7209
7210
7211
7212
7213
7214
7215
7216
7217
7218
7219
7220
7221
7222
7223
7224
7225
7226
7227
7228
7229
7230
7231
7232
7233
7234
7235
7236
7237
7238
7239
7240
7241
7242
7243
7244
7245
7246
7247
7248
7249
7250
7251
7252
7253
7254
7255
7256
7257
7258
7259
7260
7261
7262
7263
7264
7265
7266
7267
7268
7269
7270
7271
7272
7273
7274
7275
7276
7277
7278
7279
7280
7281
7282
7283
7284
7285
7286
7287
7288
7289
7290
7291
7292
7293
7294
7295
7296
7297
7298
7299
7300
7301
7302
7303
7304
7305
7306
7307
7308
7309
7310
7311
7312
7313
7314
7315
7316
7317
7318
7319
7320
7321
7322
7323
7324
7325
7326
7327
7328
7329
7330
7331
7332
7333
7334
7335
7336
7337
7338
7339
7340
7341
7342
7343
7344
7345
7346
7347
7348
7349
7350
7351
7352
7353
7354
7355
7356
7357
7358
7359
7360
7361
7362
7363
7364
7365
7366
7367
7368
7369
7370
7371
7372
7373
7374
7375
7376
7377
7378
7379
7380
7381
7382
7383
7384
7385
7386
7387
7388
7389
7390
7391
7392
7393
7394
7395
7396
7397
7398
7399
7400
7401
7402
7403
7404
7405
7406
7407
7408
7409
7410
7411
7412
7413
7414
7415
7416
7417
7418
7419
7420
7421
7422
7423
7424
7425
7426
7427
7428
7429
7430
7431
7432
7433
7434
7435
7436
7437
7438
7439
7440
7441
7442
7443
7444
7445
7446
7447
7448
7449
7450
7451
7452
7453
7454
7455
7456
7457
7458
7459
7460
7461
7462
7463
7464
7465
7466
7467
7468
7469
7470
7471
7472
7473
7474
7475
7476
7477
7478
7479
7480
7481
7482
7483
7484
7485
7486
7487
7488
7489
7490
7491
7492
7493
7494
7495
7496
7497
7498
7499
7500
7501
7502
7503
7504
7505
7506
7507
7508
7509
7510
7511
7512
7513
7514
7515
7516
7517
7518
7519
7520
7521
7522
7523
7524
7525
7526
7527
7528
7529
7530
7531
7532
7533
7534
7535
7536
7537
7538
7539
7540
7541
7542
7543
7544
7545
7546
7547
7548
7549
7550
7551
7552
7553
7554
7555
7556
7557
7558
7559
7560
7561
7562
7563
7564
7565
7566
7567
7568
7569
7570
7571
7572
7573
7574
7575
7576
7577
7578
7579
7580
7581
7582
7583
7584
7585
7586
7587
7588
7589
7590
7591
7592
7593
7594
7595
7596
7597
7598
7599
7600
7601
7602
7603
7604
7605
7606
7607
7608
7609
7610
7611
7612
7613
7614
7615
7616
7617
7618
7619
7620
7621
7622
7623
7624
7625
7626
7627
7628
7629
7630
7631
7632
7633
7634
7635
7636
7637
7638
7639
7640
7641
7642
7643
7644
7645
7646
7647
7648
7649
7650
7651
7652
7653
7654
7655
7656
7657
7658
7659
7660
7661
7662
7663
7664
7665
7666
7667
7668
7669
7670
7671
7672
7673
7674
7675
7676
7677
7678
7679
7680
7681
7682
7683
7684
7685
7686
7687
7688
7689
7690
7691
7692
7693
7694
7695
7696
7697
7698
7699
7700
7701
7702
7703
7704
7705
7706
7707
7708
7709
7710
7711
7712
7713
7714
7715
7716
7717
7718
7719
7720
7721
7722
7723
7724
7725
7726
7727
7728
7729
7730
7731
7732
7733
7734
7735
7736
7737
7738
7739
7740
7741
7742
7743
7744
7745
7746
7747
7748
7749
7750
7751
7752
7753
7754
7755
7756
7757
7758
7759
7760
7761
7762
7763
7764
7765
7766
7767
7768
7769
7770
7771
7772
7773
7774
7775
7776
7777
7778
7779
7780
7781
7782
7783
7784
7785
7786
7787
7788
7789
7790
7791
7792
7793
7794
7795
7796
7797
7798
7799
7800
7801
7802
7803
7804
7805
7806
7807
7808
7809
7810
7811
7812
7813
7814
7815
7816
7817
7818
7819
7820
7821
7822
7823
7824
7825
7826
7827
7828
7829
7830
7831
7832
7833
7834
7835
7836
7837
7838
7839
7840
7841
7842
7843
7844
7845
7846
7847
7848
7849
7850
7851
7852
7853
7854
7855
7856
7857
7858
7859
7860
7861
7862
7863
7864
7865
7866
7867
7868
7869
7870
7871
7872
7873
7874
7875
7876
7877
7878
7879
7880
7881
7882
7883
7884
7885
7886
7887
7888
7889
7890
7891
7892
7893
7894
7895
7896
7897
7898
7899
7900
7901
7902
7903
7904
7905
7906
7907
7908
7909
7910
7911
7912
7913
7914
7915
7916
7917
7918
7919
7920
7921
7922
7923
7924
7925
7926
7927
7928
7929
7930
7931
7932
7933
7934
7935
7936
7937
7938
7939
7940
7941
7942
7943
7944
7945
7946
7947
7948
7949
7950
7951
7952
7953
7954
7955
7956
7957
7958
7959
7960
7961
7962
7963
7964
7965
7966
7967
7968
7969
7970
7971
7972
7973
7974
7975
7976
7977
7978
7979
7980
7981
7982
7983
7984
//! areev — the Areev CLI (brand Areev, package areev, run `areev`).
//!
//! Thin shell over areev-store + areev-cal. One memory = one file.

mod corpus;
// `pack` lives in the library half of this crate (#315), so a Rust host
// can install an agent without shipping and spawning this binary.
use areev::pack;
mod run_stack;
mod tune;
mod trigger_cli;

use std::collections::HashMap;
use std::process::ExitCode;

use areev_cal::{CalExecutor, CalExecutorConfig, AreevFacade};
use areev_core::error::Hash;
use areev_core::types::{ContentBlock, Event, Fact, Grain, TokenUsage, Tool};
use areev_store::{is_pg_dsn, Axis, Areev, Direction};
use areev_loop_adapter::{now_ms, AreevSubstrate};
use areev_loop::{Decision, Engine, ObserverType, Policy, RecStatus, RunOptions, ScopeSet, Severity};

const USAGE: &str = "\
areev — embedded memory engine for AI agents (OMS + CAL on Turso)

USAGE:
  areev <command> [--db <memory.db>] [options]   (-d = --db)
  areev --version | -V                 print the version and exit
  areev help | --help | -h             show this help

COMMANDS:
  init     [--template blank|demo|coding-agent] [--ns NS]   seed a backend +
           print the Claude Code hook snippet (never writes your settings)
  loop     <run|reflect|list|show|approve|reject|apply|rollback|analyzers|policy|replay>
           the governed self-improvement loop (deterministic core; optional verified LLM):
           run    [--min-new N --min-new-errors N --if-stale 6h --format json --quiet]
                  [--model provider:name | --llm-cmd 'CMD']   optional LLM reflection
                  (--model reads the key from $ANTHROPIC_API_KEY/$OPENAI_API_KEY/etc.)
                  [--ground-model provider:name | --ground-cmd 'CMD']  separate
                  grounding backend (defaults to the reflection model)
                  [--analyzer-cmd 'CMD']   register an external analyzer
                  (advisory only — never auto-applies)
           reflect  like run, but re-analyzes the whole memory (ignores the
                  incremental watermark) — a full sweep; same flags as run
           list   [--status pending|all|applied|...] [--fail-on high]  (exit 2 on match)
           show <hash> | approve/reject/apply/rollback <hash> --because \"...\" [--actor A]
           outcomes  the Verify gate: did applied advice hold, or regress?
           replay --config FILE [--window 90d | --since MS] [--step per-pass|1d]
                  score a candidate config against the recorded past, beside the
                  incumbent — zero writes, prefix-only reads, LLM/command not replayed
           [--policy FILE] grants auto-apply (else $AREEV_LOOP_POLICY); `policy` prints it
  add      <subject> <relation> <object>       store a fact (positional)
           [--subject S --relation R --object O] [--ns NS] [--confidence C]
           [--idempotent]   no-op if this exact value is already the head
  record-tool-call --name NAME [--input JSON] --result TEXT [--is-error]
           [--thread ID] [--call-id ID] [--ns NS]   append one tool invocation
  run-manifest --run-id ID --config JSON   persist a reproducible harness
           configuration and its run link in agent:harness
  recall   <subject> | --subject S   [--relation R] [--ns NS] [-k N]
           [--render sml|toon|markdown|plain|json] [--budget TOKENS]
           --ns accepts a prefix scope 'org.*' (= org + its .-descendants);
           writes and destruction never accept patterns
  cal      <QUERY> [--ns NS]          execute a CAL statement
  corpus   --select '<READ CAL>' [--out FILE] [--recipient ID]
                                      stream governed OpenAI chat
                                      JSONL and record its provenance registry
  tune     --cmd 'TRAINER' --evalset HASH
           (--select '<READ CAL>' --out FILE | --corpus FILE --manifest HASH)
           [--recipient ID] [--timeout-secs N]
                                      hand the corpus to YOUR trainer (JSON on
                                      stdio; Areev never trains) and register
                                      the returned adapter with full lineage;
                                      promotion then rides the loop:
                                      `loop run` proposes, `eval run --model`
                                      gates, `loop apply --gating-run` admits
  search   --query TEXT [--subject S] [-k N]   hybrid recall (BM25 + structural, RRF);
           each JSON row carries `score` (fusion, top = 1.0, or the reranker's)
  history  --subject S --relation R [--ns NS]
  provenance <source-hash>            grains distilled from a source (reverse)
  forks                               open forks (>1 head for a subject+relation)
  merge    --subject S --relation R --object O   close a fork with a resolved value
  subject-report <subject> [--ns NS] [--text-mentions] [--out FILE] [--bundle FILE]
                                      DSAR read (GDPR Art. 15/20): everything
                                      forget-subject WOULD erase — exact +
                                      partition keys, history — as JSONL
                                      (stdout or --out), and optionally a
                                      portable .mgb bundle (--bundle)
  forget-subject <subject> [--ns NS] [--text-mentions] [--because \"why\"]
                 [--override-hold] --yes
                                      erase EVERY grain referencing an
                                      identity (--because rides the audit
                                      record) — exact +
                                      partition keys (pat, pat#visit1), history
                                      included, + its dictionary entries;
                                      --text-mentions also erases grains whose
                                      indexed text mentions the identity;
                                      replicates as tombstones.
                                      A namespace under a legal hold refuses
                                      (STO-E009) and the refusal is itself
                                      recorded; --override-hold --because
                                      destroys anyway, names the hold in the
                                      audit record, and needs admin on the
                                      namespace as well as erase
  purge-older-than <days> [--ns NS] [--type event] --yes   retention sweep:
                                      erase grains older than N days
                                      (--ns \"\" sweeps every namespace)
  retention <set|list|clear|sweep|floor|floor-clear|floors>
           [--days N] [--min-days N] [--ns NS] [--type event]
           [--because \"why\"] [--yes]  declarative storage limitation: the
                                      policy is a file-truth that travels
                                      with the memory; `set` declares,
                                      `sweep --yes` enforces (audited).
                                      `floor --min-days N` declares a
                                      MINIMUM any sweep must respect —
                                      destruction younger than it refuses
  hold     <set|release|list> [--ns NS] --because \"why\" [--by PRINCIPAL]
           list also takes [--format json] (adds at_ms, the placement time)
                                      legal hold: while one is live on a
                                      namespace, EVERY destruction path there
                                      refuses (STO-E009) with the hold on
                                      record — the age sweeps, FORGET by hash,
                                      FORGET SUBJECT, the memory tool, the
                                      loop rollback, and DROP SCHEMA.
                                      A file-truth; `set` and `release` both
                                      demand a reason and both land in
                                      `areev audit export`
  trigger  add --type KIND --workflow HASH --because \"why\"
           [--context-query SPEC]     a saved query the evaluator runs at
                                      fire time; its result rides into the
                                      run input as `context` (how a
                                      trigger-started run reads its own
                                      memory on the embedded backend).
                                      SPEC is `name` or `name($p = /ptr,
                                      ...)` — pointers resolve against the
                                      firing item's payload (fail-closed)
           [--interval SECS | --cron EXPR | --at MS] [--observer NAME]
           [--connector-tool HASH]    the connector's CODE as a grain: a Tool
                                      Definition whose executor_uri carries the
                                      blob. --observer/--connector still names
                                      it (that name is half the run-id dedup
                                      identity). Nothing runs unless the
                                      evaluating host pinned the address with
                                      --allow-executor
           [--scope S] [--dedup-key PTR] [--catchup last|none|all]
           [--where EXPR] [--members ALIAS=HASH,...] [--correlate PTR]
           [--window 10m]
                                      declare a trigger. Like retention, the
                                      declaration is a file-truth that
                                      travels with the memory and is enforced
                                      separately. --where is CAL WHERE syntax:
                                      it selects grains for a `memory` trigger
                                      and gates member aliases for a
                                      `composite` one
  trigger  run [--id T] [--connector-cmd CMD] [--tool-cmd CMD] [--dry-run]
           [--lease SECS] [--max-items N] [--credential NAME=ENV_VAR|cmd:CMD|vault:P#F]
           [--credential-ttl SECS] [--resolver-env VAR,...]
           [--allow-executor HEX,...] [--sandbox-cmd CMD] [--executor-cache DIR]
           [--executor-timeout SECS] [--tool-env VAR,...]
           [--model SPEC] [--base-url URL] [--key-env VAR]
           [--max-tokens N] [--max-usd USD] [--max-wall-ms MS] [--ask-ttl SECS]
           [--max-effects N] [--llm-tool-result-chars N] [--llm-context-tokens N]
                                      evaluate once and exit — the cadence is
                                      data in the memory, so the heartbeat can
                                      be coarse. Safe to invoke concurrently.
                                      A firing gets the SAME runner `run start`
                                      builds: the executor pin, the sandbox and
                                      the model all reach it, so a plan that
                                      runs by hand runs on a heartbeat — and
                                      the same pin decides whether a trigger's
                                      own --connector-tool code may run. Every
                                      one of those also reads its $AREEV_RUN_*
                                      variable, because a heartbeat is a cron
                                      line, not an interactive command.
                                      With none of --tool-cmd/--allow-executor/
                                      --model it ingests without executing;
                                      --dry-run touches nothing.
                                      --credential names an env var whose value
                                      the egress broker attaches on the way out,
                                      so the connector never holds the token.
                                      cmd:/vault: MINT one per call instead —
                                      what an unattended heartbeat wants, since
                                      a token minted at boot expires by morning.
                                      The budget flags are the ones `run start`
                                      takes, and bound the runs a firing starts
  trigger  render --target cron|launchd|systemd|k8s-cronjob
                                      emit heartbeat config for infrastructure
                                      you already run; never creates anything
  trigger  deliver --id T [< payload.json] [--tool-cmd CMD] [budget flags]
                                      hand a webhook/manual payload to Areev.
                                      The host owns the listener — Areev never
                                      opens a port. Idempotent on the dedup key.
                                      Takes the same runner and budget flags as
                                      `trigger run`
  trigger  list | show <T> | status   what is declared, and what has actually
                                      fired (a trigger that never fired is
                                      reported, not silent). `show` also
                                      surfaces the cursor and, for a
                                      superseded declaration, the state key
                                      its evaluation actually lives under
  trigger  retarget <T> [--workflow HASH] --because \"why\"
                                      point a trigger at the CURRENT version of
                                      its plan (editing a plan mints a new hash
                                      and triggers do not follow heads). Without
                                      --workflow it follows the plan's own chain
                                      to the live head; the destination is
                                      validated before anything is written, and
                                      the cursor/dedup fence carry over
  trigger  pause <T> --because \"why\" | resume <T> --because \"why\"
                                      operational brake; unlike the
                                      declaration's own enabled flag it stays
                                      on this host and does not replicate
  blob     put <FILE> | put --stdin   store bytes in the content-addressed
                                      blob store; prints the cas:// URI
                                      (idempotent — the address IS the content)
           get <cas-uri>              write those bytes to stdout, hash-verified.
                                      Reads the .blobs sidecar WITHOUT opening
                                      the memory, so a --tool-cmd subprocess can
                                      fetch an attachment while its run holds
                                      the single writer (an encrypted memory
                                      still needs --passphrase-env)
  blobs encrypt                       encrypt CAS attachments written before
                                      sidecar encryption landed (needs the
                                      memory's key; new blobs are sealed on
                                      write). Idempotent
  audit export [--since MS] [--until MS] [--out FILE] [--with-outcomes]
                                      accountability evidence as JSONL: every
                                      destructive op (who/what/why/how many)
                                      + the loop lifecycle with its gating
                                      edge. BOTH trails hash-chained and
                                      verified — a missing predecessor is a
                                      chain_break, one merely outside --since
                                      is previous_outside_window, and a
                                      pre-chain record is unchained, never a
                                      break. --with-outcomes adds the Verify
                                      gate's measured checkpoints, marked
                                      chained: false. It contains NO read
                                      records: access logging is the host's
  novelty  --text T [--subject S] [--relation R] [-k N] [--ns NS]
                                      nearest existing grains
                                      (paraphrase check; needs --embed-cmd)
           --ns accepts a prefix scope 'org.*' like recall does
  log      [--since OP] [--limit N] [--ns a,b]
                                      op-log (change feed). --ns narrows it to
                                      those namespaces and attributes every
                                      row, TOMBSTONES INCLUDED — resolving a
                                      forget's hash cannot, because the grain
                                      is gone. op_seq stays the memory-wide
                                      sequence, so a scoped cursor is still
                                      comparable with an unscoped one
  telemetry scrub --ns NS --yes       drop every recall-telemetry row for one
                                      namespace, plus buffered events. Reaches
                                      the row no other scrub can: a
                                      zero-result free-text query names no
                                      grain hash
  bundle   --out FILE [--since OP]    incremental backup (git-shaped)
  import   --bundle FILE              apply a bundle (fast-forward)
  pack     validate DIR               check a pack without opening a memory:
                                      it builds every grain, addresses it, and
                                      compares against the manifest's
                                      expected_hash. Prints the pins its code
                                      needs
  pack     install DIR [--dry-run]    seed a pack into --db: blobs into the
                                      CAS, `blob:`/`grain:` references
                                      rewritten to the addresses they turn out
                                      to have, saved queries restored. An
                                      expected_hash that does not match is
                                      REFUSED with nothing written.
           [--expected-hash H]        refuse unless the pack's plan builds to H
           [--pin TOOL=ADDR,...]      check this host's executor pins against
                                      the pack's code (tool_name, grain id or
                                      blob name → address); a mismatch or a
                                      pin naming no code-carrying tool is
                                      PCK-E005, nothing written. Pins are
                                      checked, never stored
  pack     export --out DIR [--pack-format source|bundle] [--name N]
                                      turn this memory's namespace into an
                                      installable pack. `source` writes
                                      reviewable grain JSON (and refuses to
                                      write anything it cannot rebuild to the
                                      same address); `bundle` writes a bundle
                                      plus a manifest of what it must contain.
                                      See docs/pack.md
  migrate  --from SRC --file PATH [--history PATH]   import another system's
           export: mem0 | mem0-history | langgraph | letta | letta-archival |
           zep | basic-memory (PATH = vault dir) | jsonl (generic
           {subject,relation,object}|{content} lines) | tool-log (OpenAI-style
           tool-call JSONL → Tool grains, feeds tool-failure clustering).
           Re-runs skip what is already imported; see docs/migrate.md.
  reindex                             backfill + rebuild the BM25 text index
                                      (e.g. after --index-text true on a file
                                      written with indexing off)
  vector-index <status|build|drop|check> [--m N] [--ef-construction N]
           [--ef-search N] [--queries FILE.json --ns SCOPE] [--k N]
                                      the ANN (pgvector HNSW) index over the
                                      stored vectors. Postgres only: build
                                      answers STO-E007 on a file memory, which
                                      scans exactly. `check` grades the index
                                      against the exact scan with YOUR query
                                      vectors (recall@k) over the WIDE --ns
                                      scope you actually query; --ef-search
                                      retunes the session first (no rebuild).
                                      `status` says whether reads are exact.
  stream   --to DIR [--interval-ms N] [--once] [--checkpoint] [--retain 30d]
                                      continuous op-log shipping; --checkpoint
                                      opens a new generation with a full
                                      snapshot, --retain drops generations
                                      older than the window (so erasure
                                      reaches archives — see docs/gdpr.md)
  restore  --from DIR [--until-hlc T]            rebuild from stream dir (PITR)
  follow   --from DIR [--interval-ms N] [--once]  subscribe: apply new segments
                                                  (org/category distribution)
  related  --start TERM --relations R1,R2 [--direction out|in|both]
           [--depth N] [--limit N] [--ns a,b]
                                      walk the entity graph (bounded k-hop).
                                      in/both only see relations the file
                                      declares entity-valued. --ns with a
                                      comma list walks the SET: a walk is not
                                      composable from per-namespace calls, and
                                      every named namespace is read-checked as
                                      itself
  entity-at --subject S --relation R --at MS [--axis world|knowledge] [--ns a,b]
                                      as-of read: what was true at T (world)
                                      or what was known at T (knowledge).
                                      The world axis prefers the window that
                                      took effect most recently, so an
                                      out-of-order backfill reads correctly.
                                      --ns with a comma list answers each
                                      namespace independently
  step-actions --workflow HASH [--node ID] [--limit N]
                                      execution records for a workflow —
                                      which grains ran which of its nodes
  eval     <create|run>                the §7.4 gating edge: create stores an
           evalset (--name N --cases FILE); run --evalset HASH executes it
           against --tool-cmd CMD or --model provider:name ([--base-url URL]
           [--key-env VAR] [--llm-max-tokens N] — how a tuned adapter served
           by vLLM/SGLang/Ollama is graded; --baseline RUN [--tolerance N]
           re-accepts against a recorded run within N percentage points,
           the Verify gate's own regression rule), journals each case under an
           eval- run id, and records the summary `areev loop apply
           --gating-run` loads.
           --case-ns NS puts the evalset and every case's input and output in
           NS instead of agent:harness, so confidential cases are governed by
           the namespace they came from; the summary stays in the harness.
           A grader may report field metrics and usage out of band by writing
           a JSON object with `metrics` and `usage` members to
           $AREEV_EVAL_REPORT — each metric's MEAN lands in the summary as
           <name> beside <name>_n, which the Verify gate reads like any
           host-defined field, and usage sums into input_tokens /
           output_tokens / usd_micros
  tool     provenance <hash> [--depth N]   one-command code forensics: the
           recommendations targeting this code, each transition's approver +
           BECAUSE + gating edge, the runs that touched it, and the executor
           blob its executor_uri points at (present? how many bytes? — read
           lock-free, so it answers while the run is still holding the file)
  run      <start|resume|respond|input|pause|cancel|list|inspect|verify|fork|
           shadow|oversight-report|demo>   the governed
           workflow runtime: journaled, checkpointed, HITL-pausable runs of
           Workflow grains. list [--last N] [--offset N] prints the newest
           runs with outcome + spend (default 20; stderr says when the page
           truncated). An explicit --ns scopes it to that session namespace;
           without one, every namespace is listed.
           start --workflow HASH --run-id ID [--input JSON]
           [--tool-cmd CMD] [--model provider:name] [--base-url URL]
           [--key-env VAR] [--llm-max-tokens N] [--max-effects N]
           [--llm-tool-result-chars N] [--llm-context-tokens N]
           [--events] [--otel-endpoint http://HOST:4318]
           [--as PRINCIPAL] [--max-tokens N --max-usd F ...]
           [--allow-executor ADDR,...] [--executor-cache DIR]
           [--sandbox-cmd 'areev-sandbox'] [--executor-timeout SECS]
           [--tool-env VAR,...]
           [--credential NAME=ENV_VAR[@PRINCIPAL],...] [--allow-host URL,...]
           [--tool-egress TOOL:CRED[@HOST]+...:METHOD+METHOD,...]
           [--credential-ttl SECS] [--resolver-env VAR,...]
           [--initiator WHO] [--allow-confirmation-asks]
           [--input-placement manifest|run-ns] [--harness-ns NS]
           [--max-run-effects N] [--max-tool-calls N]
           [--max-concurrent N] [--max-concurrent-per-principal N]
           [--lease SECS] [--node ID]
           [--llm-token-field max_tokens|max_completion_tokens]
           [--llm-no-temperature] [--llm-extra-body JSON];
           --initiator names who a run is started ON BEHALF OF: frozen in the
           manifest, and an approval ask refuses them as well as the run's
           principal. A resume refuses a model or scheduler-epoch mismatch
           (RUN-E025/E026) before taking the lease — `run fork` is the way
           through. --input-placement run-ns and --harness-ns move the run's
           content-bearing records into the run's own namespace, so they are
           governed by it rather than by the memory-wide agent:harness.
           Every one of these has an $AREEV_RUN_* twin, because a run started
           from a cron line is configured out of band.
           --credential/--allow-host/--tool-egress broker a tool's outbound
           calls: it gets the broker's address and a capability token, never
           the secret. A tool with no grant gets nothing, and a grant naming
           no method may only read. NAME=ENV_VAR@PRINCIPAL binds the
           credential to a run principal, so a run executing as anyone else is
           refused it — for a process holding several principals' secrets.
           CRED@HOST pairs a credential with the bare hostname it may be sent
           to, so a tool holding two services' secrets cannot send one to the
           other. A credential can also be MINTED per call instead of read
           from the environment: NAME=cmd:COMMAND takes the command's stdout
           (`cmd:gcloud auth print-access-token`, `cmd:vault kv get -field=t
           secret/x`) and NAME=vault:PATH#FIELD reads Vault/OpenBao directly
           over $VAULT_ADDR/$VAULT_TOKEN — both cached for --credential-ttl
           (default 300s), re-minted after it, and refused rather than sent
           unauthenticated if the resolver fails. Bind a principal to a minted
           credential on the NAME side (NAME@PRINCIPAL=cmd:...), because a
           command may itself contain '@'. --resolver-env names the variables
           a resolver needs for its OWN authentication ($VAULT_TOKEN,
           $AWS_PROFILE): they are withheld from every other subprocess and
           re-admitted only for resolvers. All five also read their
           $AREEV_RUN_CREDENTIAL / _ALLOW_HOST / _TOOL_EGRESS /
           _CREDENTIAL_TTL / _RESOLVER_ENV variable (the flag wins), which
           is how `areev serve` and a heartbeat configure the broker;
           --allow-executor pins the content address of a code-carrying tool
           (a Definition whose executor_uri names a cas:// blob). Nothing
           code-carrying runs unpinned, because the blob travels with the
           memory and the authorization must not;
           --executor-timeout overrides the fixed 300s wall-clock ceiling a
           host-executed tool (--tool-cmd or a pinned --allow-executor blob)
           otherwise runs under — a document-analysis leg making a dozen
           model calls needs longer than that default was sized for. 0 means
           wait forever;
           --events streams the run's §6.10 events to stderr as JSON lines
           (stdout stays the machine surface); --otel-endpoint also exports
           the run as ONE OTLP/HTTP JSON trace at completion — http:// only,
           terminate TLS at a local collector. Its spans carry the
           OpenTelemetry GenAI attributes (gen_ai.request.model,
           gen_ai.usage.*, gen_ai.tool.call.id, …) beside Areev's own
           superstep/task_path/attempt provenance, so a GenAI-aware backend
           reads them with no Areev-specific configuration;
           --tool-env inverts how a tool's environment is decided: without it
           a tool inherits this process's environment minus the variables
           named to --passphrase-env/--token-env/--credential, with it the
           environment is cleared and only the named variables (plus PATH and
           the few a command needs to start) get through. A host that keeps
           its own secrets in the environment should name what a tool sees
           rather than name what it must not. A bare --tool-env passes nothing
           but that minimal set. Naming a variable already registered as
           holding a secret does NOT re-admit it: it is dropped and reported;
           input --run-id ID --message TEXT [--as PRINCIPAL] queues a
           steering message: the next superstep hands it to its nodes under
           `$inbox`, so a person redirects a running run in band instead of
           through a human-gate ask;
           pause --run-id ID [--because TEXT] asks a live run to stop at its
           next superstep boundary and park, resumably: the open superstep
           finishes and checkpoints, nothing past it dispatches, and
           `run resume` continues it under the same run id, manifest and
           pins (no fork). Needs run.execute, the grant resume takes;
           idempotent; RUN-E029 on a finished run or a pending cancel —
           cancel wins, and cancel on a paused run finalizes it;
           fork --run-id BASE --as-run NEW [--at N] [--plan HASH]
           time-travels or migrates a run;
           shadow [--runs a,b,c | --last N] [--plan HASH | --plan-file F]
           [--reexecute pure] rehearses journaled runs. Bare, it re-drives
           each under its OWN manifest and reports consistency; with a
           candidate plan it re-drives them under that, answering every
           effect from the journal — zero dispatches, zero writes — and
           reports outcome, spend and out-of-support per run.
           --reexecute pure additionally RE-RUNS the candidate's pure
           wasm32-areev modules in the sandbox on the replayed input, so a
           change to a tool's bytes stops rehearsing as `same`; the report
           then names which terminal state keys moved (changed_keys /
           added_keys / removed_keys — key paths, never values) and counts
           sandbox_executions. Native, wasm32-areev-io, client and abstract
           nodes still answer from the journal and are listed under
           not_reexecuted with the reason, and a module still runs only if
           this host --allow-executor pinned it and configured --sandbox-cmd.
           `areev run demo` seeds the 10-minute proof
  run-trace --run-id ID [--limit N]   what a run recorded, and what it
                                      produced downstream (facts/lessons)
  runs-touching --hash H [--depth N]  which runs produced or refined a grain —
                                      and, for a tool definition, which ran it
                                      (walks provenance both ways)
  verify   [--attestations]           integrity + content-address recheck
                                      (--attestations also checks every
                                       attestation against --trusted-authors)
  attest   <hash> | --all [--ns PREFIX]  sign a stored grain with the author
                                      key (--signing-key-env); --all retro-
                                      fills a memory that predates its key
  stats                               store counters
  serve    --mcp [--ns NS] [--mount alias=path|DSN,...] [--no-destructive-ops] [--lock-ns NS] [--profile memory|full]  MCP server on stdio
                                      (--mount adds read-only memories for
                                       cross-file ASSEMBLE; ns \"alias.inner\".
                                       A target is a memory FILE or a postgres
                                       DSN (postgres://…?schema=NAME) — either
                                       backend, always opened read-only, so a
                                       missing file is refused rather than
                                       created and a SELECT-only pg role is
                                       enough. Commas separate mounts only
                                       before another alias=, so a multi-host
                                       DSN survives. A mount's vector leg uses
                                       ITS OWN embedder, and --embed-cmd
                                       installs one on the primary only, so
                                       ABOUT/NOVELTY do not cross a mount;
                                       --profile memory drops the run/loop
                                       tool family, default full)
  repl     [--ns NS]                  interactive CAL console in the terminal
  remember --content TEXT [--facts JSON] [--observer ID]
           [--session-id ID] [--run-id ID] [--role user|assistant|system|tool]
           [--model SPEC | --llm-cmd CMD] [--extract-hint TEXT]
           [--ground-model SPEC | --ground-cmd CMD]
           [--min-confidence F] [--dry-run]
                                      store free text as an Event, then
                                      attach the facts distilled from it.
                                      --facts is host-supplied and skips the
                                      model; --model/--llm-cmd extract with an
                                      LLM (stamped verification_status
                                      \"unverified\" unless --ground-* checks
                                      them). --dry-run prints, stores nothing.
  hook     claude-code               print settings.json hook snippet
                                      (auto recall-before-prompt, capture-on-stop,
                                      and capture-before-compaction). Prints only —
                                      areev never edits your settings
  capture-stop [--policy-version V]   the Stop AND PreCompact handler: reads
                                      Claude Code hook JSON on stdin and stores
                                      the transcript's turns as thread-indexed
                                      Events. Idempotent by content address, so
                                      both events can point at it. A compaction
                                      summary is tagged compact_summary; a
                                      missing transcript exits 0 silently — a
                                      hook must never cost you a compaction
  anonymize scan [--text T] [--policy-file F]
                                      detect sensitive spans (Tier-0 chain:
                                      structural, regex+checksum, secrets,
                                      keyword cues, dictionary). Reads stdin
                                      when --text is absent; prints JSON.
                                      Pure text — needs no memory file.
  anonymize test --fixtures F [--policy-file F]
                                      Assert a policy against a fixture file
                                      of must-redact / must-not-redact strings.
                                      Exits non-zero on any miss or false
                                      positive — run it in CI.
  anonymize set --ns NS (--policy-file F | --policy JSON)
                                      declare a per-namespace egress/audit
                                      policy (travels with the file; stamps
                                      min_reader_version). `list` shows the
                                      declared policies, `clear --ns NS`
                                      removes one, `mappings` prints this
                                      process's live pseudonym mappings, and
                                      `reveal --ns NS --token T` reverse-looks
                                      one up (admin verb; Tier-2 audited by
                                      fingerprint). Add --anonymize-egress to
                                      any verb to force egress on as a host
                                      floor, and --anonymize-cmd 'CMD' to
                                      install a Tier-1 NER detector (JSON
                                      probe/detect over stdin/stdout).
  decide   --state <TEXT|@FILE> (--questions <JSON|@FILE>
           | --noul \"INSTRUCTIONS\"
           | --choice \"INSTRUCTIONS\" --option KEY=DESC [--option ...]
           | --score \"INSTRUCTIONS\" --level DESC [--level ...])
                                      ask the decision chain (--decide /
                                      --decide-cmd, below) typed questions
                                      about a state; prints the wire response
                                      plus provider, calibrated, latency_ms.
                                      The shorthands ask one question, id
                                      \"q\"; levels go lowest first. --state
                                      is used as JSON when it parses. No --db:
                                      it names no memory. A 429 with
                                      Retry-After is retried once (<= 60s)
  auth     mint|list|revoke --auth FILE
                                      manage the credential map (no --db: it
                                      names no memory). mint --id NAME
                                      --principal NAME [--label TEXT]
                                      [--expires 90d|<ISO-8601>]
                                      [--memories A,B] prints a 256-bit
                                      areev_pat_ token ONCE on stdout and
                                      stores only its SHA-256; revoke --id
                                      NAME drops one credential without
                                      touching the principal's others
                                      (restart `areev ui` to apply)
  provision [--check [--format json]] --db DSN [--schema NAME]
            [--meta-schema NAME] [--telemetry off|aggregate|aggregate-hashed|full]
                                      create/migrate a postgres memory's
                                      schema AHEAD of use, so no request ever
                                      pays for bootstrap DDL. Postgres only
                                      (a file memory bootstraps itself at
                                      open). Run it with a role that owns the
                                      schema; the runtime role then needs no
                                      CREATE, and can pin that with
                                      `?provision=never` on its own DSN, which
                                      refuses (STO-E008) instead of issuing
                                      DDL. --schema supplies or overrides the
                                      DSN's ?schema=; --meta-schema supplies
                                      or overrides ?meta_schema=, the PAIRED
                                      layout that keeps the engine's metadata
                                      (meta, counters, ns_reg, telem_*) in a
                                      second, physically separate schema —
                                      every later DSN must then name both
                                      (a mismatched layout is refused,
                                      STO-E011). It also provisions the
                                      telemetry tables, since --telemetry
                                      defaults to aggregate on every verb —
                                      pass --telemetry off to skip them.
                                      --check is the READ-ONLY probe: SELECTs
                                      only, no lock, no DDL, no meta write, so
                                      it runs under a least-privilege role. It
                                      reports every stamp's found-vs-wanted
                                      value, what is pending, and
                                      rolling_deploy: safe |
                                      drain_writers_first | unknown. Exit 0
                                      current, 2 pending or absent
  ui       [--addr HOST:PORT] [--allow-remote] [--allow-origin ORIGIN[,ORIGIN...]]
           [--token-env VAR] [--no-destructive-ops] [--tls-cert PATH --tls-key PATH]
           [--sso-header NAME --sso-secret-env VAR [--sso-secret-env-next VAR]]
           [--sso-approvals deny|allow] [--sso-groups-header NAME]
           [--sso-principal-prefix PREFIX]
           [--oidc-issuer URL --oidc-client-id ID --oidc-client-secret-env VAR
            --oidc-redirect-uri URL [--oidc-scopes S] [--oidc-principal-claim C]]
                                      web console (default 127.0.0.1:7437).
                                      --allow-origin accepts a cross-origin
                                      POST from an EXACT origin (comma-
                                      separated for more than one; no
                                      wildcards) — the Origin check is not
                                      lifted by --allow-remote, so a console
                                      behind a reverse proxy needs its public
                                      origin named here to be usable.
                                      --sso-secret-env-next opens a rotation
                                      window: both secrets prove the proxy, so
                                      the fleet moves over one node at a time
                                      (docs/runbooks/sso-secret-rotation.md)
                                      --sso-approvals (default deny) decides
                                      whether a proxy-asserted identity may
                                      answer a HITL approval: its only proof
                                      is the shared proxy secret, so 'allow'
                                      makes every approval only as strong as
                                      that one value. Approvers should hold a
                                      per-principal credential (--auth).
                                      --sso-groups-header maps IdP groups to
                                      principals via --auth's \"groups\" table
                                      (needs --auth); an identity with its own
                                      grants outranks its groups, and a
                                      group-derived principal is a ROLE — it
                                      may never approve, under any setting.
                                      --sso-principal-prefix stamps every
                                      proxy-asserted principal so IdP names
                                      stay distinct from local ones.
                                      --oidc-* (build with --features oidc)
                                      runs the auth-code+PKCE flow in-process
                                      instead: the console verifies the IdP's
                                      signature against its published key set
                                      and issues an HttpOnly SameSite=Strict
                                      session cookie. Login at /auth/login,
                                      logout at /auth/logout. An OIDC identity
                                      MAY approve (no --sso-approvals needed):
                                      a verified signature is a stronger claim
                                      than a shared proxy secret. The redirect
                                      URI must match the provider's exactly.

Namespace defaults to \"shared\". Exit code 0 on success.
--db is optional for one-shot commands: it falls back to $AREEV_DB, then
~/.areev/default.db. `serve` and `ui` require an explicit --db (or $AREEV_DB).
Files carry their own settings (text index, entity relations, embedding
provenance) in an internal meta table; a bare open honors them.
--index-text true|false explicitly re-stamps the file's declaration.
--assembly-manifest-sample-rate 0..1 samples ASSEMBLE provenance into
agent:harness (host-only, default 0/off).

Principals: add --as <principal> to cal/repl/serve/subject-report/forget-subject/
purge-older-than to run the session under the file's grants for that
principal (fail closed; see GRANT in docs/cal-reference.md §9). --auth FILE
validates the principal against a credential map, and `areev ui --auth FILE`
serves the console in multi-principal mode (tokens → principals,
unauthenticated = read-only \"anonymous\").

Console auth: prefer --auth <map> — per-principal credentials, so a write or
an approval names WHO did it, one credential can be revoked without disturbing
the principal's others, and `expires_at` bounds a leak. `areev auth mint`
creates them. --token-env <VAR> remains the single-user shortcut: one shared
secret, implied admin, unattributable (it can never answer a HITL approval).
On that path the token's entropy is the ONLY control — use at least 32 hex
characters, or let `areev auth mint` choose; comparison against the presented
credential is constant-time. After 10 consecutive failed authentications from
one source address, further credential-bearing requests from it are refused
with 429 until the streak goes idle (15 min). Browsers authenticate via HTTP Basic, which the
browser caches per origin and RE-ATTACHES AUTOMATICALLY, including on
cross-site requests — so the Origin check (--allow-origin, above) is
load-bearing, not defence in depth. There is no logout: closing the tab does
not clear a cached Basic credential, so a browser used to demo the console
stays authenticated until it is restarted or its saved credentials are
cleared. A wrong token is counted per source IP and logged to stderr as
\"console auth FAILED from <ip> (<n> consecutive)\" (greppable for a
fail2ban-style rule; the token itself is never logged) — but it is NOT
delayed or locked out in-process: `ui` serves one connection at a time, so a
sleep before responding would let an unauthenticated caller stall the
console for everyone, and behind a reverse proxy every request logs the
PROXY's IP anyway, so an IP lockout here would lock out every user at once.
Rate limiting belongs at that proxy (the documented default deployment
shape) — write the fail2ban-style rule against its access log, not this
one. A SameSite/HttpOnly/Secure session cookie is the intended future fix
for the caching/logout problem above and is tracked separately — it does
not exist yet.

Encryption at rest: add --passphrase-env <VAR> to any command to derive an
AES-256 key (Argon2id) from the passphrase in environment variable VAR. The
non-secret salt is kept in a <memory.db>.kdf sidecar — back it up with the db.

Anonymization key: add --anon-key-env <VAR> to any command to supply the
32-byte root (64 hex characters in VAR) the pseudonym session/memory/vault
subkeys are derived from. Independent of the page cipher, so the mapping vault
and value-derived tokens also work on postgres and on plaintext files. Never
persisted; rotating it is a crypto-erasure of the mapping table.

Grain attestation: add --signing-key-env <VAR> (a 32-byte Ed25519 seed, 64
hex characters in VAR) to any command and every grain it writes is followed by
an attestation — a detached signature over the grain's content hash, stored as
an Observation in agent:attest. Add --trusted-authors FILE (a JSON map of
key_id -> public key, with an optional policy of off | verify | require) to
check attestations at import/follow and in `verify --attestations`; add
--require-attested to refuse any bundle carrying a grain without a valid
attestation from a trusted key. Keys are host config, never written to the
memory; the attested grain's hash never changes. docs/grain-attestation-plan.md

Vector recall: add --embed-cmd 'CMD' [--embed-model NAME] to any command to
install a command embedder — CMD gets the text on stdin and must print a JSON
array of numbers. Turns on the vector leg for search/serve, and embeds grains
written by add/remember/migrate.

Decision backends (optional, off unless configured): add --decide <CHAIN>
to any command — a comma-separated, ordered list of providers
(typesafe:MODEL, openrouter:MODEL, vercel:MODEL, openjev:MODEL,
cloudflare:MODEL, systemone:URL[#MODEL], llm:LLM-SPEC), tried in order;
only the first colon splits, so URLs and nested LLM specs pass through.
--decide-cmd 'CMD' appends a command backend as the LAST entry (wire request
JSON on stdin, wire response JSON on stdout; no shell). --decide-timeout-ms N
bounds the whole chain (default 2000); llm: entries generate text and usually
need a larger value. Each falls back to $AREEV_DECIDE, $AREEV_DECIDE_CMD,
$AREEV_DECIDE_TIMEOUT_MS. A bad spec or missing provider key fails at
startup (DEC-E001). A decision backend may score and order, never omit;
llm: entries are uncalibrated. docs/decision-model-proposal.md

Reranking and recall deadline: with --decide set, the chain is installed as
the recall reranker (each candidate scored for relevance, then reordered).
--rerank-cmd 'CMD' [--rerank-model NAME] installs a command reranker instead
(stdin {\"query\": \"...\", \"docs\": [...]}, stdout a JSON array of
docs.len() numbers) — an explicit command wins over --decide. search and
recall-hook rerank whenever one is installed; CAL does under WITH rerank.
--recall-deadline-ms N bounds each hybrid recall (0 = none, the default;
recall-hook defaults to 1500 when a reranker is installed); past it recall
fails open to what it gathered. Env: $AREEV_RERANK_CMD,
$AREEV_RECALL_DEADLINE_MS. Under an egress anonymization policy (or
--anonymize-egress) what a decision backend receives is pseudonymized.

Read-only: add --read-only to any command to open the memory refusing every
write (add/supersede/forget/reindex/blob-put and so on fail with a coded
STO-E004 error); reads and CAL SELECT work normally. On postgres this also
skips schema/table bootstrap, so a role holding only CONNECT + USAGE + SELECT
grants can open an existing, already-migrated memory — see
docs/deployment-profile.md for the grant recipe. --read-only combined with an
explicit --index-text is refused up front (--index-text always re-stamps the
file's declaration, which read-only mode cannot do).

Recall telemetry: add --telemetry off|aggregate|aggregate-hashed|full to any
command. Default aggregate (off under --read-only unless asked for
explicitly). It is HOST config, never a file-truth. aggregate-hashed keeps the
same rollups with the query key HMAC'd under a subkey derived from the
memory's own AEAD key, keeps no sample and writes no ring log — so what a
person typed is never retained and there is nothing to erase later. full adds
a per-recall ring log. `areev telemetry scrub --ns NS --yes` reaches the rows
a namespace erasure cannot.";

fn flag(args: &HashMap<String, String>, k: &str) -> Option<String> {
    args.get(k).cloned()
}

fn assembly_manifest_sample_rate(flags: &HashMap<String, String>) -> Result<f64, String> {
    let Some(raw) = flag(flags, "assembly-manifest-sample-rate") else {
        return Ok(0.0);
    };
    let rate: f64 = raw
        .parse()
        .map_err(|_| "--assembly-manifest-sample-rate must be a number from 0 to 1".to_string())?;
    if !rate.is_finite() || !(0.0..=1.0).contains(&rate) {
        return Err("--assembly-manifest-sample-rate must be from 0 to 1".into());
    }
    Ok(rate)
}

/// Map a short flag to its long name. Terse aliases for what you type on every
/// invocation: `-d` for `--db`, `-k` for the recall/search limit.
fn short_flag(a: &str) -> Option<&'static str> {
    match a {
        "-d" => Some("db"),
        "-k" => Some("k"),
        _ => None,
    }
}

fn need(args: &HashMap<String, String>, k: &str) -> Result<String, String> {
    flag(args, k).ok_or_else(|| format!("missing required --{k}"))
}

/// Resolve the memory file: `--db`/`-d`, else `$AREEV_DB`, else the default
/// personal memory `~/.areev/default.db` (its parent dir is created, and a
/// one-line note prints to stderr so the file stays discoverable).
///
/// When `require_explicit` is set, the default fallback is refused with an
/// error instead. Long-lived, potentially network-exposed commands (`serve`,
/// `ui`) pass this: silently serving the personal default memory — over MCP or
/// an unauthenticated HTTP console — risks exposing or mutating the wrong file,
/// so those commands must name their memory explicitly.
/// A host-supplied 32-byte anonymization root, as 64 hex characters.
///
/// Wrong length or a stray non-hex character has to fail here, loudly. The key
/// derives the token space, so a silently different key looks like working
/// software right up until a rehydrate comes back empty — and by then the
/// tokens it wrote are already in the file.
fn parse_anon_key(hex: &str) -> Result<[u8; 32], String> {
    if hex.len() != 64 {
        return Err(format!(
            "expected 64 hex characters (a 32-byte key), got {}",
            hex.len()
        ));
    }
    let mut out = [0u8; 32];
    for (i, byte) in out.iter_mut().enumerate() {
        let pair = &hex[i * 2..i * 2 + 2];
        *byte = u8::from_str_radix(pair, 16)
            .map_err(|_| format!("not hex: {pair:?} at byte {i}"))?;
    }
    Ok(out)
}

/// Open a memory on the postgres backend from a `postgres://…?schema=<name>`
/// DSN, mirroring the file-backend branches (explicit options re-stamp;
/// telemetry rides the memory's schema). Encryption keys don't apply here —
/// the `--passphrase-env` path derives them from a `.kdf` sidecar next to a
/// FILE, so a DSN is rejected before derivation.
///
/// Transport security is the DSN's business, not a flag's: `sslmode=` and
/// `sslrootcert=` ride through `split_schema_url` untouched and are honored by
/// the store (`feature = "postgres-tls"`; without it an encrypting DSN is
/// refused with `STO-E003` rather than downgraded). See
/// `docs/deployment-profile.md` §"Postgres connection contract".
#[cfg(feature = "postgres")]
fn open_postgres_store(
    db: &str,
    tel_mode: areev_store::TelemetryMode,
    explicit_index: Option<&str>,
    anon_key: Option<[u8; 32]>,
    read_only: bool,
) -> Result<Areev, String> {
    let (url, schema) = areev_store::pg::split_schema_url(db).map_err(|e| e.to_string())?;
    // An --anon-key-env key is the whole reason the mapping vault and
    // value-derived tokens are reachable on this backend at all: Postgres
    // refuses `encryption_key` (a page-cipher capability), so without a
    // host-supplied root there is no key material to derive them from.
    // --read-only also forces the explicit-options path: it needs an
    // `AreevOptions` to carry even when nothing else does, so the least-
    // privilege open (skip bootstrap, verify instead) actually happens.
    if explicit_index.is_some() || anon_key.is_some() || read_only {
        let o = areev_store::AreevOptions {
            index_text: explicit_index
                .map(|v| !matches!(v, "false" | "0" | "off" | "no"))
                .unwrap_or(areev_store::AreevOptions::default().index_text),
            anon_key,
            telemetry: tel_mode,
            read_only,
            ..Default::default()
        };
        Areev::open_postgres_with(&url, &schema, o)
    } else if tel_mode != areev_store::TelemetryMode::Off {
        Areev::open_postgres_with_telemetry(&url, &schema, tel_mode)
    } else {
        Areev::open_postgres(&url, &schema)
    }
    .map_err(|e| e.to_string())
}

#[cfg(not(feature = "postgres"))]
fn open_postgres_store(
    _db: &str,
    _tel_mode: areev_store::TelemetryMode,
    _explicit_index: Option<&str>,
    _anon_key: Option<[u8; 32]>,
    _read_only: bool,
) -> Result<Areev, String> {
    // Name `postgres-tls`, not `postgres`: the bare `postgres` feature
    // REFUSES any DSN carrying `sslmode=` (that gate is `postgres-tls`'s
    // job), and every managed Postgres that requires TLS on the wire —
    // Azure Flexible Server, RDS with `rds.force_ssl`, Cloud SQL — needs
    // exactly that. `cargo install areev` itself is real (crates.io has it);
    // only the feature name was wrong.
    Err("this build lacks the postgres backend — reinstall with \
         `cargo install areev --features postgres-tls` (or build with \
         --features postgres-tls), or grab the `-postgres` asset from a \
         GitHub release, which ships the backend already compiled in"
        .into())
}

fn resolve_db(args: &HashMap<String, String>, require_explicit: bool) -> Result<String, String> {
    if let Some(p) = flag(args, "db") {
        return Ok(p);
    }
    if let Ok(p) = std::env::var("AREEV_DB") {
        if !p.trim().is_empty() {
            return Ok(p);
        }
    }
    if require_explicit {
        return Err(
            "this command needs an explicit memory file — pass --db <file> (or -d), \
             or set $AREEV_DB. It will not fall back to the personal default memory \
             (~/.areev/default.db), to avoid serving the wrong file."
                .to_string(),
        );
    }
    let home = std::env::var("HOME")
        .or_else(|_| std::env::var("USERPROFILE"))
        .map_err(|_| "no --db given, and neither $AREEV_DB nor $HOME is set".to_string())?;
    let path = format!("{home}/.areev/default.db");
    if let Some(parent) = std::path::Path::new(&path).parent() {
        std::fs::create_dir_all(parent)
            .map_err(|e| format!("cannot create {}: {e}", parent.display()))?;
    }
    eprintln!("areev: using default memory {path} (override with -d/--db or $AREEV_DB)");
    Ok(path)
}

/// The process-level decision-backend chain (docs/decision-model-proposal.md
/// §5): `--decide <chain>`, `--decide-cmd <cmd>` and `--decide-timeout-ms <n>`,
/// each falling back to `$AREEV_DECIDE`, `$AREEV_DECIDE_CMD` and
/// `$AREEV_DECIDE_TIMEOUT_MS` when the flag is absent. `Ok(None)` is the
/// deterministic floor (nothing configured). Resolved once at startup so a
/// bad spec or a missing provider key fails every verb loudly with its
/// `DEC-Ennn` message, the way a broken `--embed-cmd` does — never silently
/// at the first judgment.
fn resolve_decider(
    flags: &HashMap<String, String>,
) -> Result<Option<std::sync::Arc<dyn areev_llm::DecisionBackend>>, String> {
    let spec = run_stack::flag_or_env(flags, "decide", "AREEV_DECIDE");
    let cmd = run_stack::flag_or_env(flags, "decide-cmd", "AREEV_DECIDE_CMD");
    let deadline = match run_stack::flag_or_env(flags, "decide-timeout-ms", "AREEV_DECIDE_TIMEOUT_MS") {
        None => areev_llm::decide::DEFAULT_DECIDE_TIMEOUT,
        Some(ms) => match ms.parse::<u64>() {
            Ok(n) if n > 0 => std::time::Duration::from_millis(n),
            _ => {
                return Err(areev_llm::DecideError::NotConfigured(format!(
                    "--decide-timeout-ms (or $AREEV_DECIDE_TIMEOUT_MS) must be a positive whole \
                     number of milliseconds, got {ms:?}"
                ))
                .to_string())
            }
        },
    };
    // A present-but-valueless flag (`--decide` with nothing after it) parses
    // as "true"; name the mistake instead of resolving a provider "true".
    for (key, v) in [("decide", &spec), ("decide-cmd", &cmd)] {
        if flags.get(key).map(String::as_str) == Some("true") && v.is_some() {
            return Err(areev_llm::DecideError::NotConfigured(format!("--{key} needs a value")).to_string());
        }
    }
    areev_llm::resolve_chain(spec.as_deref(), cmd.as_deref(), Some(deadline)).map_err(|e| e.to_string())
}

/// Wrap the decision chain for egress: under an active egress
/// anonymization policy (or the `--anonymize-egress` host floor) the `state`
/// a remote backend receives is memory egress, and goes through the same
/// pseudonymization as LLM egress (proposal §2, "Egress").
fn decider_for_egress(
    chain: std::sync::Arc<dyn areev_llm::DecisionBackend>,
    egress: bool,
) -> Result<std::sync::Arc<dyn areev_llm::DecisionBackend>, String> {
    if !egress {
        return Ok(chain);
    }
    // The same session-scoped policy `remember` wraps its LLM backend in.
    // Fail-closed: a pseudonymization failure is DEC-E008, which stops the
    // chain — the raw state never goes out instead.
    let policy = areev_core::anon::AnonPolicy { scope: "session".into(), ..Default::default() };
    Ok(std::sync::Arc::new(
        areev_llm::PseudonymizingDecider::new(chain, policy).map_err(|e| e.to_string())?,
    ))
}

/// Whether text leaving this handle for a decision backend is egress under
/// an anonymization policy: the `--anonymize-egress` host floor, or any
/// namespace declaring `egress` (a recall may span namespaces, so one
/// declaring it is enough).
fn store_egress_active(m: &Areev) -> bool {
    m.anonymize_egress_floor() || m.anon_declared().iter().any(|(_, mode)| mode == "egress")
}

/// Every value of a flag that may repeat (`--option`, `--level`), in order.
/// `parse_args` keeps only the last occurrence, so this rescans argv with the
/// same rule: a value is the next token unless that token starts with `-`.
fn flag_values(argv: &[String], name: &str) -> Vec<String> {
    let long = format!("--{name}");
    let mut out = Vec::new();
    let mut i = 0;
    while i < argv.len() {
        if argv[i] == long {
            if let Some(v) = argv.get(i + 1).filter(|v| !v.starts_with('-')) {
                out.push(v.clone());
                i += 2;
                continue;
            }
        }
        i += 1;
    }
    out
}

/// A `--flag` value, or the contents of the file it names as `@path`.
fn text_or_file(flag_name: &str, v: &str) -> Result<String, String> {
    match v.strip_prefix('@') {
        Some(path) => std::fs::read_to_string(path).map_err(|e| format!("--{flag_name} @{path}: {e}")),
        None => Ok(v.to_string()),
    }
}

/// The most a `Retry-After` is honoured by `areev decide`'s one retry. The
/// header is the provider's to set; an interactive command should not hang
/// for an hour because one said so.
const DECIDE_RETRY_AFTER_CAP_SECS: u64 = 60;

/// `areev decide` — ask the configured decision chain typed questions about a
/// state and print `Decision::to_json()` (the wire response plus `provider`,
/// `calibrated`, `latency_ms`). docs/decision-model-proposal.md §5.
///
/// `--state` is text or `@file`, parsed as JSON when it parses to a string,
/// object or array, else used as-is. The questions come from exactly one of
/// `--questions` (the wire `questions` object, or `@file`), or a shorthand
/// that asks one question with id `q`: `--noul`, `--choice` with repeated
/// `--option k=desc`, `--score` with repeated `--level desc` (lowest first).
/// Interactive, so unlike the recall path it honours a `DEC-E007`
/// `Retry-After` once (capped at [`DECIDE_RETRY_AFTER_CAP_SECS`]).
fn run_decide(
    decider: Option<std::sync::Arc<dyn areev_llm::DecisionBackend>>,
    flags: &HashMap<String, String>,
    argv: &[String],
) -> Result<(), String> {
    use areev_llm::decide::{questions_from_wire, Question};
    use areev_llm::{DecideError, DecideRequest};
    use std::collections::BTreeMap;

    let decider = decider.ok_or_else(|| {
        DecideError::NotConfigured(
            "areev decide needs a backend — pass --decide <chain> and/or --decide-cmd <cmd> \
             (or set $AREEV_DECIDE / $AREEV_DECIDE_CMD)"
                .into(),
        )
        .to_string()
    })?;
    let decider = decider_for_egress(decider, flags.contains_key("anonymize-egress"))?;

    let raw_state = text_or_file("state", &need(flags, "state")?)?;
    let state = match serde_json::from_str::<serde_json::Value>(&raw_state) {
        Ok(v) if v.is_string() || v.is_object() || v.is_array() => v,
        _ => serde_json::Value::String(raw_state),
    };

    let forms: Vec<&str> = ["questions", "noul", "choice", "score"]
        .into_iter()
        .filter(|k| flags.contains_key(*k))
        .collect();
    if forms.len() != 1 {
        return Err(format!(
            "areev decide needs exactly one of --questions, --noul, --choice or --score (got {})",
            if forms.is_empty() { "none".to_string() } else { forms.iter().map(|f| format!("--{f}")).collect::<Vec<_>>().join(", ") }
        ));
    }
    let one = |q: Question| BTreeMap::from([("q".to_string(), q)]);
    let questions: BTreeMap<String, Question> = match forms[0] {
        "questions" => {
            let raw = text_or_file("questions", &need(flags, "questions")?)?;
            let v: serde_json::Value = serde_json::from_str(&raw)
                .map_err(|e| DecideError::InvalidQuestion(format!("--questions is not JSON: {e}")).to_string())?;
            questions_from_wire(&v).map_err(|e| e.to_string())?
        }
        "noul" => one(Question::noul(need(flags, "noul")?)),
        "choice" => {
            let mut options = Vec::new();
            for o in flag_values(argv, "option") {
                let (k, d) = o.split_once('=').ok_or_else(|| {
                    format!("--option {o:?}: expected KEY=DESCRIPTION (e.g. --option billing=\"money owed\")")
                })?;
                let k = k.trim().to_string();
                if options.iter().any(|(seen, _)| *seen == k) {
                    return Err(DecideError::InvalidQuestion(format!("--option {k:?} is given twice")).to_string());
                }
                options.push((k, d.trim().to_string()));
            }
            one(Question::choice(need(flags, "choice")?, options))
        }
        "score" => one(Question::score(need(flags, "score")?, flag_values(argv, "level"))),
        _ => unreachable!("forms holds only the four names above"),
    };

    let req = DecideRequest::new(state, questions);
    let decision = match decider.decide(&req) {
        Ok(d) => d,
        Err(e) => {
            // DEC-E007 directly, or a chain in which every entry failed and
            // one was rate limited with a Retry-After: wait once, retry once.
            let retry_after = match &e {
                DecideError::ChainExhausted(errs) => errs.iter().filter_map(|(_, e)| e.retry_after_secs()).min(),
                other => other.retry_after_secs(),
            };
            match retry_after {
                Some(secs) => {
                    let secs = secs.min(DECIDE_RETRY_AFTER_CAP_SECS);
                    eprintln!("areev: {e} — retrying once in {secs}s");
                    std::thread::sleep(std::time::Duration::from_secs(secs));
                    decider.decide(&req).map_err(|e| e.to_string())?
                }
                None => return Err(e.to_string()),
            }
        }
    };
    println!(
        "{}",
        serde_json::to_string_pretty(&decision.to_json()).map_err(|e| e.to_string())?
    );
    Ok(())
}

/// Bind the session principal from `--as` (validated against `--auth`'s
/// credential map when one is given): rights become exactly what the file's
/// grant grains cover for that principal — fail closed. Absent `--as`, the
/// local session stays the owner.
fn apply_principal(
    facade: areev_cal::AreevFacade,
    flags: &std::collections::HashMap<String, String>,
) -> Result<areev_cal::AreevFacade, String> {
    let Some(p) = flag(flags, "as") else {
        return Ok(facade);
    };
    if let Some(path) = flag(flags, "auth") {
        let text = std::fs::read_to_string(&path).map_err(|e| format!("--auth {path}: {e}"))?;
        let map = areev_core::authz::CredentialMap::from_json(&text).map_err(|e| e.to_string())?;
        map.knows_principal(&p).map_err(|e| e.to_string())?;
    }
    let bound = facade.with_principal(&p).map_err(|e| e.to_string())?;
    eprintln!("areev: session bound to principal '{p}' (rights from the file's grants)");
    Ok(bound)
}

/// Record a Tier-2 audit Observation for a host-level erasure (GDPR
/// Art. 5(2)/30). The CLI is a host: REQ-ERASE-5 keeps the audit grain out
/// of the *engine* so an erasure never writes the identity back, and leaves
/// the record to whoever invoked it — which for `areev forget-subject` /
/// `purge-older-than` is this. Uses the same builder as the CAL path so
/// `areev audit export` reads one shape, and the principal is `--as` when
/// given (else the local owner session).
///
/// Best-effort by construction: the erasure has already committed and
/// replicated. A failure to append the audit grain is reported loudly on
/// stderr but must not turn an accomplished erasure into an error exit —
/// that would tell the operator the deletion failed when it did not.
fn write_erasure_audit(
    m: &mut areev_store::Areev,
    flags: &HashMap<String, String>,
    verb: &str,
    target: &str,
    count: usize,
    stale_exports: &[areev_store::CorpusExportRegistry],
    // The legal hold this destruction overrode (#278), when it overrode one.
    overridden: Option<&areev_store::HoldRecord>,
) {
    let principal = flag(flags, "as").unwrap_or_else(|| "local:owner".to_string());
    let now = std::time::SystemTime::now()
        .duration_since(std::time::UNIX_EPOCH)
        .map(|d| d.as_millis() as i64)
        .unwrap_or(0);
    let because = flag(flags, "because");
    let mut obs = areev_core::authz::audit_observation(
        &principal,
        verb,
        target,
        because.as_deref(),
        count,
        now,
    );
    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: adapters trained on a stale corpus
        // are stale too (`areev tune` writes `derived_from` = the export
        // manifest). The erasure cannot reach into a checkpoint; it CAN say
        // precisely which adapters must be retired or re-derived — that
        // report is the whole point of the lineage.
        let mut stale_adapters = Vec::new();
        for export in stale_exports {
            let Ok(h) = Hash::from_hex(&export.manifest_hash) else {
                continue;
            };
            let kids = m.grains_derived_from(&h).unwrap_or_default();
            for g in kids {
                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));
        for export in stale_exports {
            let recipient = export
                .recipient
                .as_deref()
                .map(|id| format!(" for recipient {id}"))
                .unwrap_or_default();
            eprintln!(
                "areev: corpus {} at {}{} is stale and must be retired or re-derived",
                export.export_id, export.destination, recipient
            );
        }
        for a in &stale_adapters {
            eprintln!(
                "areev: adapter {} (grain {}) derives from stale corpus {} — retire or re-derive",
                a["subject"].as_str().unwrap_or("?"),
                a["grain_hash"].as_str().unwrap_or("?"),
                a["export_id"].as_str().unwrap_or("?"),
            );
        }
    }
    if let Some(hold) = overridden {
        let ctx = obs.common.context.get_or_insert_with(|| serde_json::json!({}));
        if let Some(o) = ctx.as_object_mut() {
            o.insert(
                "hold_overridden".into(),
                serde_json::json!({
                    "ns": hold.ns,
                    "placed_by": hold.placed_by,
                    "because": hold.because,
                }),
            );
        }
    }
    // Appended to the memory's ONE destruction chain (#280), not added
    // standalone: a record with no predecessor and no sequence is a record
    // whose deletion leaves the export looking clean.
    if let Err(e) = m.append_audit(&mut obs) {
        eprintln!("areev: warning: erasure succeeded but its audit record failed to write: {e}");
    }
}

/// True when a `host:port` (or bare host) names a loopback interface. Used to
/// refuse binding the unauthenticated `ui` console to a routable address.
/// Print any saved query or template the file carries that this build cannot
/// load, the same way `open_warnings` is printed.
///
/// Forces the registries to rehydrate first — they load lazily, so a verb that
/// never touches one would otherwise report nothing and the operator would find
/// out by noticing a saved query had gone missing.
fn report_meta_warnings(facade: &areev_cal::AreevFacade) {
    use areev_cal::CalStoreFacade;
    let _ = facade.list_queries();
    let _ = facade.list_templates();
    for w in facade.meta_warnings() {
        eprintln!("areev: warning: {w}");
    }
}

/// Would this mount point at the SAME memory as the primary?
///
/// The embedded backend refuses that by construction — a second handle on one
/// file fails at open with `STO-E002`, because two handles drift on their
/// cached allocators. Postgres has no such guard (it is genuinely
/// multi-writer), so the asymmetry would be silent: the mount would open, and
/// `alias.ns` would answer from the very store `ns` already reaches, doubling
/// every row an ASSEMBLE drew from both sources. Refuse it here instead.
#[cfg(feature = "postgres")]
fn mount_is_the_primary(primary: &str, mount: &str) -> bool {
    if !(is_pg_dsn(primary) && is_pg_dsn(mount)) {
        return false;
    }
    let norm = |d: &str| {
        areev_store::pg::split_schema_url(&areev_store::pg::strip_provision(d)).ok()
    };
    match (norm(primary), norm(mount)) {
        (Some(a), Some(b)) => a == b,
        _ => false,
    }
}

#[cfg(not(feature = "postgres"))]
fn mount_is_the_primary(_primary: &str, _mount: &str) -> bool {
    false
}

/// Redact a DSN's password for display. One implementation, shared with the
/// console (which needs it for the same reason: `--db` reaches log lines and
/// response bodies, and on the postgres backend it carries a secret).
fn redact_dsn(label: &str) -> String {
    areev_server::redact_dsn(label)
}

/// Does `s` begin with `alias=`? The one shape a `--mount` entry always has,
/// and the one shape the interior of a DSN never has at the top level.
fn starts_a_mount_entry(s: &str) -> bool {
    let Some((name, _)) = s.split_once('=') else { return false };
    !name.is_empty()
        && name
            .chars()
            .all(|c| c.is_ascii_alphanumeric() || matches!(c, '_' | '.' | '-'))
}

/// Parse `--mount alias=target[,alias=target...]` into `(alias, target)` pairs.
///
/// Splitting on every `,` is wrong the moment a target can be a DSN: libpq's
/// multi-host form (`postgres://h1:5432,h2:5432/db`) and an `options=` list
/// both contain commas, and cutting there produces two nonsense mounts instead
/// of one working one. A comma therefore separates mounts only when another
/// `alias=` follows it.
fn parse_mounts(spec: Option<&str>) -> Result<Vec<(String, String)>, String> {
    let Some(spec) = spec else { return Ok(Vec::new()) };
    let mut entries: Vec<&str> = Vec::new();
    let mut start = 0usize;
    for (i, c) in spec.char_indices() {
        if c == ',' && starts_a_mount_entry(spec[i + 1..].trim_start()) {
            entries.push(&spec[start..i]);
            start = i + 1;
        }
    }
    entries.push(&spec[start..]);
    let mut out = Vec::new();
    for entry in entries.into_iter().map(str::trim).filter(|e| !e.is_empty()) {
        let (alias, target) = entry
            .split_once('=')
            .map(|(a, t)| (a.trim(), t.trim()))
            .filter(|(a, t)| !a.is_empty() && !t.is_empty())
            .ok_or_else(|| {
                format!("--mount expects alias=<path|DSN>, got '{}'", redact_dsn(entry))
            })?;
        // The alias becomes a namespace prefix (`alias.inner`), so it must be
        // one identifier — no dot (the facade routes on the FIRST dot, so a
        // dotted alias could never be matched) and nothing a DSN contains.
        // Without this, a bare DSN passed with no alias splits at its
        // `?schema=` and mounts something nonsensical under an alias made of
        // half a connection string.
        if alias.is_empty()
            || !alias.chars().all(|c| c.is_ascii_alphanumeric() || matches!(c, '_' | '-'))
        {
            // Redacted like every other echo of caller text: a bare DSN
            // passed with no alias lands its userinfo in exactly this slot.
            return Err(format!(
                "--mount alias {:?} is not a name: an alias is [A-Za-z0-9_-]+ and becomes a \
                 namespace prefix (\"alias.inner\"). Write --mount <alias>=<path|DSN>",
                redact_dsn(alias)
            ));
        }
        out.push((alias.to_string(), target.to_string()));
    }
    Ok(out)
}

/// Open one `--mount` target: a memory FILE, or a postgres DSN
/// (`postgres://…?schema=<name>`) — the mount tier is not file-only.
///
/// Always **read-only**, on either backend. Mounts were already read-only by
/// construction (CAL routes writes to the session store and never to a mount),
/// so this makes the guarantee real rather than incidental, and it buys two
/// things that construction could not: a least-privilege postgres role with no
/// DDL grant can back a mount, and a file path that does not exist is refused
/// (`STO-E005`) instead of quietly becoming a new, empty memory that then
/// answers every cross-file question with silence.
///
/// Telemetry is `Off` explicitly: a sidecar per mount would be a second
/// connection and a second bootstrap for a store nothing writes to, and a
/// read-only handle refuses one anyway — passing the host default would only
/// print a "telemetry disabled" warning per mount.
fn open_mount(target: &str) -> Result<Areev, String> {
    if is_pg_dsn(target) {
        return open_postgres_store(target, areev_store::TelemetryMode::Off, None, None, true);
    }
    let opts = areev_store::AreevOptions { read_only: true, ..Default::default() };
    Areev::open_with(target, opts).map_err(|e| {
        let mut msg = e.to_string();
        if e.code() == "STO-E004" {
            // The read-only reconciliation refuses a declaration disagreement,
            // and a mount has no flag to spell the file's declaration with.
            msg.push_str(
                " — a mount is opened read-only, and a read-only open cannot re-stamp a \
                 declaration. Open this memory read-write once with the settings it should \
                 declare, then mount it",
            );
        }
        msg
    })
}

fn addr_is_loopback(addr: &str) -> bool {
    let a = addr.trim();
    // IPv6 bracketed form: [::1]:port
    if let Some(rest) = a.strip_prefix('[') {
        let host = rest.split(']').next().unwrap_or("");
        return host == "::1" || host.eq_ignore_ascii_case("localhost");
    }
    let host = a.rsplit_once(':').map(|(h, _)| h).unwrap_or(a);
    if host.eq_ignore_ascii_case("localhost") {
        return true;
    }
    match host.parse::<std::net::IpAddr>() {
        Ok(ip) => ip.is_loopback(),
        // An unqualified hostname or 0.0.0.0 is not provably loopback → treat as remote.
        Err(_) => false,
    }
}

fn parse_args(rest: &[String]) -> (HashMap<String, String>, Vec<String>) {
    let mut flags = HashMap::new();
    let mut positional = Vec::new();
    let mut i = 0;
    while i < rest.len() {
        let a = &rest[i];
        if let Some(name) = a.strip_prefix("--") {
            // A value is the next token only if it is not itself a flag. Reject
            // any leading '-' (not just "--"), so a valueless long flag doesn't
            // swallow a following short flag as its value — e.g. `serve --mcp -d
            // db` must parse `-d` as --db, not as the value of `--mcp`. This
            // matches the short-flag branch below. Flag values in this CLI never
            // start with '-'.
            if i + 1 < rest.len() && !rest[i + 1].starts_with('-') {
                flags.insert(name.to_string(), rest[i + 1].clone());
                i += 2;
            } else {
                flags.insert(name.to_string(), "true".to_string());
                i += 1;
            }
        } else if let Some(long) = short_flag(a) {
            if i + 1 < rest.len() && !rest[i + 1].starts_with('-') {
                flags.insert(long.to_string(), rest[i + 1].clone());
                i += 2;
            } else {
                flags.insert(long.to_string(), "true".to_string());
                i += 1;
            }
        } else {
            positional.push(a.clone());
            i += 1;
        }
    }
    (flags, positional)
}

/// Map one Claude Code transcript message onto OMS Event content blocks.
/// Tool-result bodies are bounded so a single command cannot exceed the grain
/// size cap; every elision is explicit and records the original byte length.
fn transcript_content_blocks(
    content: &serde_json::Value,
    turn: usize,
) -> (String, Vec<ContentBlock>, Vec<serde_json::Value>) {
    const TOOL_RESULT_CHARS: usize = 32 * 1024;

    fn truncate(s: &str, max: usize) -> (String, bool) {
        if s.chars().count() <= max {
            (s.to_string(), false)
        } else {
            (s.chars().take(max).collect(), true)
        }
    }
    fn tool_result_body(content: &serde_json::Value) -> String {
        match content {
            serde_json::Value::String(s) => s.clone(),
            serde_json::Value::Array(blocks) => blocks
                .iter()
                .filter_map(|b| b["text"].as_str().or_else(|| b.as_str()))
                .collect::<Vec<_>>()
                .join("\n"),
            other if other.is_object() => other["text"].as_str().unwrap_or("").to_string(),
            _ => String::new(),
        }
    }
    let input_blocks: Vec<&serde_json::Value> = match content {
        serde_json::Value::String(_) => Vec::new(),
        serde_json::Value::Array(blocks) => blocks.iter().collect(),
        _ => Vec::new(),
    };
    if let serde_json::Value::String(s) = content {
        return (
            s.clone(),
            vec![ContentBlock::Text { text: s.clone() }],
            Vec::new(),
        );
    }

    let mut rendered = Vec::new();
    let mut typed = Vec::new();
    let mut elisions = Vec::new();
    for (block_index, b) in input_blocks.into_iter().enumerate() {
        match b["type"].as_str() {
            Some("text") => {
                if let Some(text) = b["text"].as_str() {
                    rendered.push(text.to_string());
                    typed.push(ContentBlock::Text { text: text.to_string() });
                }
            }
            Some("tool_use") => {
                let name = b["name"].as_str().unwrap_or("tool").to_string();
                let id = b["id"]
                    .as_str()
                    .map(str::to_string)
                    .unwrap_or_else(|| format!("synthetic:{turn}:{block_index}"));
                let input = b.get("input").cloned().unwrap_or(serde_json::Value::Null);
                rendered.push(format!("[tool_use {name}] {input}"));
                typed.push(ContentBlock::ToolUse { id, name, input });
            }
            Some("tool_result") => {
                let original = tool_result_body(&b["content"]);
                let original_bytes = original.len();
                let (body, elided) = truncate(&original, TOOL_RESULT_CHARS);
                let is_error = b.get("is_error").and_then(serde_json::Value::as_bool);
                let flag = if is_error == Some(true) { " ERROR" } else { "" };
                rendered.push(format!("[tool_result{flag}] {body}"));
                typed.push(ContentBlock::ToolResult {
                    tool_use_id: b["tool_use_id"]
                        .as_str()
                        .map(str::to_string)
                        .unwrap_or_else(|| format!("synthetic:{turn}:{block_index}")),
                    content: body,
                    is_error,
                });
                if elided {
                    elisions.push(serde_json::json!({
                        "block_index": block_index,
                        "kind": "tool_result",
                        "original_bytes": original_bytes,
                        "kept_chars": TOOL_RESULT_CHARS,
                    }));
                }
            }
            // Bare `{text: ...}` blocks occur in older transcripts.
            _ => {
                if let Some(text) = b["text"].as_str() {
                    rendered.push(text.to_string());
                    typed.push(ContentBlock::Text { text: text.to_string() });
                }
            }
        }
    }
    (rendered.join("\n"), typed, elisions)
}

/// The turn's own timestamp in epoch milliseconds, if the transcript carries
/// one — epoch integers, numeric strings, or the ISO-8601 form Claude Code
/// writes.
///
/// `capture-stop` pins `created_at` from this so a turn's content address is
/// stable across hook firings. Without a stable stamp the cumulative transcript
/// re-hashes every turn on every firing, and the dedup that makes the capture
/// idempotent stops working.
fn transcript_turn_ms(record: &serde_json::Value) -> Option<i64> {
    let value = record.get("timestamp").or_else(|| record.get("created_at"))?;
    if let Some(ms) = value.as_i64() {
        return Some(ms);
    }
    let text = value.as_str()?;
    if let Ok(ms) = text.parse::<i64>() {
        return Some(ms);
    }
    chrono::DateTime::parse_from_rfc3339(text)
        .ok()
        .map(|dt| dt.timestamp_millis())
}

fn transcript_token_usage(message: &serde_json::Value) -> Option<TokenUsage> {
    let usage = message.get("usage")?.as_object()?;
    let u32_field = |primary: &str, alias: &str| {
        usage
            .get(primary)
            .or_else(|| usage.get(alias))
            .and_then(serde_json::Value::as_u64)
            .map(|n| n.min(u32::MAX as u64) as u32)
    };
    Some(TokenUsage {
        input_tokens: u32_field("input_tokens", "input").unwrap_or(0),
        output_tokens: u32_field("output_tokens", "output").unwrap_or(0),
        cache_read_tokens: u32_field("cache_read_tokens", "cache_read_input_tokens"),
        cache_creation_tokens: u32_field(
            "cache_creation_tokens",
            "cache_creation_input_tokens",
        ),
    })
}

/// Dispatch one `areev migrate --from <src>` run. Every source is file-based
/// (docs/migrate.md has the dump one-liners); `basic-memory` takes the vault
/// directory and walks its markdown files.
fn run_migrate(
    m: &mut Areev,
    ns: &str,
    from: &str,
    file: &str,
    history: Option<String>,
) -> Result<areev_store::migrate::MigrateReport, String> {
    use areev_store::migrate as mig;
    let read = |p: &str| std::fs::read_to_string(p).map_err(|e| format!("{p}: {e}"));
    let parse = |p: &str, s: &str| {
        serde_json::from_str::<serde_json::Value>(s).map_err(|e| format!("{p}: bad JSON: {e}"))
    };
    let rep = match from {
        "mem0" => {
            let export = parse(file, &read(file)?)?;
            let history = match &history {
                Some(h) => Some(parse(h, &read(h)?)?),
                None => None,
            };
            mig::migrate_mem0(m, ns, Some(&export), history.as_ref())
        }
        "mem0-history" => {
            let h = parse(file, &read(file)?)?;
            mig::migrate_mem0(m, ns, None, Some(&h))
        }
        "langgraph" | "langmem" => mig::migrate_langgraph(m, ns, &read(file)?),
        "letta" => {
            let af = parse(file, &read(file)?)?;
            mig::migrate_letta(m, ns, &af)
        }
        "letta-archival" => mig::migrate_letta_archival(m, ns, &read(file)?),
        "zep" | "graphiti" => {
            let v = parse(file, &read(file)?)?;
            mig::migrate_zep(m, ns, &v)
        }
        "jsonl" => mig::migrate_jsonl(m, ns, &read(file)?),
        // Generic tool-call log (OpenAI-style JSONL) → Tool grains, so the
        // flagship analyzer can cluster failures from history that predates
        // Areev. One line per record; assistant `tool_calls` arrays expand.
        "tool-log" | "openai-tools" => {
            let mut rep = mig::MigrateReport::default();
            for (i, line) in read(file)?.lines().enumerate() {
                let line = line.trim();
                if line.is_empty() {
                    continue;
                }
                let v: serde_json::Value = serde_json::from_str(line)
                    .map_err(|e| format!("{file}:{}: bad JSON: {e}", i + 1))?;
                for (record_index, record) in extract_tool_records(&v).into_iter().enumerate() {
                    use sha2::{Digest, Sha256};
                    let synthetic_call_id = || {
                        let mut digest = Sha256::new();
                        digest.update(file.as_bytes());
                        digest.update([0]);
                        digest.update(line.as_bytes());
                        digest.update((i as u64).to_le_bytes());
                        digest.update((record_index as u64).to_le_bytes());
                        format!("import:{}", &hex::encode(digest.finalize())[..24])
                    };
                    let mut tool = Tool::new(&record.name)
                        .is_error(record.is_error)
                        // Unknown source time is pinned, not replaced with the
                        // import wall clock, so rerunning the same import can
                        // actually deduplicate it.
                        .created_at(record.created_at.unwrap_or(0));
                    if let Some(input) = record.input {
                        tool = tool.input(input);
                    }
                    if !record.content.is_empty() {
                        tool = tool.content(&record.content);
                    }
                    // The per-record digest is stable across reruns but
                    // distinguishes identical retries on separate lines.
                    let call_id = record.call_id.unwrap_or_else(synthetic_call_id);
                    tool = tool.tool_call_id(&call_id);
                    let tool = tool.namespace(ns);
                    let (_, hash) = areev_core::format::serialize::serialize_grain(&tool)
                        .map_err(|e| e.to_string())?;
                    if m.get(&hash).is_ok() {
                        rep.skipped += 1;
                    } else {
                        m.add(&tool).map_err(|e| e.to_string())?;
                        rep.added += 1;
                    }
                }
            }
            Ok(rep)
        }
        "basic-memory" => {
            let root = std::path::PathBuf::from(file);
            if !root.is_dir() {
                return Err(format!(
                    "--from basic-memory expects --file to be the vault directory (got {file})"
                ));
            }
            // Deterministic walk: collect *.md paths, sorted.
            let mut notes: Vec<std::path::PathBuf> = Vec::new();
            let mut stack = vec![root.clone()];
            while let Some(d) = stack.pop() {
                let entries = std::fs::read_dir(&d).map_err(|e| format!("{}: {e}", d.display()))?;
                for entry in entries {
                    let path = entry.map_err(|e| e.to_string())?.path();
                    if path.is_dir() {
                        stack.push(path);
                    } else if path.extension().is_some_and(|x| x == "md") {
                        notes.push(path);
                    }
                }
            }
            notes.sort();
            let mut rep = mig::MigrateReport::default();
            for path in notes {
                let rel = path
                    .strip_prefix(&root)
                    .unwrap_or(&path)
                    .to_string_lossy()
                    .replace('\\', "/");
                let md = read(&path.to_string_lossy())?;
                let mtime_ms = std::fs::metadata(&path)
                    .and_then(|md| md.modified())
                    .ok()
                    .and_then(|t| t.duration_since(std::time::UNIX_EPOCH).ok())
                    .map(|d| d.as_millis() as i64);
                mig::migrate_basic_memory_note(m, ns, &rel, &md, mtime_ms, &mut rep)
                    .map_err(|e| e.to_string())?;
            }
            Ok(rep)
        }
        other => {
            return Err(format!(
                "unknown --from '{other}' — sources: mem0, mem0-history, langgraph, letta, \
                 letta-archival, zep, basic-memory, jsonl, tool-log"
            ))
        }
    };
    rep.map_err(|e| e.to_string())
}

#[derive(Debug, Clone, PartialEq)]
struct ImportedToolRecord {
    name: String,
    input: Option<serde_json::Value>,
    content: String,
    is_error: bool,
    call_id: Option<String>,
    created_at: Option<i64>,
}

/// Extract typed tool records from one tool-log JSONL
/// line: a direct `{tool_name, content, is_error}` record, an OpenAI
/// `role:"tool"` result, or an assistant message carrying a `tool_calls` array.
fn extract_tool_records(v: &serde_json::Value) -> Vec<ImportedToolRecord> {
    let stringify = |x: &serde_json::Value| match x {
        serde_json::Value::String(s) => s.clone(),
        other => other.to_string(),
    };
    let created_at = v
        .get("created_at")
        .or_else(|| v.get("timestamp"))
        .and_then(|value| {
            value
                .as_i64()
                .or_else(|| value.as_str().and_then(|s| s.parse::<i64>().ok()))
        });
    // Assistant message with a tool_calls array: one record per call.
    if let Some(calls) = v.get("tool_calls").and_then(|c| c.as_array()) {
        return calls
            .iter()
            .filter_map(|c| {
                let name = c
                    .get("function")
                    .and_then(|f| f.get("name"))
                    .and_then(|n| n.as_str())
                    .or_else(|| c.get("name").and_then(|n| n.as_str()))?;
                let input = c
                    .get("function")
                    .and_then(|f| f.get("arguments"))
                    .or_else(|| c.get("input"))
                    .map(|value| match value {
                        serde_json::Value::String(raw) => serde_json::from_str(raw)
                            .unwrap_or_else(|_| serde_json::Value::String(raw.clone())),
                        other => other.clone(),
                    });
                let is_error = c
                    .get("is_error")
                    .and_then(|e| e.as_bool())
                    .unwrap_or_else(|| c.get("error").is_some());
                let call_id = c
                    .get("id")
                    .or_else(|| c.get("tool_call_id"))
                    .and_then(|id| id.as_str())
                    .map(str::to_string);
                Some(ImportedToolRecord {
                    name: name.to_string(),
                    input,
                    content: String::new(),
                    is_error,
                    call_id,
                    created_at,
                })
            })
            .collect();
    }
    // A single tool record / tool-result message.
    let name = v
        .get("tool_name")
        .and_then(|n| n.as_str())
        .or_else(|| v.get("name").and_then(|n| n.as_str()))
        .or_else(|| v.get("function").and_then(|f| f.get("name")).and_then(|n| n.as_str()));
    match name {
        Some(name) => {
            let content = v
                .get("content")
                .or_else(|| v.get("output"))
                .or_else(|| v.get("result"))
                .map(&stringify)
                .unwrap_or_default();
            let is_error = v
                .get("is_error")
                .and_then(|e| e.as_bool())
                .unwrap_or_else(|| v.get("error").is_some());
            let input = v.get("input").or_else(|| v.get("arguments")).map(|value| match value {
                serde_json::Value::String(raw) => serde_json::from_str(raw)
                    .unwrap_or_else(|_| serde_json::Value::String(raw.clone())),
                other => other.clone(),
            });
            let call_id = v
                .get("tool_call_id")
                .or_else(|| v.get("call_id"))
                .or_else(|| v.get("id"))
                .and_then(|id| id.as_str())
                .map(str::to_string);
            vec![ImportedToolRecord {
                name: name.to_string(),
                input,
                content,
                is_error,
                call_id,
                created_at,
            }]
        }
        None => Vec::new(),
    }
}

fn run() -> Result<(), String> {
    let argv: Vec<String> = std::env::args().skip(1).collect();
    let cmd = match argv.first() {
        Some(c) => c.clone(),
        None => {
            println!("{USAGE}");
            return Ok(());
        }
    };
    if cmd == "help" || cmd == "--help" || cmd == "-h" {
        println!("{USAGE}");
        return Ok(());
    }
    if cmd == "version" || cmd == "--version" || cmd == "-V" {
        println!("areev {}", env!("CARGO_PKG_VERSION"));
        return Ok(());
    }
    let (flags, positional) = parse_args(&argv[1..]);

    // Register the environment variables the operator has told us hold secrets,
    // before anything can spawn a child. Every subprocess seam scrubs these.
    // Registering by NAME is what makes this possible: `--passphrase-env VAR`
    // passes the variable name, not the value, so we know exactly what to
    // withhold without ever having to guess which ambient variables are
    // sensitive. Done here, at the one choke point every verb passes through,
    // rather than at each flag's read site — `--token-env` is consumed inside
    // two different verb arms, and a seam that spawned before the arm ran would
    // have leaked it.
    // Both registries: areev-loop owns the `--llm-cmd` and `--analyzer-cmd`
    // seams and cannot depend on an areev-* sibling, so it keeps its own.
    for var_flag in [
        "passphrase-env",
        "token-env",
        "anon-key-env",
        "signing-key-env",
        // [A0/A3] Both are impersonation-grade: the proxy secret can assert
        // any identity, and the OIDC client secret can redeem codes as the
        // console itself. Neither may reach a --tool-cmd subprocess.
        "sso-secret-env",
        "sso-secret-env-next",
        "oidc-client-secret-env",
    ] {
        if let Some(var) = flag(&flags, var_flag) {
            areev_core::proc::deny_env_var(&var);
            areev_loop::proc::deny_env_var(&var);
        }
    }
    // `--credential NAME=ENV_VAR` names a variable the same way, but spells it
    // on the right of an `=` — so it needs its own parse rather than a fourth
    // entry in the list above (#100). `Credential::bearer_from_env` registers
    // the core seam for every host that reads one; this adds the loop mirror,
    // and does it HERE rather than in `build_egress` because the choke point
    // runs before any verb arm can spawn. The variable spelling (#201) is
    // read here too: a secret named out of band is still a secret.
    if let Some(list) = run_stack::flag_or_env(&flags, "credential", areev_run::egress_spec::ENV_CREDENTIAL) {
        for pair in list.split(',') {
            if let Some((_, spec)) = pair.split_once('=') {
                let spec = spec.trim();
                // A `cmd:` spec names no variable to withhold — the secret is
                // minted at call time and never sits in the environment at
                // all, which is the point of #113. Skipping it also keeps a
                // shell command from being registered as a nonsense variable
                // name.
                if spec.starts_with("cmd:") {
                    continue;
                }
                // A `vault:` spec DOES imply variables: the broker reads
                // `$VAULT_TOKEN` (and friends) in-process to authenticate.
                // `CredentialSource::from_spec` registers them in the core
                // registry; the loop mirror is only reachable from here, so
                // both are done at this choke point like every other secret.
                if spec.starts_with("vault:") {
                    for var in ["VAULT_TOKEN", "VAULT_ADDR", "VAULT_NAMESPACE"] {
                        areev_core::proc::deny_env_var(var);
                        areev_loop::proc::deny_env_var(var);
                    }
                    continue;
                }
                // The spec may carry a `VAR@principal` owner (#101); the deny
                // list wants the bare variable name, so strip the qualifier.
                let var = spec.split_once('@').map(|(v, _)| v).unwrap_or(spec).trim();
                if !var.is_empty() {
                    areev_core::proc::deny_env_var(var);
                    areev_loop::proc::deny_env_var(var);
                }
            }
        }
    }
    // `--resolver-env` names the variables a credential RESOLVER needs for its
    // own authentication — `VAULT_TOKEN`, `AWS_PROFILE`, a service-account
    // path (#113). Registering them here is the load-bearing half: a vault
    // token is a secret one class more powerful than the credential it
    // fetches, since it can fetch all of them, and leaving it in the ambient
    // environment would put it inside every `--tool-cmd` subprocess — the #100
    // leak reopened one level up. Withheld from every child here, and
    // re-admitted only for resolver spawns (`CredentialSource::spawn_policy`).
    if let Some(list) = run_stack::flag_or_env(&flags, "resolver-env", areev_run::egress_spec::ENV_RESOLVER_ENV) {
        for var in list.split(',').map(str::trim).filter(|v| !v.is_empty()) {
            areev_core::proc::deny_env_var(var);
            areev_loop::proc::deny_env_var(var);
        }
    }

    // The decision-backend chain is host config (per-process, never in the
    // file), resolved before any dispatch so a bad spec fails every verb.
    let decider = resolve_decider(&flags)?;
    // Same for the recall deadline: a malformed value fails every verb here,
    // not only the ones that happen to recall.
    run_stack::recall_deadline(&flags)?;
    if cmd == "decide" {
        // `decide` judges a state it is handed; it names no memory, so it
        // dispatches before `resolve_db` like `auth` and `provision`.
        return run_decide(decider, &flags, &argv[1..]);
    }

    // `auth` manages the host-side credential map (`areev-auth.json`) and
    // never opens a memory. Dispatched BEFORE `resolve_db` on purpose: the
    // map holds no policy and names no file, so resolving a default memory
    // here would both be wasted work and print a line implying an
    // association between a credential and a database that does not exist.
    if cmd == "auth" {
        return run_auth(&flags, &positional);
    }

    // `provision` bootstraps a postgres schema OFF the request path. Also
    // dispatched before `resolve_db`, and for a related reason: it does not
    // open a memory the way every verb below does — it must not fall back to
    // the personal default file (a file memory has nothing to provision), and
    // it takes its DSN explicitly so the schema it creates is never a
    // surprise.
    if cmd == "provision" {
        return run_provision(&flags);
    }

    // `pack validate` reads a directory and opens nothing: content addressing
    // is a pure function of the grain, so what a pack WILL install is knowable
    // without a memory to install it into. Dispatched here for the same reason
    // `auth` is — resolving a default memory would create a file the command
    // has no use for, and print a line implying an association that does not
    // exist. `install`/`export` fall through and take one normally.
    if cmd == "pack" && positional.first().map(|s| s.as_str()) == Some("validate") {
        return pack::run_pack(None, "shared", &flags, &positional);
    }

    // Long-lived / exposed surfaces must name their memory explicitly rather
    // than silently defaulting to the personal file.
    let db = resolve_db(&flags, matches!(cmd.as_str(), "serve" | "ui"))?;
    let ns = flag(&flags, "ns").unwrap_or_else(|| "shared".to_string());

    // print-only verbs never open the store (paths may be untilde-expanded)
    if cmd == "hook" {
        let target = positional.first().map(String::as_str).unwrap_or("claude-code");
        if target != "claude-code" {
            return Err(format!("unknown hook target '{target}'"));
        }
        let exe = std::env::current_exe()
            .map(|p| p.display().to_string())
            .unwrap_or_else(|_| "areev".into());
        println!(
            r#"Add to ~/.claude/settings.json (hooks section) to close the learning
loop automatically — inject relevant memory before each prompt, and capture
each exchange (with tool outcomes) when a turn ends:

{{
  "hooks": {{
    "UserPromptSubmit": [{{ "hooks": [{{
      "type": "command",
      "command": "{exe} recall-hook --db {db} --ns {ns} --with-loop"
    }}] }}],
    "Stop": [{{ "hooks": [{{
      "type": "command",
      "command": "{exe} capture-stop --db {db} --ns {ns}"
    }}] }}],
    "PreCompact": [{{ "hooks": [{{
      "type": "command",
      "command": "{exe} capture-stop --db {db} --ns {ns}"
    }}] }}]
  }}
}}

PreCompact is the same verb on the event that says the conversation is about
to be dropped: it captures whatever the last Stop did not, so a compaction
costs the model its context and costs the memory nothing. No matcher, so it
fires for manual /compact and automatic compaction alike, and it exits
silently when the host gives it no transcript — a hook must never be why a
compaction stalls. The summary a compaction produces is stored with
`compact_summary: true`, so a reader can tell a machine's recap from what the
person actually typed.

recall-hook reads the prompt and prints matching memories to stdout, which
Claude Code injects as context — so retrieval no longer depends on the model
choosing to call a tool. For on-demand reads/writes by the model itself, also
register the MCP server:
  claude mcp add areev -- {exe} serve --mcp --db {db} --ns {ns}

Nothing was written — apply the snippet yourself (or rerun with your own paths)."#
        );
        return Ok(());
    }

    // `anonymize scan` and `anonymize test` are pure text processing: they
    // never open the store, so they dispatch BEFORE `resolve_db` for the same
    // reason `auth` does — resolving a default memory here is wasted work, and
    // it prints a line naming a database the command never touches. The policy
    // verbs (set/list/clear/mappings) are store-backed and dispatch below.
    if cmd == "anonymize" && positional.first().map(String::as_str) == Some("scan") {
        let text = match flag(&flags, "text") {
            Some(t) => t,
            None => {
                let mut buf = String::new();
                std::io::Read::read_to_string(&mut std::io::stdin(), &mut buf)
                    .map_err(|e| format!("reading stdin: {e}"))?;
                buf
            }
        };
        let policy = match flag(&flags, "policy-file") {
            Some(path) => {
                let json = std::fs::read_to_string(&path)
                    .map_err(|e| format!("--policy-file {path}: {e}"))?;
                areev_core::anon::AnonPolicy::from_json(&json).map_err(|e| e.to_string())?
            }
            None => areev_core::anon::AnonPolicy::default(),
        };
        let out = areev_core::anon::scan(&text, &policy, &[]).map_err(|e| e.to_string())?;
        println!(
            "{}",
            serde_json::to_string_pretty(&out).map_err(|e| e.to_string())?
        );
        return Ok(());
    }

    // `anonymize test` is pure text processing too: a policy plus a fixture
    // file, no store. It exists because an untestable egress control is close
    // to an unusable one — an operator could not assert "this policy must
    // redact these strings and must not redact those" and have CI fail on a
    // regression, which is the first artifact an auditor asks to see.
    if cmd == "anonymize" && positional.first().map(String::as_str) == Some("test") {
        let path = flag(&flags, "fixtures")
            .ok_or("anonymize test requires --fixtures <FILE> (JSON)")?;
        let raw = std::fs::read_to_string(&path)
            .map_err(|e| format!("--fixtures {path}: {e}"))?;
        let fx: serde_json::Value =
            serde_json::from_str(&raw).map_err(|e| format!("--fixtures {path}: {e}"))?;
        let must_redact = fixture_strings(&fx, "must_redact", &path)?;
        let must_not_redact = fixture_strings(&fx, "must_not_redact", &path)?;
        // A policy on the CLI overrides the one in the file, so one fixture
        // set can be run against a candidate policy before it is deployed.
        let policy = match flag(&flags, "policy-file") {
            Some(pp) => {
                let json = std::fs::read_to_string(&pp)
                    .map_err(|e| format!("--policy-file {pp}: {e}"))?;
                areev_core::anon::AnonPolicy::from_json(&json).map_err(|e| e.to_string())?
            }
            None => match fx.get("policy") {
                Some(v) => areev_core::anon::AnonPolicy::from_json(&v.to_string())
                    .map_err(|e| e.to_string())?,
                None => return Err(format!("{path} has no \"policy\" and no --policy-file given")),
            },
        };

        let mut misses: Vec<String> = Vec::new();
        let mut false_positives: Vec<String> = Vec::new();
        for want in &must_redact {
            let got = areev_core::anon::anonymize(want, &policy, &[], None)
                .map_err(|e| e.to_string())?;
            // "Redacted" means the text changed: the policy acted on it,
            // whether by pseudonym, mask or redaction.
            if got.text == *want {
                misses.push(want.clone());
            }
        }
        for want in &must_not_redact {
            let got = areev_core::anon::anonymize(want, &policy, &[], None)
                .map_err(|e| e.to_string())?;
            if got.text != *want {
                false_positives.push(format!("{want}  ->  {}", got.text));
            }
        }

        let total = must_redact.len() + must_not_redact.len();
        let failed = misses.len() + false_positives.len();
        for m in &misses {
            eprintln!("MISS (should have been redacted): {m}");
        }
        for f in &false_positives {
            eprintln!("FALSE POSITIVE (should have been left alone): {f}");
        }
        println!(
            "{} fixtures: {} passed, {} failed ({} missed, {} false positive)",
            total,
            total - failed,
            failed,
            misses.len(),
            false_positives.len()
        );
        if failed > 0 {
            // Non-zero exit is the point: this runs in CI.
            std::process::exit(1);
        }
        return Ok(());
    }

    // Long-lived / exposed surfaces must name their memory explicitly rather
    // than silently defaulting to the personal file.
    let db = resolve_db(&flags, matches!(cmd.as_str(), "serve" | "ui"))?;
    let ns = flag(&flags, "ns").unwrap_or_else(|| "shared".to_string());

    // print-only verbs never open the store (paths may be untilde-expanded)
    if cmd == "hook" {
        let target = positional.first().map(String::as_str).unwrap_or("claude-code");
        if target != "claude-code" {
            return Err(format!("unknown hook target '{target}'"));
        }
        let exe = std::env::current_exe()
            .map(|p| p.display().to_string())
            .unwrap_or_else(|_| "areev".into());
        println!(
            r#"Add to ~/.claude/settings.json (hooks section) to close the learning
loop automatically — inject relevant memory before each prompt, and capture
each exchange (with tool outcomes) when a turn ends:

{{
  "hooks": {{
    "UserPromptSubmit": [{{ "hooks": [{{
      "type": "command",
      "command": "{exe} recall-hook --db {db} --ns {ns} --with-loop"
    }}] }}],
    "Stop": [{{ "hooks": [{{
      "type": "command",
      "command": "{exe} capture-stop --db {db} --ns {ns}"
    }}] }}],
    "PreCompact": [{{ "hooks": [{{
      "type": "command",
      "command": "{exe} capture-stop --db {db} --ns {ns}"
    }}] }}]
  }}
}}

PreCompact is the same verb on the event that says the conversation is about
to be dropped: it captures whatever the last Stop did not, so a compaction
costs the model its context and costs the memory nothing. No matcher, so it
fires for manual /compact and automatic compaction alike, and it exits
silently when the host gives it no transcript — a hook must never be why a
compaction stalls. The summary a compaction produces is stored with
`compact_summary: true`, so a reader can tell a machine's recap from what the
person actually typed.

recall-hook reads the prompt and prints matching memories to stdout, which
Claude Code injects as context — so retrieval no longer depends on the model
choosing to call a tool. For on-demand reads/writes by the model itself, also
register the MCP server:
  claude mcp add areev -- {exe} serve --mcp --db {db} --ns {ns}

Nothing was written — apply the snippet yourself (or rerun with your own paths)."#
        );
        return Ok(());
    }

    // `--read-only` is needed before the key derivation just below (which
    // creates a .kdf sidecar for an absent path), and again for `tel_mode`,
    // the `--index-text` conflict check, and the open itself.
    let read_only = flags.contains_key("read-only");

    // Optional encryption: when --passphrase-env <VAR> is given, derive an
    // AES-256 key from the passphrase held in that environment variable
    // (Argon2id; salt in a <db>.kdf sidecar). The passphrase and the derived
    // key are held in zeroizing buffers; note the storage engine keeps the key
    // resident in memory while the database is open.
    let is_pg_url = is_pg_dsn(&db);
    let enc_key = match flag(&flags, "passphrase-env") {
        Some(_) if is_pg_url => {
            return Err(
                "--passphrase-env applies to file-backed memories (page cipher + .kdf \
                 sidecar); on the postgres backend use TDE/pgcrypto at the deployment layer"
                    .into(),
            );
        }
        Some(var) => {
            let pass = zeroize::Zeroizing::new(std::env::var(&var).map_err(|_| {
                format!("--passphrase-env {var}: environment variable is not set")
            })?);
            if pass.trim().is_empty() {
                return Err(format!("--passphrase-env {var}: passphrase is empty"));
            }
            // Deriving writes the .kdf sidecar when absent, so the read-only
            // precondition has to be checked first or a refused open leaves a
            // stray file behind.
            if !is_pg_url {
                areev_store::read_only_requires_existing(&db, read_only)
                    .map_err(|e| e.to_string())?;
            }
            Some(Areev::derive_key_for(&db, pass.as_str()).map_err(|e| e.to_string())?)
        }
        None => None,
    };

    // The anonymization root (--anon-key-env VAR, 64 hex characters in that
    // variable). Independent of the page cipher: it is the HKDF root for the
    // session/memory/vault subkeys when supplied, which is what makes the
    // mapping vault and deterministic value-derived tokens work on Postgres
    // (no page cipher there) and on plaintext files. Named by variable, never
    // taken on the command line, so it stays out of shell history and `ps`.
    // Never persisted — rotating it is a crypto-erasure of the mapping table,
    // so it belongs in a KMS.
    let anon_key = match flag(&flags, "anon-key-env") {
        Some(var) => {
            let raw = zeroize::Zeroizing::new(std::env::var(&var).map_err(|_| {
                format!("--anon-key-env {var}: environment variable is not set")
            })?);
            Some(parse_anon_key(raw.trim()).map_err(|e| format!("--anon-key-env {var}: {e}"))?)
        }
        None => None,
    };

    // Recall-telemetry sidecar (host capability, §8): the agent-host default is
    // `aggregate`; `--telemetry off|aggregate|full` overrides. It is NOT a
    // file-truth, so it never re-stamps the file's declarations. A read-only
    // handle attaches no sidecar regardless (its flush is a write) — when the
    // caller never asked for telemetry, resolve straight to `Off` so there is
    // nothing for the store to override (and nothing to warn about) on the
    // common `--read-only` path. An EXPLICIT `--telemetry aggregate|full`
    // together with `--read-only` is a real, deliberate conflict, so that
    // still flows through unchanged and the store's own override/warning
    // applies.
    let tel_mode = match flag(&flags, "telemetry") {
        Some(v) => areev_store::TelemetryMode::parse(&v)
            .ok_or_else(|| {
                format!("--telemetry: unknown mode '{v}' (off|aggregate|aggregate-hashed|full)")
            })?,
        None if read_only => areev_store::TelemetryMode::Off,
        None => areev_store::TelemetryMode::Aggregate,
    };

    // `areev blob get` is served BEFORE the open, from the `.blobs` sidecar.
    // The embedded backend's file lock is exclusive — while a run holds a
    // memory, a second process is refused even for a read — which would put an
    // attachment out of reach of the very `--tool-cmd` subprocess the run
    // spawned to process it. Blobs are immutable, live beside the file, and
    // carry their checksum as their address, so reading one needs neither the
    // database nor a lock — on postgres, one connection of its own and a
    // schema-qualified SELECT. A sealed blob still needs the memory's derived
    // key, so that case falls through to the normal open below.
    if cmd == "blob" && positional.first().map(String::as_str) == Some("get") {
        let uri = positional
            .get(1)
            .ok_or("usage: areev blob get <cas-uri> --db <file|dsn>")?;
        if let Some(bytes) = areev_store::read_blob_offline(&db, uri).map_err(|e| e.to_string())? {
            use std::io::Write;
            std::io::stdout().write_all(&bytes).map_err(|e| e.to_string())?;
            return Ok(());
        }
    }

    // Files carry their own declarations (meta table); a bare open honors
    // them. --index-text is an explicit, deliberate re-stamp; encryption is a
    // host-supplied capability that also requires open_with.
    let explicit_index = flag(&flags, "index-text");
    // --index-text always re-stamps the file's declaration (a write); a
    // read-only handle can never honor that, so refuse up front rather than
    // failing partway through open with a less legible error.
    if read_only && explicit_index.is_some() {
        return Err(
            "--read-only cannot be combined with an explicit --index-text: --index-text \
             always re-stamps the file's declaration, and a read-only open never writes. \
             Drop --index-text (a read-only open honors whatever the file already declares) \
             or drop --read-only"
                .into(),
        );
    }
    let mut m = if is_pg_url {
        open_postgres_store(&db, tel_mode, explicit_index.as_deref(), anon_key, read_only)?
    } else {
        if explicit_index.is_some() || enc_key.is_some() || anon_key.is_some() || read_only {
            let mut o = areev_store::AreevOptions::default();
            if let Some(v) = &explicit_index {
                o.index_text = !matches!(v.as_str(), "false" | "0" | "off" | "no");
            }
            if let Some(key) = &enc_key {
                o.encryption_key = Some(**key);
            }
            o.anon_key = anon_key;
            o.telemetry = tel_mode;
            o.read_only = read_only;
            Areev::open_with(&db, o)
        } else if tel_mode != areev_store::TelemetryMode::Off {
            // Honor the file's declarations AND attach the telemetry sidecar.
            Areev::open_with_telemetry(&db, tel_mode)
        } else {
            Areev::open(&db)
        }
        .map_err(|e| {
            let mut msg = e.to_string();
            // A .kdf sidecar means the file was created encrypted; opening it
            // without a key fails with an unhelpful "not a database" — say why.
            if enc_key.is_none() && std::path::Path::new(&format!("{db}.kdf")).exists() {
                msg.push_str(&format!(
                    " — {db}.kdf exists, so this memory is encrypted; pass --passphrase-env <VAR>"
                ));
            }
            msg
        })?
    };
    for w in m.open_warnings() {
        eprintln!("areev: warning: {w}");
    }
    // Host-scoped trajectory context for recall telemetry. The same flag is
    // also consumed by run-manifest/run-trace commands; it is not a file
    // declaration.
    m.set_run_id(flag(&flags, "run-id").as_deref());

    // Host cap (per-process, never persisted): --anonymize-egress forces
    // egress anonymization on every namespace without a declared policy and
    // upgrades a declared "off". It can never weaken a declared policy.
    if flags.contains_key("anonymize-egress") {
        m.set_anonymize_egress_floor(true);
    }
    // Tier-1 NER detector over the command seam (probed here, so a broken
    // command fails at startup instead of failing every covered read closed).
    if let Some(cmd_line) = flag(&flags, "anonymize-cmd") {
        let backend =
            areev_store::CommandAnonymize::new(&cmd_line).map_err(|e| e.to_string())?;
        m.set_anonymizer(Box::new(backend));
    }
    // Tier-2 LLM detector: a host command wrapping a (local-first) model.
    // Grounded — the model proposes span texts, never offsets, and anything
    // not present verbatim in the source is discarded.
    if let Some(cmd_line) = flag(&flags, "anonymize-llm-cmd") {
        let model = flag(&flags, "anonymize-llm-model");
        let llm = areev_loop::CommandLlm::new(&cmd_line, model.as_deref())
            .map_err(|e| e.to_string())?;
        m.set_anonymizer(Box::new(areev_llm::LlmDetector::new(llm)));
    }

    // Optional host-supplied embedder: --embed-cmd 'CMD' spawns CMD per embed
    // (text on stdin, JSON array of numbers on stdout). Enables the vector
    // recall leg and embeds newly written grains; the file records the model
    // as embedding provenance.
    if let Some(cmd_line) = flag(&flags, "embed-cmd") {
        let model = flag(&flags, "embed-model");
        let seen = m.open_warnings().len();
        let ce = areev_store::CommandEmbed::new(&cmd_line, model.as_deref())
            .map_err(|e| e.to_string())?;
        m.set_embedder(Box::new(ce));
        for w in &m.open_warnings()[seen..] {
            eprintln!("areev: warning: {w}");
        }
    }

    // Optional reranker (host config, per-process). `--rerank-cmd 'CMD'`
    // (or $AREEV_RERANK_CMD) installs a command reranker; otherwise a
    // decision chain (--decide / --decide-cmd) is installed as one — scoring
    // each candidate's relevance, reordering, never omitting. An explicit
    // command wins over the chain. Either way it runs where a recall asks for
    // rerank: `search` and `recall-hook` always do when one is installed,
    // CAL on `WITH rerank`. A failure falls back to fusion order.
    if let Some(cmd_line) = run_stack::flag_or_env(&flags, "rerank-cmd", "AREEV_RERANK_CMD") {
        // Refused at startup when the program cannot be found (the MCP
        // server's rule): a reranker that silently fails open on every
        // recall would look like working software.
        let program = cmd_line.split_whitespace().next().unwrap_or_default();
        if !areev_mcp::program_resolves(program) {
            return Err(format!(
                "--rerank-cmd (or $AREEV_RERANK_CMD): '{program}' is not an executable file or a \
                 command on PATH"
            ));
        }
        let model = flag(&flags, "rerank-model");
        let rr = areev_store::CommandRerank::new(&cmd_line, model.as_deref())
            .map_err(|e| format!("--rerank-cmd: {e}"))?;
        m.set_reranker(Box::new(rr));
    } else if let Some(chain) = &decider {
        let chain = decider_for_egress(chain.clone(), store_egress_active(&m))?;
        m.set_reranker(Box::new(areev_store::DecisionRerank::new(chain)));
    }

    // Grain attestation (docs/grain-attestation-plan.md). The author key is
    // named by variable like every other secret here; the trusted-authors
    // document is a host file. Both are handle-level host config, never
    // written to the memory.
    if let Some(var) = flag(&flags, "signing-key-env") {
        let raw = zeroize::Zeroizing::new(std::env::var(&var).map_err(|_| {
            format!("--signing-key-env {var}: environment variable is not set")
        })?);
        m.set_signing_key_hex(raw.trim())
            .map_err(|e| format!("--signing-key-env {var}: {e}"))?;
    }
    if let Some(path) = flag(&flags, "trusted-authors") {
        let doc = std::fs::read_to_string(&path)
            .map_err(|e| format!("--trusted-authors {path}: {e}"))?;
        m.set_trusted_authors(&doc).map_err(|e| format!("--trusted-authors {path}: {e}"))?;
    }
    if flags.contains_key("require-attested") {
        if flag(&flags, "trusted-authors").is_none() {
            return Err("--require-attested needs --trusted-authors FILE (nothing to require against)".into());
        }
        m.set_attest_policy(areev_store::AttestPolicy::Require);
    }

    match cmd.as_str() {
        "add" => {
            // Positional `areev add <subject> <relation> <object>`, or the
            // explicit --subject/--relation/--object flags.
            let (s, r, o) = match (
                flag(&flags, "subject"),
                flag(&flags, "relation"),
                flag(&flags, "object"),
            ) {
                (Some(s), Some(r), Some(o)) => (s, r, o),
                _ if positional.len() >= 3 => (
                    positional[0].clone(),
                    positional[1].clone(),
                    positional[2].clone(),
                ),
                _ => {
                    return Err("usage: areev add <subject> <relation> <object>  \
                                (or --subject S --relation R --object O)"
                        .to_string())
                }
            };
            // An empty subject/relation/object stores an unrecallable fact —
            // reject at the door rather than pollute the memory file.
            for (name, v) in [("subject", &s), ("relation", &r), ("object", &o)] {
                if v.trim().is_empty() {
                    return Err(format!("{name} must not be empty"));
                }
            }
            let conf: f64 = flag(&flags, "confidence")
                .map(|c| c.parse().map_err(|_| "bad --confidence".to_string()))
                .transpose()?
                .unwrap_or(0.9);
            let mut f = Fact::new(&s, &r, &o).confidence(conf);
            f.common.namespace = Some(ns);
            // `--idempotent` collapses a re-add of the current value: if the
            // head for (subject, relation) already holds this object, the
            // existing grain's hash is returned instead of minting a new one.
            if flags.contains_key("idempotent") {
                let (h, inserted) = m.add_if_novel(&f).map_err(|e| e.to_string())?;
                println!("{h}");
                if !inserted {
                    eprintln!("(unchanged — value already current, no new grain)");
                }
            } else {
                let h = m.add(&f).map_err(|e| e.to_string())?;
                println!("{h}");
            }
        }
        "record-tool-call" => {
            let name = flag(&flags, "name")
                .or_else(|| positional.first().cloned())
                .ok_or_else(|| "usage: areev record-tool-call --name NAME --result TEXT [--input JSON] [--is-error] [--thread ID] [--call-id ID] [--run-id ID] [--workflow HASH --node ID] [--status pending|completed|failed] [--failure-cause CAUSE] [--executor-kind host|client] [--correlation-id ID]".to_string())?;
            let result = flag(&flags, "result")
                .or_else(|| positional.get(1).cloned())
                .ok_or_else(|| "record-tool-call requires --result TEXT".to_string())?;
            let input = flag(&flags, "input");
            let is_error = flag(&flags, "is-error")
                .map(|v| !matches!(v.as_str(), "false" | "0" | "off" | "no"))
                .unwrap_or(false);
            let facade = AreevFacade::with_session(m, Some(ns.clone()), None);
            let facade = apply_principal(facade, &flags)?;
            let hash = facade
                .record_tool_call(
                    &ns,
                    &name,
                    input.as_deref(),
                    &result,
                    is_error,
                    flag(&flags, "thread").as_deref(),
                    flag(&flags, "call-id").as_deref(),
                    flag(&flags, "run-id").as_deref(),
                    flag(&flags, "workflow").as_deref(),
                    flag(&flags, "node").as_deref(),
                    flag(&flags, "status").as_deref(),
                    flag(&flags, "failure-cause").as_deref(),
                    flag(&flags, "executor-kind").as_deref(),
                    flag(&flags, "correlation-id").as_deref(),
                )
                .map_err(|e| e.to_string())?;
            println!("{hash}");
        }
        "run-manifest" => {
            let run_id = flag(&flags, "run-id")
                .or_else(|| positional.first().cloned())
                .ok_or_else(|| "run-manifest requires --run-id ID".to_string())?;
            let config = flag(&flags, "config")
                .ok_or_else(|| "run-manifest requires --config JSON".to_string())?;
            let facade = AreevFacade::with_session(m, Some(ns), None);
            let facade = apply_principal(facade, &flags)?;
            let (config_hash, link_hash) = facade
                .record_run_manifest(&run_id, &config)
                .map_err(|e| e.to_string())?;
            println!(
                "{}",
                serde_json::json!({
                    "run_id": run_id,
                    "config_hash": config_hash.to_hex(),
                    "link_hash": link_hash.to_hex(),
                })
            );
        }
        "recall" => {
            // Positional `areev recall <subject>`, or --subject S.
            let s = flag(&flags, "subject")
                .or_else(|| positional.first().cloned())
                .ok_or_else(|| "usage: areev recall <subject>  (or --subject S)".to_string())?;
            let rel = flag(&flags, "relation");
            let k: usize = flag(&flags, "k").and_then(|v| v.parse().ok()).unwrap_or(16);
            let grains = m
                .recall(&ns, &s, rel.as_deref(), k)
                .map_err(|e| e.to_string())?;
            match flag(&flags, "render") {
                None => {
                    for g in grains {
                        let line = serde_json::json!({
                            "hash": g.hash.to_hex(),
                            "type": format!("{:?}", g.grain_type).to_lowercase(),
                            "fields": g.fields,
                        });
                        println!("{line}");
                    }
                }
                Some(render) => {
                    // model-ready context via areev-context (§7.5)
                    use areev_context::{ContextAssembler, FormatPolicy, OutputFormat};
                    let mut policy = match render.as_str() {
                        "sml" => FormatPolicy::claude(),
                        "markdown" => FormatPolicy::gpt4(),
                        "toon" => FormatPolicy::new(OutputFormat::Toon),
                        "plain" => FormatPolicy::new(OutputFormat::PlainText),
                        "json" => FormatPolicy::json_api(),
                        other => return Err(format!("unknown --render '{other}'")),
                    };
                    if let Some(b) = flag(&flags, "budget").and_then(|v| v.parse().ok()) {
                        policy.token_budget = Some(b);
                    }
                    let hits: Vec<areev_cal::store_types::SearchHit> = grains
                        .into_iter()
                        .map(|grain| {
                            let hash = grain.hash;
                            areev_cal::store_types::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,
                            }
                        })
                        .collect();
                    let ctx = ContextAssembler::new().format(&hits, &policy);
                    println!("{}", ctx.text);
                    eprintln!(
                        "-- {} grains, ~{} tokens{}",
                        ctx.included_count,
                        ctx.estimated_tokens,
                        if ctx.truncated { " (truncated to budget)" } else { "" }
                    );
                }
            }
        }
        "search" => {
            let q = need(&flags, "query")?;
            let subject = flag(&flags, "subject");
            let k: usize = flag(&flags, "k").and_then(|v| v.parse().ok()).unwrap_or(10);
            // Scored: `score` is the rank-normalized fusion score (top =
            // 1.0), or the installed reranker's normalized score when one
            // ran. The deadline fails open to what was gathered.
            let tuning = areev_store::RecallTuning { rerank: m.has_reranker(), ..Default::default() };
            let hits = m
                .recall_hybrid_scored(
                    &ns,
                    subject.as_deref(),
                    None,
                    Some(&q),
                    k,
                    run_stack::recall_deadline(&flags)?,
                    tuning,
                )
                .map_err(|e| e.to_string())?;
            for (g, score) in hits {
                println!("{}", serde_json::json!({
                    "hash": g.hash.to_hex(),
                    "type": format!("{:?}", g.grain_type).to_lowercase(),
                    "score": score,
                    "fields": g.fields,
                }));
            }
        }
        "cal" => {
            let query = positional
                .first()
                .ok_or_else(|| "usage: areev cal '<QUERY>' --db <file>".to_string())?
                .clone();
            let facade = run_stack::host_facade(m, Some(ns), &flags)?;
            report_meta_warnings(&facade);
            let facade = apply_principal(facade, &flags)?;
            let ex = CalExecutor::new(CalExecutorConfig {
                allow_destructive_ops: !flags.contains_key("no-destructive-ops"),
                assembly_manifest_sample_rate: assembly_manifest_sample_rate(&flags)?,
                ..CalExecutorConfig::default()
            })
            .with_governance(std::sync::Arc::new(areev_loop_adapter::LoopGovernance::new()));
            let res = ex.execute(&query, &facade).map_err(|e| e.to_string())?;
            let payload = serde_json::to_string_pretty(&res.result).map_err(|e| e.to_string())?;
            println!("{payload}");
            for w in res.warnings {
                eprintln!("warning: {w}");
            }
        }
        "corpus" => {
            let selector = flag(&flags, "select")
                .or_else(|| positional.first().cloned())
                .ok_or_else(|| {
                    "usage: areev corpus --select '<READ CAL>' [--out FILE] [--recipient ID]"
                        .to_string()
                })?;
            let facade = run_stack::host_facade(m, Some(ns), &flags)?;
            report_meta_warnings(&facade);
            let facade = apply_principal(facade, &flags)?;
            let destination = flag(&flags, "out").unwrap_or_else(|| "stdout".to_string());
            let recipient = flag(&flags, "recipient");
            let (summary, manifest) =
                corpus::export(&facade, &selector, &destination, recipient.as_deref(), now_ms())?;
            eprintln!(
                "corpus export: {} row(s), {} source grain(s), manifest {}",
                summary.rows,
                summary.source_hashes.len(),
                manifest
            );
        }
        "tune" => {
            let facade = run_stack::host_facade(m, Some(ns), &flags)?;
            report_meta_warnings(&facade);
            let facade = apply_principal(facade, &flags)?;
            return tune::run_tune(&facade, &flags);
        }
        "history" => {
            let s = need(&flags, "subject")?;
            let r = need(&flags, "relation")?;
            let versions = m.history(&ns, &s, &r).map_err(|e| e.to_string())?;
            for v in versions {
                println!(
                    "{}",
                    serde_json::json!({
                        "hash": v.hash.to_hex(),
                        "object": v.object,
                        "created_at": v.created_at,
                        "confidence": v.confidence,
                        "superseded_by": v.superseded_by.map(|h| h.to_hex()),
                    })
                );
            }
        }
        "log" => {
            let since: i64 = flag(&flags, "since").and_then(|v| v.parse().ok()).unwrap_or(0);
            let limit: usize = flag(&flags, "limit").and_then(|v| v.parse().ok()).unwrap_or(50);
            // #307: `--ns a,b` narrows the feed to those namespaces and
            // attributes every row, TOMBSTONES INCLUDED. A per-namespace
            // projector previously had to read every operation in the memory
            // and resolve each hash to find its namespace — and could not
            // attribute a forget at all, because its grain is gone. `op_seq`
            // stays the memory-wide sequence, so a scoped cursor is still
            // comparable with the unscoped one.
            let scope: Vec<String> = flag(&flags, "ns")
                .map(|v| {
                    v.split(',')
                        .map(|s| s.trim().to_string())
                        .filter(|s| !s.is_empty())
                        .collect()
                })
                .unwrap_or_default();
            let ops = m
                .changes_since_scoped(since, &scope, limit)
                .map_err(|e| e.to_string())?;
            for op in ops {
                let kind = match op.op {
                    areev_store::OP_ADD => "add",
                    areev_store::OP_SUPERSEDE => "supersede",
                    areev_store::OP_FORGET => "forget",
                    _ => "?",
                };
                println!(
                    "{:>6}  {:>20}  {:<9}  {}  {}",
                    op.op_seq,
                    op.hlc,
                    kind,
                    op.hash.to_hex(),
                    op.ns.as_deref().unwrap_or("-")
                );
            }
        }
        "telemetry" => {
            // #306: erasing a namespace should take its recall evidence with
            // it. The per-hash and per-subject scrubs cannot reach a
            // ZERO-RESULT free-text query — it names no grain and need not
            // contain the erased identity — and that is precisely the row
            // that retains what a person typed.
            let action = positional.first().map(String::as_str).unwrap_or("");
            if action != "scrub" {
                return Err(
                    "usage: areev telemetry scrub --ns NS --yes".into()
                );
            }
            let ns = need(&flags, "ns")?;
            if !flags.contains_key("yes") {
                return Err(format!(
                    "refusing to scrub telemetry for {ns:?} without --yes — this removes \
                     recall evidence permanently"
                ));
            }
            m.telemetry_scrub_namespace(&ns).map_err(|e| e.to_string())?;
            println!("scrubbed telemetry for namespace {ns:?}");
        }
        "stream" => {
            // Litestream-shaped: a full snapshot as segment 0 of each
            // generation, then incrementing delta segments. Cursor,
            // generation, and NEXT SEGMENT NUMBER live in the target dir,
            // so any machine holding the dir can restore.
            //
            // The segment number is tracked in CURSOR rather than derived
            // by counting directory entries: retention deletes old
            // generations, and a counted number would regress and
            // overwrite live segments.
            let to = need(&flags, "to")?;
            let interval: u64 = flag(&flags, "interval-ms").and_then(|v| v.parse().ok()).unwrap_or(500);
            let once = flags.contains_key("once");
            let checkpoint = flags.contains_key("checkpoint");
            let retain_ms = match flag(&flags, "retain") {
                Some(v) => Some(
                    parse_duration(&v)
                        .ok_or_else(|| format!("--retain takes a duration like 30d, got '{v}'"))?,
                ),
                None => None,
            };
            std::fs::create_dir_all(&to).map_err(|e| e.to_string())?;
            let cursor_path = format!("{to}/CURSOR");
            let (mut gen_id, mut cursor, mut seg) = read_stream_cursor(&cursor_path, &to);
            // A checkpoint (explicit, or the first run in an empty dir)
            // opens a NEW generation whose segment 0 is a full snapshot of
            // the live — already-erased — store. That is what lets
            // retention drop older generations without losing history:
            // everything still reachable is in this snapshot.
            if gen_id.is_empty() || checkpoint {
                let g = format!(
                    "{:016x}",
                    std::time::SystemTime::now()
                        .duration_since(std::time::UNIX_EPOCH)
                        .unwrap()
                        .as_nanos() as u64
                );
                std::fs::create_dir_all(format!("{to}/gen-{g}")).map_err(|e| e.to_string())?;
                let snap = format!("{to}/gen-{g}/segment-{:08}.mgb", 0);
                let st = m.bundle_since(0, &snap).map_err(|e| e.to_string())?;
                gen_id = g;
                cursor = st.last_op_seq;
                seg = 1;
                std::fs::write(&cursor_path, format!("{gen_id} {cursor} {seg}"))
                    .map_err(|e| e.to_string())?;
                eprintln!("checkpoint: full snapshot of {} ops → {snap}", st.ops);
                if let Some(window) = retain_ms {
                    let dropped = prune_generations(&to, &gen_id, window)?;
                    if dropped > 0 {
                        eprintln!(
                            "retention: dropped {dropped} generation(s) older than the window \
                             (their contents are in this checkpoint, minus anything erased since)"
                        );
                    }
                }
            }
            loop {
                let ops_now = m.changes_since(cursor, 1).map_err(|e| e.to_string())?;
                if !ops_now.is_empty() {
                    let seg_path = format!("{to}/gen-{gen_id}/segment-{seg:08}.mgb");
                    let st = m.bundle_since(cursor, &seg_path).map_err(|e| e.to_string())?;
                    cursor = st.last_op_seq;
                    seg += 1;
                    std::fs::write(&cursor_path, format!("{gen_id} {cursor} {seg}"))
                        .map_err(|e| e.to_string())?;
                    eprintln!("shipped {} ops → {seg_path}", st.ops);
                }
                if once {
                    break;
                }
                std::thread::sleep(std::time::Duration::from_millis(interval));
            }
        }
        "follow" => {
            // Subscription pull (§5.10d): apply new segments from a stream
            // dir (local, NFS, or object-store mount). Follower keeps its
            // own cursor beside its db — offline edges catch up by replay.
            let from = need(&flags, "from")?;
            let interval: u64 = flag(&flags, "interval-ms").and_then(|v| v.parse().ok()).unwrap_or(1000);
            let once = flags.contains_key("once");
            // The follower cursor lives beside a FILE db; a DSN has no
            // "beside", so a postgres-backed follower keeps its cursor in
            // the stream dir, keyed by the memory's schema.
            #[cfg(feature = "postgres")]
            let fcur_path = if is_pg_url {
                let (_, schema) =
                    areev_store::pg::split_schema_url(&db).map_err(|e| e.to_string())?;
                format!("{from}/{schema}.follow")
            } else {
                format!("{db}.follow")
            };
            #[cfg(not(feature = "postgres"))]
            let fcur_path = format!("{db}.follow");
            loop {
                let cursor = std::fs::read_to_string(format!("{from}/CURSOR")).unwrap_or_default();
                let gen_id = cursor.trim().split(' ').next().unwrap_or("").to_string();
                if !gen_id.is_empty() {
                    let (fgen, fseg) = match std::fs::read_to_string(&fcur_path) {
                        Ok(s) => {
                            let mut it = s.trim().splitn(2, ' ');
                            (it.next().unwrap_or("").to_string(),
                             it.next().and_then(|v| v.parse::<u32>().ok()).unwrap_or(0))
                        }
                        Err(_) => (String::new(), 0),
                    };
                    // Re-baseline: the generation this follower was tracking
                    // may have aged out under `--retain`. Its segments are
                    // gone, but segment 0 of the CURRENT generation is a full
                    // snapshot — so restart from there rather than stalling
                    // forever on a missing file. Replay is idempotent, so
                    // re-importing already-held grains is a no-op.
                    if !fgen.is_empty()
                        && fgen != gen_id
                        && !std::path::Path::new(&format!("{from}/gen-{fgen}")).exists()
                    {
                        eprintln!(
                            "follow: generation {fgen} has aged out of the stream dir — \
                             re-baselining from generation {gen_id}'s snapshot"
                        );
                    }
                    let mut fseg = if fgen != gen_id { 0 } else { fseg };
                    loop {
                        let seg_path = format!("{from}/gen-{gen_id}/segment-{fseg:08}.mgb");
                        if !std::path::Path::new(&seg_path).exists() {
                            break;
                        }
                        let st = m.import_bundle(&seg_path).map_err(|e| e.to_string())?;
                        eprintln!("applied segment {fseg} ({} ops, {} skipped)", st.applied, st.skipped);
                        fseg += 1;
                        std::fs::write(&fcur_path, format!("{gen_id} {fseg}")).map_err(|e| e.to_string())?;
                    }
                }
                if once {
                    break;
                }
                std::thread::sleep(std::time::Duration::from_millis(interval));
            }
        }
        "restore" => {
            let from = need(&flags, "from")?;
            let until: Option<i64> = flag(&flags, "until-hlc").and_then(|v| v.parse().ok());
            let cursor = std::fs::read_to_string(format!("{from}/CURSOR"))
                .map_err(|_| "no CURSOR in stream dir".to_string())?;
            let gen_id = cursor.trim().split(' ').next().unwrap_or("").to_string();
            let dir = format!("{from}/gen-{gen_id}");
            let mut segs: Vec<String> = std::fs::read_dir(&dir)
                .map_err(|e| e.to_string())?
                .filter_map(|e| e.ok().map(|e| e.path().display().to_string()))
                .filter(|p| p.ends_with(".mgb"))
                .collect();
            segs.sort();
            let mut applied = 0usize;
            let mut meta_applied = 0usize;
            let mut meta_skipped = 0usize;
            for s in &segs {
                let st = m.import_bundle_until(s, until).map_err(|e| e.to_string())?;
                applied += st.applied;
                meta_applied += st.meta_applied;
                meta_skipped += st.meta_skipped;
            }
            let registry = if meta_applied > 0 {
                format!(", {meta_applied} registry entries")
            } else {
                String::new()
            };
            println!(
                "restored {} ops from {} segments (gen {gen_id}){registry}",
                applied,
                segs.len()
            );
            if until.is_some() && meta_skipped > 0 {
                eprintln!(
                    "note: {meta_skipped} registry entries (saved queries/templates/retention) \
                     skipped — a point-in-time restore replays grain history only"
                );
            }
        }
        "bundle" => {
            let out = need(&flags, "out")?;
            let since: i64 = flag(&flags, "since").and_then(|v| v.parse().ok()).unwrap_or(0);
            let st = m.bundle_since(since, &out).map_err(|e| e.to_string())?;
            println!(
                "bundled {} ops ({} bytes) → {} (next --since {})",
                st.ops, st.bytes, out, st.last_op_seq
            );
        }
        "import" => {
            let bundle = need(&flags, "bundle")?;
            let st = m.import_bundle(&bundle).map_err(|e| e.to_string())?;
            let registry = if st.meta_applied > 0 {
                format!(", {} registry entries", st.meta_applied)
            } else {
                String::new()
            };
            println!("applied {} ops, skipped {}{registry}", st.applied, st.skipped);
        }
        "migrate" => {
            let from = need(&flags, "from")?;
            let file = need(&flags, "file")?;
            // Bulk-load fast path: drop the FTS index for the duration and
            // rebuild once at the end — Turso indexes all existing rows at
            // CREATE INDEX time, instead of ~150ms of FTS bookkeeping per
            // write transaction.
            let deferred = m.defer_text_index().map_err(|e| e.to_string())?;
            let rep = run_migrate(&mut m, &ns, &from, &file, flag(&flags, "history"));
            if deferred {
                m.rebuild_text_index().map_err(|e| e.to_string())?;
            }
            let rep = rep?;
            for n in &rep.notes {
                eprintln!("areev: migrate: {n}");
            }
            println!("{}", rep.to_json());
        }
        "reindex" => {
            let n = m.rebuild_text_index().map_err(|e| e.to_string())?;
            println!(
                "text index rebuilt: {} grains indexed ({n} needed their text backfilled)",
                m.indexed_documents()
            );
            // Secondary indexes added after 1.0: reverse provenance, run
            // correlation, and related_to cross-links. A file written before
            // they existed answers provenance and run questions with nothing
            // until this runs.
            let links = m.rebuild_link_indexes().map_err(|e| e.to_string())?;
            println!("link indexes rebuilt: {links} rows (provenance, runs, cross-links)");
        }
        // ── areev vector-index: the ANN index, from the shell (#141) ──
        "vector-index" => {
            let usage = "usage: areev vector-index <status|build|drop|check> --db DSN \
                         [build: --m N --ef-construction N --ef-search N] \
                         [check: --queries FILE.json --ns SCOPE --k N --ef-search N]";
            let num = |key: &str, default: usize| -> Result<usize, String> {
                flag(&flags, key)
                    .map_or(Ok(default), |v| v.parse::<usize>())
                    .map_err(|_| format!("--{key} must be a number"))
            };
            match positional.first().map(String::as_str).unwrap_or("status") {
                "status" => {
                    let name = m.vector_index().map_err(|e| e.to_string())?;
                    println!("{}", serde_json::json!({"index": name}));
                }
                "build" => {
                    let (hm, efc, efs) =
                        (num("m", 16)?, num("ef-construction", 64)?, num("ef-search", 40)?);
                    m.ensure_vector_index(hm, efc, efs).map_err(|e| e.to_string())?;
                    let name = m.vector_index().map_err(|e| e.to_string())?;
                    println!("{}", serde_json::json!({"index": name, "m": hm, "ef_construction": efc, "ef_search": efs}));
                }
                "drop" => {
                    m.drop_vector_index().map_err(|e| e.to_string())?;
                    println!("{}", serde_json::json!({"index": serde_json::Value::Null}));
                }
                "check" => {
                    // The queries are the caller's own vectors: recall is a
                    // property of THEIR model's geometry, not of the index.
                    let path = flag(&flags, "queries")
                        .ok_or("vector-index check requires --queries FILE.json (a JSON array of vectors)")?;
                    // An explicit scope, because the global default ("shared")
                    // is a narrow one the structural index serves exactly —
                    // grading it says nothing about the ANN graph.
                    if !flags.contains_key("ns") {
                        return Err("vector-index check requires --ns SCOPE — the WIDE scope you actually \
                                    query (e.g. --ns 'firm.deals.*'); a narrow scope is exact regardless"
                            .into());
                    }
                    let text = std::fs::read_to_string(&path)
                        .map_err(|e| format!("cannot read --queries {path}: {e}"))?;
                    let queries: Vec<Vec<f32>> = serde_json::from_str(&text)
                        .map_err(|e| format!("--queries must be a JSON array of number arrays: {e}"))?;
                    let k = num("k", 10)?;
                    if let Some(ef) = flag(&flags, "ef-search") {
                        let ef: usize = ef.parse().map_err(|_| "--ef-search must be a number")?;
                        m.set_vector_ef_search(ef).map_err(|e| e.to_string())?;
                    }
                    let report = m.vector_recall_check(&ns, &queries, k).map_err(|e| e.to_string())?;
                    println!("{}", serde_json::to_string_pretty(&report).unwrap());
                }
                _ => return Err(usage.into()),
            }
        }
        "related" => {
            let start = flag(&flags, "start").ok_or("related requires --start")?;
            let rels = areev_store::parse_relations(
                &flag(&flags, "relations").ok_or("related requires --relations")?,
            );
            if rels.is_empty() {
                return Err("--relations must name at least one relation".to_string());
            }
            let dir = Direction::parse(&flag(&flags, "direction").unwrap_or_default())
                .ok_or("--direction must be one of: out, in, both")?;
            let depth: usize = flag(&flags, "depth")
                .map_or(Ok(2), |d| d.parse())
                .map_err(|_| "--depth must be a number")?;
            let cap: usize = flag(&flags, "limit")
                .map_or(Ok(64), |l| l.parse())
                .map_err(|_| "--limit must be a number")?;
            let refs: Vec<&str> = rels.iter().map(String::as_str).collect();
            // #303: `--ns a,b` walks the SET. A walk is not composable from
            // per-namespace calls — the frontier, `seen`, depth and cap are
            // shared state.
            let scope: Vec<String> = ns
                .split(',')
                .map(|s| s.trim().to_string())
                .filter(|s| !s.is_empty())
                .collect();
            let reached = if scope.len() > 1 {
                m.related_scoped(&scope, &start, &refs, dir, depth, cap)
            } else {
                m.related(&ns, &start, &refs, dir, depth, cap)
            }
            .map_err(|e| e.to_string())?;
            if reached.is_empty() {
                println!("(nothing reachable from {start})");
            }
            for r in reached {
                println!("{r}");
            }
        }
        "entity-at" => {
            let subject = flag(&flags, "subject").ok_or("entity-at requires --subject")?;
            let relation = flag(&flags, "relation").ok_or("entity-at requires --relation")?;
            let at: i64 = flag(&flags, "at")
                .ok_or("entity-at requires --at (epoch ms)")?
                .parse()
                .map_err(|_| "--at must be epoch milliseconds")?;
            let axis = Axis::parse(&flag(&flags, "axis").unwrap_or_default())
                .ok_or("--axis must be one of: world, knowledge")?;
            // #303: `--ns a,b` answers each namespace INDEPENDENTLY, paired
            // with the namespace it came from. No cross-namespace precedence
            // is invented, because there is none to invent.
            let scope: Vec<String> = ns
                .split(',')
                .map(|s| s.trim().to_string())
                .filter(|s| !s.is_empty())
                .collect();
            if scope.len() > 1 {
                let rows = m
                    .entity_at_scoped(&scope, &subject, &relation, at, axis)
                    .map_err(|e| e.to_string())?;
                if rows.is_empty() {
                    println!("(nothing known for {subject} {relation} at {at})");
                } else {
                    let out: Vec<_> = rows
                        .iter()
                        .map(|(n, g)| serde_json::json!({"namespace": n, "grain": g}))
                        .collect();
                    println!("{}", serde_json::to_string_pretty(&out).unwrap_or_default());
                }
                return Ok(());
            }
            match m
                .entity_at(&ns, &subject, &relation, at, axis)
                .map_err(|e| e.to_string())?
            {
                Some(g) => println!("{}", serde_json::to_string_pretty(&g).unwrap_or_default()),
                None => println!("(nothing known for {subject} {relation} at {at})"),
            }
        }
        "step-actions" => {
            let wf = flag(&flags, "workflow").ok_or("step-actions requires --workflow")?;
            let wf = Hash::from_hex(&wf).map_err(|e| e.to_string())?;
            let node = flag(&flags, "node");
            let limit: usize = flag(&flags, "limit")
                .map_or(Ok(64), |l| l.parse())
                .map_err(|_| "--limit must be a number")?;
            let rows = m
                .step_actions(&ns, &wf, node.as_deref(), limit)
                .map_err(|e| e.to_string())?;
            if rows.is_empty() {
                println!("(no execution records for {})", wf.to_hex());
            }
            for (n, h) in rows {
                println!("{n}\t{}", h.to_hex());
            }
        }
        "run-trace" => {
            let run = flag(&flags, "run-id").ok_or("run-trace requires --run-id")?;
            let limit: usize = flag(&flags, "limit")
                .map_or(Ok(64), |l| l.parse())
                .map_err(|_| "--limit must be a number")?;
            let trace = m.run_trace(&ns, &run, limit).map_err(|e| e.to_string())?;
            let produced = m.run_yield(&ns, &run, limit).map_err(|e| e.to_string())?;
            if trace.is_empty() {
                println!("(no grains recorded for run {run})");
            }
            println!("recorded during {run}: {} grain(s)", trace.len());
            for g in &trace {
                println!("  {} {:?}", g.hash.to_hex(), g.grain_type);
            }
            println!("produced by {run}: {} grain(s)", produced.len());
            for g in &produced {
                println!("  {} {:?}", g.hash.to_hex(), g.grain_type);
            }
        }
        "runs-touching" => {
            let h = flag(&flags, "hash").ok_or("runs-touching requires --hash")?;
            let h = Hash::from_hex(&h).map_err(|e| e.to_string())?;
            let depth: usize = flag(&flags, "depth")
                .map_or(Ok(4), |d| d.parse())
                .map_err(|_| "--depth must be a number")?;
            let runs = m.runs_touching(&ns, &h, depth).map_err(|e| e.to_string())?;
            if runs.is_empty() {
                println!("(no run produced or refined {})", h.to_hex());
            }
            for r in runs {
                println!("{r}");
            }
        }
        "verify" => {
            let rep = m.verify().map_err(|e| e.to_string())?;
            println!(
                "integrity: {} | grains: {} | hash mismatches: {} | undecodable: {}",
                rep.integrity, rep.grains, rep.hash_mismatches, rep.undecodable
            );
            let mut failed = rep.integrity != "ok" || rep.hash_mismatches > 0 || rep.undecodable > 0;
            // Opt-in so the line above stays byte-identical for every caller
            // that never asked about attestations.
            if flags.contains_key("attestations") {
                let a = m.verify_attestations().map_err(|e| e.to_string())?;
                println!(
                    "attestations: {} | policy: {} | attested: {} | unattested: {} | invalid: {} | unknown key: {} | orphaned: {}",
                    a.attestations, a.policy, a.attested, a.unattested, a.attest_invalid,
                    a.attest_unknown_key, a.attest_orphaned
                );
                for line in &a.invalid {
                    eprintln!("areev: invalid attestation: {line}");
                }
                // An attestation from a trusted key that fails is tampering
                // under any policy; missing ones fail only under `require`.
                failed |= a.attest_invalid > 0
                    || (a.policy == "require" && (a.unattested > 0 || a.attest_unknown_key > 0));
            }
            if failed {
                return Err("verification FAILED".to_string());
            }
        }
        "attest" => {
            // `areev attest <hash>` signs one stored grain; `areev attest --all
            // [--ns PREFIX]` retro-fills a memory that predates its key. Both
            // need --signing-key-env; both are idempotent.
            if m.signing_key().is_none() {
                return Err("areev attest needs --signing-key-env VAR (the author key)".into());
            }
            if flags.contains_key("all") {
                let prefix = flag(&flags, "ns");
                let st = m.attest_all(prefix.as_deref()).map_err(|e| e.to_string())?;
                println!("attested: {} | already attested: {}", st.attested, st.skipped);
            } else {
                let Some(h) = positional.first().cloned().or_else(|| flag(&flags, "hash")) else {
                    return Err("usage: areev attest <hash> | areev attest --all [--ns PREFIX]".into());
                };
                let hash = Hash::from_hex(&h).map_err(|e| e.to_string())?;
                let att = m.attest(&hash).map_err(|e| e.to_string())?;
                println!("{}", att.to_hex());
            }
        }
        "stats" => {
            let s = m.stats().map_err(|e| e.to_string())?;
            println!(
                "grains: {} ({} current) | triples: {} | terms: {} | ops: {} | thread-indexed events: {}",
                s.grains, s.current, s.triples, s.terms, s.ops, s.events_indexed
            );
        }
        "serve" => {
            if !flags.contains_key("mcp") {
                return Err("only --mcp transport is available (areev serve --mcp)".to_string());
            }
            let mut facade = run_stack::host_facade(m, Some(ns), &flags)?;
            report_meta_warnings(&facade);
            // Optional read-only mounts for cross-file ASSEMBLE:
            //   --mount alias=<path|DSN>[,alias=<path|DSN>...]
            // A recall/query in namespace "alias.inner" routes to the mount;
            // writes always stay on the primary memory (mounts are read-only
            // by construction), so this only widens what recall/ASSEMBLE can
            // read.
            for (alias, target) in parse_mounts(flag(&flags, "mount").as_deref())? {
                if mount_is_the_primary(&db, &target) {
                    return Err(format!(
                        "mount '{alias}' names the same postgres memory as --db — a mount is a \
                         SECOND store, and mounting the primary would make \"{alias}.<ns>\" and \
                         \"<ns>\" the same rows read twice. Point it at another schema, or drop \
                         the mount and query the namespace directly"
                    ));
                }
                let store = open_mount(&target)
                    .map_err(|e| format!("mount '{alias}' ({}): {e}", redact_dsn(&target)))?;
                // NEVER the raw target: a postgres DSN carries a password, and
                // this line goes to the operator's terminal and their logs.
                eprintln!("areev: mounted '{alias}' (read-only) → {}", redact_dsn(&target));
                facade.mount(&alias, store);
            }
            let facade = apply_principal(facade, &flags)?;
            // The recall deadline and reranker were installed above from
            // the flags (each falling back to its variable), so the server
            // must not re-read the environment over them.
            let mut server = areev_mcp::McpServer::host_configured(facade, None)
                .with_memory_path(&db)
                .assembly_manifest_sample_rate(assembly_manifest_sample_rate(&flags)?);
            if flags.contains_key("no-destructive-ops") {
                server = server.allow_destructive_ops(false);
                eprintln!("areev: destructive operations disabled (read-only session)");
            }
            if let Some(lock) = flag(&flags, "lock-ns") {
                server = server.lock_namespace(lock.clone());
                eprintln!("areev: namespace locked to '{lock}' (per-call namespace ignored)");
            }
            if let Some(p) = flag(&flags, "profile") {
                let profile = areev_mcp::ToolProfile::parse(&p)?;
                server = server.tool_profile(profile);
                if profile == areev_mcp::ToolProfile::Memory {
                    eprintln!("areev: MCP tool profile 'memory' (run/loop tools unavailable)");
                }
            }
            // Host loop policy (--policy FILE or $AREEV_LOOP_POLICY): the
            // areev_loop tool honors the same grants as the CLI run. Host
            // config set at process start — never controllable by the client.
            if let Some(p) = load_policy(&flags)? {
                server = server.with_loop_policy(p);
                eprintln!("areev: loop host policy attached to areev_loop");
            }
            server.serve_stdio().map_err(|e| e.to_string())?;
        }
        "capture-stop" => {
            // Claude Code Stop AND PreCompact hook: JSON on stdin with
            // session_id + transcript_path. Store every ordered turn as a
            // typed Event.
            //
            // One verb serves both events because the write path is already
            // exactly right for a compaction: it reads the cumulative
            // transcript and is idempotent by content address (see below), so
            // firing it again just before the host drops the conversation
            // stores whatever the last Stop did not — which is the point. On
            // PreCompact that is the difference between memory surviving a
            // compaction and not.
            use std::io::Read as IoRead;
            let mut input = String::new();
            std::io::stdin().read_to_string(&mut input).map_err(|e| e.to_string())?;
            let hook: serde_json::Value =
                serde_json::from_str(&input).map_err(|e| format!("bad hook json: {e}"))?;
            let session = hook["session_id"].as_str().unwrap_or("unknown-session").to_string();
            // FAIL OPEN on a missing path. PreCompact has been observed firing
            // with an empty `transcript_path` (anthropics/claude-code#13668),
            // and this verb must never be the reason a compaction is delayed
            // or noisy: there is nothing to capture, so say nothing and exit 0.
            // Erroring here would surface on the user's every auto-compaction.
            let tpath = match hook["transcript_path"].as_str().map(str::trim) {
                Some(p) if !p.is_empty() => p,
                _ => return Ok(()),
            };
            // Same reasoning for an unreadable transcript: the file is written
            // asynchronously and can lag the conversation a hook fires from.
            let Ok(transcript) = std::fs::read_to_string(tpath) else { return Ok(()) };
            // Which event this is, when the host says. Carried onto the turns
            // a compaction is about to cost, so a later reader can tell them
            // from an ordinary Stop capture.
            let compact_trigger = hook["hook_event_name"]
                .as_str()
                .filter(|e| e.eq_ignore_ascii_case("precompact"))
                .map(|_| hook["trigger"].as_str().unwrap_or("unknown").to_string());
            // Claude's Stop hook points at the cumulative transcript, so every
            // firing re-reads turns already captured. Identify a turn by its
            // own content address rather than by its position in the thread: a
            // positional watermark counts grains any other writer put in the
            // same `(namespace, session)` — `areev remember --session-id`, a
            // binding, a second hook — and every foreign grain silently skips a
            // real turn. Re-adding a stored grain is already a free no-op, so
            // pinning `created_at` from the transcript makes the whole chain a
            // pure function of the transcript and the rerun idempotent by
            // construction.
            let policy_version = flag(&flags, "policy-version");
            let mut parent: Option<String> = None;
            let mut stored = 0;
            let mut skipped = 0;
            for (turn, line) in transcript.lines().enumerate() {
                let Ok(v) = serde_json::from_str::<serde_json::Value>(line) else { continue };
                let message = &v["message"];
                let Some(role) = message["role"].as_str() else { continue };
                let Some(role) = areev_core::types::Role::from_str(role) else {
                    continue;
                };
                let (text, blocks, elisions) =
                    transcript_content_blocks(&message["content"], turn);
                if text.trim().is_empty() && blocks.is_empty() {
                    continue;
                }
                let mut event = Event::new(&text)
                    .namespace(&ns)
                    .session(session.clone())
                    // Deterministic stamp: the transcript's own time when it
                    // has one, else the turn's position. Never the wall clock —
                    // that would re-hash every turn on every hook firing and
                    // defeat the dedup this relies on.
                    .created_at(transcript_turn_ms(&v).unwrap_or(turn as i64))
                    .role(role)
                    .content_blocks(blocks);
                if let Some(p) = parent.clone() {
                    event = event.parent_message(p);
                }
                if let Some(model) = message["model"].as_str().or_else(|| v["model"].as_str()) {
                    event = event.model(model.to_string());
                }
                if let Some(stop) = message["stop_reason"]
                    .as_str()
                    .or_else(|| v["stop_reason"].as_str())
                {
                    event = event.stop_reason(stop.to_string());
                }
                if let Some(usage) = transcript_token_usage(message) {
                    event = event.token_usage(usage);
                }
                if !elisions.is_empty() {
                    event
                        .common
                        .extra_fields
                        .insert("elisions".into(), serde_json::Value::Array(elisions));
                }
                // A compaction summary is a transcript line with
                // `isCompactSummary: true` and `message.role: "user"` — so
                // without this it lands as an ordinary user Event,
                // indistinguishable from what the person actually typed.
                //
                // TAG, do not skip. The summary is the only record of what the
                // model believed after a compaction, which makes it worth
                // keeping; but a `RECALL events` consumer building a picture of
                // what the USER asked for must be able to tell a machine's
                // recap from a human's words. `role` deliberately stays `user`:
                // that IS how the model saw it.
                if v["isCompactSummary"].as_bool() == Some(true) {
                    event
                        .common
                        .extra_fields
                        .insert("compact_summary".into(), serde_json::Value::Bool(true));
                }
                // The policy in force when the turn happened. `areev corpus`
                // reports it under `binding.policy_versions`, which is how a
                // training row states which governance regime produced it —
                // without a producer that binding was always empty.
                if let Some(policy) = policy_version.as_deref() {
                    event.common.context = Some(serde_json::json!({
                        "policy_version": policy,
                    }));
                }
                // A hook capture is not a run; run_id deliberately stays None.
                let (_, hash) = areev_core::format::serialize::serialize_grain(&event)
                    .map_err(|e| e.to_string())?;
                if m.get(&hash).is_ok() {
                    skipped += 1;
                } else {
                    m.add(&event).map_err(|e| e.to_string())?;
                    stored += 1;
                }
                parent = Some(hash.to_hex());
            }
            // On a compaction, record that this happened — in `agent:harness`,
            // never the captured namespace: this is evidence ABOUT the session,
            // not a turn of it, and mixing the two would put harness noise into
            // every `RECALL events` the agent does.
            //
            // It is the only durable answer to "did memory survive the
            // compaction?", asked after the fact when the transcript is gone.
            if let Some(trigger) = &compact_trigger {
                let mut obs = areev_core::types::Observation::new("agent:hook", "system")
                    .subject(&format!("session:{session}"))
                    .object(&format!(
                        "compaction (trigger={trigger}) — {stored} turns captured, \
                         {skipped} already stored"
                    ))
                    .namespace(areev_core::authz::HARNESS_NS)
                    // Positional, like the turns above: a wall clock here would
                    // re-hash on every firing and defeat the same dedup.
                    .created_at((stored + skipped) as i64);
                let ex = &mut obs.common.extra_fields;
                ex.insert("observation_kind".into(), serde_json::json!("compaction"));
                ex.insert("session_id".into(), serde_json::json!(session));
                ex.insert("compact_trigger".into(), serde_json::json!(trigger));
                ex.insert("captured".into(), serde_json::json!(stored));
                ex.insert("already_stored".into(), serde_json::json!(skipped));
                // Fail open, like every other PreCompact path: a hook error
                // must never cost the user a compaction.
                let _ = m.add(&obs);
            }
            println!("captured {stored} events for session {session} ({skipped} already stored)");
        }
        "recall-hook" => {
            // Claude Code UserPromptSubmit hook: read the hook JSON on stdin,
            // hybrid-search memory for the prompt, and print matching grains to
            // stdout — which Claude Code injects into the model's context. This
            // is the retrieval half of the learning loop, made automatic
            // (no reliance on the model deciding to call a recall tool).
            use std::io::Read as IoRead;
            let mut input = String::new();
            std::io::stdin().read_to_string(&mut input).map_err(|e| e.to_string())?;
            let hook: serde_json::Value =
                serde_json::from_str(&input).unwrap_or(serde_json::Value::Null);
            // UserPromptSubmit carries `prompt`; SessionStart has none, so we
            // stay silent rather than inject noise.
            let query = hook["prompt"].as_str().unwrap_or("").trim().to_string();
            if query.is_empty() {
                return Ok(());
            }
            let k: usize = flag(&flags, "k").and_then(|v| v.parse().ok()).unwrap_or(5);
            // --with-loop additionally injects the pending recommendation
            // queue (a compact, capped block) so the loop closes into the
            // agent's context instead of waiting to be polled.
            let with_loop = flag(&flags, "with-loop").is_some();
            // A hook must stay snappy: with a reranker installed and no
            // explicit deadline, recall is bounded at 1500 ms (fails open to
            // fusion order past it).
            let deadline = match run_stack::recall_deadline(&flags)? {
                Some(d) => Some(d),
                None if m.has_reranker() => Some(std::time::Duration::from_millis(1500)),
                None => None,
            };
            let tuning = areev_store::RecallTuning { rerank: m.has_reranker(), ..Default::default() };
            let grains = m
                .recall_hybrid_scored(&ns, None, None, Some(&query), k, deadline, tuning)
                .map_err(|e| e.to_string())?;
            if grains.is_empty() && !with_loop {
                return Ok(());
            }
            if !grains.is_empty() {
                use areev_context::{ContextAssembler, DecidePolicy, FormatPolicy};
                // The query is what the allocator's questions are about
                // (proposal row A5): with a decision backend installed the
                // assembler asks intent + per-grain disclosure under the same
                // hook deadline, and falls open to the keyword/type-table
                // rules on any failure. No decider → byte-identical to before.
                let mut policy = FormatPolicy::claude().query_text(query.clone());
                policy.token_budget =
                    Some(flag(&flags, "budget").and_then(|v| v.parse().ok()).unwrap_or(400));
                let mut assembler = ContextAssembler::new();
                if let Some(chain) = &decider {
                    let chain = decider_for_egress(chain.clone(), store_egress_active(&m))?;
                    let deadline_ms = deadline
                        .or(Some(std::time::Duration::from_millis(1500)))
                        .map(|d| d.as_millis() as u64);
                    policy = policy.decide(DecidePolicy { deadline_ms, ..Default::default() });
                    assembler = assembler.with_decider(chain);
                }
                let hits: Vec<areev_cal::store_types::SearchHit> = grains
                    .into_iter()
                    .map(|(grain, score)| {
                        let hash = grain.hash;
                        areev_cal::store_types::SearchHit {
                            grain,
                            score: f64::from(score),
                            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,
                        }
                    })
                    .collect();
                let ctx = assembler.format(&hits, &policy);
                if !ctx.text.trim().is_empty() {
                    println!("Relevant memory from Areev:\n{}", ctx.text);
                }
            }
            if with_loop {
                // Read-only listing over the same store handle (single writer
                // per file — never a second open). Engine-templated summaries;
                // origin=llm entries are labeled. Capped so a long queue can't
                // flood the prompt; the console/CLI remain the review surface.
                let sub = AreevSubstrate::new(m, Some(ns.to_string()));
                let engine = Engine::with_builtins();
                let mut pending = engine
                    .recommendations(&sub, Some(RecStatus::Pending))
                    .map_err(|e| e.to_string())?;
                if !pending.is_empty() {
                    pending.sort_by(|a, b| b.severity.cmp(&a.severity).then(a.hash.cmp(&b.hash)));
                    const CAP: usize = 3;
                    println!(
                        "\nAreev Loop: {} pending recommendation(s) for this memory (review with `areev loop list`, act with approve/apply/reject --because):",
                        pending.len()
                    );
                    for r in pending.iter().take(CAP) {
                        let origin = match r.origin {
                            areev_loop::Origin::Llm { .. } => " [llm]",
                            areev_loop::Origin::Command { .. } => " [external]",
                            _ => "",
                        };
                        println!("  [{}] {}{}  {}", r.severity.as_str(), short(&r.hash), origin, r.summary.render());
                    }
                    if pending.len() > CAP {
                        println!("  … and {} more", pending.len() - CAP);
                    }
                }
            }
        }
        "remember" => run_remember(m, &ns, &flags)?,
        "memtool" => {
            let cmd = positional
                .first()
                .ok_or_else(|| "usage: areev memtool '<json>' --db <file>".to_string())?;
            let cmd: serde_json::Value =
                serde_json::from_str(cmd).map_err(|e| format!("bad command json: {e}"))?;
            let mut t = areev_store::memory_tool::MemoryTool::new(&mut m, &ns);
            println!("{}", t.execute(&cmd).map_err(|e| e.to_string())?);
        }
        "repl" => {
            use std::io::{BufRead, Write as IoWrite};
            let facade = run_stack::host_facade(m, Some(ns.clone()), &flags)?;
            report_meta_warnings(&facade);
            let facade = apply_principal(facade, &flags)?;
            let ex = CalExecutor::new(CalExecutorConfig {
                allow_destructive_ops: !flags.contains_key("no-destructive-ops"),
                assembly_manifest_sample_rate: assembly_manifest_sample_rate(&flags)?,
                ..CalExecutorConfig::default()
            })
            .with_governance(std::sync::Arc::new(areev_loop_adapter::LoopGovernance::new()));
            eprintln!("areev repl — namespace '{ns}' · CAL statements, or .stats .log .help .quit");
            let stdin = std::io::stdin();
            let mut lines = stdin.lock().lines();
            loop {
                eprint!("cal> ");
                std::io::stderr().flush().ok();
                let line = match lines.next() {
                    Some(Ok(l)) => l,
                    _ => break,
                };
                let line = line.trim();
                match line {
                    "" => continue,
                    ".quit" | ".exit" => break,
                    ".help" => eprintln!(
                        "CAL: RECALL / ASSEMBLE / EXISTS / HISTORY / ADD / SUPERSEDE / DESCRIBE / | COUNT\n\
                         dot: .stats  .log  .verify  .quit"
                    ),
                    ".stats" => match facade.with_store(|st| st.stats()) {
                        Ok(s) => eprintln!(
                            "grains {} ({} current) · triples {} · ops {}",
                            s.grains, s.current, s.triples, s.ops
                        ),
                        Err(e) => eprintln!("error: {e}"),
                    },
                    ".log" => match facade.with_store(|st| st.changes_since(0, 20)) {
                        Ok(ops) => {
                            for o in ops {
                                eprintln!("{:>5}  {:<9}  {}", o.op_seq, o.op, o.hash.to_hex());
                            }
                        }
                        Err(e) => eprintln!("error: {e}"),
                    },
                    ".verify" => match facade.with_store(|st| st.verify()) {
                        Ok(r) => eprintln!(
                            "integrity {} · {} grains · {} mismatches",
                            r.integrity, r.grains, r.hash_mismatches
                        ),
                        Err(e) => eprintln!("error: {e}"),
                    },
                    q => match ex.execute(q, &facade) {
                        Ok(res) => {
                            println!(
                                "{}",
                                serde_json::to_string_pretty(&res.result).unwrap_or_default()
                            );
                            for w in res.warnings {
                                eprintln!("warning: {w}");
                            }
                        }
                        Err(e) => eprintln!("error: {e}"),
                    },
                }
            }
        }
        "ui" => {
            let addr = flag(&flags, "addr").unwrap_or_else(|| "127.0.0.1:7437".to_string());
            let allow_remote = flag(&flags, "allow-remote").is_some();

            // Optional console authentication. `--token-env <VAR>` names an
            // environment variable holding the shared secret, keeping it out of
            // argv and shell history (same convention as --passphrase-env).
            // When set, every request needs it: browsers via the native HTTP
            // Basic prompt (any username, password = token), scripts via
            // `Authorization: Bearer <token>`.
            let auth_token = match flag(&flags, "token-env") {
                Some(var) => {
                    let t = std::env::var(&var).map_err(|_| {
                        format!("--token-env {var}: environment variable is not set")
                    })?;
                    if t.trim().is_empty() {
                        return Err(format!("--token-env {var}: token is empty"));
                    }
                    // [A1] The shared secret's entropy is the ONLY control on
                    // this path, and nothing here can measure it — but a
                    // token Areev did not mint is one an operator chose, and
                    // operator-chosen secrets are the reason the stored
                    // digest is worth grinding at all. Warn, never refuse:
                    // an existing deployment must not break on upgrade.
                    if !areev_core::authz::token_is_minted(&t) {
                        eprintln!(
                            "areev: ⚠ --token-env {var} holds a token Areev did not mint, so \
                             its entropy is unknown. Prefer `areev auth mint` (256-bit) and a \
                             per-principal credential map (--auth), which is also the only \
                             way approvals get an attributable identity."
                        );
                    }
                    Some(t)
                }
                None => None,
            };
            let has_auth = auth_token.is_some();

            if !addr_is_loopback(&addr) && !allow_remote {
                let why = if has_auth {
                    "It is authenticated, but still plaintext HTTP — the token and all \
                     memory cross the wire in the clear. Terminate TLS in front of it, \
                     or pass --allow-remote to accept that risk."
                } else {
                    "With no --token-env it is an UNAUTHENTICATED, writable console over \
                     plaintext HTTP — anyone who can reach it could read or modify your \
                     memory. Add --token-env <VAR>, keep it on loopback, put it behind a \
                     TLS-terminating proxy, or pass --allow-remote to override."
                };
                return Err(format!(
                    "refusing to bind the console to a non-loopback address ({addr}). {why}"
                ));
            }

            let facade = run_stack::host_facade(m, Some(ns), &flags)?;
            report_meta_warnings(&facade);
            let mut server = areev_server::UiServer::new(facade, db.clone());
            // `GET /api/config` names the decision chain (label + calibrated
            // only — the console never calls it).
            if let Some(d) = &decider {
                server = server.with_decider(d.describe(), d.calibrated());
            }
            if let Some(path) = flag(&flags, "auth") {
                let text = std::fs::read_to_string(&path)
                    .map_err(|e| format!("--auth {path}: {e}"))?;
                let map = areev_core::authz::CredentialMap::from_json(&text)
                    .map_err(|e| e.to_string())?;
                eprintln!(
                    "areev: credential map loaded ({} token(s)); rights come from the \
                     file's grant grains; unauthenticated requests run as 'anonymous'",
                    map.tokens.len()
                );
                // [A1] Name what is about to expire, every start. A console
                // that first mentions an expiry at the moment it starts
                // refusing is a console that mentions it during an incident.
                let now = areev_core::time::now_ms();
                for (id, when) in map.expiring_within(now, 14 * 86_400_000) {
                    let entry = map.tokens.iter().find(|t| t.id() == id);
                    if entry.is_some_and(|t| t.is_expired_at(now)) {
                        eprintln!(
                            "areev: ⚠ credential {id} EXPIRED {when} — it authenticates nobody; \
                             mint a replacement (areev auth mint) and revoke it"
                        );
                    } else {
                        eprintln!("areev: credential {id} expires {when} (within 14 days)");
                    }
                }
                server = server.with_credentials(map);
            }
            if allow_remote {
                server = server.allow_remote(true);
            }
            // Cross-origin POST allowlist (issue #125). The console's Origin
            // drive-by check is NOT lifted by --allow-remote: HTTP Basic is
            // cached by the browser and re-attached cross-site, so Origin is
            // the only thing telling the console's own page apart from an
            // attacker's page riding a viewer's cached credential.
            // --allow-origin names the exact origin(s) (the reverse proxy's
            // public hostname) permitted to POST cross-origin instead —
            // comma-separated for more than one, no wildcards, no subdomain
            // matching. (`parse_args` overwrites a repeated flag rather than
            // accumulating it, so comma-separation is the only list form.)
            if let Some(raw) = flag(&flags, "allow-origin") {
                fn validate_origin(o: &str) -> Result<String, String> {
                    let o = o.trim();
                    if o.is_empty() {
                        return Err("--allow-origin: empty origin".to_string());
                    }
                    if o == "*" {
                        return Err(
                            "--allow-origin: '*' is not accepted — name the exact origin(s) \
                             allowed to POST"
                                .to_string(),
                        );
                    }
                    let (scheme, rest) = if let Some(r) = o.strip_prefix("https://") {
                        ("https", r)
                    } else if let Some(r) = o.strip_prefix("http://") {
                        ("http", r)
                    } else {
                        return Err(format!("--allow-origin {o}: must start with http:// or https://"));
                    };
                    if rest.contains('@') {
                        return Err(format!("--allow-origin {o}: must not contain userinfo"));
                    }
                    if rest.contains('?') || rest.contains('#') {
                        return Err(format!("--allow-origin {o}: must not contain a query or fragment"));
                    }
                    let host = rest.strip_suffix('/').unwrap_or(rest);
                    if host.is_empty() {
                        return Err(format!("--allow-origin {o}: missing host"));
                    }
                    if host.contains('/') {
                        return Err(format!(
                            "--allow-origin {o}: must not contain a path beyond an optional \
                             trailing '/'"
                        ));
                    }
                    Ok(format!("{scheme}://{host}"))
                }

                let mut origins = Vec::new();
                for part in raw.split(',') {
                    let part = part.trim();
                    if part.is_empty() {
                        continue;
                    }
                    let normalized = validate_origin(part)?;
                    if normalized.starts_with("http://")
                        && !addr_is_loopback(normalized.trim_start_matches("http://"))
                    {
                        eprintln!(
                            "areev: WARNING — --allow-origin {normalized} is http:// \
                             (non-TLS) and non-loopback; a Basic credential the browser \
                             caches for that origin would cross the wire in the clear."
                        );
                    }
                    server = server.allow_origin(normalized.clone());
                    origins.push(normalized);
                }
                if origins.is_empty() {
                    return Err("--allow-origin: no origins given".to_string());
                }
                eprintln!("areev: cross-origin POSTs accepted from: {}", origins.join(", "));
            }
            if flags.contains_key("no-destructive-ops") {
                server = server.allow_destructive_ops(false);
                eprintln!("areev: destructive operations disabled (read-only console)");
            }
            if let Some(tok) = auth_token {
                server = server.with_auth(tok);
                eprintln!(
                    "areev: console authentication ENABLED — HTTP Basic \
                     (any username, password = the token)"
                );
            } else {
                eprintln!(
                    "areev: console is UNAUTHENTICATED — enable with --auth <map> \
                     (per-principal, attributable; `areev auth mint` creates one) or \
                     --token-env <VAR> (one shared secret, cannot approve)"
                );
            }
            // Host loop policy (--policy FILE or $AREEV_LOOP_POLICY): a
            // console-triggered loop run honors the same grants as the CLI
            // run. Never grantable from the console itself.
            if let Some(p) = load_policy(&flags)? {
                server = server.with_loop_policy(p);
                eprintln!("areev: loop host policy attached to the console's loop routes");
            }
            // [A0] Whether a proxy-asserted identity may answer a HITL
            // approval. Parsed BEFORE the SSO arm below so an invalid value —
            // or one given without SSO configured at all — is an error rather
            // than a silently-ignored security flag.
            let sso_approvals = match flag(&flags, "sso-approvals").as_deref() {
                None | Some("deny") => false,
                Some("allow") => true,
                Some(other) => {
                    return Err(format!(
                        "--sso-approvals {other}: expected 'deny' (default) or 'allow'"
                    ))
                }
            };
            if flag(&flags, "sso-approvals").is_some() && flag(&flags, "sso-header").is_none() {
                return Err(
                    "--sso-approvals applies to trusted-header SSO only — it has no effect \
                     without --sso-header/--sso-secret-env. Credential-map principals (--auth) \
                     may always approve; shared-token and anonymous callers never may."
                        .into(),
                );
            }
            // SSO v0 — trusted-header auth: an authenticating proxy does
            // OIDC/SAML and forwards identity in --sso-header; honored only
            // with the proxy shared secret (--sso-secret-env) in
            // x-areev-proxy-secret. Rights come from the file's grants.
            match (flag(&flags, "sso-header"), flag(&flags, "sso-secret-env")) {
                (Some(header), Some(var)) => {
                    let secret = std::env::var(&var)
                        .map_err(|_| format!("--sso-secret-env {var}: environment variable is not set"))?;
                    if secret.trim().is_empty() {
                        return Err(format!("--sso-secret-env {var}: secret is empty"));
                    }
                    // The rotation window (#79): while --sso-secret-env-next
                    // is set, either secret proves the proxy, so a fleet
                    // moves over one node at a time instead of atomically.
                    let next = match flag(&flags, "sso-secret-env-next") {
                        None => None,
                        Some(nvar) => {
                            let v = std::env::var(&nvar).map_err(|_| {
                                format!(
                                    "--sso-secret-env-next {nvar}: environment variable is not set"
                                )
                            })?;
                            if v.trim().is_empty() {
                                return Err(format!(
                                    "--sso-secret-env-next {nvar}: secret is empty"
                                ));
                            }
                            if v == secret {
                                return Err(format!(
                                    "--sso-secret-env-next {nvar} holds the same value as \
                                     --sso-secret-env {var} — that is a rotation that did not \
                                     happen, and it would read as 'both live' everywhere"
                                ));
                            }
                            Some(v)
                        }
                    };
                    let rotating = next.is_some();
                    server = server.with_sso_rotating(&header, secret, next);
                    eprintln!(
                        "areev: trusted-header SSO enabled ({header} + x-areev-proxy-secret)"
                    );
                    server = server.with_sso_approvals(sso_approvals);
                    // [A2] Groups → principals, so SSO scales without a grant
                    // grain per person. Resolved through --auth's `groups`
                    // table; without a map there is nothing to resolve
                    // against, so say so rather than failing silently.
                    if let Some(gh) = flag(&flags, "sso-groups-header") {
                        if flag(&flags, "auth").is_none() {
                            return Err(
                                "--sso-groups-header needs --auth <map>: the group → principal \
                                 table lives in the credential map, and without one every group \
                                 would resolve to nothing"
                                    .into(),
                            );
                        }
                        server = server.with_sso_groups_header(&gh);
                        eprintln!(
                            "areev: SSO groups honored via {gh} (group-derived principals are \
                             roles: they may never answer a HITL approval)"
                        );
                    }
                    if let Some(prefix) = flag(&flags, "sso-principal-prefix") {
                        if prefix.trim().is_empty() {
                            return Err("--sso-principal-prefix: empty prefix".into());
                        }
                        server = server.with_sso_principal_prefix(&prefix);
                        eprintln!("areev: proxy-asserted principals are prefixed {prefix:?}");
                    }
                    if sso_approvals {
                        eprintln!(
                            "areev: ⚠ --sso-approvals allow — a proxy-asserted identity may \
                             answer HITL approvals. Every approval's audit record is then only \
                             as strong as the proxy secret: anyone holding it can approve as \
                             anyone. Prefer per-principal credentials (--auth) for approvers."
                        );
                    } else {
                        eprintln!(
                            "areev: SSO identities may review but NOT approve (run.respond); \
                             approvers need a per-principal credential (--auth). Override with \
                             --sso-approvals allow."
                        );
                    }
                    if rotating {
                        // Loud, every start: a rotation window left open is
                        // an extra impersonation-grade credential live in
                        // production, and the whole risk of the feature is
                        // that nobody remembers to close it.
                        eprintln!(
                            "areev: ⚠ SSO secret ROTATION WINDOW open — two proxy secrets are \
                             accepted. Retire the old one (drop --sso-secret-env-next and \
                             promote its value) as soon as every proxy presents the new one: \
                             docs/runbooks/sso-secret-rotation.md"
                        );
                    }
                }
                (None, None) => {}
                _ => return Err("--sso-header and --sso-secret-env must be given together".into()),
            }
            // [A3] Native OIDC (`oidc` build feature): the console runs the
            // authorization-code+PKCE flow itself and issues a session
            // cookie. Unlike --sso-header, the identity is proven by a
            // signature over the issuer's published key set — which is why an
            // OIDC principal may approve without --sso-approvals.
            if let Some(issuer) = flag(&flags, "oidc-issuer") {
                    #[cfg(feature = "oidc")]
                    {
                        let client_id = flag(&flags, "oidc-client-id").ok_or(
                            "--oidc-issuer needs --oidc-client-id".to_string(),
                        )?;
                        let secret_var = flag(&flags, "oidc-client-secret-env").ok_or(
                            "--oidc-issuer needs --oidc-client-secret-env VAR (the secret is \
                             named, never passed on the command line)"
                                .to_string(),
                        )?;
                        let client_secret = std::env::var(&secret_var).map_err(|_| {
                            format!(
                                "--oidc-client-secret-env {secret_var}: environment variable is \
                                 not set"
                            )
                        })?;
                        if client_secret.trim().is_empty() {
                            return Err(format!(
                                "--oidc-client-secret-env {secret_var}: secret is empty"
                            ));
                        }
                        let redirect_uri = flag(&flags, "oidc-redirect-uri").ok_or(
                            "--oidc-issuer needs --oidc-redirect-uri (registered VERBATIM with \
                             the provider — RFC 9700 requires exact matching)"
                                .to_string(),
                        )?;
                        if !issuer.starts_with("https://") {
                            return Err(format!("--oidc-issuer {issuer}: must be https"));
                        }
                        let cfg = areev_server::oidc::OidcConfig {
                            issuer,
                            client_id,
                            client_secret,
                            redirect_uri: redirect_uri.clone(),
                            scopes: flag(&flags, "oidc-scopes")
                                .unwrap_or_else(|| "openid email profile".to_string()),
                            principal_claim: flag(&flags, "oidc-principal-claim")
                                .unwrap_or_else(|| "email".to_string()),
                            principal_prefix: flag(&flags, "oidc-principal-prefix"),
                        };
                        // Discovery happens NOW: a console that cannot reach
                        // its IdP should fail to start loudly, not fail every
                        // login later with the operator none the wiser.
                        let provider = areev_server::oidc::OidcProvider::discover(cfg)
                            .map_err(|e| e.to_string())?;
                        eprintln!("areev: native OIDC enabled — login at /auth/login");
                        if !redirect_uri.starts_with("https://") {
                            eprintln!(
                                "areev: ⚠ --oidc-redirect-uri is not https, so the session \
                                 cookie cannot be marked Secure. Acceptable on loopback; on any \
                                 real deployment terminate TLS first."
                            );
                        }
                        server = server.with_oidc(provider);
                    }
                    #[cfg(not(feature = "oidc"))]
                    {
                        let _ = issuer;
                        return Err(
                            "this build has no native OIDC — rebuild with `--features oidc`, or \
                             use trusted-header SSO behind an authenticating proxy \
                             (--sso-header), which is the documented default"
                                .into(),
                        );
                    }
            }
            // Native TLS (`tls` build feature): --tls-cert/--tls-key PEM
            // paths. The documented default remains a TLS-terminating
            // proxy; this is for deployments with nowhere to put one.
            match (flag(&flags, "tls-cert"), flag(&flags, "tls-key")) {
                (Some(cert), Some(key)) => {
                    #[cfg(feature = "tls")]
                    {
                        server = server.with_tls(&cert, &key).map_err(|e| e.to_string())?;
                        eprintln!("areev: native TLS enabled (cert {cert})");
                    }
                    #[cfg(not(feature = "tls"))]
                    {
                        let _ = (&cert, &key);
                        return Err(
                            "this build has no native TLS — rebuild with `--features tls`, \
                             or use the documented TLS-terminating proxy"
                                .into(),
                        );
                    }
                }
                (None, None) => {}
                _ => return Err("--tls-cert and --tls-key must be given together".into()),
            }
            let listener = areev_server::UiServer::bind(&addr).map_err(|e| e.to_string())?;
            if !addr_is_loopback(&addr) {
                eprintln!(
                    "areev: WARNING — bound to non-loopback {addr} over plaintext HTTP; {}",
                    if has_auth {
                        "the token crosses the wire in the clear — use a TLS-terminating proxy."
                    } else {
                        "UNAUTHENTICATED — anyone who can reach it can read/modify memory."
                    }
                );
            }
            eprintln!(
                "areev console → http://{}  (Ctrl-C to stop)",
                listener.local_addr().map_err(|e| e.to_string())?
            );
            server.serve(listener).map_err(|e| e.to_string())?;
        }
        "get" => {
            let h = positional
                .first()
                .ok_or_else(|| "usage: areev get <hash> --db <file>".to_string())?;
            let hash = Hash::from_hex(h).map_err(|e| e.to_string())?;
            let g = m.get(&hash).map_err(|e| e.to_string())?;
            println!(
                "{}",
                serde_json::json!({
                    "hash": g.hash.to_hex(),
                    "type": format!("{:?}", g.grain_type).to_lowercase(),
                    "fields": g.fields,
                })
            );
        }
        "provenance" => {
            // Reverse provenance: grains distilled from a source (credit
            // assignment / episode-scoped unlearn). Forward provenance — a
            // grain's own `derived_from` — is already visible via `areev get`.
            let h = flag(&flags, "of")
                .or_else(|| positional.first().cloned())
                .ok_or_else(|| {
                    "usage: areev provenance <source-hash> --db <file>  \
                     (lists grains whose derived_from is that hash)"
                        .to_string()
                })?;
            let h = h.strip_prefix("sha256:").unwrap_or(&h);
            let parent = Hash::from_hex(h).map_err(|e| e.to_string())?;
            let kids = m.grains_derived_from(&parent).map_err(|e| e.to_string())?;
            for g in kids {
                println!(
                    "{}",
                    serde_json::json!({
                        "hash": g.hash.to_hex(),
                        "type": format!("{:?}", g.grain_type).to_lowercase(),
                        "subject": g.get_str("subject"),
                        "relation": g.get_str("relation"),
                        "object": g.get_str("object"),
                    })
                );
            }
        }
        "forks" => {
            // Surface open forks: (ns, subject, relation) with >1 live head,
            // from concurrent supersession of the same value (e.g. edits synced
            // from two writers). Both tips are kept — nothing is lost — until an
            // explicit `areev merge` closes the fork.
            let forks = m.open_forks().map_err(|e| e.to_string())?;
            if forks.is_empty() {
                eprintln!("no open forks");
            }
            for f in forks {
                println!(
                    "{}",
                    serde_json::json!({
                        "namespace": f.namespace,
                        "subject": f.subject,
                        "relation": f.relation,
                        "heads": f.heads.iter().map(|h| h.to_hex()).collect::<Vec<_>>(),
                    })
                );
            }
        }
        "subject-report" => {
            // The DSAR read (GDPR Art. 15 access / Art. 20 portability):
            // everything forget-subject WOULD erase — the same selector in
            // show-me mode. JSONL to stdout (or --out), optionally plus a
            // portable subject-scoped bundle (--bundle). Read-only: no
            // --yes, and --as needs only the read verb.
            let subject = positional.first().cloned().or_else(|| flag(&flags, "subject")).ok_or(
                "usage: areev subject-report <subject> [--ns NS] [--text-mentions] \
                 [--out FILE] [--bundle FILE]"
                    .to_string(),
            )?;
            let opts = areev_store::ErasureOptions {
                text_mentions: flag(&flags, "text-mentions")
                    .map(|v| !matches!(v.as_str(), "false" | "0" | "off" | "no"))
                    .unwrap_or(false),
            };
            if let Some(principal) = flag(&flags, "as") {
                let grants = m.authz_grants(&principal).map_err(|e| e.to_string())?;
                areev_core::authz::AuthzSet::restricted(&principal, grants)
                    .check(areev_core::authz::Verb::Read, &ns)
                    .map_err(|e| e.to_string())?;
            }
            let report = m.subject_report_with(&ns, &subject, opts).map_err(|e| e.to_string())?;
            let mut lines = String::new();
            for g in &report.grains {
                let fields: serde_json::Map<String, serde_json::Value> =
                    g.fields.clone().into_iter().collect();
                let row = serde_json::json!({
                    "hash": g.hash.to_hex(),
                    "type": g.grain_type.as_str(),
                    "fields": fields,
                });
                lines.push_str(&row.to_string());
                lines.push('\n');
            }
            match flag(&flags, "out") {
                Some(path) => {
                    std::fs::write(&path, &lines).map_err(|e| e.to_string())?;
                    println!("wrote {} grains to {path}", report.grains.len());
                }
                None => print!("{lines}"),
            }
            if let Some(bpath) = flag(&flags, "bundle") {
                let stats = m
                    .subject_bundle_with(&ns, &subject, opts, &bpath)
                    .map_err(|e| e.to_string())?;
                eprintln!("bundle: {} records, {} bytes -> {bpath}", stats.ops, stats.bytes);
            }
            eprintln!(
                "subject-report '{subject}' ns '{ns}': {} grains; matched identities: {}",
                report.grains.len(),
                report.identity_names.join(", ")
            );
        }
        "forget-subject" => {
            // Right-to-erasure for one identity: erase every grain holding a
            // structured reference to the subject (history included), its
            // thread events, its dictionary entry, and erased-only
            // vocabulary — with replicating tombstones. Destructive and
            // bulk, so it demands an explicit --yes.
            let subject = positional.first().cloned().or_else(|| flag(&flags, "subject")).ok_or(
                "usage: areev forget-subject <subject> [--ns NS] [--text-mentions] --yes"
                    .to_string(),
            )?;
            if flags.contains_key("no-destructive-ops") {
                return Err(
                    "destructive operations are disabled for this invocation \
                     (--no-destructive-ops)"
                        .into(),
                );
            }
            if !flags.contains_key("yes") {
                return Err(format!(
                    "forget-subject erases EVERY grain referencing '{subject}' in namespace \
                     '{ns}' (history included) and replicates the erasure to peers. \
                     Re-run with --yes to proceed."
                ));
            }
            // Same truthiness idiom as --index-text: bare presence enables,
            // an explicit falsy value disables — "--text-mentions false"
            // must not silently widen the erasure.
            let opts = areev_store::ErasureOptions {
                text_mentions: flag(&flags, "text-mentions")
                    .map(|v| !matches!(v.as_str(), "false" | "0" | "off" | "no"))
                    .unwrap_or(false),
            };
            if let Some(principal) = flag(&flags, "as") {
                let grants = m.authz_grants(&principal).map_err(|e| e.to_string())?;
                areev_core::authz::AuthzSet::restricted(&principal, grants)
                    .check(areev_core::authz::Verb::Erase, &ns)
                    .map_err(|e| e.to_string())?;
            }
            // #278: `--override-hold` destroys in a HELD namespace. Explicit
            // and audited: the Tier-2 record names the hold it overrode, and
            // a refusal without the flag is recorded too — the evidence a
            // controller needs to answer an Art. 17 request on an Art. 17(3)
            // ground.
            let override_hold = flags.contains_key("override-hold");
            let audit_target = format!(
                "subject:{} ns:{ns}",
                areev_core::authz::subject_fingerprint(&subject)
            );
            let (rep, overridden) = if override_hold {
                let because = flag(&flags, "because").ok_or_else(|| {
                    "--override-hold requires --because: destroying records someone \
                     placed a hold on is a decision, and it has a ground"
                        .to_string()
                })?;
                let who = flag(&flags, "as").unwrap_or_else(|| "local:owner".to_string());
                let over = areev_store::HoldOverride::new(who, because)
                    .map_err(|e| e.to_string())?;
                m.forget_subject_overriding(&ns, &subject, opts, &over)
                    .map_err(|e| e.to_string())?
            } else {
                match m.forget_subject_with(&ns, &subject, opts) {
                    Ok(r) => (r, None),
                    Err(e) => {
                        if e.code() == "STO-E009" {
                            let mut obs = areev_core::authz::audit_observation(
                                &flag(&flags, "as").unwrap_or_else(|| "local:owner".into()),
                                "erase.refused",
                                &audit_target,
                                Some(&e.to_string()),
                                0,
                                areev_core::time::now_ms(),
                            );
                            let _ = m.append_audit(&mut obs);
                        }
                        return Err(e.to_string());
                    }
                }
            };
            if let Some(hold) = &overridden {
                eprintln!(
                    "areev: overrode the legal hold on '{}' placed by {} ({})",
                    hold.ns, hold.placed_by, hold.because
                );
            }
            let stale_exports = m
                .corpus_exports_touching_subject(&subject)
                .unwrap_or_else(|e| {
                    eprintln!("areev: warning: could not consult corpus registry: {e}");
                    Vec::new()
                });
            // The CLI is a host, and hosts audit (REQ-ERASE-5 leaves the
            // record to the host precisely so the engine never writes the
            // identity back). Same builder as the CAL path, so `areev audit
            // export` sees one shape whichever surface erased.
            write_erasure_audit(
                &mut m,
                &flags,
                "erase",
                // A fingerprint, never the identity — the audit grain
                // outlives the erasure and replicates.
                &audit_target,
                rep.grains_erased,
                &stale_exports,
                overridden.as_ref(),
            );
            println!(
                "erased {} grains ({} dictionary entries, {} vocabulary tokens, {} blobs reclaimed)",
                rep.grains_erased, rep.terms_removed, rep.vocab_removed, rep.blobs_reclaimed
            );
        }
        "purge-older-than" => {
            // Retention sweep: erase grains older than N days (created_at),
            // optionally limited to one grain type. --ns "" sweeps every
            // namespace. Destructive and bulk: demands --yes.
            let days: i64 = positional
                .first()
                .and_then(|v| v.parse().ok())
                .or_else(|| flag(&flags, "days").and_then(|v| v.parse().ok()))
                .ok_or("usage: areev purge-older-than <days> [--ns NS] [--type event] --yes".to_string())?;
            let gt = match flag(&flags, "type") {
                Some(t) => Some(
                    areev_core::types::GrainType::from_str(&t)
                        .ok_or_else(|| format!("unknown grain type '{t}'"))?,
                ),
                None => None,
            };
            if flags.contains_key("no-destructive-ops") {
                return Err(
                    "destructive operations are disabled for this invocation \
                     (--no-destructive-ops)"
                        .into(),
                );
            }
            if !flags.contains_key("yes") {
                let scope = if ns.is_empty() {
                    "across EVERY namespace".to_string()
                } else {
                    format!("in namespace '{ns}'")
                };
                return Err(format!(
                    "purge-older-than erases every{} grain older than {days} days {scope} \
                     and replicates the erasure to peers. Re-run with --yes to proceed.",
                    gt.map(|g| format!(" {g:?}")).unwrap_or_default()
                ));
            }
            let cutoff = std::time::SystemTime::now()
                .duration_since(std::time::UNIX_EPOCH)
                .map(|d| d.as_millis() as i64)
                .unwrap_or(0)
                - days * 24 * 3600 * 1000;
            let ns_opt = if ns.is_empty() { None } else { Some(ns.as_str()) };
            if let Some(principal) = flag(&flags, "as") {
                let grants = m.authz_grants(&principal).map_err(|e| e.to_string())?;
                // An all-namespace sweep needs erase on `*`.
                areev_core::authz::AuthzSet::restricted(&principal, grants)
                    .check(areev_core::authz::Verb::Erase, ns_opt.unwrap_or("*"))
                    .map_err(|e| e.to_string())?;
            }
            let exports = m.corpus_exports().unwrap_or_else(|e| {
                eprintln!("areev: warning: could not consult corpus registry: {e}");
                Vec::new()
            });
            let rep = m.forget_older_than(ns_opt, cutoff, gt).map_err(|e| e.to_string())?;
            let stale_exports =
                areev_store::exports_touching_hashes(&exports, &rep.erased_hashes);
            write_erasure_audit(
                &mut m,
                &flags,
                "erase",
                &format!(
                    "older_than:{days}d ns:{}{}",
                    if ns.is_empty() { "*" } else { ns.as_str() },
                    flag(&flags, "type").map(|t| format!(" type:{t}")).unwrap_or_default()
                ),
                rep.grains_erased,
                &stale_exports,
                None,
            );
            println!(
                "erased {} grains ({} vocabulary tokens, {} blobs reclaimed)",
                rep.grains_erased, rep.vocab_removed, rep.blobs_reclaimed
            );
        }
        "merge" => {
            // Close an open fork by writing a resolved value that supersedes
            // every tip; the merge grain records all parents in its blob.
            let s = need(&flags, "subject")?;
            let r = need(&flags, "relation")?;
            let o = need(&flags, "object")?;
            let conf: f64 = flag(&flags, "confidence")
                .map(|c| c.parse().map_err(|_| "bad --confidence".to_string()))
                .transpose()?
                .unwrap_or(0.9);
            let mut merged = Fact::new(&s, &r, &o).confidence(conf);
            merged.common.namespace = Some(ns.clone());
            let h = m
                .merge_heads(&ns, &s, &r, &mut merged)
                .map_err(|e| e.to_string())?;
            println!("{h}");
        }
        "novelty" => {
            // Advise-mode paraphrase novelty check: nearest existing grains to
            // a candidate text (needs --embed-cmd). A reflection harness reads
            // the top similarity and decides to supersede vs add — the engine
            // never drops anything on its own.
            let text = need(&flags, "text")?;
            let subject = flag(&flags, "subject");
            let relation = flag(&flags, "relation");
            let k: usize = flag(&flags, "k").and_then(|v| v.parse().ok()).unwrap_or(5);
            let matches = m
                .nearest_semantic(&ns, subject.as_deref(), relation.as_deref(), &text, k)
                .map_err(|e| e.to_string())?;
            for (h, sim) in matches {
                let object = m.get(&h).ok().and_then(|g| g.get_str("object").map(String::from));
                println!(
                    "{}",
                    serde_json::json!({
                        "hash": h.to_hex(),
                        "similarity": (sim * 1000.0).round() / 1000.0,
                        "object": object,
                    })
                );
            }
        }
        "init" => {
            run_init(m, &ns, &flags, &positional)?;
        }
        "loop" => {
            run_loop(m, &ns, &flags, &positional)?;
        }
        "audit" => {
            run_audit(&mut m, &flags, &positional)?;
        }
        "anonymize" => run_anonymize(m, &flags, &positional)?,
        "pack" => {
            return pack::run_pack(Some(m), &ns, &flags, &positional);
        }
        "trigger" => {
            // The locator rides along so a connector module declaring
            // `{"blob": {"read": true}}` can be served by the per-poll broker
            // (#185): the read never opens the memory the evaluator holds.
            return trigger_cli::run_trigger(m, &ns, &db, &flags, &positional);
        }
        "retention" => {
            run_retention(&mut m, &ns, &flags, &positional)?;
        }
        "hold" => {
            run_hold(&mut m, &ns, &flags, &positional)?;
        }
        // ── areev run: the governed workflow runtime (governed-agents §8) ──
        "run" => {
            return run_run(m, &db, &ns, &flags, &positional);
        }
        // ── areev eval: evalsets + the §7.4 gating edge ──
        "eval" => {
            return run_eval(m, &flags, &positional);
        }
        // ── areev tool provenance: one-command code forensics (§7.4) ──
        "tool" => {
            let sub_cmd = positional.first().map(|s| s.as_str()).unwrap_or("");
            let hash_arg = positional.get(1).cloned();
            if sub_cmd != "provenance" || hash_arg.is_none() {
                return Err("usage: areev tool provenance <hash> [--depth N]".into());
            }
            return run_tool_provenance(m, &db, &ns, &hash_arg.unwrap(), &flags);
        }
        "blob" => {
            // `blob put` writes; `blob get` normally never reaches here (it is
            // served pre-open above) — it lands here only for a sealed blob or
            // a Postgres memory, both of which genuinely need the open handle.
            match positional.first().map(String::as_str).unwrap_or("") {
                "put" => {
                    let bytes = match positional.get(1) {
                        Some(path) => std::fs::read(path)
                            .map_err(|e| format!("blob put: reading {path}: {e}"))?,
                        None => {
                            if !flags.contains_key("stdin") {
                                return Err("usage: areev blob put <FILE> --db <file>  (or --stdin)".into());
                            }
                            use std::io::Read;
                            let mut buf = Vec::new();
                            std::io::stdin()
                                .read_to_end(&mut buf)
                                .map_err(|e| format!("blob put: reading stdin: {e}"))?;
                            buf
                        }
                    };
                    // Idempotent by construction: the address is the content.
                    println!("{}", m.put_blob(&bytes).map_err(|e| e.to_string())?);
                }
                "get" => {
                    let uri = positional
                        .get(1)
                        .ok_or("usage: areev blob get <cas-uri> --db <file>")?;
                    use std::io::Write;
                    let bytes = m.get_blob(uri).map_err(|e| e.to_string())?;
                    std::io::stdout().write_all(&bytes).map_err(|e| e.to_string())?;
                }
                other => {
                    return Err(format!(
                        "unknown blob subcommand '{other}' — try `areev blob put|get`"
                    ))
                }
            }
        }
        "blobs" => {
            // `areev blobs encrypt` — migrate CAS attachments written before
            // sidecar encryption landed (GDPR Art. 32; docs/gdpr.md §4).
            // New attachments are sealed on write, so this is a one-time
            // catch-up for existing files. Idempotent.
            let sub_cmd = positional.first().map(|s| s.as_str()).unwrap_or("");
            if sub_cmd != "encrypt" {
                return Err("usage: areev blobs encrypt --db <file> --passphrase-env VAR".into());
            }
            let (encrypted, already) = m.encrypt_blobs().map_err(|e| e.to_string())?;
            println!(
                "encrypted {encrypted} attachment(s); {already} were already encrypted"
            );
        }
        other => return Err(format!("unknown command '{other}' — try `areev help`")),
    }
    Ok(())
}

/// `areev retention <set|list|clear|sweep>` — declarative storage limitation
/// (GDPR Art. 5(1)(e)).
///
/// Policy is a **file-truth** (`retention:<ns>` meta rows), so it travels
/// with the memory: a copy, a sync, or a restore on another host still says
/// "events here live 90 days". Declaring is separate from enforcing —
/// `set` never deletes anything; `sweep` does, and demands `--yes` like
/// every other bulk erasure. The governed alternative is the loop's
/// `retention_sweep` analyzer, which proposes the same purge through review
/// and audit instead of performing it.
/// A declarative anonymization fixture set (issue #47).
///
/// ```json
/// {
///   "policy": { "mode": "egress", "categories": { "sg_nric": "redact" } },
///   "must_redact":     ["NRIC S1234567D", "MRN 00456123"],
///   "must_not_redact": ["invoice 4471820", "2026-08-19"]
/// }
/// ```
///
/// Deliberately symmetric: a policy that redacts everything passes
/// `must_redact` trivially, so the `must_not_redact` half is what stops an
/// over-broad policy from looking correct.
///
/// Read with the `serde_json` value API rather than a derive — this crate
/// hand-rolls its argument parsing and carries no `serde` derive dependency.
fn fixture_strings(root: &serde_json::Value, key: &str, path: &str) -> Result<Vec<String>, String> {
    match root.get(key) {
        None => Ok(Vec::new()),
        Some(serde_json::Value::Array(items)) => items
            .iter()
            .map(|v| {
                v.as_str()
                    .map(str::to_string)
                    .ok_or_else(|| format!("{path}: every \"{key}\" entry must be a string"))
            })
            .collect(),
        Some(_) => Err(format!("{path}: \"{key}\" must be an array of strings")),
    }
}

/// `areev anonymize <set|list|clear|mappings>` — the per-namespace policy
/// surface (docs/anonymization-proposal.md P1). `scan` is handled pre-open.
fn run_anonymize(
    mut m: Areev,
    flags: &HashMap<String, String>,
    positional: &[String],
) -> Result<(), String> {
    let sub = positional.first().map(String::as_str).unwrap_or("");
    match sub {
        "set" => {
            let ns = flag(flags, "ns").ok_or("anonymize set requires --ns")?;
            let policy = match (flag(flags, "policy"), flag(flags, "policy-file")) {
                (Some(j), _) => j,
                (None, Some(path)) => std::fs::read_to_string(&path)
                    .map_err(|e| format!("--policy-file {path}: {e}"))?,
                (None, None) => return Err("anonymize set requires --policy or --policy-file".into()),
            };
            m.set_anon_policy(&ns, &policy).map_err(|e| e.to_string())?;
            println!("anonymization policy declared for namespace '{ns}' — egress reads are transformed from now on; older builds opening this file will warn");
            Ok(())
        }
        "list" => {
            let policies = m.anon_policies().map_err(|e| e.to_string())?;
            if policies.is_empty() {
                println!("no anonymization policies declared");
                return Ok(());
            }
            for (ns, p) in policies {
                println!(
                    "{}",
                    serde_json::json!({"ns": ns, "policy": p})
                );
            }
            Ok(())
        }
        "clear" => {
            let ns = flag(flags, "ns").ok_or("anonymize clear requires --ns")?;
            m.clear_anon_policy(&ns).map_err(|e| e.to_string())?;
            println!("anonymization policy cleared for namespace '{ns}'");
            Ok(())
        }
        "reveal" => {
            let ns = flag(flags, "ns").ok_or("anonymize reveal requires --ns")?;
            let token = flag(flags, "token").ok_or("anonymize reveal requires --token")?;
            // Facade path: admin-gated + Tier-2 audited (fingerprints only).
            let facade =
                areev_cal::AreevFacade::with_session(m, Some(ns.clone()), None);
            let out = facade
                .reveal_tokens(&ns, &[token])
                .map_err(|e| e.to_string())?;
            println!("{out}");
            Ok(())
        }
        "mappings" => {
            // In-process custody (D5): the operator running this process may
            // see the live placeholder->value mappings for rehydration.
            let maps = m.anon_mappings().map_err(|e| e.to_string())?;
            for (ns, id, mapping) in maps {
                println!(
                    "{}",
                    serde_json::json!({"ns": ns, "mapping_id": id, "mapping": mapping})
                );
            }
            Ok(())
        }
        other => Err(format!(
            "unknown anonymize subcommand '{other}' (expected scan, set, list, clear, or mappings)"
        )),
    }
}

fn run_retention(
    m: &mut Areev,
    ns: &str,
    flags: &HashMap<String, String>,
    positional: &[String],
) -> Result<(), String> {
    let sub_cmd = positional.first().map(|s| s.as_str()).unwrap_or("list");
    match sub_cmd {
        "set" => {
            let days: f64 = flag(flags, "days")
                .and_then(|v| v.parse().ok())
                .or_else(|| positional.get(1).and_then(|v| v.parse().ok()))
                .ok_or_else(|| {
                    "usage: areev retention set --days N [--ns NS] [--type event] \
                     [--because \"why\"]"
                        .to_string()
                })?;
            let policy = areev_store::RetentionPolicy {
                days,
                grain_type: flag(flags, "type"),
                because: flag(flags, "because"),
            };
            m.set_retention_policy(ns, &policy).map_err(|e| e.to_string())?;
            println!(
                "retention policy for '{ns}': {days} days{}{}",
                policy.grain_type.map(|t| format!(", type {t}")).unwrap_or_default(),
                policy.because.map(|b| format!(" — {b}")).unwrap_or_default()
            );
            eprintln!(
                "areev: declared, not enforced — run `areev retention sweep --yes` (cron), \
                 or let the loop's retention_sweep analyzer propose it for review"
            );
        }
        "list" => {
            let policies = m.retention_policies().map_err(|e| e.to_string())?;
            if policies.is_empty() {
                println!("no retention policies declared in this memory");
            }
            for (pns, p) in policies {
                println!(
                    "{}",
                    serde_json::json!({
                        "namespace": pns,
                        "days": p.days,
                        "type": p.grain_type,
                        "because": p.because,
                    })
                );
            }
        }
        "clear" => {
            m.clear_retention_policy(ns).map_err(|e| e.to_string())?;
            println!("cleared the retention policy for '{ns}'");
        }
        "sweep" => {
            if flags.contains_key("no-destructive-ops") {
                return Err(
                    "destructive operations are disabled for this invocation \
                     (--no-destructive-ops)"
                        .into(),
                );
            }
            let policies = m.retention_policies().map_err(|e| e.to_string())?;
            if policies.is_empty() {
                println!("no retention policies declared — nothing to sweep");
                return Ok(());
            }
            if !flags.contains_key("yes") {
                let plan: Vec<String> = policies
                    .iter()
                    .map(|(pns, p)| {
                        format!(
                            "  {pns}: erase grains older than {} days{}",
                            p.days,
                            p.grain_type.as_deref().map(|t| format!(" (type {t})")).unwrap_or_default()
                        )
                    })
                    .collect();
                return Err(format!(
                    "retention sweep would apply {} policy/policies:\n{}\nRe-run with --yes \
                     to proceed.",
                    policies.len(),
                    plan.join("\n")
                ));
            }
            let now = std::time::SystemTime::now()
                .duration_since(std::time::UNIX_EPOCH)
                .map(|d| d.as_millis() as i64)
                .unwrap_or(0);
            let exports = m.corpus_exports().unwrap_or_else(|e| {
                eprintln!("areev: warning: could not consult corpus registry: {e}");
                Vec::new()
            });
            let results = m.sweep_retention(now).map_err(|e| e.to_string())?;
            let mut total = 0usize;
            for sweep in &results {
                let (pns, days) = (&sweep.ns, sweep.days);
                match &sweep.outcome {
                    areev_store::RetentionOutcome::Skipped { why } => {
                        // A held or floored namespace SKIPS with the refusal
                        // printed — never silently, never aborting the pass.
                        println!("{pns}: SKIPPED — {why}");
                        continue;
                    }
                    areev_store::RetentionOutcome::Swept(rep) => {
                        total += rep.grains_erased;
                        println!(
                            "{pns}: erased {} grains older than {days} days ({} vocabulary tokens, \
                             {} blobs reclaimed)",
                            rep.grains_erased, rep.vocab_removed, rep.blobs_reclaimed
                        );
                        // Audited like every other host-level erasure, one record per
                        // policy so the evidence names which rule fired — but only
                        // when something was actually erased. A destruction trail
                        // records destructions; a nightly no-op sweep would
                        // otherwise add 365 immutable, replicating grains a year per
                        // policy for zero information.
                        if rep.grains_erased > 0 {
                            let stale_exports = areev_store::exports_touching_hashes(
                                &exports,
                                &rep.erased_hashes,
                            );
                            write_erasure_audit(
                                m,
                                flags,
                                "erase",
                                &format!("retention:{days}d ns:{pns}"),
                                rep.grains_erased,
                                &stale_exports,
                None,
            );
                        }
                    }
                }
            }
            println!("retention sweep: {total} grains erased across {} policies", results.len());
        }
        // The FLOOR half (governed-agents §5.4): destruction younger than
        // the floor refuses everywhere — CAL PURGE, sweeps, the loop.
        "floor" => {
            let min_days: f64 = flag(flags, "min-days")
                .and_then(|v| v.parse().ok())
                .ok_or_else(|| {
                    "usage: areev retention floor --min-days N --because \"why\" [--ns NS]"
                        .to_string()
                })?;
            let because = flag(flags, "because").ok_or_else(|| {
                "retention floor requires --because (a floor with no recorded \
                 rationale is not auditable)"
                    .to_string()
            })?;
            m.set_retention_floor(ns, min_days, &because)
                .map_err(|e| e.to_string())?;
            println!("retention floor for '{ns}': ≥{min_days} days — {because}");
        }
        "floor-clear" => {
            m.clear_retention_floor(ns).map_err(|e| e.to_string())?;
            println!("retention floor cleared for '{ns}'");
        }
        "floors" => {
            let floors = m.retention_floors().map_err(|e| e.to_string())?;
            if floors.is_empty() {
                println!("no retention floors declared in this memory");
            }
            for (fns, days, because) in floors {
                println!("{fns}: ≥{days} days — {because}");
            }
        }
        other => {
            return Err(format!(
                "unknown retention subcommand '{other}' — usage: areev retention \
                 <set|list|clear|sweep|floor|floor-clear|floors>"
            ))
        }
    }
    Ok(())
}

/// `areev run` — the governed workflow runtime: start, resume, respond,
/// cancel, verify, fork, and the 10-minute proof (`demo`). Host tools
/// execute through `--tool-cmd` (input JSON on stdin, `AREEV_TOOL_NAME` /
/// `AREEV_IDEMPOTENCY_KEY` in the env, result JSON on stdout — the
/// `--embed-cmd` pattern); Client-bound nodes park the run and print the
/// `requires_action` envelope, answered with `areev run respond` by a
/// SECOND principal (approval separation of duties is refused structurally,
/// not documented). Wave 2: `--model provider:name` powers abstract nodes
/// (`--llm-max-tokens` is the per-turn OUTPUT ceiling AND the §6.7
/// reservation; `--max-effects` bounds how many turns + tool calls one node
/// attempt may spend, `--llm-tool-result-chars` how much of ONE tool result the
/// model is shown — the journal keeps all of it — and `--llm-context-tokens`
/// the whole transcript, past which the middle is folded into one journaled
/// summary; all frozen into the manifest so a resume bounds them alike),
/// `--events` streams §6.10 run events to stderr as JSON lines, and
/// `fork --run-id BASE --as-run NEW [--at N] [--plan HASH]` is §5.4
/// time-travel / in-flight migration.
fn run_run(
    m: Areev,
    // The memory's own path, threaded in so the broker can serve this run's
    // CAS blobs to a declared capability tool (#106). Taken from the resolved
    // `--db` rather than from the open handle, because the lock-free blob read
    // deliberately works from the path and never the handle.
    db: &str,
    ns: &str,
    flags: &HashMap<String, String>,
    positional: &[String],
) -> Result<(), String> {
    use areev_run::{RunSession, Runner, SystemClock};
    use std::sync::Arc;

    let sub_cmd = positional.first().map(|s| s.as_str()).unwrap_or("");
    let principal = flag(flags, "as").unwrap_or_else(|| "user:local".to_string());
    // The credential broker. A tool that posts to a vendor gets the broker's
    // address and a capability token -- never the token itself -- so the
    // secret stays in this process. `--tool-egress` is the per-tool grant:
    // which credentials a named tool may spend, and which methods it may
    // issue. A tool with no grant cannot even see the broker.
    // Held so the broker outlives the run; also the handle refusals are read
    // back from once it finishes.
    let mut broker_guard: Option<Arc<areev_run::Broker>> = None;
    let egress: Option<areev_run::EgressHandle> = match run_stack::build_egress(flags)? {
        None => None,
        Some(broker) => {
            // The other mediated door (#106): a module that declared
            // `{"blob": {"read": true}}` reads stored bytes through this same
            // broker, on this same token. Wired from the run's own memory
            // path, and by path rather than by handle — `read_blob_offline`
            // takes no lock, so serving an attachment never contends with the
            // driver's exclusive hold on the file it came from.
            broker.serve_blobs(db);
            let broker = Arc::new(broker);
            broker_guard = Some(Arc::clone(&broker));
            Some(areev_run::EgressHandle::new(broker))
        }
    };
    // The executor stack, the model and the ceilings all come from
    // `run_stack` — the one builder `trigger run` calls too, so a plan that
    // executes here executes there (#90).
    let executor = run_stack::tool_executor(flags, egress.as_ref());
    let llm = run_stack::toolcall_llm(flags)?;
    let observer = run_stack::observer(flags)?;
    // The decision chain is read before `m` moves into the facade: it needs
    // the handle's egress declarations to decide whether to wrap.
    let decider = run_stack::decider(flags, &m)?;
    let runner = Runner {
        facade: Arc::new(run_stack::host_facade(m, Some(ns.to_string()), flags)?),
        clock: Arc::new(SystemClock),
        executor,
        llm,
        observer,
        ns: ns.to_string(),
        principal: principal.clone(),
    };
    let runner = match decider {
        Some(d) => runner.with_decider(d),
        None => runner,
    };
    let opts = run_stack::run_options(flags);

    let need = |key: &str, usage: &str| -> Result<String, String> {
        flag(flags, key).ok_or_else(|| format!("usage: {usage}"))
    };
    let print_session = |session: RunSession| match session {
        RunSession::Finished { outcome, run_id } => {
            println!(
                "{}",
                serde_json::json!({"run_id": run_id, "finished": format!("{outcome:?}")})
            );
        }
        RunSession::Parked { envelope, run_id } => {
            println!("{envelope}");
            if envelope["kind"] == "paused" {
                eprintln!(
                    "areev: run paused by its host — `areev run resume --run-id {run_id}` \
                     continues it under the same run id"
                );
            } else {
                eprintln!(
                    "areev: run parked — answer with `areev run respond --run-id ID \
                     --ask TOOL_CALL_ID --result JSON --as PRINCIPAL`, then \
                     `areev run resume --run-id ID`"
                );
            }
        }
    };

    let report_refusals = run_stack::report_refusals;
    match sub_cmd {
        "start" => {
            let wf = need("workflow", "areev run start --workflow HASH --run-id ID [--input JSON] [--tool-cmd CMD] [--as PRINCIPAL]")?;
            let run_id = need("run-id", "areev run start --workflow HASH --run-id ID")?;
            let input: serde_json::Value = match flag(flags, "input") {
                Some(raw) => serde_json::from_str(&raw)
                    .map_err(|e| format!("--input must be valid JSON: {e}"))?,
                None => serde_json::json!({}),
            };
            let h = Hash::from_hex(&wf).map_err(|e| e.to_string())?;
            // A plan is addressed by hash, so it runs from any namespace —
            // but the journal, the results and every namespace-scoped read
            // land in the RUN's namespace, not the plan's. That is by design
            // (the run's namespace is the policy choice, docs/run.md), and it
            // is also the shape of a forgotten `--ns`: the run works, and its
            // record is invisible everywhere the operator looks for it (#230).
            // Say it once, on stderr, and carry on.
            if let Ok(plan_grain) = runner.facade.with_store(|m| m.get(&h)) {
                if let Some(plan_ns) = plan_grain.get_str("namespace") {
                    if plan_ns != runner.ns {
                        eprintln!(
                            "areev: note: this plan lives in namespace '{plan_ns}', but the run \
                             reads and journals in '{}' — pass `--ns {plan_ns}` if its record \
                             should sit with the plan",
                            runner.ns
                        );
                    }
                }
            }
            let session = runner.start(&h, &run_id, input, &opts).map_err(|e| e.to_string())?;
            print_session(session);
        }
        "resume" => {
            let run_id = need("run-id", "areev run resume --run-id ID [--tool-cmd CMD]")?;
            let session = runner.resume(&run_id, &opts).map_err(|e| e.to_string())?;
            print_session(session);
        }
        "respond" => {
            let run_id = need("run-id", "areev run respond --run-id ID --ask TOOL_CALL_ID --result JSON --as PRINCIPAL")?;
            let ask = need("ask", "areev run respond --run-id ID --ask TOOL_CALL_ID --result JSON --as PRINCIPAL")?;
            let result: serde_json::Value = serde_json::from_str(
                &need("result", "areev run respond … --result JSON")?,
            )
            .map_err(|e| format!("--result must be valid JSON: {e}"))?;
            let is_error = flag(flags, "is-error")
                .map(|v| !matches!(v.as_str(), "false" | "0" | "off" | "no"))
                .unwrap_or(false);
            runner
                .respond(&run_id, &ask, result, is_error, &principal)
                .map_err(|e| e.to_string())?;
            println!("response recorded — `areev run resume --run-id {run_id}` to continue");
        }
        "input" => {
            let run_id = need("run-id", "areev run input --run-id ID --message TEXT")?;
            let message = need("message", "areev run input --run-id ID --message TEXT")?;
            runner.input(&run_id, &message, &principal).map_err(|e| e.to_string())?;
            println!(
                "steering message queued for '{run_id}' — the next superstep hands it \
                 to its nodes under `$inbox`"
            );
        }
        "cancel" => {
            let run_id = need("run-id", "areev run cancel --run-id ID [--because \"why\"]")?;
            let because = flag(flags, "because").unwrap_or_else(|| "canceled".into());
            runner
                .cancel(&run_id, &principal, &because)
                .map_err(|e| e.to_string())?;
            println!(
                "cancel recorded for '{run_id}' — a live driver drains at its next \
                 superstep boundary; `areev run resume --run-id {run_id}` finalizes a \
                 parked one"
            );
        }
        "pause" => {
            let usage = "areev run pause --run-id ID [--because \"why\"]";
            let run_id = need("run-id", usage)?;
            let because = flag(flags, "because").unwrap_or_else(|| "paused".into());
            let receipt = runner
                .pause(&run_id, &principal, &because)
                .map_err(|e| e.to_string())?;
            println!("{}", serde_json::to_string(&receipt).unwrap());
            eprintln!(
                "areev: pause {} for '{run_id}' — a live driver parks at its next \
                 superstep boundary; `areev run resume --run-id {run_id}` continues it",
                if receipt.already { "already standing" } else { "recorded" }
            );
        }
        "verify" => {
            let run_id = need("run-id", "areev run verify --run-id ID")?;
            let report = runner.verify(&run_id).map_err(|e| e.to_string())?;
            println!("{}", serde_json::to_string_pretty(&report).unwrap());
            if !report.verified {
                return Err("verification did not pass".into());
            }
        }
        "list" => {
            // Recent runs, newest first, with terminal outcome + spend when
            // recorded (the run-outcome Observation) — "what has this
            // memory been running?" as one command.
            // Outcomes come from the run index (#165), which reads each
            // run's own census record by index rather than rescanning the
            // whole census once per row. An EXPLICIT --ns scopes the listing
            // to that session namespace (the one `run start` stamps); with
            // no --ns every namespace is listed, which is what this command
            // has always done. The truncation note goes to stderr, so the
            // JSON array scripts consume is unchanged.
            let n = flag(flags, "last").and_then(|v| v.parse().ok()).unwrap_or(20);
            let offset = flag(flags, "offset").and_then(|v| v.parse().ok()).unwrap_or(0);
            let scope = flags.contains_key("ns").then_some(ns);
            let page = runner.list_runs(scope, offset, n).map_err(|e| e.to_string())?;
            let rows: Vec<serde_json::Value> = page
                .runs
                .iter()
                .map(|r| {
                    // Still a real check, not a constant: the row proves a
                    // link Fact EXISTED, and this asks whether it is still
                    // the live head (a forgotten or superseded link answers
                    // false). One indexed point read per row.
                    let has_manifest = runner
                        .facade
                        .with_store(|m| {
                            m.latest("agent:harness", &format!("run:{}", r.run_id), "mg:harness")
                        })
                        .ok()
                        .flatten()
                        .is_some();
                    serde_json::json!({
                        "run_id": r.run_id,
                        "ns": r.ns,
                        "outcome": r.outcome,
                        "usd_micros": r.spent_usd_micros,
                        "tokens": r.spent_tokens,
                        "has_manifest": has_manifest,
                    })
                })
                .collect();
            println!("{}", serde_json::to_string_pretty(&rows).unwrap());
            if page.truncated {
                eprintln!(
                    "areev: showing {} of {} runs (newest first) — raise --last or page with --offset",
                    rows.len(),
                    page.total
                );
            }
            if page.unattributed > 0 {
                eprintln!(
                    "areev: {} more run(s) predate the session-namespace stamp and cannot be \
                     attributed to a namespace — list them without --ns",
                    page.unattributed
                );
            }
        }
        "inspect" => {
            // One run, whole picture: the frozen manifest, terminal outcome,
            // spend, journal size, pending asks, fork lineage — a thin
            // wrapper over Runner::inspect (also reachable in-process from
            // the Python/Node bindings, issue #34).
            let run_id = need("run-id", "areev run inspect --run-id ID")?;
            let report = runner.inspect(&run_id).map_err(|e| e.to_string())?;
            println!("{}", serde_json::to_string_pretty(&report).unwrap());
        }
        "oversight-report" => {
            // The Art. 14 row as a command (docs/eu-ai-act.md): where can a
            // human intervene, who is AUTHORIZED to, what expires when, and
            // how fast the kill switch actually drained — measured from the
            // journal, not asserted. A thin wrapper over
            // Runner::oversight_report (also reachable in-process from the
            // Python/Node bindings, issue #34).
            let plan_hash = flag(flags, "plan")
                .map(|p| {
                    areev_core::error::Hash::from_hex(&p)
                        .map_err(|_| format!("--plan is not a valid hash: {p}"))
                })
                .transpose()?;
            let report = runner
                .oversight_report(flag(flags, "run-id").as_deref(), plan_hash.as_ref())
                .map_err(|e| e.to_string())?;
            println!("{}", serde_json::to_string_pretty(&report).unwrap());
        }
        "shadow" => {
            // §7.4's pre-apply check as a product surface: replay journaled
            // runs with zero effect dispatches (structural — the verify path
            // has no executor) and report per-run consistency.
            let ids: Vec<String> = match flag(flags, "runs") {
                Some(csv) => csv.split(',').map(|s| s.trim().to_string()).filter(|s| !s.is_empty()).collect(),
                None => {
                    let n = flag(flags, "last").and_then(|v| v.parse().ok()).unwrap_or(5);
                    runner.recent_runs(n).map_err(|e| e.to_string())?
                }
            };
            if ids.is_empty() {
                return Err("no runs to shadow (give --runs a,b or record some runs first)".into());
            }
            // Under a CANDIDATE plan (`--plan HASH` or `--plan-file draft.json`)
            // the same runs are re-driven through the pure scheduler with
            // every effect answered from the journal: the rehearsal a plan
            // revision gets before anyone approves it. Out of support is a
            // report field, never an error; a draft that fails validation
            // surfaces its RUN-Ennn.
            let candidate = match (flag(flags, "plan"), flag(flags, "plan-file")) {
                (Some(_), Some(_)) => return Err("give --plan or --plan-file, not both".into()),
                (Some(h), None) => Some(areev_run::PlanCandidate::Hash(
                    Hash::from_hex(&h).map_err(|e| e.to_string())?,
                )),
                (None, Some(path)) => {
                    let text = std::fs::read_to_string(&path).map_err(|e| format!("{path}: {e}"))?;
                    let body: serde_json::Value =
                        serde_json::from_str(&text).map_err(|e| format!("{path}: {e}"))?;
                    let fields = body
                        .as_object()
                        .cloned()
                        .ok_or_else(|| format!("{path}: a plan draft must be a JSON object"))?;
                    Some(areev_run::PlanCandidate::Body(fields))
                }
                (None, None) => None,
            };
            // `--reexecute pure` (#277) rehearses a candidate VERSION rather
            // than only a candidate plan: a bound node whose candidate
            // Definition is a pure wasm32-areev module runs in the sandbox on
            // the replayed input, so a patch that changes only a tool's bytes
            // stops rehearsing as `same` by construction. Every other node
            // still answers from the journal, and the module still has to be
            // --allow-executor pinned with a --sandbox-cmd configured — a
            // rehearsal is the same act of running someone's code as a run.
            let reexecute = match flag(flags, "reexecute") {
                None => areev_run::Reexecute::Off,
                Some(mode) => areev_run::Reexecute::parse(&mode).ok_or_else(|| {
                    format!("--reexecute takes 'pure' or 'off', not {mode:?}")
                })?,
            };
            if let Some(candidate) = candidate {
                let opts = areev_run::ShadowOptions::reexecute(reexecute);
                let report =
                    runner.shadow_plan_with(&ids, &candidate, &opts).map_err(|e| e.to_string())?;
                println!("{}", serde_json::to_string_pretty(&report).unwrap());
                return Ok(());
            }
            if reexecute != areev_run::Reexecute::Off {
                return Err(
                    "--reexecute needs a candidate: add --plan HASH or --plan-file draft.json"
                        .into(),
                );
            }
            let report = runner.shadow_eval(&ids);
            println!("{}", serde_json::to_string_pretty(&report).unwrap());
            if !report.all_consistent {
                return Err("shadow evaluation found inconsistent runs".into());
            }
        }
        "fork" => {
            let usage = "areev run fork --run-id BASE --as-run NEW [--at SUPERSTEP] [--plan HASH]";
            let base = need("run-id", usage)?;
            let new_id = need("as-run", usage)?;
            let at = flag(flags, "at").and_then(|v| v.parse().ok());
            let plan = match flag(flags, "plan") {
                Some(h) => Some(Hash::from_hex(&h).map_err(|e| e.to_string())?),
                None => None,
            };
            let seed = runner
                .fork(&base, at, &new_id, plan.as_ref(), &opts)
                .map_err(|e| e.to_string())?;
            println!(
                "fork '{new_id}' created from '{base}' (seed checkpoint {seed}) — \
                 `areev run resume --run-id {new_id}` continues it"
            );
        }
        // The 10-minute proof: seed a two-node plan (host tool + human
        // approval) and print the exact sequence to run it, pause it,
        // approve it as a second principal, resume it, and verify it.
        "demo" => {
            let (wf_hash, greet_hash, approve_hash) = runner.facade.with_store(|m| {
                let greet = areev_core::types::Tool::new("greet")
                    .kind(areev_core::types::ToolKind::Definition)
                    .tool_description("Greets the subject (host-executed)")
                    .created_at(1_000)
                    .namespace(ns);
                let gh = m.add(&greet)?;
                let approve = areev_core::types::Tool::new("approve")
                    .kind(areev_core::types::ToolKind::Definition)
                    .tool_description("A human approves the greeting")
                    .executor_kind(areev_core::types::ExecutorKind::Client)
                    .created_at(1_001)
                    .namespace(ns);
                let ah = m.add(&approve)?;
                let wf = areev_core::types::Workflow::new(vec!["greet".into(), "approve".into()])
                    .edge("greet", "approve")
                    .bind("greet", &gh.to_hex())
                    .bind("approve", &ah.to_hex())
                    .created_at(1_002)
                    .namespace(ns);
                let wh = m.add(&wf)?;
                Ok::<_, areev_core::error::AreevError>((wh, gh, ah))
            })
            .map_err(|e| e.to_string())?;
            println!("demo plan seeded (workflow {wf_hash})");
            println!("  greet   -> host tool {greet_hash}");
            println!("  approve -> human approval {approve_hash}");
            println!();
            println!("the 10-minute proof (no LLM key required):");
            println!(
                "  1. areev run start --db <DB> --workflow {wf_hash} --run-id demo-1 \\\n\
                 \x20      --input '{{\"who\":\"world\"}}' --tool-cmd 'printf '\\''{{\"greeting\":\"hello\"}}'\\'''"
            );
            println!("     → parks with a requires_action envelope; copy its tool_call_id");
            println!(
                "  2. areev run respond --db <DB> --run-id demo-1 --ask <TOOL_CALL_ID> \\\n\
                 \x20      --result '{{\"approved\":true}}' --as user:officer"
            );
            println!("     (responding as the starter is REFUSED — separation of duties)");
            println!("  3. areev run resume --db <DB> --run-id demo-1  → Completed");
            println!("  4. areev run verify --db <DB> --run-id demo-1  → journal-consistent replay");
            println!("  5. areev run-trace --db <DB> --run-id demo-1   → the full journal");
        }
        other => {
            return Err(format!(
                "unknown run subcommand '{other}' — usage: areev run \
                 <start|resume|respond|input|pause|cancel|list|inspect|verify|fork|shadow|oversight-report|demo>"
            ))
        }
    }
    report_refusals(&broker_guard);
    Ok(())
}

/// `areev tool provenance <hash>` (§7.4): the full chain for one piece of
/// governed code, as ONE command — the recommendation(s) targeting it, each
/// lifecycle transition with approver + BECAUSE, the recorded gating edge
/// (evalset hash, gate run, stats), which runs the code touched since, and
/// the **executor blob itself**: the question a reviewer actually asks is
/// "what code ran", and a Tool grain answers it only by reference
/// (`executor_uri`). Chasing that reference by hand — parse the `cas://`
/// address, find the sidecar, check the digest — is the step that got skipped,
/// so the command takes it. One-command forensics is a product surface, not an
/// implied join.
fn run_tool_provenance(
    mut m: Areev,
    db_path: &str,
    ns: &str,
    hash_arg: &str,
    flags: &HashMap<String, String>,
) -> Result<(), String> {
    use areev_loop::SubstrateRead;
    let depth = flag(flags, "depth").and_then(|v| v.parse().ok()).unwrap_or(2);
    // Store-level joins FIRST (the substrate takes ownership below).
    let mut executor: Option<serde_json::Value> = None;
    let runs = match Hash::from_hex(hash_arg) {
        Ok(h) => {
            executor = m
                .get(&h)
                .ok()
                .and_then(|g| g.to_tool().ok())
                .and_then(|t| t.executor_uri.clone())
                .map(|uri| executor_blob_report(db_path, &uri));
            let mut all = m.runs_touching(ns, &h, depth).unwrap_or_default();
            if ns != "agent:harness" {
                all.extend(m.runs_touching("agent:harness", &h, depth).unwrap_or_default());
            }
            all.sort();
            all.dedup();
            all
        }
        Err(_) => Vec::new(),
    };
    let sub = AreevSubstrate::new(m, None);
    let engine = Engine::with_builtins();
    let target = format!("tool:{hash_arg}");
    let recs: Vec<_> = engine
        .recommendations(&sub, None)
        .map_err(|e| e.to_string())?
        .into_iter()
        .filter(|r| r.target_ref == target)
        .collect();
    // Audit chain per recommendation, oldest first (loop_audit observations).
    let audits = sub
        .grains_of_type("observation", Some("areev-loop"), Default::default())
        .unwrap_or_default();
    let mut out_recs = Vec::new();
    for r in &recs {
        let mut chain: Vec<serde_json::Value> = audits
            .iter()
            .filter(|a| a.str_field("rec_hash") == Some(r.hash.as_str()))
            .map(|a| {
                let mut row = serde_json::json!({
                    "to": a.str_field("to_status"),
                    "actor": a.str_field("actor"),
                    "because": a.str_field("because"),
                    "at_ms": a.fields.get("at_ms"),
                });
                if let Some(es) = a.str_field("gating_evalset") {
                    row["gating"] = serde_json::json!({
                        "evalset": es,
                        "run_id": a.str_field("gating_run_id"),
                        "passed": a.fields.get("gating_passed"),
                        "failed": a.fields.get("gating_failed"),
                    });
                }
                row
            })
            .collect();
        chain.sort_by_key(|c| c.get("at_ms").and_then(|v| v.as_i64()).unwrap_or(0));
        out_recs.push(serde_json::json!({
            "recommendation": r.hash,
            "status": r.status.as_str(),
            "summary": r.summary.render(),
            "evalset_pin": r.evalset_hash,
            "lifecycle": chain,
        }));
    }
    let mut report = serde_json::json!({
        "tool": hash_arg,
        "recommendations": out_recs,
        "runs_touching": runs,
        "runs_touching_count": runs.len(),
    });
    if let Some(e) = executor {
        report["executor"] = e;
    }
    println!("{}", serde_json::to_string_pretty(&report).unwrap());
    if out_recs.is_empty() && runs.is_empty() {
        eprintln!("note: nothing recorded for this hash yet (no recommendations target it; no runs touch it)");
    }
    Ok(())
}

/// What the Tool's `executor_uri` actually points at, resolved.
///
/// Reads through [`areev_store::read_blob_offline`] — lock-free, straight off
/// the `.blobs` sidecar — for the reason that function exists: this command
/// is most useful WHILE something is running, and the embedded backend's file
/// lock is exclusive, so a read that needed the database would be refused by
/// the very run being investigated.
///
/// Only a `cas://` address can be chased: it is content, and the address is
/// the checksum. Any other scheme (a command, an endpoint) names something
/// this process cannot verify, and is reported as unresolvable rather than
/// as missing — "we did not look" and "it is not there" are different
/// findings.
fn executor_blob_report(db_path: &str, uri: &str) -> serde_json::Value {
    let mut out = serde_json::json!({"executor_uri": uri});
    if !uri.starts_with("cas://") {
        out["blob_present"] = serde_json::json!(false);
        out["note"] = serde_json::json!(
            "not a cas:// address — the code is not content-addressed in this memory, \
             so what ran cannot be verified from here"
        );
        return out;
    }
    match areev_store::read_blob_offline(db_path, uri) {
        Ok(Some(bytes)) => {
            out["blob_present"] = serde_json::json!(true);
            out["blob_bytes"] = serde_json::json!(bytes.len());
        }
        // Sealed: the blob IS here, the bytes need the memory's derived key.
        // Reporting it absent would be a false negative on the one question
        // this command exists to answer.
        Ok(None) => {
            out["blob_present"] = serde_json::json!(true);
            out["blob_sealed"] = serde_json::json!(true);
        }
        Err(e) => {
            out["blob_present"] = serde_json::json!(false);
            out["error"] = serde_json::json!(e.to_string());
        }
    }
    out
}

/// `areev eval` — evalsets and the §7.4 gating edge.
///
/// - `create --name N --cases FILE` stores an evalset grain (cases as
///   content: `[{"name", "input", "expect": {"equals": …}|{"contains": …}}]`)
///   and prints its hash — the hash a `code_revision` recommendation pins.
/// - `run --evalset HASH --tool-cmd CMD` executes every case through the
///   subprocess seam (case input on stdin, result JSON on stdout,
///   `AREEV_EVAL_CASE`/`AREEV_EVALSET` in the env), journals each case as a
///   Tool grain under a fresh `eval-…` run id, writes the summary Fact
///   (`evalset:<hash> mg:eval_run {run_id, passed, failed}`), and prints the
///   stats. That summary IS the gating evidence `areev loop apply
///   --gating-run` loads — apply of a code revision without it is refused.
fn run_eval(
    m: Areev,
    flags: &HashMap<String, String>,
    positional: &[String],
) -> Result<(), String> {
    // Where the NUMBERS live. `areev_loop::eval` reads `mg:eval_run` Facts
    // from here, and `Engine::gating_evidence` goes through the same reader,
    // so the summary and the re-acceptance record must not move.
    const EVAL_NS: &str = "agent:harness";
    let sub_cmd = positional.first().map(|s| s.as_str()).unwrap_or("");
    // Where the CONTENT lives (#314). Evaluation cases are built from a
    // firm's own confidential documents, and `run_eval` wrote the evalset,
    // every case's input and every case's output to the memory-wide
    // `agent:harness` — outside the grants, retention and erasure of the
    // namespace they came from — while ignoring the global `--ns` entirely.
    //
    // An explicit flag rather than the global `--ns`, so no existing
    // invocation changes placement under anyone's feet. The split is the one
    // `areev run` already makes: effect grains in the run's namespace,
    // evidence ABOUT the run in the harness.
    let case_ns = flag(flags, "case-ns").unwrap_or_else(|| EVAL_NS.to_string());
    let facade = run_stack::host_facade(m, Some(EVAL_NS.to_string()), flags)?;
    let need = |key: &str, usage: &str| -> Result<String, String> {
        flag(flags, key).ok_or_else(|| format!("usage: {usage}"))
    };
    match sub_cmd {
        "create" => {
            let usage = "areev eval create --name NAME --cases FILE";
            let name = need("name", usage)?;
            let path = need("cases", usage)?;
            let text = std::fs::read_to_string(&path).map_err(|e| format!("{path}: {e}"))?;
            let cases: Vec<serde_json::Value> =
                serde_json::from_str(&text).map_err(|e| format!("cases must be a JSON list: {e}"))?;
            if cases.is_empty() {
                return Err("an evalset needs at least one case".into());
            }
            for (i, c) in cases.iter().enumerate() {
                let ok = c.get("name").and_then(|v| v.as_str()).is_some()
                    && c.get("input").is_some()
                    && c.get("expect").is_some_and(|e| {
                        e.get("equals").is_some() || e.get("contains").and_then(|v| v.as_str()).is_some()
                    });
                if !ok {
                    return Err(format!(
                        "case {i} must be {{\"name\", \"input\", \"expect\": {{\"equals\": …}} | {{\"contains\": \"…\"}}}}"
                    ));
                }
            }
            let payload = serde_json::json!({"name": name, "cases": cases});
            let mut fact = areev_core::types::Fact::new(
                &format!("evalset:{name}"),
                "mg:evalset",
                &payload.to_string(),
            )
            .namespace(&case_ns);
            fact.common.extra_fields.insert("evalset_name".into(), serde_json::json!(name));
            let h = facade.with_store(|m| m.add(&fact)).map_err(|e| e.to_string())?;
            println!("evalset '{name}' stored: {h} ({} cases)", cases.len());
            Ok(())
        }
        "run" => {
            let usage = "areev eval run --evalset HASH (--tool-cmd CMD | --model provider:name \
                         [--base-url URL] [--key-env VAR] [--llm-max-tokens N]) \
                         [--baseline RUN_ID [--tolerance POINTS]]";
            let evalset_hex = need("evalset", usage)?;
            // Exactly one executor: a host command, or a model behind the
            // ToolCallLlm seam (how a tuned adapter served by vLLM / SGLang /
            // Ollama is graded — `--model openai-compat:<served-name>`).
            let cmd = flag(flags, "tool-cmd");
            let model = flag(flags, "model");
            let llm = match (&cmd, &model) {
                (Some(_), Some(_)) => {
                    return Err("give either --tool-cmd or --model, not both".into());
                }
                (None, None) => return Err(usage.to_string()),
                (Some(_), None) => None,
                (None, Some(spec)) => Some(
                    areev_llm::resolve_toolcall(
                        spec,
                        flag(flags, "base-url").as_deref(),
                        flag(flags, "key-env").as_deref(),
                    )
                    .map_err(|e| e.to_string())?,
                ),
            };
            let llm_max_tokens: u32 = flag(flags, "llm-max-tokens")
                .map(|v| v.parse().map_err(|_| "--llm-max-tokens must be a number".to_string()))
                .transpose()?
                .unwrap_or(1024);
            let h = Hash::from_hex(&evalset_hex).map_err(|e| e.to_string())?;
            let grain = facade.with_store(|m| m.get(&h)).map_err(|e| e.to_string())?;
            let payload: serde_json::Value = grain
                .get_str("object")
                .and_then(|o| serde_json::from_str(o).ok())
                .ok_or("grain is not an evalset (no JSON object payload)")?;
            let cases = payload
                .get("cases")
                .and_then(|c| c.as_array())
                .cloned()
                .ok_or("evalset payload carries no cases")?;
            let run_id = format!(
                "eval-{}",
                std::time::SystemTime::now()
                    .duration_since(std::time::UNIX_EPOCH)
                    .map(|d| d.as_millis())
                    .unwrap_or(0)
            );
            // Fail-closed: a gate run that cannot run EVERY case records
            // nothing. The model path constrains case-input shapes (a prompt
            // string or a messages array); tool-cmd cases stay any-JSON.
            if llm.is_some() {
                for case in &cases {
                    let cname = case.get("name").and_then(|v| v.as_str()).unwrap_or("case");
                    let input = case.get("input").cloned().unwrap_or(serde_json::json!({}));
                    eval_model_messages(&input).map_err(|e| format!("case '{cname}': {e}"))?;
                }
            }
            let (mut passed, mut failed) = (0u64, 0u64);
            // What the run cost, beside what it scored (`docs/loop.md`,
            // "Evalset-backed outcomes"): every case is one executor call
            // (an effect), timed; the model path also sums the provider's
            // reported usage. Journaled as integer keys the Verify gate's
            // cost bound reads fail-closed.
            let (mut effects, mut wall_ms) = (0u64, 0u64);
            let (mut input_tokens, mut output_tokens) = (0u64, 0u64);
            // #313: host-graded FIELD metrics and usage, reported by the
            // grader out of band and aggregated here.
            //
            // A `--tool-cmd` case could only say pass or fail: the per-case
            // row was `{"case","ok"}` and the summary carried no tokens at
            // all, so a grader scoring value/period/unit/basis per extracted
            // figure had no way into `mg:eval_run` — although the Verify gate
            // already reads host-defined summary fields. The only route was
            // to bypass the verb and journal the Facts by hand.
            let mut metric_totals: std::collections::BTreeMap<String, (f64, u64)> =
                std::collections::BTreeMap::new();
            let mut usd_micros = 0u64;
            let mut reported_usage = false;
            let mut rows = Vec::new();
            for case in &cases {
                let cname = case.get("name").and_then(|v| v.as_str()).unwrap_or("case");
                let input = case.get("input").cloned().unwrap_or(serde_json::json!({}));
                let expect = case.get("expect").cloned().unwrap_or(serde_json::json!({}));
                let started = std::time::Instant::now();
                let mut case_report: Option<Result<EvalCaseReport, String>> = None;
                let (ok, got) = match &llm {
                    Some(llm) => {
                        let (ok, got, usage) =
                            run_eval_case_model(llm.as_ref(), &input, &expect, llm_max_tokens);
                        if let Some((i, o)) = usage {
                            input_tokens += i;
                            output_tokens += o;
                        }
                        (ok, got)
                    }
                    None => {
                        let (ok, got, report) = run_eval_case(
                            cmd.as_deref().unwrap_or_default(),
                            &evalset_hex,
                            cname,
                            &input,
                            &expect,
                        );
                        case_report = report;
                        (ok, got)
                    }
                };
                // Read fail-closed, the way the cost keys are: a report that
                // is present and malformed FAILS the case with the reason. A
                // grader that produced garbage graded nothing.
                let mut ok = ok;
                let mut got = got;
                if let Some(Err(why)) = &case_report {
                    ok = false;
                    got = format!("{got}\n[eval report rejected: {why}]");
                }
                effects += 1;
                wall_ms += started.elapsed().as_millis() as u64;
                if ok { passed += 1 } else { failed += 1 };
                let mut case_metrics = serde_json::Map::new();
                let mut case_usage = serde_json::Map::new();
                if let Some(Ok(report)) = &case_report {
                    for (name, v) in &report.metrics {
                        let e = metric_totals.entry(name.clone()).or_insert((0.0, 0));
                        e.0 += v;
                        e.1 += 1;
                        case_metrics.insert(name.clone(), serde_json::json!(v));
                    }
                    if let Some(n) = report.input_tokens {
                        input_tokens += n;
                        reported_usage = true;
                        case_usage.insert("input_tokens".into(), serde_json::json!(n));
                    }
                    if let Some(n) = report.output_tokens {
                        output_tokens += n;
                        reported_usage = true;
                        case_usage.insert("output_tokens".into(), serde_json::json!(n));
                    }
                    if let Some(n) = report.usd_micros {
                        usd_micros += n;
                        reported_usage = true;
                        case_usage.insert("usd_micros".into(), serde_json::json!(n));
                    }
                }
                // Each case is journaled — the gate run is inspectable with
                // `areev run-trace --run-id <eval id>` like any other run.
                facade
                    .record_tool_call(
                        // The case's input and output are CONTENT (#314).
                        &case_ns,
                        &format!("eval:{cname}"),
                        Some(&input.to_string()),
                        &got,
                        !ok,
                        None,
                        None,
                        Some(&run_id),
                        None,
                        None,
                        Some(if ok { "completed" } else { "failed" }),
                        None,
                        Some("host"),
                        None,
                    )
                    .map_err(|e| e.to_string())?;
                let mut row = serde_json::json!({"case": cname, "ok": ok});
                if !case_metrics.is_empty() {
                    row["metrics"] = serde_json::Value::Object(case_metrics);
                }
                if !case_usage.is_empty() {
                    row["usage"] = serde_json::Value::Object(case_usage);
                }
                rows.push(row);
            }
            // The summary Fact — the RECORDED edge apply-gating loads. The
            // grading model rides beside the stats: for an adapter gate,
            // WHICH served model was judged is part of the evidence.
            let mut summary = serde_json::json!({
                "run_id": run_id, "passed": passed, "failed": failed,
                "effects": effects, "wall_ms": wall_ms,
            });
            if let Some(spec) = &model {
                summary["model"] = serde_json::json!(spec);
                summary["input_tokens"] = serde_json::json!(input_tokens);
                summary["output_tokens"] = serde_json::json!(output_tokens);
            }
            // #314: the summary stays in the harness — ids, counts and cost
            // only — and says where the content went, so `run-trace --ns NS`
            // finds the cases.
            if case_ns != EVAL_NS {
                summary["case_ns"] = serde_json::json!(case_ns);
            }
            // #313: host-graded field metrics and usage, aggregated.
            for (name, (sum, n)) in &metric_totals {
                summary[name.as_str()] = serde_json::json!(sum / *n as f64);
                summary[format!("{name}_n")] = serde_json::json!(n);
            }
            if reported_usage {
                summary["input_tokens"] = serde_json::json!(input_tokens);
                summary["output_tokens"] = serde_json::json!(output_tokens);
                if usd_micros > 0 {
                    summary["usd_micros"] = serde_json::json!(usd_micros);
                }
            }
            let mut fact = areev_core::types::Fact::new(
                &format!("evalset:{evalset_hex}"),
                "mg:eval_run",
                &summary.to_string(),
            )
            .namespace(EVAL_NS);
            fact.common.extra_fields.insert("run_id".into(), serde_json::json!(run_id));
            facade.with_store(|m| m.add(&fact)).map_err(|e| e.to_string())?;

            // Re-acceptance (the enterprise plane's model-swap harness):
            // --baseline RUN_ID compares this run's pass rate against a
            // RECORDED earlier gate run of the same evalset, within
            // --tolerance percentage points (default 0 — any drop fails).
            // The comparison itself is recorded as a Fact, so "we re-ran
            // acceptance after the model swap" is evidence, not a claim.
            // The arithmetic is the Verify gate's `is_regression` — one
            // reader of "did it get worse" for both edges, so a swap cannot
            // be re-accepted on one rule and its lessons judged on another.
            let mut reacceptance = serde_json::Value::Null;
            if let Some(baseline_run) = flag(flags, "baseline") {
                let tolerance: f64 = match flag(flags, "tolerance") {
                    None => 0.0,
                    Some(v) => match v.parse::<f64>() {
                        Ok(t) if t.is_finite() && t >= 0.0 => t,
                        _ => return Err("--tolerance must be a number of percentage points ≥ 0".into()),
                    },
                };
                let baseline = json_from_facade_recall(&facade, EVAL_NS, &format!("evalset:{evalset_hex}"))?
                    .into_iter()
                    .filter(|row| row["fields"]["relation"] == "mg:eval_run")
                    .filter_map(|row| {
                        serde_json::from_str::<serde_json::Value>(row["fields"]["object"].as_str()?)
                            .ok()
                    })
                    .find(|s| s["run_id"] == baseline_run.as_str())
                    .ok_or_else(|| {
                        format!("no recorded gate run '{baseline_run}' for this evalset")
                    })?;
                let rate = |p: u64, f: u64| {
                    if p + f == 0 { 0.0 } else { p as f64 / (p + f) as f64 * 100.0 }
                };
                let base_rate = rate(
                    baseline["passed"].as_u64().unwrap_or(0),
                    baseline["failed"].as_u64().unwrap_or(0),
                );
                let this_rate = rate(passed, failed);
                let within =
                    !areev_loop::recommendation::is_regression(base_rate, this_rate, true, tolerance);
                reacceptance = serde_json::json!({
                    "baseline_run": baseline_run,
                    "baseline_pass_rate": base_rate,
                    "pass_rate": this_rate,
                    "tolerance_points": tolerance,
                    "accepted": within,
                });
                let mut cmp = areev_core::types::Fact::new(
                    &format!("evalset:{evalset_hex}"),
                    "mg:reacceptance",
                    &reacceptance.to_string(),
                )
                .namespace(EVAL_NS);
                cmp.common.extra_fields.insert("run_id".into(), serde_json::json!(run_id));
                facade.with_store(|m| m.add(&cmp)).map_err(|e| e.to_string())?;
                if !within {
                    println!(
                        "{}",
                        serde_json::to_string_pretty(&serde_json::json!({
                            "evalset": evalset_hex, "run_id": run_id,
                            "passed": passed, "failed": failed,
                            "reacceptance": reacceptance,
                        }))
                        .unwrap()
                    );
                    return Err(format!(
                        "re-acceptance FAILED: pass rate {this_rate:.1}% vs baseline \
                         {base_rate:.1}% (tolerance {tolerance} points)"
                    ));
                }
            }

            println!(
                "{}",
                // Derived from the STORED summary rather than rebuilt, so the
                // printed JSON and the `mg:eval_run` Fact cannot drift on
                // what a run recorded (#313).
                serde_json::to_string_pretty(&{
                    let mut printed = summary.clone();
                    printed["evalset"] = serde_json::json!(evalset_hex);
                    printed["cases"] = serde_json::Value::Array(rows.clone());
                    printed["reacceptance"] = reacceptance.clone();
                    if !reported_usage && model.is_none() {
                        // Nothing reported usage: say so with null rather
                        // than an unearned zero.
                        printed["input_tokens"] = serde_json::Value::Null;
                        printed["output_tokens"] = serde_json::Value::Null;
                    }
                    printed
                })
                .unwrap()
            );
            if failed > 0 {
                return Err(format!("{failed} case(s) failed"));
            }
            Ok(())
        }
        other => Err(format!(
            "unknown eval subcommand '{other}' — usage: areev eval <create|run>"
        )),
    }
}

/// Recall a subject's rows through a facade as parsed JSON.
fn json_from_facade_recall(
    facade: &AreevFacade,
    ns: &str,
    subject: &str,
) -> Result<Vec<serde_json::Value>, String> {
    let rows = facade
        .with_store(|m| m.recall(ns, subject, None, 100_000))
        .map_err(|e| e.to_string())?;
    Ok(rows
        .into_iter()
        .map(|g| serde_json::json!({"fields": g.fields, "hash": g.hash.to_hex()}))
        .collect())
}

/// What a grader may report OUT OF BAND about one case (#313).
///
/// Off stdout on purpose: `equals` / `contains` scoring reads stdout, and a
/// reserved trailer or an envelope would change what every existing grader
/// has to print. The command writes one JSON object to the file named by
/// `$AREEV_EVAL_REPORT` instead, and a grader that writes nothing produces a
/// summary byte-identical to today's.
#[derive(Debug, Default, Clone)]
pub(crate) struct EvalCaseReport {
    /// Field metrics, each a finite number. A 0/1 field result reads as a
    /// ratio once averaged, which is what `min_effect.points` assumes of a
    /// host-defined summary field.
    pub(crate) metrics: std::collections::BTreeMap<String, f64>,
    pub(crate) input_tokens: Option<u64>,
    pub(crate) output_tokens: Option<u64>,
    pub(crate) usd_micros: Option<u64>,
}

/// Summary keys the verb owns. A metric may not collide with one — a metric
/// named `passed` would overwrite the count the gate reads.
pub(crate) const RESERVED_EVAL_KEYS: &[&str] = &[
    "run_id",
    "passed",
    "failed",
    "effects",
    "wall_ms",
    "input_tokens",
    "output_tokens",
    "usd_micros",
    "model",
    "case_ns",
];

/// Parse a grader's report. Fail-closed throughout: a non-integer usage
/// value is an ERROR, never a zero — reading a malformed cost as free is the
/// failure `areev_loop::eval` is explicit about refusing.
pub(crate) fn parse_eval_report(text: &str) -> Result<EvalCaseReport, String> {
    let v: serde_json::Value = serde_json::from_str(text.trim())
        .map_err(|e| format!("$AREEV_EVAL_REPORT is not valid JSON: {e}"))?;
    let obj = v
        .as_object()
        .ok_or_else(|| "$AREEV_EVAL_REPORT must be a JSON object".to_string())?;
    let mut out = EvalCaseReport::default();
    if let Some(metrics) = obj.get("metrics") {
        let metrics = metrics
            .as_object()
            .ok_or_else(|| "\"metrics\" must be an object".to_string())?;
        for (name, value) in metrics {
            if !name
                .chars()
                .next()
                .is_some_and(|c| c.is_ascii_lowercase())
                || !name
                    .chars()
                    .all(|c| c.is_ascii_lowercase() || c.is_ascii_digit() || c == '_')
            {
                return Err(format!(
                    "metric name {name:?} must match [a-z][a-z0-9_]*"
                ));
            }
            if RESERVED_EVAL_KEYS.contains(&name.as_str()) {
                return Err(format!(
                    "metric name {name:?} collides with a summary key this verb owns \
                     (reserved: {})",
                    RESERVED_EVAL_KEYS.join(", ")
                ));
            }
            let n = value
                .as_f64()
                .filter(|n| n.is_finite())
                .ok_or_else(|| format!("metric {name:?} must be a finite number"))?;
            out.metrics.insert(name.clone(), n);
        }
    }
    if let Some(usage) = obj.get("usage") {
        let usage = usage
            .as_object()
            .ok_or_else(|| "\"usage\" must be an object".to_string())?;
        for (key, slot) in [
            ("input_tokens", &mut out.input_tokens),
            ("output_tokens", &mut out.output_tokens),
            ("usd_micros", &mut out.usd_micros),
        ] {
            if let Some(v) = usage.get(key) {
                *slot = Some(
                    v.as_u64()
                        .ok_or_else(|| format!("usage.{key} must be a non-negative integer"))?,
                );
            }
        }
    }
    Ok(out)
}

/// One eval case through the subprocess seam. Returns (passed, output text,
/// the grader's optional out-of-band report).
#[allow(clippy::type_complexity)]
fn run_eval_case(
    cmd: &str,
    evalset: &str,
    case: &str,
    input: &serde_json::Value,
    expect: &serde_json::Value,
) -> (bool, String, Option<Result<EvalCaseReport, String>>) {
    use areev_core::proc::{self, SpawnPolicy};
    use std::process::Command;
    // The platform shell: /bin/sh -c on unix, cmd /C on Windows. The
    // Windows command string must go through raw_arg — Command::arg
    // MSVC-quotes embedded quotes, which cmd.exe does not parse.
    #[cfg(not(windows))]
    let mut shell = Command::new("/bin/sh");
    #[cfg(not(windows))]
    shell.arg("-c").arg(cmd);
    #[cfg(windows)]
    let mut shell = Command::new("cmd");
    #[cfg(windows)]
    {
        use std::os::windows::process::CommandExt;
        shell.raw_arg("/C").raw_arg(cmd);
    }
    // The report file is created empty and named to the child, beside
    // `AREEV_EVALSET` and `AREEV_EVAL_CASE` (#313). A grader that ignores it
    // behaves exactly as before.
    let report_dir = std::env::temp_dir();
    let report_path = report_dir.join(format!(
        "areev-eval-{}-{}.json",
        std::process::id(),
        case.chars()
            .map(|c| if c.is_ascii_alphanumeric() { c } else { '_' })
            .collect::<String>()
    ));
    let _ = std::fs::remove_file(&report_path);
    let report_env = report_path.to_string_lossy().to_string();
    let out = match proc::run(
        shell,
        Some(input.to_string().as_bytes()),
        &[
            ("AREEV_EVALSET", evalset),
            ("AREEV_EVAL_CASE", case),
            ("AREEV_EVAL_REPORT", report_env.as_str()),
        ],
        &SpawnPolicy::default(),
    ) {
        Ok(o) => o,
        Err(e) => return (false, format!("spawn failed: {e}"), None),
    };
    let report = match std::fs::read_to_string(&report_path) {
        Ok(text) if !text.trim().is_empty() => Some(parse_eval_report(&text)),
        // Absent or empty: the grader did not report, which is not an error.
        _ => None,
    };
    let _ = std::fs::remove_file(&report_path);
    let stdout = String::from_utf8_lossy(&out.stdout).trim().to_string();
    if let Some(why) = out.failure("eval case") {
        return (false, why, report);
    }
    (eval_expect_matches(expect, &stdout), stdout, report)
}

/// The ONE scorer, shared by the tool-cmd and model paths: `expect.equals`
/// compares parsed JSON, `expect.contains` is a substring test, anything
/// else fails. Two scorers would let the two paths drift on what "passed"
/// means — the gate's whole job.
fn eval_expect_matches(expect: &serde_json::Value, got: &str) -> bool {
    if let Some(eq) = expect.get("equals") {
        serde_json::from_str::<serde_json::Value>(got)
            .map(|parsed| &parsed == eq)
            .unwrap_or(false)
    } else if let Some(needle) = expect.get("contains").and_then(|v| v.as_str()) {
        got.contains(needle)
    } else {
        false
    }
}

/// Map a model-path case `input` onto chat messages: a string is one user
/// message; an array of `{role, content}` (`system` | `user` | `assistant`)
/// is a conversation, with at most one leading `system` lifted into the
/// request's system slot. Anything else is refused — BEFORE any case runs.
fn eval_model_messages(
    input: &serde_json::Value,
) -> Result<(Option<String>, Vec<areev_llm::ChatMessage>), String> {
    use areev_llm::ChatMessage;
    if let Some(prompt) = input.as_str() {
        return Ok((None, vec![ChatMessage::User(prompt.to_string())]));
    }
    let Some(turns) = input.as_array() else {
        return Err(
            "--model cases need a string prompt or an array of {role, content} \
             messages (tool-cmd cases take any JSON)"
                .into(),
        );
    };
    let mut system = None;
    let mut messages = Vec::new();
    for (i, turn) in turns.iter().enumerate() {
        let role = turn.get("role").and_then(|r| r.as_str()).unwrap_or_default();
        let content = turn
            .get("content")
            .and_then(|c| c.as_str())
            .ok_or_else(|| format!("message {i} has no string content"))?;
        match role {
            "system" if i == 0 => system = Some(content.to_string()),
            "system" => return Err(format!("message {i}: system must be the first message")),
            "user" => messages.push(ChatMessage::User(content.to_string())),
            "assistant" => messages.push(ChatMessage::Assistant {
                text: Some(content.to_string()),
                tool_calls: vec![],
                provider_content: None,
            }),
            other => return Err(format!("message {i} has unsupported role {other:?}")),
        }
    }
    if messages.is_empty() {
        return Err("a --model case needs at least one user or assistant message".into());
    }
    Ok((system, messages))
}

/// Run one case against the model behind the ToolCallLlm seam: no tools,
/// temperature 0.0, the response text scored by the same matcher as a
/// tool-cmd case's stdout. Returns (passed, output text, (input, output)
/// tokens the provider reported).
fn run_eval_case_model(
    llm: &dyn areev_llm::ToolCallLlm,
    input: &serde_json::Value,
    expect: &serde_json::Value,
    max_tokens: u32,
) -> (bool, String, Option<(u64, u64)>) {
    use areev_llm::{ToolCallRequest, ToolChoice};
    // Prevalidated before the run started; a failure here is still a case
    // failure rather than a panic.
    let (system, messages) = match eval_model_messages(input) {
        Ok(v) => v,
        Err(e) => return (false, e, None),
    };
    let req = ToolCallRequest {
        system,
        messages,
        tools: &[],
        tool_choice: ToolChoice::None,
        max_tokens,
        temperature: 0.0,
    };
    match llm.call(&req) {
        Ok(resp) => {
            let usage = (resp.usage.input_tokens, resp.usage.output_tokens);
            let text = resp.text.unwrap_or_default().trim().to_string();
            (eval_expect_matches(expect, &text), text, Some(usage))
        }
        Err(e) => (false, format!("model call failed: {}", e.message), None),
    }
}

/// Record a hold transition on the Tier-2 trail `areev audit export` reads.
///
/// The hold row itself is a file-truth that is DELETED on release, so without
/// this the release leaves no trace at all — the placement would be the only
/// half on record.
fn audit_hold(
    m: &mut Areev,
    verb: &str,
    ns: &str,
    because: &str,
    by: &str,
    now: i64,
) -> Result<(), String> {
    let mut obs = areev_core::authz::audit_observation(
        by,
        verb,
        &format!("hold ns:{ns}"),
        Some(because),
        0,
        now,
    );
    m.append_audit(&mut obs).map(|_| ()).map_err(|e| e.to_string())
}

/// `areev hold` — legal holds (governed-agents §5.4): while a hold is live on
/// a namespace, EVERY destruction path there refuses with `STO-E009`
/// (#278) — the age-based sweeps, `forget` by hash, identity erasure, the
/// memory tool, the loop's rollback, and on Postgres the schema drop. Sweeps
/// skip a held namespace with the refusal on record, and a refused erasure
/// is itself recorded. D10's override shipped in 1.9.0:
/// `--override-hold --because`, requiring `admin` on the namespace.
fn run_hold(
    m: &mut Areev,
    ns: &str,
    flags: &HashMap<String, String>,
    positional: &[String],
) -> Result<(), String> {
    let sub_cmd = positional.first().map(|s| s.as_str()).unwrap_or("list");
    match sub_cmd {
        "set" => {
            let because = flag(flags, "because").ok_or_else(|| {
                "usage: areev hold set --because \"litigation X\" [--ns NS] [--by PRINCIPAL]"
                    .to_string()
            })?;
            let by = flag(flags, "by").unwrap_or_else(|| "user:local".into());
            let now = now_ms();
            m.place_hold(ns, &because, &by, now).map_err(|e| e.to_string())?;
            audit_hold(m, "hold.set", ns, &because, &by, now)?;
            println!("hold placed on '{ns}' by {by}: {because}");
        }
        // Releasing is the act an auditor asks about, so it is held to the
        // same bar as placing: a reason is mandatory, and both ends land in
        // `areev audit export` rather than only the placement.
        "release" => {
            let because = flag(flags, "because").ok_or_else(|| {
                "usage: areev hold release --because \"matter closed\" [--ns NS] \
                 [--by PRINCIPAL] — a release with no recorded rationale is the \
                 half of the trail an auditor actually asks for"
                    .to_string()
            })?;
            let by = flag(flags, "by").unwrap_or_else(|| "user:local".into());
            let now = now_ms();
            m.release_hold(ns).map_err(|e| e.to_string())?;
            audit_hold(m, "hold.release", ns, &because, &by, now)?;
            println!("hold released on '{ns}' by {by}: {because}");
        }
        "list" => {
            // #323: `at_ms` has always been stored; only the read dropped it.
            let holds = m.hold_records().map_err(|e| e.to_string())?;
            if flag(flags, "format").as_deref() == Some("json") {
                let rows: Vec<serde_json::Value> = holds
                    .iter()
                    .map(|h| {
                        serde_json::json!({
                            "ns": h.ns,
                            "because": h.because,
                            "placed_by": h.placed_by,
                            "at_ms": h.at_ms,
                        })
                    })
                    .collect();
                println!("{}", serde_json::to_string(&rows).map_err(|e| e.to_string())?);
                return Ok(());
            }
            if holds.is_empty() {
                println!("no legal holds in this memory");
            }
            for h in holds {
                // A hold from before 1.9.1 has no stored time; say so rather
                // than printing the epoch, which reads as 1970.
                let when = if h.at_ms == 0 {
                    "placed at an unrecorded time".to_string()
                } else {
                    format!("placed at {}", h.at_ms)
                };
                println!("{}: held by {} — {} ({when})", h.ns, h.placed_by, h.because);
            }
        }
        other => {
            return Err(format!(
                "unknown hold subcommand '{other}' — usage: areev hold <set|release|list>"
            ))
        }
    }
    Ok(())
}

/// Read a stream dir's `CURSOR`: `"<gen_id> <op_seq> <next_seg>"`.
///
/// The third field is what keeps retention safe. Dirs written before it
/// existed carry only two fields; for those we fall back to counting
/// segment files, which is correct precisely because such a dir has never
/// been pruned (counting is what pruning breaks).
fn read_stream_cursor(cursor_path: &str, to: &str) -> (String, i64, u32) {
    let Ok(s) = std::fs::read_to_string(cursor_path) else {
        return (String::new(), 0, 0);
    };
    let mut parts = s.trim().splitn(3, ' ');
    let gen_id = parts.next().unwrap_or("").to_string();
    let cursor: i64 = parts.next().and_then(|v| v.parse().ok()).unwrap_or(0);
    let seg = match parts.next().and_then(|v| v.parse::<u32>().ok()) {
        Some(n) => n,
        None => std::fs::read_dir(format!("{to}/gen-{gen_id}"))
            .map(|d| d.filter_map(|e| e.ok()).filter(|e| e.path().extension().is_some_and(|x| x == "mgb")).count() as u32)
            .unwrap_or(0),
    };
    (gen_id, cursor, seg)
}

/// Drop whole generations older than `window_ms`, never individual segments
/// inside one — a hole in a live generation strands every follower at the
/// gap, while dropping a whole generation is a re-baseline the follower
/// handles. The current generation is always kept.
///
/// This is what makes the Art. 17 archive guarantee true: each generation's
/// segment 0 is a snapshot of the already-erased store, so once the
/// pre-erasure generations age out, the erased bytes are gone from the
/// archive as well as the live store. See docs/gdpr.md §3.
fn prune_generations(to: &str, current_gen: &str, window_ms: i64) -> Result<usize, String> {
    let now = std::time::SystemTime::now();
    let mut dropped = 0usize;
    for entry in std::fs::read_dir(to).map_err(|e| e.to_string())?.flatten() {
        let path = entry.path();
        let name = entry.file_name().to_string_lossy().to_string();
        if !path.is_dir() || !name.starts_with("gen-") || name == format!("gen-{current_gen}") {
            continue;
        }
        // Age by the NEWEST segment in the generation: a generation is only
        // expendable once everything in it has aged out.
        let newest = std::fs::read_dir(&path)
            .map_err(|e| e.to_string())?
            .flatten()
            .filter_map(|f| f.metadata().ok().and_then(|md| md.modified().ok()))
            .max();
        let Some(newest) = newest else { continue };
        let age_ms = now.duration_since(newest).map(|d| d.as_millis() as i64).unwrap_or(0);
        if age_ms > window_ms {
            std::fs::remove_dir_all(&path).map_err(|e| e.to_string())?;
            dropped += 1;
        }
    }
    Ok(dropped)
}

/// Parse a duration like `6h` / `30m` / `2d` / `3600s` into milliseconds.
fn parse_duration(s: &str) -> Option<i64> {
    let s = s.trim();
    let split = s.find(|c: char| !c.is_ascii_digit())?;
    let n: i64 = s[..split].parse().ok()?;
    let mult = match &s[split..] {
        "s" => 1_000,
        "m" => 60_000,
        "h" => 3_600_000,
        "d" => 86_400_000,
        _ => return None,
    };
    Some(n * mult)
}

fn parse_severity(s: &str) -> Severity {
    match s.to_ascii_lowercase().as_str() {
        "high" => Severity::High,
        "medium" => Severity::Medium,
        "low" => Severity::Low,
        _ => Severity::Info,
    }
}

/// `--status` filter; default is `pending`, `all` clears the filter.
fn status_filter(flags: &HashMap<String, String>) -> Option<RecStatus> {
    match flag(flags, "status").as_deref() {
        Some("approved") => Some(RecStatus::Approved),
        Some("rejected") => Some(RecStatus::Rejected),
        Some("applied") => Some(RecStatus::Applied),
        Some("rolled_back") => Some(RecStatus::RolledBack),
        Some("expired") => Some(RecStatus::Expired),
        Some("withdrawn") => Some(RecStatus::Withdrawn),
        Some("all") => None,
        _ => Some(RecStatus::Pending),
    }
}

fn short(hash: &str) -> &str {
    &hash[..hash.len().min(12)]
}

/// Resolve a git-style unique hash prefix to a full recommendation hash.
/// Reconstruct the §7.4 gating evidence from the RECORDED gate-run summary
/// (`evalset:<pin> mg:eval_run` Fact in `agent:harness`) — the operator
/// names the run; the numbers come from what `areev eval run` wrote, never
/// from the command line.
fn load_gating_evidence(
    sub: &AreevSubstrate,
    engine: &Engine,
    rec_hash: &str,
    run_id: &str,
) -> Result<areev_loop::GatingEvidence, String> {
    // The ONE loader every surface shares (`Engine::gating_evidence`): the
    // stats that admit a gated revision are read back from the recorded
    // `mg:eval_run` Fact, never taken from the caller.
    engine.gating_evidence(sub, rec_hash, run_id).map_err(|e| e.to_string())
}

fn resolve_hash(engine: &Engine, sub: &AreevSubstrate, prefix: &str) -> Result<String, String> {
    let recs = engine.recommendations(sub, None).map_err(|e| e.to_string())?;
    Ok(areev_loop_adapter::find_recommendation(&recs, prefix)?.hash.clone())
}

/// Resolve an LLM backend from a `--<prefix>cmd` / `--<prefix>model` flag pair,
/// the same two ways `areev loop run` attaches one: a subprocess (the
/// zero-dependency escape hatch) or a built-in HTTP provider whose key is read
/// from the environment, never from the command line. The subprocess wins when
/// both are given. Both fail at construction, before anything is written.
fn resolve_llm(
    flags: &HashMap<String, String>,
    cmd_flag: &str,
    model_flag: &str,
) -> Result<Option<Box<dyn areev_loop::LlmBackend>>, String> {
    if let Some(cmd) = flag(flags, cmd_flag) {
        let label = flag(flags, "llm-model");
        let llm = areev_loop::CommandLlm::new(&cmd, label.as_deref()).map_err(|e| e.to_string())?;
        return Ok(Some(Box::new(llm)));
    }
    if let Some(spec) = flag(flags, model_flag) {
        let base = flag(flags, "llm-base-url");
        let key_env = flag(flags, "llm-api-key-env");
        let llm = areev_llm::resolve(&spec, base.as_deref(), key_env.as_deref())
            .map_err(|e| e.to_string())?;
        return Ok(Some(llm));
    }
    Ok(None)
}

/// `areev remember` — store free text as an Event, then attach the facts
/// distilled from it.
///
/// Three routes to those facts, in precedence order:
///
/// - `--facts JSON` — the host already extracted them; no model is called and
///   the facts carry no model attribution (the host is asserting them).
/// - `--llm-cmd CMD` — a subprocess backend.
/// - `--model provider:name` — a built-in HTTP backend, key from the env.
///
/// The raw text is written **before** the model is called, so a failed or
/// garbage extraction never costs the raw text. Model-extracted facts are
/// stamped `verification_status = "unverified"` (CAL-filterable, so they can be
/// reviewed) unless `--ground-model`/`--ground-cmd` runs a separate entailment
/// pass over them — a different call from the one that proposed them, the same
/// proposer ≠ scorer rule the Areev Loop verifier follows. Facts the grounder does
/// not support are dropped; survivors are stamped `"verified"`.
fn run_remember(mut m: Areev, ns: &str, flags: &HashMap<String, String>) -> Result<(), String> {
    let mut content = need(flags, "content")?;
    // Anonymization boundaries (docs/anonymization-proposal.md §4.1–4.2):
    // under an INGRESS policy, transform before the extractor OR the store
    // sees the text — the CLI composes capture+attach itself, so it must not
    // hand the raw text to the model first. Under an EGRESS policy the
    // extraction request is additionally covered below by the
    // PseudonymizingBackend wrap, so identities stay in-process even when
    // the stored form is raw.
    if let Some(t) = m.ingress_transform_text(ns, &content).map_err(|e| e.to_string())? {
        content = t;
    }
    let egress_wrap = matches!(
        m.anon_active_mode(ns).map_err(|e| e.to_string())?.as_deref(),
        Some("egress")
    );
    let observer = flag(flags, "observer").unwrap_or_else(|| "cli".to_string());
    let dry_run = flag(flags, "dry-run").is_some();
    let hint = flag(flags, "extract-hint");
    let min_confidence = match flag(flags, "min-confidence") {
        Some(s) => s
            .parse::<f64>()
            .map_err(|e| format!("bad --min-confidence: {e}"))?,
        None => 0.0,
    };
    // The store drops an unrecognized role (forward-compatible, which MCP
    // clients rely on), but a typo'd flag silently losing data is a bad trade
    // for a human at a terminal — reject it before anything runs.
    let role = flags.get("role").map(String::as_str);
    if let Some(r) = role.filter(|r| areev_core::types::Role::from_str(r).is_none()) {
        return Err(format!("--role {r:?}: expected user|assistant|system|tool"));
    }

    // Host-supplied drafts short-circuit the model entirely.
    let explicit = match flag(flags, "facts") {
        Some(j) => Some(areev_store::FactDraft::from_json_array(&j).map_err(|e| e.to_string())?),
        None => None,
    };
    let llm = match explicit {
        Some(_) => None,
        None => resolve_llm(flags, "llm-cmd", "model")?,
    };
    let grounder = match llm {
        Some(_) => resolve_llm(flags, "ground-cmd", "ground-model")?,
        None => None,
    };
    // Under an egress policy, extraction requests leave the process
    // pseudonymized and responses come back rehydrated (D5/D6). Fail-closed:
    // the wrap itself erroring fails remember, it never falls back to raw.
    let wrap = |b: Box<dyn areev_loop::LlmBackend>| -> Result<Box<dyn areev_loop::LlmBackend>, String> {
        if egress_wrap {
            let policy = areev_core::anon::AnonPolicy {
                scope: "session".into(),
                ..Default::default()
            };
            Ok(Box::new(
                areev_llm::PseudonymizingBackend::new(b, policy).map_err(|e| e.to_string())?,
            ))
        } else {
            Ok(b)
        }
    };
    let llm = llm.map(wrap).transpose()?;
    let grounder = grounder.map(wrap).transpose()?;
    let model = llm.as_ref().map(|l| l.model().to_string());

    // --dry-run: extract and print, write nothing. For iterating on
    // --extract-hint without leaving drafts behind in the memory.
    if dry_run {
        let (proposed, facts) = match &llm {
            Some(l) => {
                let (proposed, facts, _) = extract_drafts(
                    l.as_ref(),
                    grounder.as_deref(),
                    "dry-run",
                    &content,
                    hint.as_deref(),
                    min_confidence,
                )?;
                (proposed, facts)
            }
            None => {
                let f = explicit.unwrap_or_default();
                (f.len(), f)
            }
        };
        println!(
            "{}",
            serde_json::json!({
                "dry_run": true,
                "model": model,
                "proposed": proposed,
                "facts": facts.iter().map(draft_json).collect::<Vec<_>>(),
            })
        );
        return Ok(());
    }

    // The raw text lands first and unconditionally: whatever the model does
    // next, the source of the extraction is already durable.
    let capture = areev_store::Capture {
        observer: Some(observer.as_str()),
        session_id: flags.get("session-id").map(String::as_str),
        role,
        run_id: flags.get("run-id").map(String::as_str),
    };
    let event = m
        .capture(ns, &content, &capture)
        .map_err(|e| e.to_string())?;
    let report = |facts: &[Hash], extra: serde_json::Value| {
        let mut out = serde_json::json!({
            "event": event.to_hex(),
            "facts": facts.iter().map(|h| h.to_hex()).collect::<Vec<_>>(),
        });
        if let (Some(obj), Some(extra)) = (out.as_object_mut(), extra.as_object()) {
            obj.extend(extra.clone());
        }
        println!("{out}");
    };
    // A model call that fails still leaves the raw text stored — print the
    // hash so the caller can retry the extraction against it, then exit
    // non-zero so the missing facts are not mistaken for "nothing to extract".
    let failed = |e: String| -> String {
        report(&[], serde_json::json!({ "error": e }));
        e
    };

    let (proposed, drafts, status) = match &llm {
        None => {
            let d = explicit.unwrap_or_default();
            (d.len(), d, None)
        }
        Some(l) => match extract_drafts(
            l.as_ref(),
            grounder.as_deref(),
            &event.to_hex(),
            &content,
            hint.as_deref(),
            min_confidence,
        ) {
            Ok((proposed, drafts, grounded)) => (
                proposed,
                drafts,
                Some(if grounded { "verified" } else { "unverified" }),
            ),
            Err(e) => return Err(failed(e)),
        },
    };

    let attribution = areev_store::FactAttribution {
        verification_status: status,
        extractor_model: model.as_deref(),
    };
    let facts = m
        .attach_facts(ns, &event, &drafts, &attribution)
        .map_err(|e| e.to_string())?;
    let extra = match &model {
        // What the model proposed vs what survived the confidence floor and
        // the grounder — a silent drop would read as "the model found less".
        Some(model) => serde_json::json!({
            "model": model,
            "verification_status": status,
            "proposed": proposed,
            "dropped": proposed.saturating_sub(facts.len()),
        }),
        None => serde_json::json!({}),
    };
    report(&facts, extra);
    Ok(())
}

/// Run the shared extract → confidence floor → ground pipeline and convert the
/// survivors to store drafts. Warns on stderr when a response hit the per-call
/// cap, so a truncated extraction is never silent.
fn extract_drafts(
    llm: &dyn areev_loop::LlmBackend,
    grounder: Option<&dyn areev_loop::LlmBackend>,
    source: &str,
    content: &str,
    hint: Option<&str>,
    min_confidence: f64,
) -> Result<(usize, Vec<areev_store::FactDraft>, bool), String> {
    let ex =
        areev_llm::extract_pipeline(llm, grounder, source, content, hint, min_confidence)
            .map_err(|e| e.to_string())?;
    if ex.proposed >= areev_llm::extract::MAX_FACTS {
        eprintln!(
            "note: extraction hit the {}-fact cap; some facts may have been dropped",
            areev_llm::extract::MAX_FACTS
        );
    }
    let drafts = ex
        .facts
        .into_iter()
        .map(|f| areev_store::FactDraft {
            subject: f.subject,
            relation: f.relation,
            object: f.object,
            confidence: f.confidence,
        })
        .collect();
    Ok((ex.proposed, drafts, ex.grounded))
}

fn draft_json(d: &areev_store::FactDraft) -> serde_json::Value {
    serde_json::json!({
        "subject": d.subject,
        "relation": d.relation,
        "object": d.object,
        "confidence": d.confidence,
    })
}

/// `areev provision --db <DSN> [--schema NAME] [--telemetry MODE]` — bootstrap
/// a postgres memory's schema ahead of use (issue #180).
///
/// The whole point is that the FIRST real open afterwards writes nothing at
/// all — no DDL, no advisory lock, no meta stamps, no `ns_reg` rebuild. That
/// is achieved by doing exactly what a first open would do and then closing:
/// `PgDb::open` runs `PG_SCHEMA` + `PG_SEED` and stamps `meta.pg_schema`, and
/// `finish_open` stamps `text_index`, `entity_relations`, `link_index` and
/// `ns_registry`. Re-deriving that list here would be a second copy of the
/// bootstrap to keep in sync — and a copy that fell behind would leave the
/// request path doing the writes this command exists to remove.
///
/// Telemetry is provisioned too unless `--telemetry off`: the sidecar bootstrap
/// is a SECOND `PgDb::open` with its own tables and its own stamp, and every
/// other verb defaults to `--telemetry aggregate`, so a schema provisioned
/// without it would still bootstrap seven tables on the first real request.
fn run_provision(flags: &HashMap<String, String>) -> Result<(), String> {
    let db = flag(flags, "db")
        .or_else(|| std::env::var("AREEV_DB").ok().filter(|v| !v.trim().is_empty()))
        .ok_or_else(|| {
            "areev provision: --db <postgres DSN> names the memory to create".to_string()
        })?;
    if !is_pg_dsn(&db) {
        return Err(format!(
            "areev provision is postgres-only, and {db:?} is not a postgres DSN. A file-backed \
             memory has nothing to provision: it creates and migrates itself at open, with no \
             privilege system to fail against"
        ));
    }
    let tel_mode = match flag(flags, "telemetry") {
        Some(v) => areev_store::TelemetryMode::parse(&v)
            .ok_or_else(|| {
                format!("--telemetry: unknown mode '{v}' (off|aggregate|aggregate-hashed|full)")
            })?,
        // Matches the default every other verb resolves to, so provisioning
        // covers what the request path will actually open.
        None => areev_store::TelemetryMode::Aggregate,
    };
    // #308: `--check` is the READ-ONLY probe. SELECTs only — no advisory
    // lock, no DDL, no `meta` write — so it runs under the documented
    // least-privilege read-only role, and a release pipeline can decide
    // between a rolling swap and a drain window per deployment instead of
    // diffing three version constants out of source.
    // `--meta-schema` (#353) is the flag spelling of `?meta_schema=`: the
    // flag wins, exactly as `--schema` wins over `?schema=`, and the result
    // rides the DSN from here on so the store reads the layout the one way
    // it knows.
    let db = match flag(flags, "meta-schema") {
        Some(m) => with_meta_schema(&db, &m),
        None => db,
    };
    if flags.contains_key("check") || flags.contains_key("dry-run") {
        return check_provision_cmd(
            &db,
            flag(flags, "schema").as_deref(),
            tel_mode,
            flag(flags, "format").as_deref() == Some("json"),
        );
    }
    provision_postgres(&db, flag(flags, "schema").as_deref(), tel_mode)
}

/// `db` with `?meta_schema=<m>` replacing whatever the DSN carried.
#[cfg(feature = "postgres")]
fn with_meta_schema(db: &str, m: &str) -> String {
    let base = areev_store::pg::strip_meta_schema(db);
    let sep = if base.contains('?') { '&' } else { '?' };
    format!("{base}{sep}meta_schema={m}")
}

#[cfg(not(feature = "postgres"))]
fn with_meta_schema(db: &str, _m: &str) -> String {
    db.to_string()
}

/// Exit code 2 means "pending or absent" (the `loop list --fail-on`
/// convention), 1 an error, 0 current — so a pipeline branches on the code
/// and reads the JSON only when it wants detail. Gated with its one caller:
/// a build without the `postgres` feature has no provisioning command.
#[cfg(feature = "postgres")]
pub(crate) const EXIT_PENDING: i32 = 2;

#[cfg(feature = "postgres")]
fn check_provision_cmd(
    db: &str,
    schema_override: Option<&str>,
    tel_mode: areev_store::TelemetryMode,
    json_out: bool,
) -> Result<(), String> {
    let dsn = areev_store::pg::strip_provision(db);
    let (url, dsn_schema) = match schema_override {
        Some(_) => (areev_store::pg::strip_schema(&dsn), String::new()),
        None => areev_store::pg::split_schema_url(&dsn).map_err(|e| e.to_string())?,
    };
    let schema = schema_override.map(str::to_string).unwrap_or(dsn_schema);
    if schema.is_empty() {
        return Err("areev provision --check: name the schema with --schema NAME or ?schema=NAME".into());
    }
    let report = areev_store::pg::check_provision(&url, &schema, tel_mode)
        .map_err(|e| e.to_string())?;
    if json_out {
        println!(
            "{}",
            serde_json::to_string_pretty(&report).map_err(|e| e.to_string())?
        );
    } else {
        println!(
            "schema {:?}{}: {}",
            report.schema,
            match &report.meta_schema {
                Some(m) => format!(" + metadata schema {m:?}"),
                None => String::new(),
            },
            if report.exists { "exists" } else { "ABSENT" }
        );
        for st in &report.stamps {
            println!(
                "  {:14} found {:8} wanted {:8} {}",
                st.name,
                st.found.as_deref().unwrap_or("-"),
                st.wanted,
                if st.is_current() { "ok" } else { "PENDING" }
            );
        }
        println!("  rolling_deploy: {}", report.rolling_deploy);
        if !report.pending.is_empty() {
            println!("  pending: {}", report.pending.join(", "));
        }
    }
    if !report.is_current() {
        std::process::exit(EXIT_PENDING);
    }
    Ok(())
}

#[cfg(not(feature = "postgres"))]
fn check_provision_cmd(
    _db: &str,
    _schema_override: Option<&str>,
    _tel_mode: areev_store::TelemetryMode,
    _json_out: bool,
) -> Result<(), String> {
    Err("this build lacks the postgres backend — rebuild with --features postgres-tls".into())
}

#[cfg(feature = "postgres")]
fn provision_postgres(
    db: &str,
    schema_override: Option<&str>,
    tel_mode: areev_store::TelemetryMode,
) -> Result<(), String> {
    // `?provision=never` is the runtime role's guard rail; on THIS command it
    // would refuse the very work asked for, so it is stripped rather than
    // honored. An operator can then keep one DSN in one secret and use it for
    // both the migration job and the request path.
    let dsn = areev_store::pg::strip_provision(db);
    let (url, dsn_schema) = match schema_override {
        // `--schema` may supply the name a bare DSN omits, so the split is
        // attempted only when the DSN is expected to carry one.
        Some(_) => (areev_store::pg::strip_schema(&dsn), String::new()),
        None => areev_store::pg::split_schema_url(&dsn).map_err(|e| e.to_string())?,
    };
    let schema = schema_override.map(str::to_string).unwrap_or(dsn_schema);
    if schema.is_empty() {
        return Err("areev provision: name the schema with --schema NAME or ?schema=NAME".into());
    }
    let mut m = match tel_mode {
        areev_store::TelemetryMode::Off => Areev::open_postgres(&url, &schema),
        mode => Areev::open_postgres_with_telemetry(&url, &schema, mode),
    }
    .map_err(|e| e.to_string())?;
    for w in m.open_warnings() {
        eprintln!("areev: warning: {w}");
    }
    // Flush so the telemetry sidecar's own tables are exercised, then drop the
    // handle: provisioning holds nothing open.
    let _ = m.telemetry_flush();
    drop(m);
    println!(
        "provisioned postgres schema {schema:?}{}{} — the next open runs no DDL",
        match areev_store::pg::meta_schema(&url).map_err(|e| e.to_string())? {
            Some(m) => format!(" + metadata schema {m:?}"),
            None => String::new(),
        },
        match tel_mode {
            areev_store::TelemetryMode::Off => " (telemetry tables NOT created)",
            _ => " (including telemetry tables)",
        }
    );
    Ok(())
}

#[cfg(not(feature = "postgres"))]
fn provision_postgres(
    _db: &str,
    _schema_override: Option<&str>,
    _tel_mode: areev_store::TelemetryMode,
) -> Result<(), String> {
    Err("this build lacks the postgres backend — rebuild with --features postgres-tls".into())
}

/// `areev auth mint|list|revoke` — the credential-map lifecycle (A1).
///
/// The map is host config: it holds no policy, no raw secrets, and names no
/// memory, so none of these verbs open a store. They exist because the
/// alternative — hand-editing JSON and hand-computing SHA-256 — is how
/// operator-chosen, low-entropy tokens end up with their digests in a file
/// that gets shared across server instances.
fn run_auth(flags: &HashMap<String, String>, positional: &[String]) -> Result<(), String> {
    use areev_core::authz::{CredentialMap, TOKEN_PREFIX};

    let sub = positional.first().map(String::as_str).unwrap_or("");
    let path = flag(flags, "auth")
        .ok_or_else(|| "areev auth: --auth <FILE> names the credential map".to_string())?;

    // Parse `--expires 90d|12h|2026-12-31T23:59:59Z` to an ISO-8601 instant.
    let expires_at = match flag(flags, "expires") {
        None => None,
        Some(spec) => Some(parse_expiry(&spec)?),
    };

    match sub {
        "mint" => {
            let principal = flag(flags, "principal").ok_or_else(|| {
                "areev auth mint: --principal <NAME> says who the token authenticates as".to_string()
            })?;
            let id = flag(flags, "id").ok_or_else(|| {
                "areev auth mint: --id <NAME> names this credential so it can be revoked \
                 independently of the principal's other tokens"
                    .to_string()
            })?;

            // 256 bits from the OS CSPRNG. This is the whole point of the
            // verb: the operator never chooses the secret, so its entropy is
            // never a question and the stored SHA-256 is never grindable.
            let mut raw = [0u8; 32];
            getrandom::fill(&mut raw)
                .map_err(|e| format!("areev auth mint: no system randomness available: {e}"))?;
            let token = format!("{TOKEN_PREFIX}{}", areev_core::authz::encode_token_body(&raw));
            let digest = {
                use sha2::Digest;
                hex::encode(sha2::Sha256::digest(token.as_bytes()))
            };

            // Read-modify-write the map, refusing a duplicate id BEFORE the
            // token is printed — otherwise the operator has a live secret
            // that was never recorded anywhere.
            let mut map = read_map_or_empty(&path)?;
            if map.tokens.iter().any(|t| t.id() == id) {
                return Err(format!(
                    "areev auth mint: {path} already has a credential with id {id:?} — \
                     revoke it first, or choose another id"
                ));
            }
            map.tokens.push(areev_core::authz::CredentialEntry {
                id: Some(id.clone()),
                label: flag(flags, "label"),
                sha256: Some(digest),
                env: None,
                principal: principal.clone(),
                memories: flag(flags, "memories")
                    .map(|m| m.split(',').map(|s| s.trim().to_string()).collect()),
                expires_at: expires_at.clone(),
            });
            // Validate through the same loader the server uses, so a map this
            // verb wrote can never be one the server refuses to load.
            let json = serde_json::to_string_pretty(&map)
                .map_err(|e| format!("areev auth mint: {e}"))?;
            CredentialMap::from_json(&json).map_err(|e| format!("areev auth mint: {e}"))?;
            write_map(&path, &json)?;

            // The token goes to STDOUT (pipeable into a secret store); the
            // commentary to STDERR, so `... | pbcopy` copies only the secret.
            println!("{token}");
            eprintln!("areev: minted {id} for {principal} — recorded in {path}");
            if let Some(exp) = &expires_at {
                eprintln!("areev: expires {exp}");
            }
            eprintln!(
                "areev: this is the ONLY time the token is shown; {path} stores its SHA-256, \
                 which cannot be reversed. Store it now."
            );
        }
        "list" => {
            let map = read_map_or_empty(&path)?;
            let now = areev_core::time::now_ms();
            if map.tokens.is_empty() {
                eprintln!("areev: {path} holds no credentials");
                return Ok(());
            }
            for t in &map.tokens {
                // Never the digest and never the env var's VALUE — listing
                // must be safe to paste into a ticket.
                let state = match t.expires_at.as_deref() {
                    None => "no expiry".to_string(),
                    Some(raw) if t.is_expired_at(now) => format!("EXPIRED {raw}"),
                    Some(raw) => format!("expires {raw}"),
                };
                let scope = match &t.memories {
                    Some(m) => format!(" memories={}", m.join(",")),
                    None => String::new(),
                };
                let label = t.label.as_deref().map(|l| format!(" — {l}")).unwrap_or_default();
                println!("{}\t{}\t{state}{scope}{label}", t.id(), t.principal);
            }
        }
        "revoke" => {
            let id = flag(flags, "id")
                .ok_or_else(|| "areev auth revoke: --id <NAME> (see `areev auth list`)".to_string())?;
            let mut map = read_map_or_empty(&path)?;
            let before = map.tokens.len();
            map.tokens.retain(|t| t.id() != id);
            if map.tokens.len() == before {
                return Err(format!("areev auth revoke: {path} has no credential with id {id:?}"));
            }
            let json = serde_json::to_string_pretty(&map)
                .map_err(|e| format!("areev auth revoke: {e}"))?;
            write_map(&path, &json)?;
            eprintln!(
                "areev: revoked {id} from {path} — RESTART `areev ui` for it to take effect \
                 (the map is read once at startup)"
            );
        }
        other => {
            return Err(format!(
                "unknown auth subcommand {other:?} — one of: mint, list, revoke\n\n\
                 areev auth mint   --auth FILE --id NAME --principal NAME [--label TEXT]\n\
                 \x20                     [--expires 90d|2026-12-31T23:59:59Z] [--memories A,B]\n\
                 areev auth list   --auth FILE\n\
                 areev auth revoke --auth FILE --id NAME"
            ));
        }
    }
    Ok(())
}

/// `90d` / `12h` / an explicit ISO-8601 instant → an ISO-8601 instant.
fn parse_expiry(spec: &str) -> Result<String, String> {
    let spec = spec.trim();
    if let Some(ms) = areev_core::time::iso8601_to_ms(spec) {
        // Already a timestamp — normalize through the same formatter so the
        // file only ever holds one spelling.
        return Ok(format_epoch_ms(ms));
    }
    let (num, unit) = spec.split_at(spec.len().saturating_sub(1));
    let n: i64 = num
        .parse()
        .map_err(|_| format!("--expires {spec:?}: expected <n>d, <n>h, or an ISO-8601 instant"))?;
    let ms = match unit {
        "d" => n * 86_400_000,
        "h" => n * 3_600_000,
        _ => {
            return Err(format!(
                "--expires {spec:?}: unit must be 'd' (days) or 'h' (hours), or give a full \
                 ISO-8601 instant"
            ))
        }
    };
    if n <= 0 {
        return Err(format!("--expires {spec:?}: must be in the future"));
    }
    Ok(format_epoch_ms(areev_core::time::now_ms() + ms))
}

/// Epoch ms → `YYYY-MM-DDTHH:MM:SSZ`, the one spelling the map stores.
fn format_epoch_ms(ms: i64) -> String {
    let secs = ms.div_euclid(1000);
    let days = secs.div_euclid(86_400);
    let tod = secs.rem_euclid(86_400);
    // Inverse of `days_from_civil` (Howard Hinnant's `civil_from_days`).
    let z = days + 719_468;
    let era = if z >= 0 { z } else { z - 146_096 } / 146_097;
    let doe = z - era * 146_097;
    let yoe = (doe - doe / 1460 + doe / 36524 - doe / 146_096) / 365;
    let y = yoe + era * 400;
    let doy = doe - (365 * yoe + yoe / 4 - yoe / 100);
    let mp = (5 * doy + 2) / 153;
    let d = doy - (153 * mp + 2) / 5 + 1;
    let m = if mp < 10 { mp + 3 } else { mp - 9 };
    let y = if m <= 2 { y + 1 } else { y };
    format!(
        "{y:04}-{m:02}-{d:02}T{:02}:{:02}:{:02}Z",
        tod / 3600,
        (tod % 3600) / 60,
        tod % 60
    )
}

/// Read the credential map, or an empty one when the file does not exist yet
/// (so `areev auth mint` bootstraps a new deployment in one command).
fn read_map_or_empty(path: &str) -> Result<areev_core::authz::CredentialMap, String> {
    match std::fs::read_to_string(path) {
        Ok(s) => areev_core::authz::CredentialMap::from_json(&s).map_err(|e| format!("{path}: {e}")),
        Err(e) if e.kind() == std::io::ErrorKind::NotFound => {
            Ok(areev_core::authz::CredentialMap {
                version: 1,
                tokens: Vec::new(),
                groups: None,
            })
        }
        Err(e) => Err(format!("{path}: {e}")),
    }
}

/// Write the map with owner-only permissions.
///
/// The file holds no reversible secret, but it does enumerate every principal
/// and credential id a deployment has — a map that is world-readable is a map
/// an attacker uses to pick a target before guessing.
fn write_map(path: &str, json: &str) -> Result<(), String> {
    std::fs::write(path, format!("{json}\n")).map_err(|e| format!("{path}: {e}"))?;
    #[cfg(unix)]
    {
        use std::os::unix::fs::PermissionsExt;
        let _ = std::fs::set_permissions(path, std::fs::Permissions::from_mode(0o600));
    }
    Ok(())
}

/// Load the host policy from `--policy FILE` or `$AREEV_LOOP_POLICY` (§6.2).
fn load_policy(flags: &HashMap<String, String>) -> Result<Option<Policy>, String> {
    let path = flag(flags, "policy").or_else(|| std::env::var("AREEV_LOOP_POLICY").ok());
    match path {
        Some(p) => {
            let s = std::fs::read_to_string(&p).map_err(|e| format!("{p}: {e}"))?;
            Ok(Some(Policy::from_json(&s).map_err(|e| e.to_string())?))
        }
        None => Ok(None),
    }
}

/// `areev audit export [--since MS] [--until MS] [--out FILE]
/// [--with-outcomes]` — the accountability evidence bundle (GDPR Art.
/// 5(2)/30, and the Art. 33 breach-notification input).
///
/// Two hash-chained trails exist as grains; this formats them, nothing more.
/// Tier-2 destruction Observations live in `agent:authz` (one per FORGET /
/// FORGET SUBJECT / PURGE / hold / reveal, from CAL or the CLI alike), and
/// the loop's lifecycle audit rides as `loop_audit` Facts in `areev-loop`.
/// Output is JSONL — one record per line, oldest first — so extracting a
/// window is a pipe, not a parser.
///
/// **What it does NOT contain: read records.** No read writes an audit
/// grain (the obligation is on destruction, not access, and a read that
/// recorded the identity would re-introduce the reference an erasure just
/// removed). Access logging is the host's responsibility (#282).
///
/// **Both chains are verified, not assumed** (#280). Every Tier-2 record
/// carries `context.seq` and names its predecessor; every loop record
/// carries `derived_from = [rec_hash, previous_audit_hash]`. Three
/// distinctions that make the verification usable rather than noisy:
///
/// * a predecessor absent from the STORE is a `chain_break` — the trail was
///   truncated, and evidence that cannot say so is worse than none;
/// * a predecessor still in the store but outside `--since` is
///   `previous_outside_window`, NOT a break, so an hourly incremental import
///   is not full of false alarms;
/// * a record written before chaining existed exports as `unchained` —
///   absence of a link in an older build's record is not evidence of
///   tampering.
///
/// A gap in `seq` is a break too, which is what catches a record whose
/// successor was deleted along with it. Breaks are reported on stderr and
/// marked on the record.
///
/// Loop rows carry the recorded `gating` edge — which evaluation run
/// admitted a change, and what it scored (#319). `--with-outcomes` adds the
/// Verify gate's measured checkpoints, marked `chained: false` because they
/// come from the rebuildable state blob rather than from hash-chained
/// grains.
fn run_audit(
    m: &mut Areev,
    flags: &HashMap<String, String>,
    positional: &[String],
) -> Result<(), String> {
    let sub_cmd = positional.first().map(|s| s.as_str()).unwrap_or("export");
    if sub_cmd != "export" {
        return Err(format!(
            "unknown audit subcommand '{sub_cmd}' — usage: areev audit export \
             [--since MS] [--until MS] [--out FILE]"
        ));
    }
    let parse_ms = |k: &str| -> Result<Option<i64>, String> {
        match flag(flags, k) {
            None => Ok(None),
            Some(v) => v
                .parse::<i64>()
                .map(Some)
                .map_err(|_| format!("--{k} takes epoch milliseconds, got '{v}'")),
        }
    };
    let since = parse_ms("since")?;
    let until = parse_ms("until")?;
    let in_window = |at: i64| since.is_none_or(|s| at >= s) && until.is_none_or(|u| at <= u);

    // Tier-2 destruction audit: Observations in the reserved authz namespace.
    let mut rows: Vec<(i64, serde_json::Value)> = Vec::new();
    let mut breaks = 0usize;
    let mut tier2: Vec<(i64, serde_json::Value, serde_json::Value)> = Vec::new();
    let mut seen_tier2: std::collections::HashSet<String> = std::collections::HashSet::new();
    let authz = m
        .recent(
            areev_core::authz::AUTHZ_NS,
            Some(areev_core::types::GrainType::Observation),
            usize::MAX / 2,
        )
        .map_err(|e| e.to_string())?;
    for g in authz {
        let ctx = g.fields.get("context").cloned().unwrap_or(serde_json::Value::Null);
        if ctx.get("audit").and_then(|v| v.as_str()) != Some("tier2") {
            continue;
        }
        let at = g.fields.get("created_at").and_then(|v| v.as_i64()).unwrap_or(0);
        if !in_window(at) {
            continue;
        }
        let mut row = serde_json::json!({
            "trail": "destruction",
            "hash": g.hash.to_hex(),
            "at_ms": at,
            "principal": g.fields.get("observer_id"),
            "observer_type": g.fields.get("observer_type"),
            "verb": ctx.get("verb"),
            // For subject erasures this is `subject:<fingerprint> ns:<ns>`:
            // verify it against a candidate identity by recomputing
            // sha256(id)[..8] in hex; it deliberately cannot be mined
            // for who was erased. `subject_ref` names the scheme.
            "target": ctx.get("target"),
            "subject_ref": ctx.get("subject_ref"),
            "because": ctx.get("because"),
            "grains_erased": ctx.get("grains_erased"),
            "stale_corpora": ctx.get("stale_corpora"),
            "stale_adapters": ctx.get("stale_adapters"),
        });
        // #278: an override of a legal hold names the hold it overrode.
        if let Some(h) = ctx.get("hold_overridden") {
            row["hold_overridden"] = h.clone();
        }
        // #280: the chain. A record written before chaining existed carries
        // neither `seq` nor a predecessor, and is exported as `unchained` —
        // never as a break. Absence of a link in a record an older build
        // wrote is not evidence of tampering.
        match ctx.get("seq").and_then(|v| v.as_u64()) {
            None => {
                row["unchained"] = serde_json::json!(true);
            }
            Some(seq) => {
                row["seq"] = serde_json::json!(seq);
                if let Some(p) = ctx.get("previous_audit").and_then(|v| v.as_str()) {
                    row["previous_audit"] = serde_json::json!(p);
                }
                if ctx.get("chain_root").and_then(|v| v.as_bool()) == Some(true) {
                    row["chain_root"] = serde_json::json!(true);
                }
            }
        }
        seen_tier2.insert(g.hash.to_hex());
        tier2.push((at, row, ctx.clone()));
    }
    // Verify the destruction chain the same way the loop trail is verified
    // (#280). Two independent signals, because `derived_from` alone cannot
    // tell a forgotten interior record from a window edge:
    //
    //   * a named predecessor that is not in the store → a BREAK;
    //   * a named predecessor that IS in the store but falls outside
    //     `--since` → `previous_outside_window`, which is not a break. A
    //     windowed export that flagged every straddling chain made an hourly
    //     incremental import noisy enough to be ignored, which is worse than
    //     not verifying at all.
    //   * a gap in `seq` → a break, which is what catches a record whose
    //     successor was deleted along with it.
    let mut prev_seq: Option<u64> = None;
    for (at, mut row, ctx) in tier2 {
        if let Some(p) = ctx.get("previous_audit").and_then(|v| v.as_str()) {
            if !seen_tier2.contains(p) {
                let exists = areev_core::error::Hash::from_hex(p)
                    .ok()
                    .map(|h| m.has(&h).unwrap_or(false))
                    .unwrap_or(false);
                if exists {
                    row["previous_outside_window"] = serde_json::json!(true);
                } else {
                    breaks += 1;
                    row["chain_break"] = serde_json::json!(true);
                }
            }
        }
        if let (Some(prev), Some(seq)) = (prev_seq, row.get("seq").and_then(|v| v.as_u64())) {
            if seq > prev + 1 {
                breaks += 1;
                row["chain_break"] = serde_json::json!(true);
                row["missing_seq"] = serde_json::json!(seq - prev - 1);
            }
        }
        if let Some(seq) = row.get("seq").and_then(|v| v.as_u64()) {
            prev_seq = Some(seq);
        }
        rows.push((at, row));
    }

    // Loop lifecycle audit: `loop_audit` Facts carrying the engine's
    // field-map in `object`, hash-chained through `derived_from`.
    let mut chain_prev: std::collections::HashSet<String> = std::collections::HashSet::new();
    let mut loop_rows: Vec<(i64, serde_json::Value, Option<String>)> = Vec::new();
    let loop_grains = m
        .recent("areev-loop", Some(areev_core::types::GrainType::Fact), usize::MAX / 2)
        .map_err(|e| e.to_string())?;
    for g in loop_grains {
        if g.get_str("relation") != Some("loop_audit") {
            continue;
        }
        let Some(body) = g.get_str("object").and_then(|o| {
            serde_json::from_str::<serde_json::Value>(o).ok()
        }) else {
            continue;
        };
        let at = body.get("at_ms").and_then(|v| v.as_i64()).unwrap_or(0);
        if !in_window(at) {
            continue;
        }
        chain_prev.insert(g.hash.to_hex());
        // derived_from = [rec_hash, previous_audit_hash?]
        let prev = body
            .get("derived_from")
            .and_then(|v| v.as_array())
            .and_then(|a| a.get(1))
            .and_then(|v| v.as_str())
            .map(|s| s.to_string());
        loop_rows.push((
            at,
            serde_json::json!({
                "trail": "loop",
                "hash": g.hash.to_hex(),
                "at_ms": at,
                "rec_hash": body.get("rec_hash"),
                "from_status": body.get("from_status"),
                "to_status": body.get("to_status"),
                "actor": body.get("actor"),
                "observer_type": body.get("observer_type"),
                "because": body.get("because"),
                "previous_audit": prev.clone(),
                // #319: the recorded gating edge — which evaluation run
                // admitted this change, and what it scored. It was in the
                // parsed body all along and dropped here.
                "gating": body.get("gating_run_id").map(|run| serde_json::json!({
                    "evalset": body.get("gating_evalset"),
                    "run_id": run,
                    "passed": body.get("gating_passed"),
                    "failed": body.get("gating_failed"),
                })),
                // #312: the namespaces the finding was derived from, so an
                // export can later be filtered by them.
                "scope": body.get("scope"),
            }),
            prev,
        ));
    }
    // Chain verification: a named predecessor absent from this export means
    // the trail is truncated. Report it rather than emitting a clean-looking
    // file.
    for (at, mut row, prev) in loop_rows {
        if let Some(p) = prev {
            if !chain_prev.contains(&p) {
                // Same window-edge distinction as the destruction trail
                // (#280): a predecessor still in the store is not a break.
                let exists = areev_core::error::Hash::from_hex(&p)
                    .ok()
                    .map(|h| m.has(&h).unwrap_or(false))
                    .unwrap_or(false);
                if exists {
                    row["previous_outside_window"] = serde_json::json!(true);
                } else {
                    breaks += 1;
                    row["chain_break"] = serde_json::json!(true);
                }
            }
        }
        rows.push((at, row));
    }

    // #319: the Verify gate's outcomes, on request.
    //
    // A gated apply records `gating_evalset` / `gating_run_id` /
    // `gating_passed` / `gating_failed` on the audit grain, and the export
    // dropped all four — so "which run admitted this change" could not be
    // answered from the evidence bundle at all, only by reading `loop_audit`
    // Facts directly. The outcomes are worse still: they live in the loop's
    // state blob and were in no export.
    if flags.contains_key("with-outcomes") {
        let state = areev_loop_adapter::loop_state_of(m).map_err(|e| e.to_string())?;
        let outcomes: Vec<areev_loop::OutcomeResult> = if state.is_null() {
            Vec::new()
        } else {
            areev_loop::config::LoopPersisted::from_value(state)
                .map(|p| p.outcomes.into_values().flatten().collect())
                .unwrap_or_default()
        };
        {
            for o in outcomes {
                if !in_window(o.measured_at_ms) {
                    continue;
                }
                rows.push((
                    o.measured_at_ms,
                    serde_json::json!({
                        "trail": "loop_outcome",
                        "rec_hash": o.rec_hash,
                        "metric": o.metric,
                        "verdict": o.verdict,
                        "baseline": o.baseline,
                        "current": o.current,
                        "baseline_run_id": o.baseline_run_id,
                        "current_run_id": o.current_run_id,
                        "cost": o.cost,
                        "measured_at_ms": o.measured_at_ms,
                        // Said honestly: these come from the rebuildable
                        // state blob, not from hash-chained grains. A
                        // consumer must not treat them as tamper-evident.
                        "chained": false,
                    }),
                ));
            }
        }
    }

    rows.sort_by_key(|(at, _)| *at);
    let mut out = String::new();
    for (_, row) in &rows {
        out.push_str(&row.to_string());
        out.push('\n');
    }
    match flag(flags, "out") {
        Some(path) => {
            std::fs::write(&path, &out).map_err(|e| e.to_string())?;
            println!("wrote {} audit records to {path}", rows.len());
        }
        None => print!("{out}"),
    }
    if breaks > 0 {
        eprintln!(
            "areev: warning: {breaks} loop audit record(s) name a predecessor absent from this \
             export — the chain is truncated (widen --since, or the trail was tampered with)"
        );
    }
    eprintln!("audit export: {} records", rows.len());
    Ok(())
}

/// `areev loop <run|list|show|approve|reject|apply|rollback|analyzers|policy|status|replay>`.
fn run_loop(
    m: Areev,
    ns: &str,
    flags: &HashMap<String, String>,
    positional: &[String],
) -> Result<(), String> {
    let sub_cmd = positional.first().map(|s| s.as_str()).unwrap_or("status");
    // Read before `m` moves into the substrate: whether text leaving this
    // handle for a decision backend is egress under an anonymization policy.
    let egress = store_egress_active(&m);
    let mut sub = AreevSubstrate::new(m, Some(ns.to_string()));
    // Host policy (--policy FILE or $AREEV_LOOP_POLICY) — the only place
    // auto-apply is granted. Absent → a closed default (nothing auto-applies).
    let policy = load_policy(flags)?;
    let mut engine = match policy {
        Some(p) => Engine::with_builtins().with_policy(p),
        None => Engine::with_builtins(),
    };
    // Optional LLM reflection: the model proposes findings that are grounded +
    // adversarially verified before they can reach the queue (origin=llm, never
    // auto-applied). Two ways to attach one, both CLI-only, never persisted:
    //   --model provider:name   → a built-in HTTP backend (key from the env)
    //   --llm-cmd 'CMD'         → a subprocess backend (the zero-dep escape hatch)
    // `--llm-cmd` wins if both are given.
    if let Some(cmd) = flag(flags, "llm-cmd") {
        let model = flag(flags, "llm-model");
        let llm = areev_loop::CommandLlm::new(&cmd, model.as_deref()).map_err(|e| e.to_string())?;
        engine = engine.with_llm(Box::new(llm));
    } else if let Some(spec) = flag(flags, "model") {
        // Key is read from the environment (ANTHROPIC_API_KEY / OPENAI_API_KEY /
        // OLLAMA_HOST, or --llm-api-key-env), never taken on the command line.
        let base = flag(flags, "llm-base-url");
        let key_env = flag(flags, "llm-api-key-env");
        let llm = areev_llm::resolve(&spec, base.as_deref(), key_env.as_deref())
            .map_err(|e| e.to_string())?;
        engine = engine.with_llm(llm);
    }
    // Optional SEPARATE grounding backend (§11): point the entailment check at a
    // cheaper or specialized model, or take the generative model out of grounding
    // entirely. Falls back to the main backend when absent. `--ground-cmd` wins.
    if let Some(cmd) = flag(flags, "ground-cmd") {
        let g = areev_loop::CommandLlm::new(&cmd, None).map_err(|e| e.to_string())?;
        engine = engine.with_ground_llm(Box::new(g));
    } else if let Some(spec) = flag(flags, "ground-model") {
        let base = flag(flags, "llm-base-url");
        let key_env = flag(flags, "llm-api-key-env");
        let g = areev_llm::resolve(&spec, base.as_deref(), key_env.as_deref())
            .map_err(|e| e.to_string())?;
        engine = engine.with_ground_llm(g);
    }
    // Optional decision backend (docs/decision-model-proposal.md rows E1–E3,
    // docs/loop.md "Decision backend"): calibrated numbers for GROUND/VERIFY,
    // the near-duplicate and contradiction sweeps, and tool-failure causes.
    // Drafts only — the four gates are untouched and anything it judged never
    // auto-applies. The same `--decide` chain every other verb uses, wrapped
    // for egress under the same rule as the reranker.
    if let Some(chain) = resolve_decider(flags)? {
        let chain = decider_for_egress(chain, egress)?;
        engine = engine.with_decider(Box::new(areev_loop_adapter::LoopDecider(chain)));
    }
    // Optional external analyzer: a subprocess that flags domain-specific issues
    // (trust class Command → advisory only, never auto-applies). Registered up
    // front so it participates in the pass like a built-in.
    if let Some(cmd) = flag(flags, "analyzer-cmd") {
        let a = areev_loop::CommandAnalyzer::new(&cmd).map_err(|e| e.to_string())?;
        engine.register(Box::new(a));
    }
    let now = now_ms();
    let actor = flag(flags, "actor").unwrap_or_else(|| "user:local".to_string());
    let observer = ObserverType::Human;
    let scopes = ScopeSet::all(); // the CLI is the local root of trust
    let json = flag(flags, "format").as_deref() == Some("json");

    match sub_cmd {
        // `reflect` = a run that re-analyzes the whole memory (full sweep),
        // ignoring the incremental watermark; otherwise identical to `run`.
        "run" | "reflect" => {
            let opts = RunOptions {
                min_new: flag(flags, "min-new").and_then(|v| v.parse().ok()),
                min_new_errors: flag(flags, "min-new-errors").and_then(|v| v.parse().ok()),
                if_stale_ms: flag(flags, "if-stale").and_then(|v| parse_duration(&v)),
                namespaces: Vec::new(),
                full_sweep: sub_cmd == "reflect",
                triggering_actor: Some(actor.clone()),
            };
            let res = engine.run(&mut sub, &opts, now).map_err(|e| e.to_string())?;
            if json {
                println!("{}", serde_json::to_string(&res).map_err(|e| e.to_string())?);
            } else if res.ran() {
                if !flags.contains_key("quiet") {
                    eprintln!(
                        "loop: ran — proposed {} ({} deduped, {} auto-applied) across {} analyzer(s)",
                        res.stored,
                        res.deduped,
                        res.auto_applied,
                        res.analyzers_run.len()
                    );
                }
                if res.stored > 0 {
                    eprintln!("loop: {} new — areev loop list", res.stored);
                }
            } else if !flags.contains_key("quiet") {
                eprintln!("loop: skipped ({:?})", res.skip_reason);
            }
        }
        "list" => {
            let filter = status_filter(flags);
            // Coverage-filtered (#312). An owner session — the CLI's ordinary
            // local-root-of-trust case — holds the whole queue, so nothing
            // changes for it.
            let recs = areev_loop_adapter::visible_recommendations(
                &engine,
                &sub,
                &sub.authz(),
                filter,
            )
            .map_err(|e| e.to_string())?;
            if json {
                let rows: Vec<_> = recs
                    .iter()
                    .map(|r| {
                        let mut row = serde_json::json!({
                            "hash": r.hash,
                            "status": r.status.as_str(),
                            "severity": r.severity.as_str(),
                            "analyzer": r.analyzer,
                            "destructive": r.destructive,
                            "summary": r.summary.render(),
                        });
                        // The live lessons an authored lesson restates, when
                        // the engine found any — so a reviewer sees the pile
                        // from the listing. Absent otherwise.
                        if !r.near_duplicate_of.is_empty() {
                            row["near_duplicate_of"] = serde_json::json!(r.near_duplicate_of);
                        }
                        row
                    })
                    .collect();
                println!("{}", serde_json::to_string(&rows).map_err(|e| e.to_string())?);
            } else if recs.is_empty() {
                eprintln!("no recommendations — run `areev loop run` first");
            } else {
                for r in &recs {
                    println!(
                        "{}  {:<6}  {:<28}  {}",
                        short(&r.hash),
                        r.severity.as_str(),
                        r.analyzer,
                        r.summary.render()
                    );
                }
            }
            // CI gate: exit 2 if any pending recommendation meets --fail-on.
            if let Some(sev) = flag(flags, "fail-on") {
                let threshold = parse_severity(&sev);
                let hit = recs
                    .iter()
                    .any(|r| r.status == RecStatus::Pending && r.severity >= threshold);
                if hit {
                    eprintln!("loop: pending recommendation(s) at or above severity '{sev}'");
                    std::process::exit(2);
                }
            }
        }
        "show" => {
            let prefix = positional
                .get(1)
                .ok_or_else(|| "usage: areev loop show <hash>".to_string())?;
            let recs = engine.recommendations(&sub, None).map_err(|e| e.to_string())?;
            let r = areev_loop_adapter::find_recommendation(&recs, prefix)?;
            // The review surface — shared with the bindings' `recommendation(hash)`.
            let out = areev_loop_adapter::recommendation_detail(r);
            println!("{}", serde_json::to_string_pretty(&out).map_err(|e| e.to_string())?);
        }
        "approve" | "reject" => {
            let prefix = positional
                .get(1)
                .ok_or_else(|| format!("usage: areev loop {sub_cmd} <hash> --because \"...\""))?;
            let because = need(flags, "because")?;
            let hash = resolve_hash(&engine, &sub, prefix)?;
            let decision = if sub_cmd == "approve" { Decision::Approve } else { Decision::Reject };
            engine
                .review(&mut sub, &hash, decision, &actor, observer, &scopes, &because, now)
                .map_err(|e| e.to_string())?;
            eprintln!("{sub_cmd}d {}", short(&hash));
        }
        "apply" => {
            let prefix = positional
                .get(1)
                .ok_or_else(|| "usage: areev loop apply <hash> --because \"...\" [--gating-run RUN_ID]".to_string())?;
            let because = need(flags, "because")?;
            let hash = resolve_hash(&engine, &sub, prefix)?;
            let allow_destructive = flags.contains_key("allow-destructive");
            // §7.4: a code revision applies only through the recorded
            // evalset-run edge. The evidence is LOADED from the summary the
            // gate run wrote — never typed in by the operator.
            let applied = match flag(flags, "gating-run") {
                Some(run_id) => {
                    let gating = load_gating_evidence(&sub, &engine, &hash, &run_id)?;
                    engine
                        .apply_gated(&mut sub, &hash, &actor, observer, &scopes, &because, allow_destructive, &gating, now)
                        .map_err(|e| e.to_string())?
                }
                None => engine
                    .apply(&mut sub, &hash, &actor, observer, &scopes, &because, allow_destructive, now)
                    .map_err(|e| e.to_string())?,
            };
            eprintln!(
                "applied {} ({})",
                short(&hash),
                if applied.rollbackable { "rollbackable" } else { "non-rollbackable" }
            );
        }
        "rollback" => {
            let prefix = positional
                .get(1)
                .ok_or_else(|| "usage: areev loop rollback <hash> --because \"...\"".to_string())?;
            let because = need(flags, "because")?;
            let hash = resolve_hash(&engine, &sub, prefix)?;
            // §7.4 blast radius: reverting CODE does not revert the data the
            // code produced. Before the revert lands, report which runs
            // touched the reverted tool — the report is what makes that
            // data reviewable, so it prints even (especially) when large.
            let target_ref = engine
                .recommendations(&sub, None)
                .ok()
                .and_then(|recs| recs.into_iter().find(|r| r.hash == hash))
                .map(|r| r.target_ref);
            // The adapter mirror: retracting a promotion is the memory-side
            // inverse — the SERVING side is the host's move, and the runs the
            // adapter answered are not reverted. The opaque is a served-model
            // name, not a grain hash, so there is no runs_touching walk.
            if let Some(model) = target_ref.as_deref().and_then(|t| t.strip_prefix("model:")) {
                eprintln!(
                    "adapter promotion for model:{model} will be retracted — the host \
                     must stop serving it; runs answered since promotion are NOT reverted"
                );
            }
            let code_target = target_ref
                .as_deref()
                .and_then(|t| t.strip_prefix("tool:").map(str::to_string));
            if let Some(tool_hash) = &code_target {
                if let Ok(h) = Hash::from_hex(tool_hash) {
                    let touched = sub
                        .facade()
                        .with_store(|m| m.runs_touching("agent:harness", &h, 2))
                        .unwrap_or_default();
                    eprintln!(
                        "blast radius: {} run(s) touched tool {} since apply{}",
                        touched.len(),
                        short(tool_hash),
                        if touched.is_empty() { String::new() } else { format!(": {}", touched.join(", ")) }
                    );
                    eprintln!(
                        "  the runs' outputs are NOT reverted — inspect each with \
                         `areev run-trace --run-id <id>`"
                    );
                }
            }
            engine
                .rollback(&mut sub, &hash, &actor, observer, &scopes, &because, now)
                .map_err(|e| e.to_string())?;
            eprintln!("rolled back {}", short(&hash));
        }
        "analyzers" => {
            // One row per registered analyzer: id, tier, trust class
            // (builtin vs an external command — advisory only), default state,
            // title. Same lowercase trust strings as the console's Setup view.
            for a in engine.analyzers() {
                let m = a.manifest();
                println!(
                    "{:<28}  {:?}  {:<7}  on={}  {}",
                    m.id,
                    m.tier,
                    format!("{:?}", m.trust_class).to_lowercase(),
                    m.default_on,
                    m.title
                );
            }
        }
        // Replay — score a candidate configuration against the past, beside
        // the incumbent. Reads only; the op-log length is read before and
        // after and printed, so "zero writes" is shown, not asserted.
        "replay" => {
            use areev_loop::replay::{ReplayOptions, ReplayRequest};
            let path = flag(flags, "config")
                .ok_or("usage: areev loop replay --config FILE [--window 90d | --since MS] [--step per-pass|1d] [--format json]")?;
            let text = std::fs::read_to_string(&path).map_err(|e| format!("{path}: {e}"))?;
            let req = ReplayRequest::from_json(&text).map_err(|e| e.to_string())?;
            let (candidate, _) = req.resolve(now).map_err(|e| e.to_string())?;
            let since: Option<i64> = flag(flags, "since")
                .map(|v| v.parse().map_err(|_| "--since must be epoch milliseconds".to_string()))
                .transpose()?;
            let opts = ReplayOptions::from_args(
                flag(flags, "window").as_deref(),
                since,
                flag(flags, "step").as_deref(),
                Vec::new(),
                now,
            )
            .map_err(|e| e.to_string())?;
            let ops_before = sub.facade().with_store(|m| m.stats()).map_err(|e| e.to_string())?.ops;
            let report = engine.replay(&sub, &candidate, &opts).map_err(|e| e.to_string())?;
            let ops_after = sub.facade().with_store(|m| m.stats()).map_err(|e| e.to_string())?.ops;
            if ops_after != ops_before {
                return Err(format!(
                    "replay wrote to the memory (op-log {ops_before} → {ops_after}) — this is a bug;                      the report is discarded"
                ));
            }
            if json {
                let mut v = serde_json::to_value(&report).map_err(|e| e.to_string())?;
                v["oplog_len"] = serde_json::json!({"before": ops_before, "after": ops_after});
                println!("{}", serde_json::to_string(&v).map_err(|e| e.to_string())?);
            } else {
                println!(
                    "replay: {} step(s) ({}) from {} to {}; op-log {ops_before} → {ops_after} (unchanged)",
                    report.steps.len(),
                    report.step,
                    report.since_ms,
                    report.until_ms
                );
                let row = |name: &str, t: &areev_loop::replay::ReplayTally| {
                    format!(
                        "{name:<28} {:>8} {:>9} {:>9} {:>9} {:>9} {:>10} {:>8} {:>6}",
                        t.findings, t.approved, t.rejected, t.never_reviewed, t.never_proposed, t.regressed, t.drifted, t.held
                    )
                };
                println!(
                    "{:<28} {:>8} {:>9} {:>9} {:>9} {:>9} {:>10} {:>8} {:>6}",
                    "", "findings", "approved", "rejected", "unrevwd", "never", "regressed", "drifted", "held"
                );
                println!("{}", row("incumbent", &report.incumbent.total));
                println!("{}", row("candidate", &report.candidate.total));
                let analyzers: std::collections::BTreeSet<&String> = report
                    .incumbent
                    .per_analyzer
                    .keys()
                    .chain(report.candidate.per_analyzer.keys())
                    .collect();
                for a in analyzers {
                    let empty = areev_loop::replay::ReplayTally::default();
                    let i = report.incumbent.per_analyzer.get(a).unwrap_or(&empty);
                    let c = report.candidate.per_analyzer.get(a).unwrap_or(&empty);
                    println!("{}", row(&format!("  {a} (incumbent)"), i));
                    println!("{}", row(&format!("  {a} (candidate)"), c));
                }
                println!(
                    "queue per step — incumbent {:?}, candidate {:?}",
                    report.incumbent.queue_per_step, report.candidate.queue_per_step
                );
                for n in &report.not_replayed {
                    println!("not replayed: {} — {}", n.what, n.reason);
                }
                println!("{}", report.matching);
            }
        }
        // The Verify gate's measured history: did applied advice hold?
        "outcomes" => {
            let outcomes = engine.outcomes(&sub).map_err(|e| e.to_string())?;
            if json {
                println!("{}", serde_json::to_string(&outcomes).map_err(|e| e.to_string())?);
            } else if outcomes.is_empty() {
                eprintln!(
                    "no measured outcomes yet — outcome review runs after an applied \
                     recommendation's review window elapses"
                );
            } else {
                for o in &outcomes {
                    // A time checkpoint renders as it always has; one counted
                    // in runs or grains says so.
                    let horizon = match o.checkpoint {
                        Some(cp) => cp.label(),
                        None if o.horizon_ms % 86_400_000 == 0 => format!("{}d", o.horizon_ms / 86_400_000),
                        None => format!("{}h", o.horizon_ms / 3_600_000),
                    };
                    // The receipt names the run it compared against and,
                    // for an evalset metric, the best run before the apply —
                    // the lost opportunity a marginal `held` cannot see.
                    let mut line = format!(
                        "{}  {:<22}  @{:<4}  baseline {} → current {}  [{}]",
                        short(&o.rec_hash),
                        o.metric,
                        horizon,
                        o.baseline,
                        o.current,
                        o.verdict
                    );
                    if let Some(run) = &o.baseline_run_id {
                        line.push_str(&format!("  baseline={} ({run})", o.baseline_kind));
                    }
                    if let Some(best) = o.best_before {
                        line.push_str(&format!("  best_before {best}"));
                    }
                    // The cost column, when the policy set a bound: both
                    // figures and the delta, or an honest "not measurable".
                    if let Some(c) = &o.cost {
                        match (c.baseline, c.current) {
                            (Some(b), Some(cur)) => {
                                let ratio = if b > 0.0 { format!(" ×{:.2}", cur / b) } else { String::new() };
                                line.push_str(&format!(
                                    "  cost {} {b} → {cur}{ratio} [{}, bound ×{}]",
                                    c.field, c.status, c.max_increase_ratio
                                ));
                            }
                            _ => line.push_str(&format!("  cost {} not measurable", c.field)),
                        }
                    }
                    println!("{line}");
                }
            }
        }
        // Config reporting: the effective host policy (read-only).
        "policy" => {
            println!(
                "{}",
                serde_json::to_string_pretty(engine.policy()).map_err(|e| e.to_string())?
            );
        }
        // Bare `areev loop` (or an unknown subcommand) prints a health summary.
        _ => {
            let h = engine.health(&sub, now).map_err(|e| e.to_string())?;
            if json {
                println!("{}", serde_json::to_string(&h).map_err(|e| e.to_string())?);
            } else {
                println!(
                    "loop: {} recommendation(s) — {} pending, {} applied",
                    h.total, h.pending, h.applied
                );
                match h.last_run_ms {
                    None => println!("  never run — areev loop run"),
                    Some(last) => {
                        let days = (now - last) / 86_400_000;
                        println!(
                            "  last run {days}d ago; {} new grain(s) ({} tool error(s)) since",
                            h.grains_since_run, h.error_events_since_run
                        );
                    }
                }
                // Reflection §6b: the live approval-rate for LLM-surfaced
                // findings (only shown once the LLM path has produced any).
                let lm = engine.llm_metrics(&sub).map_err(|e| e.to_string())?;
                if lm.proposed > 0 {
                    match lm.approval_rate {
                        Some(rate) => println!(
                            "  LLM findings: {} surfaced, {:.0}% approved ({} approved / {} rejected, {} pending)",
                            lm.proposed, rate * 100.0, lm.approved, lm.rejected, lm.pending
                        ),
                        None => println!("  LLM findings: {} surfaced, none decided yet", lm.proposed),
                    }
                }
                if h.stale {
                    eprintln!("  ⚠ the loop may be stale — run `areev loop run` or wire the SessionEnd hook");
                } else if h.pending > 0 {
                    println!("  review with: areev loop list");
                }
            }
        }
    }
    Ok(())
}

/// `areev init --db <file> [--template blank|demo|coding-agent] [--ns N]` —
/// seed a working backend and print the wiring snippet (never writes settings).
fn run_init(
    m: Areev,
    ns: &str,
    flags: &HashMap<String, String>,
    _positional: &[String],
) -> Result<(), String> {
    let template = flag(flags, "template").unwrap_or_else(|| "blank".to_string());
    let mut m = m;
    let seeded = match template.as_str() {
        "blank" => 0,
        "demo" => seed_demo(&mut m, ns)?,
        "coding-agent" | "support-agent" => {
            m.add(&Fact::new("agent", "instruction", "review pending recommendations before acting").namespace(ns))
                .map_err(|e| e.to_string())?;
            1
        }
        other => return Err(format!("unknown --template '{other}' (blank|demo|coding-agent|support-agent)")),
    };

    println!("initialized backend (template: {template}, seeded {seeded} grain(s))");
    if template == "demo" {
        println!("next: areev loop run --db <file>   # ~4 recommendations across analyzers");
    }
    // Print the Claude Code hook snippet — areev never edits your settings.
    let exe = std::env::current_exe()
        .ok()
        .and_then(|p| p.to_str().map(str::to_string))
        .unwrap_or_else(|| "areev".to_string());
    eprintln!("\nClaude Code hooks (paste into settings.json — absolute path baked in):");
    eprintln!("  UserPromptSubmit → {exe} recall-hook --ns {ns} --with-loop");
    eprintln!("  Stop             → {exe} capture-stop --ns {ns}");
    eprintln!("  PreCompact       → {exe} capture-stop --ns {ns}");
    eprintln!("  SessionEnd       → {exe} loop run --min-new 20 --min-new-errors 3 --quiet --ns {ns}");
    Ok(())
}

/// Seed the demo corpus: planted duplicates, a contradiction, and a stale
/// grain, so the first `areev loop run` fires several analyzers at once.
fn seed_demo(m: &mut Areev, ns: &str) -> Result<usize, String> {
    let past = 1_000_000_000_000; // year 2001 — safely elapsed
    let grains = [
        Fact::new("acme", "tier", "Enterprise").namespace(ns),
        Fact::new("acme", "tier", "Enterprise").namespace(ns),
        Fact::new("acme", "deploy_target", "us-east-1").namespace(ns),
        Fact::new("acme", "deploy_target", "eu-west-1").namespace(ns),
        Fact::new("promo", "active", "true").namespace(ns).valid_to(past),
    ];
    for g in &grains {
        m.add(g).map_err(|e| e.to_string())?;
    }
    Ok(grains.len())
}

/// The stack `run` is given, independent of the platform default.
///
/// Windows hands a process's main thread 1 MiB; Linux and macOS hand it 8.
/// The deepest CLI paths — `loop apply`, which threads the giant `run`
/// dispatcher frame through the engine, the substrate adapter, the CAL facade
/// and the store — sit just over that 1 MiB in a debug build, so the same
/// command that works everywhere else aborted on Windows with
/// STATUS_STACK_OVERFLOW and no message. Depending on the host default meant
/// depending on a number the platform picks; this picks it.
const CLI_STACK_BYTES: usize = 16 * 1024 * 1024;

fn main() -> ExitCode {
    // Run the whole CLI on a thread whose stack size we chose. Cheap (one
    // spawn per process) and it makes stack headroom identical on every
    // platform instead of 8x smaller on one of them.
    let worker = std::thread::Builder::new()
        .stack_size(CLI_STACK_BYTES)
        .spawn(run);
    let result = match worker {
        Ok(h) => h.join(),
        // Spawning failed (a resource limit, not a bug in `run`): fall back to
        // this thread rather than refusing to run at all.
        Err(_) => Ok(run()),
    };
    match result {
        Ok(Ok(())) => ExitCode::SUCCESS,
        Ok(Err(e)) => {
            eprintln!("areev: {e}");
            ExitCode::FAILURE
        }
        // The worker panicked. Its own hook has already printed the panic;
        // adding a second message would just bury it.
        Err(_) => ExitCode::FAILURE,
    }
}

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

    fn args(a: &[&str]) -> (HashMap<String, String>, Vec<String>) {
        parse_args(&a.iter().map(|s| s.to_string()).collect::<Vec<_>>())
    }

    // ── --mount parsing (issue #184) ────────────────────────────────────

    #[test]
    fn mount_spec_splits_on_the_alias_not_on_every_comma() {
        assert_eq!(
            parse_mounts(Some("org=/srv/org.db,kb=/srv/kb.db")).unwrap(),
            vec![
                ("org".to_string(), "/srv/org.db".to_string()),
                ("kb".to_string(), "/srv/kb.db".to_string()),
            ]
        );
        // libpq's multi-host form: the comma inside the authority must not
        // cut the DSN in half.
        assert_eq!(
            parse_mounts(Some("org=postgres://u:p@h1:5432,h2:5432/db?schema=org_kb")).unwrap(),
            vec![(
                "org".to_string(),
                "postgres://u:p@h1:5432,h2:5432/db?schema=org_kb".to_string()
            )]
        );
        // …and it still separates two mounts when one of them is such a DSN.
        assert_eq!(
            parse_mounts(Some(
                "org=postgres://u:p@h1:5432,h2:5432/db?schema=org_kb, kb=/srv/kb.db"
            ))
            .unwrap(),
            vec![
                (
                    "org".to_string(),
                    "postgres://u:p@h1:5432,h2:5432/db?schema=org_kb".to_string()
                ),
                ("kb".to_string(), "/srv/kb.db".to_string()),
            ]
        );
        // An `options=` list is the other comma-carrying DSN shape.
        assert_eq!(
            parse_mounts(Some(
                "org=postgres://h/db?schema=s&options=-c%20a=1,-c%20b=2"
            ))
            .unwrap()
            .len(),
            1
        );
        assert_eq!(parse_mounts(None).unwrap(), Vec::new());
        assert!(parse_mounts(Some("no-equals-sign")).is_err());
    }

    /// A mount target may be a DSN, and a DSN carries a password. Nothing the
    /// CLI prints — the startup line or the failure — may contain it.
    #[test]
    fn mount_errors_and_logs_never_print_a_dsn_password() {
        let dsn = "postgres://areev:SUPERSECRET@pg:5432/db?schema=org_kb";
        assert!(!redact_dsn(dsn).contains("SUPERSECRET"), "{}", redact_dsn(dsn));
        assert!(redact_dsn(dsn).contains("areev:***@pg:5432"));
        // The malformed-entry error echoes the entry back; it must redact too.
        let err = parse_mounts(Some(dsn)).unwrap_err();
        assert!(!err.contains("SUPERSECRET"), "{err}");
        // A file path is left exactly as written.
        assert_eq!(redact_dsn("/srv/org.db"), "/srv/org.db");
    }

    /// Feature-gated because the comparison needs `split_schema_url`: a build
    /// without the postgres backend cannot be handed a postgres primary in
    /// the first place, so `mount_is_the_primary` is a constant `false` there.
    #[cfg(feature = "postgres")]
    #[test]
    fn a_postgres_mount_of_the_primary_schema_is_recognized() {
        let primary = "postgres://u:p@h/db?schema=main";
        assert!(mount_is_the_primary(primary, "postgres://u:p@h/db?schema=main"));
        // Same DSN, different schema — a legitimate mount.
        assert!(!mount_is_the_primary(primary, "postgres://u:p@h/db?schema=org_kb"));
        // A file mount of a file primary is left to the store's own
        // single-handle guard (STO-E002).
        assert!(!mount_is_the_primary("/srv/main.db", "/srv/main.db"));
    }

    /// [A1] `format_epoch_ms` is a hand-rolled `civil_from_days` — the exact
    /// inverse of the parser in `areev_core::time`. Round-tripping the pair
    /// is what proves neither drifted, and it is checked on the dates where
    /// calendar arithmetic actually goes wrong.
    #[test]
    fn expiry_formatting_round_trips_through_the_parser() {
        for iso in [
            "1970-01-01T00:00:00Z",
            "2026-08-27T12:34:56Z",
            // Leap day, and the day either side of it.
            "2024-02-28T23:59:59Z",
            "2024-02-29T12:00:00Z",
            "2024-03-01T00:00:00Z",
            // 2000 was a leap year (÷400); 2100 will not be (÷100, not ÷400).
            "2000-02-29T00:00:00Z",
            "2100-02-28T00:00:00Z",
            // Year and month boundaries.
            "2026-12-31T23:59:59Z",
            "2027-01-01T00:00:00Z",
        ] {
            let ms = areev_core::time::iso8601_to_ms(iso).expect(iso);
            assert_eq!(format_epoch_ms(ms), iso, "round-trip failed for {iso}");
        }
    }

    /// [A1] `--expires` accepts a relative window or an absolute instant, and
    /// refuses anything it cannot turn into a real deadline — a credential
    /// whose lifetime was silently misread is worse than one that refuses.
    #[test]
    fn expiry_parsing_accepts_windows_and_instants_and_refuses_the_rest() {
        // An absolute instant is normalized, not passed through, so the file
        // only ever holds one spelling.
        assert_eq!(
            parse_expiry("2026-12-31T23:59:59Z").unwrap(),
            "2026-12-31T23:59:59Z"
        );
        assert_eq!(parse_expiry("2026-12-31").unwrap(), "2026-12-31T00:00:00Z");

        // Relative windows land in the future, and a longer one lands later.
        let now = areev_core::time::now_ms();
        let d90 = areev_core::time::iso8601_to_ms(&parse_expiry("90d").unwrap()).unwrap();
        let h12 = areev_core::time::iso8601_to_ms(&parse_expiry("12h").unwrap()).unwrap();
        assert!(h12 > now && d90 > h12, "90d={d90} 12h={h12} now={now}");
        // ~90 days, allowing a second of slop for the two clock reads.
        assert!((d90 - now - 90 * 86_400_000).abs() < 2_000);

        for bad in ["90x", "d", "", "-5d", "0d", "soon", "90 d"] {
            assert!(parse_expiry(bad).is_err(), "{bad:?} must be refused");
        }
    }

    #[test]
    fn valueless_long_flag_does_not_swallow_short_flag() {
        // Regression: in `serve --mcp -d mem.db`, the valueless `--mcp` must not
        // consume `-d` as its value — otherwise --db is never set and serve
        // silently falls back to the default memory file.
        let (flags, pos) = args(&["--mcp", "-d", "mem.db", "--ns", "caller"]);
        assert_eq!(flags.get("mcp").map(String::as_str), Some("true"));
        assert_eq!(flags.get("db").map(String::as_str), Some("mem.db"));
        assert_eq!(flags.get("ns").map(String::as_str), Some("caller"));
        assert!(pos.is_empty(), "no stray positionals: {pos:?}");
    }

    #[test]
    fn db_flag_equivalent_across_form_and_order() {
        for a in [
            &["--mcp", "-d", "mem.db"][..],
            &["-d", "mem.db", "--mcp"][..],
            &["--mcp", "--db", "mem.db"][..],
            &["--db", "mem.db", "--mcp"][..],
        ] {
            let (flags, _) = args(a);
            assert_eq!(flags.get("db").map(String::as_str), Some("mem.db"), "args: {a:?}");
            assert_eq!(flags.get("mcp").map(String::as_str), Some("true"), "args: {a:?}");
        }
    }

    #[test]
    fn adjacent_valueless_flags_stay_true() {
        let (flags, _) = args(&["--mcp", "--no-destructive-ops"]);
        assert_eq!(flags.get("mcp").map(String::as_str), Some("true"));
        assert_eq!(flags.get("no-destructive-ops").map(String::as_str), Some("true"));
    }

    #[test]
    fn openai_tool_import_preserves_arguments_error_and_call_id() {
        let rows = extract_tool_records(&serde_json::json!({
            "created_at": 42,
            "tool_calls": [{
                "id": "call-7",
                "is_error": true,
                "function": {
                    "name": "charge",
                    "arguments": "{\"amount\":42}"
                }
            }]
        }));
        assert_eq!(rows.len(), 1);
        assert_eq!(rows[0].name, "charge");
        assert_eq!(rows[0].input, Some(serde_json::json!({"amount": 42})));
        assert!(rows[0].content.is_empty(), "arguments are not a result");
        assert!(rows[0].is_error);
        assert_eq!(rows[0].call_id.as_deref(), Some("call-7"));
        assert_eq!(rows[0].created_at, Some(42));
    }
}