mnemo-engine 0.17.1

Encrypted, single-file, portable agent memory engine with multi-signal recall, sessions, snapshots, and an IVF+PQ index
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
//! `mnemo` — command-line interface to the Mnemo encrypted memory engine.
//!
//! Passphrases are read from `--passphrase` or, if omitted, the
//! `MNEMO_PASSPHRASE` environment variable. Passing secrets on a command line
//! is insecure (they land in shell history and process listings); prefer the
//! environment variable, and for real use prefer the library API.

use std::process::ExitCode;

#[path = "mnemo/export.rs"]
mod export;
#[path = "mnemo/hook.rs"]
mod hook;
#[path = "mnemo/inspect.rs"]
mod inspect;
#[path = "mnemo/mcp_install.rs"]
mod mcp_install;
#[path = "mnemo/onboard.rs"]
mod onboard;
#[path = "mnemo/project.rs"]
mod project;

use clap::{Parser, Subcommand, ValueEnum};
use mnemo_engine::{
    Memory, MemoryType, Metric, Mnemo, MnemoConfig, RecallRequest, RecallResult, Result, Ulid,
};

/// Encrypted, single-file agent-memory engine.
#[derive(Parser)]
#[command(name = "mnemo", version, about, long_about = None)]
struct Cli {
    /// How long to wait for the brain's lock when another process holds it
    /// (12.4 shared mode): `10s`, `500ms`, `2m`, or a number of seconds.
    /// Reads run alongside other readers, and readers come first. A hook
    /// that only reads should pass `--wait 2s`; one that saves keeps the
    /// default, since busy readers can hold a write longer.
    #[arg(long, global = true, value_name = "DURATION", default_value = "10s",
          value_parser = parse_wait)]
    wait: std::time::Duration,
    /// 12.3 step 5: load the built-in embedder from this directory (its
    /// `config.json`, `tokenizer.json` and `model.safetensors`) instead of
    /// the cache, and never download. When they're the pinned files it's
    /// the built-in embedder; otherwise the identity records each file's
    /// SHA-256.
    #[arg(long, global = true, value_name = "DIR")]
    model_dir: Option<std::path::PathBuf>,
    /// 12.2: run as if started in this directory, like git's `-C`. Relative
    /// paths are read from it, and a brain argument left out is this
    /// directory's project brain.
    #[arg(short = 'C', global = true, value_name = "DIR")]
    dir: Option<std::path::PathBuf>,
    #[command(subcommand)]
    command: Command,
}

/// 12.2 step 1: the brain argument of the commands that may leave it out
/// (an empty string when it was left out), or `None` for the others.
/// `get` takes `[PATH] <ID>` ([`shift_get_args`] moves a lone ID); the
/// other commands with a positional argument after the brain (`update`,
/// `thread start`, `essence update|resolve|remove`) keep it required, and
/// so do the ones that rewrite or replace the file (`compact`, `reembed`,
/// `restore`, `import`, `index`).
fn brain_arg(cmd: &mut Command) -> Option<&mut String> {
    match cmd {
        Command::Init { path, .. }
        | Command::Unlock { path }
        | Command::RecoveryCode { path }
        | Command::Rekey { path, .. }
        | Command::Info { path, .. }
        | Command::Verify { path, .. }
        | Command::Remember { path, .. }
        | Command::About { path, .. }
        | Command::List { path, .. }
        | Command::Export { path, .. }
        | Command::Inspect { path, .. }
        | Command::Recall { path, .. }
        | Command::Get { path, .. }
        | Command::Update { path, .. }
        | Command::DefaultAgent { path, .. }
        | Command::Inbox { path, .. }
        | Command::Stale { path, .. }
        | Command::Ack { path, .. }
        | Command::Post { brain: path, .. }
        | Command::Claim { brain: path, .. }
        | Command::Task { brain: path, .. }
        | Command::Wake { brain: path, .. }
        | Command::Search { path, .. }
        | Command::Snapshots { path, .. }
        | Command::History { path, .. }
        | Command::Serve { path, .. }
        | Command::Mcp {
            cmd: McpCmd::Install { path, .. },
        }
        | Command::Thread {
            cmd:
                ThreadCmd::Ingest { path, .. }
                | ThreadCmd::Export { path, .. }
                | ThreadCmd::Forget { path, .. }
                | ThreadCmd::Start { path, .. },
        }
        | Command::Essence {
            cmd:
                EssenceCmd::Render { path, .. }
                | EssenceCmd::Add { path, .. }
                | EssenceCmd::Append { path, .. }
                | EssenceCmd::Update { path, .. }
                | EssenceCmd::Resolve { path, .. }
                | EssenceCmd::Remove { path, .. },
        } => Some(path),
        _ => None,
    }
}

/// v0.16.1: `get <ID>` is `get <project brain> <ID>`: a lone argument
/// moves to the ID, and must be a ULID (so a path given without its ID
/// says so, rather than being read as an id).
fn shift_get_args(cmd: &mut Command) -> std::result::Result<(), String> {
    // v0.17 (CLI-PATHLESS-2): the same for `update` and `essence
    // update|resolve|remove`, whose second argument is a ULID too, and
    // `thread start`, whose second is a thread id.
    let (name, path, id, ulid) = match cmd {
        Command::Get { path, id, .. } => ("get", path, id, true),
        Command::Update { path, id, .. } => ("update", path, id, true),
        Command::Ack { path, id, .. } => ("ack", path, id, true),
        Command::Essence {
            cmd:
                EssenceCmd::Update { path, id, .. }
                | EssenceCmd::Resolve { path, id, .. }
                | EssenceCmd::Remove { path, id, .. },
        } => ("essence", path, id, true),
        Command::Thread {
            cmd: ThreadCmd::Start { path, new, .. },
        } => ("thread start", path, new, false),
        _ => return Ok(()),
    };
    if id.is_some() {
        return Ok(());
    }
    if ulid && parse_ulid(path).is_err() {
        return Err(format!(
            "`{name}` takes `[PATH] <ID>`: with one argument it's the memory's id, and \
             {path:?} isn't one"
        ));
    }
    if !ulid && (path.ends_with(".mnemo") || std::path::Path::new(path.as_str()).is_file()) {
        return Err(format!(
            "`{name}` takes `[PATH] <NEW>`: with one argument it's the new thread id, and \
             {path:?} looks like a brain's path; give the thread id too"
        ));
    }
    *id = Some(std::mem::take(path));
    Ok(())
}

/// Fill in a brain argument that was left out with the project brain.
/// `init` creates the brain's directory (0700); every other command needs
/// the brain to exist. Returns whether it was left out.
fn resolve_brain_arg(cmd: &mut Command, moved: bool) -> std::result::Result<bool, String> {
    let creating = matches!(cmd, Command::Init { .. });
    let Some(path) = brain_arg(cmd) else {
        return Ok(false);
    };
    if !path.is_empty() {
        return Ok(false);
    }
    let brain = project::find(moved, false)?;
    if creating {
        project::create_dir(&brain)?;
    } else if !brain.is_file() {
        return Err(format!(
            "no project brain at {} yet; create it with `mnemo init` in this repository",
            brain.display()
        ));
    }
    *path = brain
        .to_str()
        .ok_or_else(|| format!("{}: the path isn't UTF-8", brain.display()))?
        .to_string();
    Ok(true)
}

#[derive(Subcommand)]
enum Command {
    /// Create a new empty encrypted database.
    ///
    /// By default a starter "scaffold" manifest memory is inserted so the
    /// new file is self-describing from birth (visible via `mnemo about`).
    /// Pass `--no-manifest` to skip it for an entirely empty file.
    ///
    /// With no passphrase source (`--passphrase`, `MNEMO_PASSPHRASE`,
    /// `--ask-passphrase`), `init` generates a random 256-bit key and keeps
    /// it in the OS keychain, so every tool opens the brain with nothing
    /// typed. Its recovery code is shown once, at a terminal a person is at
    /// (`mnemo recovery-code` shows it again), on the terminal's alternate
    /// screen so it doesn't stay in scrollback; on Windows the console has
    /// no alternate screen, so the code stays in its scrollback until the
    /// window is cleared or closed. A generated-key `init`
    /// refuses a path that already exists. With no keychain, it fails and
    /// creates nothing: use `--ask-passphrase` or `--key-file`.
    ///
    /// What the keychain protects: it keeps the key out of config files,
    /// dotfile repositories, backups, screen shares and shell history, and
    /// away from other users of the machine. It doesn't keep it from
    /// programs running as you: any of them can read the keychain entry or
    /// run `mnemo recovery-code`. The recovery code is shown only to a
    /// person at a terminal, so it doesn't land in an agent's transcript by
    /// accident, but that isn't a barrier against a program that sets out
    /// to read it. "The key no longer sits in plain text" is the whole
    /// claim.
    Init {
        /// Path to the new `.mnemo` file. Leave it out for this project's brain,
        /// `<git-common-dir>/mnemo/project.mnemo` (12.2), found from `-C`,
        /// else `CLAUDE_PROJECT_DIR`, else the working directory.
        #[arg(default_value = "", hide_default_value = true)]
        path: String,
        /// Embedding dimensionality. The default, 384, is the built-in
        /// embedder's (12.3 step 5; 768 before v0.15).
        #[arg(long, default_value_t = 384)]
        dimensions: usize,
        /// Skip the auto-generated scaffold manifest (create an empty file).
        #[arg(long)]
        no_manifest: bool,
        /// Passphrase (else `MNEMO_PASSPHRASE`, or `--ask-passphrase`).
        /// With none of the three, `init` generates a key instead.
        #[arg(long, conflicts_with_all = ["ask_passphrase", "key_file"])]
        passphrase: Option<String>,
        /// Ask for a passphrase twice, without echo, instead of generating
        /// a key (what `init` did before v0.15).
        #[arg(long, conflicts_with = "key_file")]
        ask_passphrase: bool,
        /// Generate a key and write it to this new file (mode 0600), instead
        /// of keeping it in the keychain.
        #[arg(long, value_name = "PATH")]
        key_file: Option<String>,
    },
    /// Keep a brain's key in this machine's keychain, from its recovery code.
    ///
    /// The code is read from a prompt (no echo) at a terminal, or from stdin
    /// (`... | mnemo unlock <file>`), never from the command line. A typo is
    /// named by group; a code that doesn't open the file isn't stored.
    Unlock {
        /// Path to the `.mnemo` file. Leave it out for this project's brain,
        /// `<git-common-dir>/mnemo/project.mnemo` (12.2), found from `-C`,
        /// else `CLAUDE_PROJECT_DIR`, else the working directory.
        #[arg(default_value = "", hide_default_value = true)]
        path: String,
    },
    /// Show a brain's recovery code, from the key store.
    ///
    /// It's shown only to a person at a terminal: stdout and stdin must be
    /// terminals, no agent harness may be driving it, and the code appears
    /// on the controlling terminal after you press Enter, then is cleared.
    RecoveryCode {
        /// Path to the `.mnemo` file. Leave it out for this project's brain,
        /// `<git-common-dir>/mnemo/project.mnemo` (12.2), found from `-C`,
        /// else `CLAUDE_PROJECT_DIR`, else the working directory.
        #[arg(default_value = "", hide_default_value = true)]
        path: String,
    },
    /// Print database statistics.
    Info {
        /// Path to the `.mnemo` file. Leave it out for this project's brain,
        /// `<git-common-dir>/mnemo/project.mnemo` (12.2), found from `-C`,
        /// else `CLAUDE_PROJECT_DIR`, else the working directory.
        #[arg(default_value = "", hide_default_value = true)]
        path: String,
        /// Unlock with a raw key (32 bytes, or 64 hex digits) instead of a
        /// passphrase.
        #[arg(long, value_name = "PATH", conflicts_with = "passphrase")]
        key_file: Option<String>,
        #[arg(long)]
        passphrase: Option<String>,
    },
    /// Re-encrypt the data key under a new passphrase.
    ///
    /// The new passphrase comes from (in priority order) `--new-passphrase`,
    /// the `MNEMO_NEW_PASSPHRASE` env var, or an interactive double-prompt
    /// without echo. The old passphrase follows the same priority chain as
    /// every other command.
    ///
    /// A plain rekey changes the secret that opens this file from now on;
    /// anyone who had the file and the old secret can still read it and
    /// later writes. Use `--rotate` to revoke (after a suspected passphrase
    /// leak, say). Rotation can't erase old ciphertext that flash storage
    /// still holds in blocks it hasn't reused.
    ///
    /// `--new-key` keeps the new key in the keychain before the rekey
    /// commits, and shows its recovery code first, at a terminal. No OS
    /// keychain promises its write is on disk when it returns, so when the
    /// code can't be shown (not a terminal, or an agent harness), `--new-key`
    /// refuses unless `--new-key-file` also writes the key to a new file:
    /// otherwise a power cut could leave the key nowhere.
    Rekey {
        /// Path to the `.mnemo` file. Leave it out for this project's brain,
        /// `<git-common-dir>/mnemo/project.mnemo` (12.2), found from `-C`,
        /// else `CLAUDE_PROJECT_DIR`, else the working directory.
        #[arg(default_value = "", hide_default_value = true)]
        path: String,
        /// Unlock with a raw key (32 bytes, 64 hex digits or a recovery
        /// code) instead of a passphrase.
        #[arg(long, value_name = "PATH", conflicts_with = "passphrase")]
        key_file: Option<String>,
        #[arg(long)]
        passphrase: Option<String>,
        /// The new passphrase. Omit to be prompted twice without echo.
        #[arg(long, conflicts_with = "new_key")]
        new_passphrase: Option<String>,
        /// Generate a new key instead of a new passphrase, keep it in the
        /// key store, and show its recovery code (at a terminal).
        #[arg(long)]
        new_key: bool,
        /// Also keep a new passphrase in the key store.
        #[arg(long, conflicts_with = "new_key")]
        store: bool,
        /// With `--new-key`, also write the new key to this new file (mode
        /// 0600).
        #[arg(long, value_name = "PATH", requires = "new_key")]
        new_key_file: Option<String>,
        /// Also rotate the data key: rekey, then compact, which rewrites the
        /// file under a fresh data key. The old passphrase then opens no
        /// copy of the file made from now on, and no earlier copy opens with
        /// the new one. Takes as long as `compact` (history is dropped).
        #[arg(long)]
        rotate: bool,
    },
    /// Rebuild the file, dropping tombstoned and expired memories. Writes
    /// v9, so this is also how a v8 (or older) file is converted: since
    /// v0.13 a v8 file opens read-only until it's compacted.
    Compact {
        /// Path to the `.mnemo` file.
        path: String,
        /// Unlock with a raw key (32 bytes, or 64 hex digits) instead of a
        /// passphrase.
        #[arg(long, value_name = "PATH", conflicts_with = "passphrase")]
        key_file: Option<String>,
        #[arg(long)]
        passphrase: Option<String>,
    },
    /// Embed every live memory again with a new embedder, and record its
    /// identity (12.3 step 4).
    ///
    /// A compaction with new vectors: it holds the file's exclusive lock
    /// (waiting `--wait`, like `compact`) for the whole run, embedding
    /// included, writes a temp copy with the same salt and renames it over
    /// the file. An interrupted run leaves the old file whole, so the file
    /// never has two identities or mixed vectors. It also rebuilds the
    /// keyword index with the current tokenizer, and drops snapshot history
    /// as compaction does.
    Reembed {
        /// Path to the `.mnemo` file.
        path: String,
        /// The new embedder's command (the `remember --embed-cmd` protocol).
        /// Without it, the file moves to the built-in embedder (12.3 step 5).
        #[arg(long, requires = "embed_name")]
        embed_cmd: Option<String>,
        /// The new embedder's identity name.
        #[arg(long, requires = "embed_cmd")]
        embed_name: Option<String>,
        /// Whether the new embedder returns unit-normalized vectors.
        #[arg(long, default_value_t = true, action = clap::ArgAction::Set)]
        embed_normalize: bool,
        /// The new embedder's query convention, if it embeds queries
        /// differently (see `remember --embed-query`).
        #[arg(long)]
        embed_query: Option<String>,
        /// The new embedder's width, when it differs from the file's.
        #[arg(long)]
        embed_dims: Option<usize>,
        /// Per-request timeout for the embedder (seconds; default 60).
        #[arg(long, default_value_t = 60)]
        embed_timeout: u64,
        /// Unlock with a raw key (32 bytes, or 64 hex digits) instead of a
        /// passphrase.
        #[arg(long, value_name = "PATH", conflicts_with = "passphrase")]
        key_file: Option<String>,
        #[arg(long)]
        passphrase: Option<String>,
    },
    /// Decrypt and re-verify every live record.
    Verify {
        /// Path to the `.mnemo` file. Leave it out for this project's brain,
        /// `<git-common-dir>/mnemo/project.mnemo` (12.2), found from `-C`,
        /// else `CLAUDE_PROJECT_DIR`, else the working directory.
        #[arg(default_value = "", hide_default_value = true)]
        path: String,
        /// Unlock with a raw key (32 bytes, or 64 hex digits) instead of a
        /// passphrase.
        #[arg(long, value_name = "PATH", conflicts_with = "passphrase")]
        key_file: Option<String>,
        #[arg(long)]
        passphrase: Option<String>,
    },
    /// Import memories from a JSON Lines file.
    ///
    /// Each line: {"content": "...", "vector": [..], "memory_type": "semantic",
    /// "agent_id": "...", "importance": 0.5}. Only `content` and `vector` are
    /// required.
    Import {
        /// Path to the `.mnemo` file.
        path: String,
        /// JSONL file to import.
        file: String,
        #[arg(long)]
        passphrase: Option<String>,
    },
    /// Store a single memory from text. It's embedded with the built-in
    /// embedder (12.3 step 5; fetched on first use, see `mnemo embedder`),
    /// or with an external command given by `--embed-cmd` (Phase 3): spawned
    /// once, it reads one JSON string per line from stdin and writes one
    /// JSON float array per line to stdout.
    Remember {
        /// Path to the `.mnemo` file. Leave it out for this project's brain,
        /// `<git-common-dir>/mnemo/project.mnemo` (12.2), found from `-C`,
        /// else `CLAUDE_PROJECT_DIR`, else the working directory.
        #[arg(default_value = "", hide_default_value = true)]
        path: String,
        /// Content to remember.
        #[arg(long)]
        text: String,
        /// Memory type: `semantic`, `episodic`, `procedural`, or
        /// `working`.
        #[arg(long, default_value = "semantic")]
        r#type: String,
        /// Optional importance weight (0.0–1.0; defaults to 0.5).
        #[arg(long)]
        importance: Option<f32>,
        /// Optional agent id to scope the memory to. Left out: the brain's
        /// default agent (`mnemo default-agent`, v0.17), else `default`.
        #[arg(long)]
        agent: Option<String>,
        /// Optional JSON object of extra metadata key/values.
        #[arg(long)]
        metadata: Option<String>,
        #[command(flatten)]
        fresh: FreshArgs,
        /// Phase 12.1: optional upsert key. When set, this `remember`
        /// behaves as a keyed write: if a live memory already holds this
        /// `(scope_owner, key)` slot, the prior record is marked
        /// `_mnemo.superseded_by` and a new record is inserted; if the
        /// incoming content, type, importance and user metadata match
        /// the live record exactly, the write is a no-op and nothing is
        /// changed. Prefer `--key` for facts that replace earlier ones
        /// (versions, current status, user preferences). Prints the id
        /// plus one of `added`/`superseded`/`unchanged` on stdout.
        #[arg(long)]
        key: Option<String>,
        /// v0.15 (with `--key`): the id of a memory written without a key,
        /// which this write adopts as the key's first version and
        /// supersedes: it stops showing in recall but stays in `mnemo
        /// history --key`. Matching content adopts it as is (`updated`).
        #[arg(long, requires = "key", value_name = "ID")]
        supersedes: Option<String>,
        /// Embedder command, in place of the built-in embedder.
        /// Shell-style quoted but **not** executed via a shell — e.g.
        /// `"python3 embedder.py"` or `"my-embed --model=foo"`. Protocol:
        /// child reads one JSON string per line from stdin, writes one JSON
        /// array of floats per line to stdout, flushes after each reply.
        #[arg(long, requires = "embed_name")]
        embed_cmd: Option<String>,
        /// Embedder identity recorded on the scaffold manifest (with
        /// `--embed-cmd`). The first `remember`/`recall` on a fresh file
        /// writes this name; later calls on the same file must pass the same
        /// name or `set_embedder` refuses with an identity mismatch.
        #[arg(long, requires = "embed_cmd")]
        embed_name: Option<String>,
        /// Whether the embedder returns unit-normalized vectors
        /// (defaults to `true`; set `--embed-normalize=false` for
        /// embedders that return raw dot-space vectors).
        #[arg(long, default_value_t = true, action = clap::ArgAction::Set)]
        embed_normalize: bool,
        /// 12.3 step 4: the embedder embeds queries differently from
        /// documents, under this convention name (recorded in the file's
        /// embedder identity, which must match). The command then gets each
        /// request as `{"kind":"query"|"document","text":…}` instead of a
        /// JSON string.
        #[arg(long)]
        embed_query: Option<String>,
        /// Per-request timeout for the embedder (seconds; default 60).
        /// A silent-but-alive child trips this deadline deterministically
        /// (PR 10b.2). A short timeout bounds CLI/MCP latency when the
        /// embedder misbehaves.
        #[arg(long, default_value_t = 60)]
        embed_timeout: u64,
        #[arg(long)]
        passphrase: Option<String>,
    },
    /// Build, rebuild, or drop the approximate-nearest-neighbour index.
    Index {
        /// Path to the `.mnemo` file.
        path: String,
        #[arg(long)]
        passphrase: Option<String>,
        /// Drop the existing index instead of building one.
        #[arg(long, conflicts_with = "rebuild")]
        drop: bool,
        /// Rebuild the ANN index from scratch using the auto-defaults
        /// for the current corpus size (re-clusters centroids and
        /// retrains the PQ codebook, undoing the cluster drift that
        /// accumulates as memories are inserted against fixed
        /// centroids). Required to pick up the ANN-1.1 defaults on an
        /// index built by v0.5.x — the shipped BP.1 fix wires this up
        /// so the v0.6.0 upgrade note's `mnemo index --rebuild` /
        /// `rebuild_index()` commands actually exist. Mutually
        /// exclusive with `--drop`.
        #[arg(long, conflicts_with = "drop")]
        rebuild: bool,
        /// IVF partitions (0 = auto, ~sqrt of memory count).
        #[arg(long, default_value_t = 0)]
        partitions: usize,
        /// PQ subspaces (0 = auto, ~8 dims each).
        #[arg(long, default_value_t = 0)]
        subspaces: usize,
        /// Partitions probed per query (0 = auto; computed from the
        /// partition count on every recall).
        #[arg(long, default_value_t = 0)]
        n_probe: usize,
        /// Candidates reranked exactly per query (0 = auto; scales
        /// with the live vector count).
        #[arg(long, default_value_t = 0)]
        n_rerank: usize,
    },
    /// Run an exact nearest-neighbour search.
    ///
    /// Provide the query vector via exactly one of `--query` (inline) or
    /// `--query-file` (file path; use `-` for stdin). Files may contain a
    /// JSON array of floats, comma-separated floats, or whitespace /
    /// newline-separated floats — the parser auto-detects.
    Search {
        /// Path to the `.mnemo` file. Leave it out for this project's brain
        /// (v0.16.1).
        #[arg(default_value = "", hide_default_value = true)]
        path: String,
        /// Query vector as comma-separated floats, e.g. `0.1,0.2,0.9`.
        /// Mutually exclusive with `--query-file`.
        #[arg(long, conflicts_with = "query_file")]
        query: Option<String>,
        /// Path to a file containing the query vector (`-` for stdin).
        /// Accepts a JSON array, comma-separated floats, or one float
        /// per line. Mutually exclusive with `--query`.
        #[arg(long, conflicts_with = "query")]
        query_file: Option<String>,
        #[arg(long, default_value_t = 5)]
        top_k: usize,
        /// 13a: the visibility levels shown: `public`, `team`, `private`,
        /// or `all` (comma-separated; default public and team).
        #[arg(long, value_name = "LEVELS", value_delimiter = ',')]
        visibility: Vec<String>,
        #[arg(long)]
        passphrase: Option<String>,
    },
    /// Self-describing briefing — print the database's onboarding memories.
    ///
    /// Surfaces memories tagged `metadata.area = "onboarding"` (most important
    /// first), prefixed by a one-line stats summary. This is how a fresh
    /// agent — yours or someone else's — gets oriented to a `.mnemo` file
    /// using only the file itself and its passphrase, with no external docs.
    ///
    /// A canonical entry tagged `metadata.topic = "manifest"` is treated as
    /// the headline orientation point.
    About {
        /// Path to the `.mnemo` file. Leave it out for this project's brain,
        /// `<git-common-dir>/mnemo/project.mnemo` (12.2), found from `-C`,
        /// else `CLAUDE_PROJECT_DIR`, else the working directory.
        #[arg(default_value = "", hide_default_value = true)]
        path: String,
        /// Output format.
        #[arg(long, value_enum, default_value_t = OutputFormat::Table)]
        format: OutputFormat,
        /// Print only the manifest memory (topic=manifest), no other onboarding entries.
        #[arg(long)]
        manifest_only: bool,
        /// 13a: the visibility levels shown: `public`, `team`, `private`,
        /// or `all` (comma-separated; default public and team).
        #[arg(long, value_name = "LEVELS", value_delimiter = ',')]
        visibility: Vec<String>,
        /// Unlock with a raw key (32 bytes, or 64 hex digits) instead of a
        /// passphrase.
        #[arg(long, value_name = "PATH", conflicts_with = "passphrase")]
        key_file: Option<String>,
        #[arg(long)]
        passphrase: Option<String>,
    },
    /// Fetch a single memory by its ULID.
    Get {
        /// Path to the `.mnemo` file, then the memory's ULID. With one
        /// argument it's the ULID, and the brain is this project's
        /// (`<git-common-dir>/mnemo/project.mnemo`, v0.16.1), as for
        /// `recall`.
        #[arg(value_name = "PATH")]
        path: String,
        /// ULID of the memory to fetch (when PATH is given).
        #[arg(value_name = "ID")]
        id: Option<String>,
        /// Output format.
        #[arg(long, value_enum, default_value_t = OutputFormat::Table)]
        format: OutputFormat,
        /// Show agent, session, timestamps, importance, scope, and metadata.
        #[arg(long)]
        verbose: bool,
        /// Include the embedding vector (json only; tables always omit it).
        #[arg(long)]
        vector: bool,
        #[arg(long)]
        passphrase: Option<String>,
    },
    /// 13a (13.1): post a message to an agent (`worker-a`), a role
    /// (`role:worker`) or everyone (`all`). It's information, never
    /// authority. Prints its id and hop count.
    Post {
        /// An agent id, `role:<role>`, or `all`.
        to: String,
        /// One line.
        subject: String,
        /// The body (at most 8 KB; a longer one belongs in a fact, named in
        /// `--refs`).
        #[arg(long, default_value = "")]
        body: String,
        /// Record ids, a PR number, an entry's title (comma-separated).
        #[arg(long, value_delimiter = ',')]
        refs: Vec<String>,
        /// The conversation this replies in (from the message you answer).
        #[arg(long)]
        conversation: Option<String>,
        #[command(flatten)]
        who: AsArgs,
        /// The brain's path. Left out, this project's brain.
        #[arg(
            long,
            value_name = "PATH",
            default_value = "",
            hide_default_value = true
        )]
        brain: String,
        #[arg(long)]
        passphrase: Option<String>,
    },
    /// 13a (13.1): your messages: those to you, your role or everyone, not
    /// yet acked (`--all` for every one). Listing marks them seen.
    Inbox {
        /// Path to the `.mnemo` file. Leave it out for this project's brain.
        #[arg(default_value = "", hide_default_value = true)]
        path: String,
        /// Acked ones too.
        #[arg(long)]
        all: bool,
        /// 13a: the visibility levels shown: `public`, `team`, `private`,
        /// or `all` (comma-separated; default public and team).
        #[arg(long, value_name = "LEVELS", value_delimiter = ',')]
        visibility: Vec<String>,
        /// Delete messages acked more than `--days` (default 30) days ago,
        /// and list nothing.
        #[arg(long)]
        prune: bool,
        /// With `--prune`: how old an acked message must be.
        #[arg(long, default_value_t = 30, requires = "prune")]
        days: u32,
        /// Output format.
        #[arg(long, value_enum, default_value_t = OutputFormat::Table)]
        format: OutputFormat,
        #[command(flatten)]
        who: AsArgs,
        #[arg(long)]
        passphrase: Option<String>,
    },
    /// 13a (13.1): ack a message (`unread → acked`), with an optional note.
    Ack {
        /// Path to the `.mnemo` file, then the message's ULID. With one
        /// argument it's the ULID, and the brain is this project's.
        #[arg(value_name = "PATH")]
        path: String,
        /// The message's ULID (when PATH is given).
        #[arg(value_name = "ID")]
        id: Option<String>,
        #[arg(long)]
        note: Option<String>,
        #[command(flatten)]
        who: AsArgs,
        #[arg(long)]
        passphrase: Option<String>,
    },
    /// 13a (13.6): the stale records, oldest first: past their review date,
    /// or older than their kind's default (essence `state` and `next` 14
    /// days, `open` 30; an `active` task with no update 3, a `blocked` one
    /// 7; an unread message 3). `--mine` keeps yours (`--as`, else
    /// `MNEMO_AGENT`).
    Stale {
        /// Path to the `.mnemo` file. Leave it out for this project's brain.
        #[arg(default_value = "", hide_default_value = true)]
        path: String,
        /// Only those that are yours: your tasks, your messages, what you
        /// wrote.
        #[arg(long)]
        mine: bool,
        /// 13a: the visibility levels shown: `public`, `team`, `private`,
        /// or `all` (comma-separated; default public and team).
        #[arg(long, value_name = "LEVELS", value_delimiter = ',')]
        visibility: Vec<String>,
        #[arg(long, value_enum, default_value_t = OutputFormat::Table)]
        format: OutputFormat,
        #[command(flatten)]
        who: AsArgs,
        #[arg(long)]
        passphrase: Option<String>,
    },
    /// 13a (13.1b): the wake-up kill switch for every session of this
    /// brain: `pause`, `resume`, or `status` (also `MNEMO_WAKE` and the
    /// `crossSessionInbound` settings it can see). Paused, nothing wakes an
    /// agent; the per-turn hook and the brief still show its work.
    Wake {
        #[command(subcommand)]
        cmd: WakeCmd,
        #[command(flatten)]
        who: AsArgs,
        /// The brain's path. Left out, this project's brain.
        #[arg(
            long,
            global = true,
            value_name = "PATH",
            default_value = "",
            hide_default_value = true
        )]
        brain: String,
        #[arg(long, global = true)]
        passphrase: Option<String>,
    },
    /// 13a (13.1): the work queue the agents share. `next` takes the oldest
    /// task for your role (or one whose owner's claim lapsed) and prints
    /// its slug and claim token; `update` moves yours along. A task is
    /// information, never authority.
    Task {
        #[command(subcommand)]
        cmd: TaskCmd,
        #[command(flatten)]
        who: AsArgs,
        /// The brain's path. Left out, this project's brain.
        #[arg(
            long,
            global = true,
            value_name = "PATH",
            default_value = "",
            hide_default_value = true
        )]
        brain: String,
        #[arg(long, global = true)]
        passphrase: Option<String>,
    },
    /// 13a (13.3): claims, so two agents don't do one thing. A claim is a
    /// record, not a lock, and it's advisory. `take` prints a token that
    /// `renew`, `release` and `check` need; `check` before anything
    /// irreversible. Exits 1 when a topic is held by another agent or a
    /// token is lost.
    Claim {
        #[command(subcommand)]
        cmd: ClaimCmd,
        #[command(flatten)]
        who: AsArgs,
        /// The brain's path. Left out, this project's brain.
        #[arg(
            long,
            global = true,
            value_name = "PATH",
            default_value = "",
            hide_default_value = true
        )]
        brain: String,
        #[arg(long, global = true)]
        passphrase: Option<String>,
    },
    /// 13a: show, set or clear the agent a write that names none is made
    /// for (the manifest's `_mnemo.default_agent`). The CLI and the MCP
    /// server use it in place of `default`.
    DefaultAgent {
        /// Path to the `.mnemo` file. Leave it out for this project's brain.
        #[arg(default_value = "", hide_default_value = true)]
        path: String,
        /// The agent id to set (1 to 64 of letters, digits, `.`, `_`, `-`).
        /// Left out, it prints the current one.
        #[arg(long, conflicts_with = "clear")]
        set: Option<String>,
        /// Clear it: writes that name no agent go to `default` again.
        #[arg(long)]
        clear: bool,
        #[arg(long)]
        passphrase: Option<String>,
    },
    /// Browse all live memories.
    List {
        /// Path to the `.mnemo` file. Leave it out for this project's brain,
        /// `<git-common-dir>/mnemo/project.mnemo` (12.2), found from `-C`,
        /// else `CLAUDE_PROJECT_DIR`, else the working directory.
        #[arg(default_value = "", hide_default_value = true)]
        path: String,
        /// Output format.
        #[arg(long, value_enum, default_value_t = OutputFormat::Table)]
        format: OutputFormat,
        /// Restrict to these memory types (comma-separated:
        /// `episodic,semantic,procedural,working`).
        #[arg(long, value_name = "T[,T...]")]
        r#type: Option<String>,
        /// Restrict to a single agent ID.
        #[arg(long)]
        agent: Option<String>,
        /// Maximum rows to print (default: all).
        #[arg(long)]
        limit: Option<usize>,
        /// Skip this many rows before printing.
        #[arg(long, default_value_t = 0)]
        offset: usize,
        /// 13a: the visibility levels shown: `public`, `team`, `private`,
        /// or `all` (comma-separated; default public and team).
        #[arg(long, value_name = "LEVELS", value_delimiter = ',')]
        visibility: Vec<String>,
        /// Sort order: `created`, `importance`, or `id`.
        #[arg(long, default_value = "created")]
        sort: String,
        /// Include the embedding vector (json/jsonl only).
        #[arg(long)]
        vector: bool,
        /// Unlock with a raw key (32 bytes, or 64 hex digits) instead of a
        /// passphrase.
        #[arg(long, value_name = "PATH", conflicts_with = "passphrase")]
        key_file: Option<String>,
        #[arg(long)]
        passphrase: Option<String>,
    },
    /// Export the live memories as readable plaintext (Markdown or JSON
    /// Lines). Opens the file read-only. Writes to stdout unless `-o` is
    /// given, and warns on stderr that the output isn't encrypted. Vectors
    /// are left out; `--git` makes the output diff-clean (ordered by key,
    /// then id; no thread turns and no access stats).
    Export {
        /// Path to the `.mnemo` file. Leave it out for this project's brain,
        /// `<git-common-dir>/mnemo/project.mnemo` (12.2), found from `-C`,
        /// else `CLAUDE_PROJECT_DIR`, else the working directory.
        #[arg(default_value = "", hide_default_value = true)]
        path: String,
        /// Output format.
        #[arg(long, value_enum, default_value_t = export::ExportFormat::Markdown)]
        format: export::ExportFormat,
        /// Restrict to these memory types (comma-separated:
        /// `episodic,semantic,procedural,working`).
        #[arg(long, value_name = "T[,T...]")]
        r#type: Option<String>,
        /// Restrict to a single agent ID.
        #[arg(long)]
        agent: Option<String>,
        /// Deterministic, diff-clean output for version control: the same
        /// unchanged file always exports to the same bytes.
        #[arg(long)]
        git: bool,
        /// 13a: `all` includes private records (a stderr line says so);
        /// `--git` never does. Default public and team.
        #[arg(long, value_name = "LEVELS", value_delimiter = ',')]
        visibility: Vec<String>,
        /// Write to this file instead of stdout. It's replaced whole (a new
        /// file renamed over it), and owner-only on Unix even if it existed
        /// with a wider mode.
        #[arg(long, short = 'o')]
        output: Option<String>,
        /// Unlock with a raw key (32 bytes, or 64 hex digits) instead of a
        /// passphrase.
        #[arg(long, value_name = "PATH", conflicts_with = "passphrase")]
        key_file: Option<String>,
        #[arg(long)]
        passphrase: Option<String>,
    },
    /// Browse the file in a local, read-only web view.
    ///
    /// Reads the file once (read-only) and closes it, so a writer is never
    /// blocked; "Reload" in the page reads it again. Serves on 127.0.0.1
    /// only, at a URL carrying a random token, and only GET: nothing in the
    /// view can change the file. Press Ctrl-C to stop.
    Inspect {
        /// Path to the `.mnemo` file. Leave it out for this project's brain,
        /// `<git-common-dir>/mnemo/project.mnemo` (12.2), found from `-C`,
        /// else `CLAUDE_PROJECT_DIR`, else the working directory.
        #[arg(default_value = "", hide_default_value = true)]
        path: String,
        /// Port on 127.0.0.1 (default: a random free one).
        #[arg(long)]
        port: Option<u16>,
        /// Open the page in the default browser. The browser gets a
        /// private local page that forwards to the URL (deleted once it has
        /// loaded), not the URL itself. On Linux, a browser installed as a
        /// snap or a flatpak (Ubuntu's default Firefox is a snap) has its
        /// own private /tmp and can't read that page: copy the printed link
        /// instead.
        #[arg(long)]
        open: bool,
        /// Stop after this long without a request from the page: `30m`,
        /// `90s`, `1h`, or `0` for never. The server then wipes the secret
        /// and exits.
        #[arg(long, default_value = "30m", value_name = "DURATION")]
        idle_timeout: String,
        /// Unlock with a raw key (32 bytes, or 64 hex digits) instead of a
        /// passphrase.
        #[arg(long, value_name = "PATH", conflicts_with = "passphrase")]
        key_file: Option<String>,
        #[arg(long)]
        passphrase: Option<String>,
    },
    /// Multi-signal ranked retrieval (similarity + recency + importance + frequency).
    ///
    /// Unlike `search`, recall blends four signals, honours type and agent
    /// filters, uses the ANN index if one has been built, and updates the
    /// returned memories' access stats (persisted on the next `flush`).
    Recall {
        /// Path to the `.mnemo` file. Leave it out for this project's brain,
        /// `<git-common-dir>/mnemo/project.mnemo` (12.2), found from `-C`,
        /// else `CLAUDE_PROJECT_DIR`, else the working directory.
        #[arg(default_value = "", hide_default_value = true)]
        path: String,
        /// Query vector as comma-separated floats. Mutually exclusive with
        /// `--query-file` and `--text`. Must match the DB's dimensionality.
        #[arg(long, conflicts_with_all = ["query_file", "text"])]
        query: Option<String>,
        /// Path to a file containing the query vector (`-` for stdin).
        /// Accepts a JSON array, comma-separated floats, or one float
        /// per line. Mutually exclusive with `--query` and `--text`.
        #[arg(long, conflicts_with_all = ["query", "text"])]
        query_file: Option<String>,
        /// Query text to embed via `--embed-cmd` and `--embed-name`
        /// (Phase 3). Without an embedder, a v9 file matches it by keyword
        /// instead (keyword-only recall); a v8 file needs the embedder.
        /// Mutually exclusive with `--query`/`--query-file`.
        #[arg(long, conflicts_with_all = ["query", "query_file"])]
        text: Option<String>,
        /// FMT-9d (v9 files): identifiers or exact terms to match (a
        /// version, a PR number, a function name). Added to vector recall
        /// as a BM25 term (hybrid recall); on its own it is keyword-only
        /// recall. Since v0.15 `--text` is matched by keyword too, so give
        /// this only for identifiers the text doesn't contain; it replaces
        /// the text for the keyword score.
        #[arg(long)]
        keywords: Option<String>,
        /// 12.3 step 4: don't match `--text` by keyword (vector-only
        /// recall). Same as `--keywords ""`.
        #[arg(long, conflicts_with = "keywords")]
        no_keywords: bool,
        #[arg(long, default_value_t = 10)]
        top_k: usize,
        /// 13a: the visibility levels shown: `public`, `team`, `private`,
        /// or `all` (comma-separated; default public and team).
        #[arg(long, value_name = "LEVELS", value_delimiter = ',')]
        visibility: Vec<String>,
        /// Output format.
        #[arg(long, value_enum, default_value_t = OutputFormat::Table)]
        format: OutputFormat,
        /// Restrict to these memory types (comma-separated:
        /// `episodic,semantic,procedural,working`).
        #[arg(long, value_name = "T[,T...]")]
        r#type: Option<String>,
        /// Restrict to one agent's view (their private memories + shared).
        #[arg(long)]
        agent: Option<String>,
        /// Similarity metric: `cosine` (default), `l2`, or `dot`.
        #[arg(long, default_value = "cosine")]
        metric: String,
        /// Override IVF partitions probed (ignored without an index).
        #[arg(long)]
        n_probe: Option<usize>,
        /// Override candidates reranked exactly (ignored without an index).
        #[arg(long)]
        n_rerank: Option<usize>,
        /// Skip access-tracking (does not bump `accessed_at` /
        /// `access_count`). Opens the file with a shared OS lock so the
        /// command can run alongside a writer holding the exclusive lock.
        #[arg(long)]
        no_track: bool,
        /// Phase 12.6: restrict recall to this session_id.
        #[arg(long)]
        session: Option<String>,
        /// Phase 12.6: repeatable metadata filter, applied before
        /// scoring. Shorthand forms, matched left-to-right:
        ///
        /// * `key=value`           — metadata[key] equals value
        /// * `key:exists`          — metadata[key] is present
        /// * `key:in=a,b,c`        — metadata[key] is one of the comma-split values
        /// * `key:gte=NUM` / `key:lte=NUM` — numeric lower / upper bound
        ///
        /// Values are parsed as JSON when the leading char is one of
        /// `[`, `{`, `"`, `-`, `0..9`, `t`, `f`, or `n` (true / false /
        /// null); otherwise treated as a string. Multiple `--filter`s
        /// AND together. For complex / nested filters, use the Python
        /// or MCP APIs.
        #[arg(long = "filter", value_name = "EXPR")]
        filter: Vec<String>,
        /// Phase 12.8: cap the total UTF-8 bytes of returned `content`
        /// fields. Stops adding hits once the running sum would exceed
        /// this many bytes. The top-1 hit is always returned, even if
        /// it alone is over budget. A trailing "(truncated: N hits
        /// dropped by --max-bytes)" line goes to stderr whenever the
        /// budget cuts something. Roughly 4 bytes per token for
        /// English text.
        #[arg(long)]
        max_bytes: Option<usize>,
        /// Embedder command for `--text` (same contract as
        /// `mnemo remember --embed-cmd`). Ignored when `--query` /
        /// `--query-file` is used.
        #[arg(long, requires = "text")]
        embed_cmd: Option<String>,
        /// Embedder identity for `--text`; must match the manifest.
        #[arg(long, requires = "text")]
        embed_name: Option<String>,
        /// Whether the embedder returns unit-normalized vectors.
        #[arg(long, default_value_t = true, action = clap::ArgAction::Set)]
        embed_normalize: bool,
        /// 12.3 step 4: the embedder embeds queries differently from
        /// documents, under this convention name (recorded in the file's
        /// embedder identity, which must match). The command then gets each
        /// request as `{"kind":"query"|"document","text":…}` instead of a
        /// JSON string.
        #[arg(long, requires = "embed_cmd")]
        embed_query: Option<String>,
        /// Per-request timeout for the embedder (seconds; default 60).
        #[arg(long, default_value_t = 60)]
        embed_timeout: u64,
        /// Unlock with a raw key (32 bytes, or 64 hex digits) instead of a
        /// passphrase.
        #[arg(long, value_name = "PATH", conflicts_with = "passphrase")]
        key_file: Option<String>,
        #[arg(long)]
        passphrase: Option<String>,
    },
    /// Create a small database and exercise the full lifecycle.
    Demo {
        /// Where to write the demo database.
        #[arg(long, default_value = "demo.mnemo")]
        path: String,
    },
    /// Edit a memory in place (Phase 12.1). Keeps the ULID, `created_at`
    /// and access stats; any of `--text`, `--importance`, `--metadata`,
    /// `--ttl-secs` may change. `--text` re-embeds through the registered
    /// embedder (`--embed-cmd` + `--embed-name` required). An identical
    /// patch is a no-op and prints `unchanged`.
    Update {
        /// Path to the `.mnemo` file, then the memory's ULID. With one
        /// argument it's the ULID, and the brain is this project's (v0.17).
        #[arg(value_name = "PATH")]
        path: String,
        /// ULID of the memory to update (when PATH is given).
        #[arg(value_name = "ID")]
        id: Option<String>,
        /// New content text; re-embeds through the built-in embedder, or
        /// the one `--embed-cmd` + `--embed-name` give.
        #[arg(long)]
        text: Option<String>,
        #[command(flatten)]
        fresh: FreshArgs,
        /// New importance in `[0, 1]`.
        #[arg(long)]
        importance: Option<f32>,
        /// Replace user-visible metadata with this JSON object. Reserved
        /// `_mnemo.*` keys on the record are preserved. Pass `{}` to
        /// clear user metadata.
        #[arg(long)]
        metadata: Option<String>,
        /// Set the TTL (seconds). Pass `--clear-ttl` to drop any
        /// existing TTL instead.
        #[arg(long, conflicts_with = "clear_ttl")]
        ttl_secs: Option<i64>,
        /// Clear any TTL on this memory.
        #[arg(long)]
        clear_ttl: bool,
        /// Embedder command for `--text` (same contract as
        /// `mnemo remember --embed-cmd`).
        #[arg(long, requires = "text")]
        embed_cmd: Option<String>,
        /// Embedder identity for `--text`; must match the manifest.
        #[arg(long, requires = "text")]
        embed_name: Option<String>,
        /// Whether the embedder returns unit-normalized vectors.
        #[arg(long, default_value_t = true, action = clap::ArgAction::Set)]
        embed_normalize: bool,
        /// 12.3 step 4: the embedder embeds queries differently from
        /// documents, under this convention name (recorded in the file's
        /// embedder identity, which must match). The command then gets each
        /// request as `{"kind":"query"|"document","text":…}` instead of a
        /// JSON string.
        #[arg(long, requires = "embed_cmd")]
        embed_query: Option<String>,
        /// Per-request embedder timeout in seconds.
        #[arg(long, default_value_t = 60)]
        embed_timeout: u64,
        #[arg(long)]
        passphrase: Option<String>,
    },
    /// Walk the full chain for a keyed slot (Phase 12.1), newest first.
    /// Entry 0 is the live record (or empty if the slot is empty);
    /// subsequent entries are the superseded history. Slot resolution
    /// matches `mnemo remember --key`: without `--agent` or `--shared`,
    /// walks the default agent's private slot (v0.8.1 bugfix); pass
    /// `--shared` for the shared slot.
    History {
        /// Path to the `.mnemo` file. Leave it out for this project's brain,
        /// `<git-common-dir>/mnemo/project.mnemo` (12.2), found from `-C`,
        /// else `CLAUDE_PROJECT_DIR`, else the working directory.
        #[arg(default_value = "", hide_default_value = true)]
        path: String,
        /// Keyed slot name (passed to `mnemo remember --key` /
        /// `remember_keyed`).
        #[arg(long)]
        key: String,
        /// Query the private slot for this agent. Omit for the default
        /// agent's private slot (pre-v0.8.1 this flag was required for
        /// a working chain; it's now optional).
        #[arg(long, conflicts_with = "shared")]
        agent: Option<String>,
        /// Query the shared slot (one per file across every agent)
        /// instead of a private slot. Mutually exclusive with `--agent`.
        #[arg(long, conflicts_with = "agent")]
        shared: bool,
        /// Output format.
        #[arg(long, value_enum, default_value_t = OutputFormat::Table)]
        format: OutputFormat,
        /// 13a: the visibility levels shown: `public`, `team`, `private`,
        /// or `all` (comma-separated; default public and team).
        #[arg(long, value_name = "LEVELS", value_delimiter = ',')]
        visibility: Vec<String>,
        #[arg(long)]
        passphrase: Option<String>,
    },
    /// Phase 12.7a thread archive: ingest a transcript into a
    /// thread's archive layer, export it back, or forget it. The
    /// archive is encrypted at rest like any record; `thread forget`
    /// soft-deletes (compact to reclaim space permanently).
    Thread {
        #[command(subcommand)]
        cmd: ThreadCmd,
    },
    /// Phase 12.7b essence (timeline + sections). `render` is the
    /// default subcommand. Section ops take `--section <name>` from
    /// {intent, conventions, decisions, state, open, next, lessons};
    /// timeline entries use `append`.
    Essence {
        #[command(subcommand)]
        cmd: EssenceCmd,
    },
    /// List the restorable snapshots (one per committed flush).
    Snapshots {
        /// Path to the `.mnemo` file. Leave it out for this project's brain
        /// (v0.16.1).
        #[arg(default_value = "", hide_default_value = true)]
        path: String,
        #[arg(long)]
        passphrase: Option<String>,
    },
    /// Restore the database to a past snapshot (point-in-time recovery).
    Restore {
        /// Path to the `.mnemo` file.
        path: String,
        /// Restore to this transaction id (see `snapshots`).
        #[arg(long, conflicts_with = "to_time")]
        to_txn: Option<u64>,
        /// Restore to the latest snapshot at or before this unix timestamp.
        #[arg(long)]
        to_time: Option<i64>,
        #[arg(long)]
        passphrase: Option<String>,
    },
    /// Set up this project's memory for Claude Code and Cursor (12.2), and
    /// print the guide. Safe to run again.
    ///
    /// In a git repository, it finds or creates the project brain
    /// (`.git/mnemo/project.mnemo`) with a generated key kept in the
    /// keychain, installs the built-in model, and wires each client: the MCP
    /// server, the hooks that load and save memory, and a skill or rule
    /// file with the guide's card. It shows the plan first and asks once;
    /// `--yes` writes without asking, `--print` only shows. With no
    /// terminal and no `--yes` it writes nothing and exits 3. `--undo`
    /// removes what it wrote, never the brain, its key or the model.
    /// `--guide` prints only the guide, which is built into this binary.
    Onboard {
        /// Print only the guide, and touch nothing.
        #[arg(long)]
        guide: bool,
        /// The clients to wire (comma-separated); by default, those found.
        #[arg(long, value_enum, value_delimiter = ',')]
        client: Vec<hook::Client>,
        /// `local` (this user only; the default) or `project` (committed
        /// files, for a team where everyone runs onboard).
        #[arg(long, value_enum, default_value = "local")]
        scope: onboard::Scope,
        /// The SessionStart hook's most bytes of context (written into its
        /// command as `--budget`; at most 9,000).
        #[arg(long, value_name = "BYTES")]
        hook_budget: Option<usize>,
        /// Write without asking.
        #[arg(long, conflicts_with = "print")]
        yes: bool,
        /// Show the plan, and write nothing.
        #[arg(long)]
        print: bool,
        /// Don't install the built-in model (recall is keyword-only, and the
        /// hooks save nothing, until `mnemo embedder install`).
        #[arg(long)]
        no_model: bool,
        /// Remove what onboard wrote (never the brain, its key or the model).
        #[arg(long)]
        undo: bool,
        /// 13a: `stop` writes the Stop continuation (an agent finishing a
        /// turn is kept going for a pre-approved task or a message to it by
        /// id; off by default); `off` removes it. Left out, a re-run keeps
        /// what an earlier one chose.
        #[arg(long, value_enum)]
        wake: Option<onboard::Wake>,
        /// Install the Claude Code plugin instead of writing the hooks and
        /// the skill (from your own terminal: Claude Code ignores `-y` when
        /// an agent runs it).
        #[arg(long)]
        plugin: bool,
        /// The guide's format: `markdown`; `llms-txt`, the site's `llms.txt`
        /// (the card and links, in the llms.txt shape); or `llms-full`, the
        /// site's `llms-full.txt` (the whole guide).
        #[arg(long, value_enum, default_value = "markdown", requires = "guide")]
        format: GuideFormat,
    },
    /// The hooks `mnemo onboard` installs for Claude Code and Cursor (12.2).
    ///
    /// Reads the client's hook JSON on stdin. `session-start` adds the
    /// guide's card, the project's notes and essence, and a short recall to
    /// the agent's context; `pre-compact` and `session-end` save the
    /// transcript into the session's thread, without tool output and with
    /// known secret shapes redacted. It always exits 0, never prompts and
    /// never downloads: a problem is a one-line note.
    Hook {
        /// The event.
        #[arg(value_enum)]
        event: hook::Event,
        /// The client that runs it (its input and output shapes).
        #[arg(long, value_enum)]
        client: hook::Client,
        /// `session-start`'s most bytes of context (default 8,000, at most
        /// 9,000; the card always fits).
        #[arg(long)]
        budget: Option<usize>,
    },
    /// MCP clients: `mcp install` adds this brain's server to one.
    Mcp {
        #[command(subcommand)]
        cmd: McpCmd,
    },
    /// Serve the `.mnemo` file as a Model Context Protocol server. Reads
    /// JSON-RPC 2.0 requests line-by-line from stdin, writes responses
    /// to stdout, and logs diagnostics to stderr. The secret comes from
    /// the key sources (`MNEMO_PASSPHRASE`, `MNEMO_KEY`, `MNEMO_KEY_FILE`,
    /// `MNEMO_KEY_COMMAND`, or the keychain); there's no flag for it, which
    /// would leak into shell history and process listings, and no prompt.
    /// A relative path is resolved against `CLAUDE_PROJECT_DIR` when Claude
    /// Code sets it, else against the working directory; a missing brain is
    /// an error, never a new one.
    Serve {
        /// Path to the `.mnemo` file. Leave it out for this project's brain,
        /// `<git-common-dir>/mnemo/project.mnemo` (12.2), found from `-C`,
        /// else `CLAUDE_PROJECT_DIR`, else the working directory.
        #[arg(default_value = "", hide_default_value = true)]
        path: String,
        /// Speak the Model Context Protocol (stdio transport). Required
        /// today — the flag exists so future transports (HTTP, SSE, ...)
        /// can co-opt `serve` without breaking scripts.
        #[arg(long)]
        mcp: bool,
        /// Embedder command. When set, the MCP `remember`/`recall`/
        /// `cache_put_semantic`/`cache_get_semantic` tools accept a
        /// `text` param in addition to `vector`; the embedder is
        /// started once at serve start and reused for every call.
        /// Same contract as `mnemo remember --embed-cmd`.
        #[arg(long, requires = "embed_name")]
        embed_cmd: Option<String>,
        /// Embedder identity (recorded on the scaffold manifest).
        #[arg(long, requires = "embed_cmd")]
        embed_name: Option<String>,
        /// Whether the embedder returns unit-normalized vectors.
        #[arg(long, default_value_t = true, action = clap::ArgAction::Set)]
        embed_normalize: bool,
        /// 12.3 step 4: the embedder embeds queries differently from
        /// documents, under this convention name (recorded in the file's
        /// embedder identity, which must match). The command then gets each
        /// request as `{"kind":"query"|"document","text":…}` instead of a
        /// JSON string.
        #[arg(long, requires = "embed_cmd")]
        embed_query: Option<String>,
        /// Per-request timeout for the embedder (seconds; default 60).
        /// Prevents a stuck child from freezing the MCP agent.
        #[arg(long, default_value_t = 60)]
        embed_timeout: u64,
        /// 12.4 shared mode: hold no lock between tool calls, so other
        /// servers, the CLI and Python can use the file meanwhile; each tool
        /// call takes the lock for itself, waiting up to `--wait`. Off by
        /// default: without it the server holds the file for its whole life,
        /// as before.
        #[arg(long)]
        shared: bool,
        /// With `--shared`: use shared mode on a network or synced folder
        /// anyway, where the lock may not reach every process.
        #[arg(long, requires = "shared")]
        allow_network_fs: bool,
    },
    /// 12.3 step 5: the built-in embedder (snowflake-arctic-embed-xs on
    /// candle). Its model is fetched once into the cache directory, on first
    /// use or with `mnemo embedder install`.
    Embedder {
        #[command(subcommand)]
        cmd: EmbedderCmd,
    },
    /// Result-cache management (Phase 10.1). One `.mnemo` file is
    /// both an agent-memory store AND a durable key/value cache;
    /// these commands manipulate the cache side.
    Cache {
        #[command(subcommand)]
        op: CacheOp,
    },
}

/// 13a (13.1b): `mnemo wake`.
#[derive(Subcommand)]
enum WakeCmd {
    /// Pause wake-ups for every session of this brain.
    Pause,
    /// Resume them.
    Resume,
    /// Whether they're paused, whether `MNEMO_WAKE` turns them off here, and
    /// the `crossSessionInbound` settings found.
    Status,
}

/// 13a: the `crossSessionInbound` values in Claude Code's settings files
/// (the user's and this project's), as `(file, value)`.
fn cross_session_inbound(dir: &std::path::Path) -> Vec<(String, String)> {
    fn find(v: &serde_json::Value) -> Option<String> {
        match v {
            serde_json::Value::Object(o) => o
                .get("crossSessionInbound")
                .and_then(|x| x.as_str().map(str::to_string))
                .or_else(|| o.values().find_map(find)),
            _ => None,
        }
    }
    let mut files = Vec::new();
    if let Some(h) = std::env::var_os("HOME") {
        files.push(std::path::PathBuf::from(h).join(".claude/settings.json"));
    }
    files.push(dir.join(".claude/settings.json"));
    files.push(dir.join(".claude/settings.local.json"));
    files
        .into_iter()
        .filter_map(|f| {
            let text = std::fs::read_to_string(&f).ok()?;
            let v: serde_json::Value = serde_json::from_str(&text).ok()?;
            Some((f.display().to_string(), find(&v)?))
        })
        .collect()
}

/// 13a (13.1): `mnemo task`.
#[derive(Subcommand)]
enum TaskCmd {
    /// Queue a task. Prints its slug and whether it was added, updated
    /// (the slug existed) or unchanged.
    Add {
        /// One line.
        title: String,
        #[arg(long, default_value = "")]
        body: String,
        /// The role that may take it (default: any).
        #[arg(long = "for", value_name = "ROLE")]
        for_role: Option<String>,
        /// Slugs it waits for (comma-separated).
        #[arg(long, value_delimiter = ',')]
        after: Vec<String>,
        /// Its owner may set `done` without you.
        #[arg(long)]
        pre_approved: bool,
        /// Its name (else made from the title).
        #[arg(long)]
        slug: Option<String>,
    },
    /// Take the next task for your role (`--role`, else `MNEMO_ROLE`).
    /// Prints its slug, the claim token, the expiry and the title; exits 1
    /// when there's nothing to take.
    Next,
    /// Move your task along (`--status ready|blocked|queued|active|done`)
    /// or add a `--note`. Exits 1 with `lost` when another agent took it
    /// back.
    Update {
        slug: String,
        #[arg(long)]
        status: Option<String>,
        #[arg(long)]
        note: Option<String>,
        /// The claim token `next` printed, for the strict check.
        #[arg(long)]
        token: Option<String>,
    },
    /// The tasks, oldest first.
    List {
        #[arg(long)]
        status: Option<String>,
        /// Only those this role may take.
        #[arg(long = "for", value_name = "ROLE")]
        for_role: Option<String>,
        #[arg(long, value_enum, default_value_t = OutputFormat::Table)]
        format: OutputFormat,
    },
    /// One task, with its history.
    Get {
        slug: String,
        #[arg(long, value_enum, default_value_t = OutputFormat::Table)]
        format: OutputFormat,
    },
}

/// 13a (13.3): `mnemo claim`.
#[derive(Subcommand)]
enum ClaimCmd {
    /// Claim a topic for `--ttl` (default 15m; 30s to 24h). Prints
    /// `claimed`, the token and the expiry.
    Take {
        /// What you claim (one line).
        topic: String,
        /// The lease: seconds, or `90s`, `15m`, `2h`.
        #[arg(long)]
        ttl: Option<String>,
    },
    /// Renew your claim from now, for `--ttl` or its lease.
    Renew {
        topic: String,
        token: String,
        #[arg(long)]
        ttl: Option<String>,
    },
    /// Release your claim.
    Release { topic: String, token: String },
    /// Whether your token still holds the topic (exit 1 when it's lost).
    Check { topic: String, token: String },
    /// The agents: role, tool, last active, whether their process is alive
    /// (`unknown` without a long-lived one), and what they hold.
    Who {
        #[arg(long, value_enum, default_value_t = OutputFormat::Table)]
        format: OutputFormat,
    },
}

/// Subcommands under `mnemo thread` (Phase 12.7a archive layer).
#[derive(Subcommand)]
enum EmbedderCmd {
    /// Download the built-in embedder's model (91.0 MB) into the cache
    /// directory, checking each file's SHA-256. Prints the size first, and
    /// fetches nothing when the model is already there.
    Install,
    /// Show the built-in embedder's model, its identity, and whether it's
    /// installed (or, with `--model-dir`, what that directory holds).
    Status,
}

/// `thread ingest --tool-results`.
#[derive(Clone, Copy, Debug, PartialEq, Eq, ValueEnum)]
enum ToolResultsArg {
    /// Keep each tool result's body.
    Full,
    /// Keep only `[tool_result ok|error, N bytes]`.
    Omit,
}

impl From<ToolResultsArg> for mnemo_engine::ToolResults {
    fn from(t: ToolResultsArg) -> Self {
        match t {
            ToolResultsArg::Full => mnemo_engine::ToolResults::Full,
            ToolResultsArg::Omit => mnemo_engine::ToolResults::Omit,
        }
    }
}

/// `onboard --guide`'s formats.
#[derive(Clone, Copy, Debug, PartialEq, Eq, ValueEnum)]
enum GuideFormat {
    /// The guide as Markdown.
    Markdown,
    /// The guide's card and links in the llms.txt shape
    /// (<https://llmstxt.org/>), as the site's `llms.txt`.
    LlmsTxt,
    /// The whole guide, as the site's `llms-full.txt`.
    LlmsFull,
    /// The Claude Code plugin's skill
    /// (`integrations/claude-code/skills/mnemo/SKILL.md`).
    #[value(hide = true)]
    PluginSkill,
}

#[derive(Subcommand)]
enum McpCmd {
    /// Add this brain's MCP server to a client's config (12.3).
    ///
    /// It writes `serve --mcp --shared <file>`, never a secret. In a project
    /// scope (a file that's committed) it writes `mnemo` from the PATH and a
    /// path relative to the project root, never an absolute path or a
    /// command. It shows a diff first (environment values masked) and asks,
    /// unless `--yes`; `--print` shows it and writes nothing. Clients:
    /// claude-code (through `claude mcp add-json` when `claude` is on the
    /// PATH, else `.mcp.json`), cursor, claude-desktop.
    Install {
        /// The client.
        #[arg(long, value_enum)]
        client: mcp_install::Client,
        /// Where: `project` (the default inside a git work tree), `local`
        /// (Claude Code only) or `user` (the default elsewhere).
        #[arg(long, value_enum)]
        scope: Option<mcp_install::Scope>,
        /// The server's name in the client.
        #[arg(long, default_value = "mnemo")]
        name: String,
        /// Show what would be written, and write nothing.
        #[arg(long)]
        print: bool,
        /// Write without asking.
        #[arg(long, conflicts_with = "print")]
        yes: bool,
        /// Path to the `.mnemo` file. Leave it out for this project's brain,
        /// `<git-common-dir>/mnemo/project.mnemo` (12.2), found from `-C`,
        /// else `CLAUDE_PROJECT_DIR`, else the working directory.
        #[arg(default_value = "", hide_default_value = true)]
        path: String,
    },
}

#[derive(Subcommand)]
enum ThreadCmd {
    /// Ingest a transcript file into a thread's archive. Idempotent
    /// by per-turn `turn_id`: running it again on a longer transcript
    /// appends only the new turns. It batch-embeds every turn, with the
    /// built-in embedder or `--embed-cmd` + `--embed-name`.
    Ingest {
        /// Path to the `.mnemo` file. Leave it out for this project's brain,
        /// `<git-common-dir>/mnemo/project.mnemo` (12.2), found from `-C`,
        /// else `CLAUDE_PROJECT_DIR`, else the working directory.
        #[arg(default_value = "", hide_default_value = true)]
        path: String,
        /// Thread id to append under. New if no prior ingest used it.
        #[arg(long)]
        thread: String,
        /// Transcript file (one JSON object per line). `-` reads stdin.
        #[arg(long)]
        transcript: String,
        /// Transcript format: `jsonl` (the generic shape) or
        /// `claude-code-jsonl` (`~/.claude/projects/<p>/<s>.jsonl`).
        #[arg(long, default_value = "jsonl")]
        format: String,
        /// 12.2: what a `claude-code-jsonl` transcript's tool results keep:
        /// `full` (the body) or `omit` (a `[tool_result ok|error, N bytes]`
        /// marker). The hooks use `omit`.
        #[arg(long, value_enum, default_value = "full")]
        tool_results: ToolResultsArg,
        /// 12.2: replace known secret shapes (private keys, cloud and API
        /// tokens, JWTs, recovery codes, secret-looking `NAME=value`s) with
        /// `[redacted: <kind>]` before storing. A best effort. The hooks
        /// always use it.
        #[arg(long)]
        redact: bool,
        /// Embedder command (same contract as `mnemo remember --embed-cmd`),
        /// in place of the built-in embedder.
        #[arg(long, requires = "embed_name")]
        embed_cmd: Option<String>,
        /// Embedder identity recorded on the scaffold manifest (with
        /// `--embed-cmd`).
        #[arg(long, requires = "embed_cmd")]
        embed_name: Option<String>,
        /// Whether the embedder returns unit-normalized vectors.
        #[arg(long, default_value_t = true, action = clap::ArgAction::Set)]
        embed_normalize: bool,
        /// 12.3 step 4: the embedder embeds queries differently from
        /// documents, under this convention name (recorded in the file's
        /// embedder identity, which must match). The command then gets each
        /// request as `{"kind":"query"|"document","text":…}` instead of a
        /// JSON string.
        #[arg(long)]
        embed_query: Option<String>,
        /// Per-request embedder timeout in seconds.
        #[arg(long, default_value_t = 60)]
        embed_timeout: u64,
        #[arg(long)]
        passphrase: Option<String>,
    },
    /// Export a thread's archive back to a JSON-lines transcript. The
    /// output shape matches the generic `--format jsonl` input, so a
    /// round trip (ingest → export) is byte-equal for turns that
    /// weren't truncated or chunked.
    Export {
        /// Path to the `.mnemo` file. Leave it out for this project's brain,
        /// `<git-common-dir>/mnemo/project.mnemo` (12.2), found from `-C`,
        /// else `CLAUDE_PROJECT_DIR`, else the working directory.
        #[arg(default_value = "", hide_default_value = true)]
        path: String,
        /// Thread id to export.
        #[arg(long)]
        thread: String,
        /// Output file. Default: stdout.
        #[arg(long, short = 'o')]
        output: Option<String>,
        #[arg(long)]
        passphrase: Option<String>,
    },
    /// Soft-delete every record in a thread's archive. Compact later
    /// to reclaim space permanently.
    Forget {
        /// Path to the `.mnemo` file. Leave it out for this project's brain,
        /// `<git-common-dir>/mnemo/project.mnemo` (12.2), found from `-C`,
        /// else `CLAUDE_PROJECT_DIR`, else the working directory.
        #[arg(default_value = "", hide_default_value = true)]
        path: String,
        /// Thread id to forget.
        #[arg(long)]
        thread: String,
        #[arg(long)]
        passphrase: Option<String>,
    },
    /// Phase 12.7c: start a new thread that continues from a previous
    /// one. Writes a link record (`_mnemo.continues`); `mnemo essence
    /// --thread <new>` then pulls the prior thread's open items,
    /// `next` and last-N timeline entries ahead of its own essence.
    Start {
        /// Path to the `.mnemo` file, then the new thread id. With one
        /// argument it's the thread id, and the brain is this project's
        /// (v0.17).
        #[arg(value_name = "PATH")]
        path: String,
        /// New thread id (when PATH is given).
        #[arg(value_name = "NEW")]
        new: Option<String>,
        /// Previous thread id to continue from.
        #[arg(long)]
        from: String,
        #[arg(long)]
        passphrase: Option<String>,
    },
}

/// Subcommands under `mnemo essence` (Phase 12.7b).
#[derive(Subcommand)]
enum EssenceCmd {
    /// Render the deterministic markdown view of a thread's essence
    /// (or the project layer with `--project`). Prints to stdout.
    Render {
        /// Path to the `.mnemo` file. Leave it out for this project's brain,
        /// `<git-common-dir>/mnemo/project.mnemo` (12.2), found from `-C`,
        /// else `CLAUDE_PROJECT_DIR`, else the working directory.
        #[arg(default_value = "", hide_default_value = true)]
        path: String,
        /// Thread id. Omit with `--project` for the project layer.
        #[arg(long, conflicts_with = "project")]
        thread: Option<String>,
        /// Render the project layer instead of a thread.
        #[arg(long, conflicts_with = "thread")]
        project: bool,
        /// Byte budget for the render (default 6144).
        #[arg(long, default_value_t = 6144)]
        budget: usize,
        #[arg(long)]
        passphrase: Option<String>,
    },
    /// Add a new section item (intent/conventions/decisions/state/
    /// open/next/lessons). Status starts at `open`.
    Add {
        /// Path to the `.mnemo` file. Leave it out for this project's brain,
        /// `<git-common-dir>/mnemo/project.mnemo` (12.2), found from `-C`,
        /// else `CLAUDE_PROJECT_DIR`, else the working directory.
        #[arg(default_value = "", hide_default_value = true)]
        path: String,
        /// Section name.
        #[arg(long)]
        section: String,
        /// Item text (≤ 280 bytes).
        #[arg(long)]
        text: String,
        /// Thread id. Omit with `--project` for the project layer.
        #[arg(long, conflicts_with = "project")]
        thread: Option<String>,
        /// Project-scoped item (every thread's render shows it).
        #[arg(long, conflicts_with = "thread")]
        project: bool,
        /// Optional refs: comma-separated turn ids, memory ids, commits, paths.
        #[arg(long)]
        refs: Option<String>,
        #[arg(long)]
        passphrase: Option<String>,
    },
    /// Append a new timeline entry (append-only, ≤ 600 bytes).
    Append {
        /// Path to the `.mnemo` file. Leave it out for this project's brain,
        /// `<git-common-dir>/mnemo/project.mnemo` (12.2), found from `-C`,
        /// else `CLAUDE_PROJECT_DIR`, else the working directory.
        #[arg(default_value = "", hide_default_value = true)]
        path: String,
        /// Entry text (≤ 600 bytes).
        #[arg(long)]
        text: String,
        /// Thread id. Omit with `--project` for the project-level
        /// timeline (rare — most milestones belong to a thread).
        #[arg(long, conflicts_with = "project")]
        thread: Option<String>,
        #[arg(long, conflicts_with = "thread")]
        project: bool,
        #[arg(long)]
        refs: Option<String>,
        #[arg(long)]
        passphrase: Option<String>,
    },
    /// Update an existing section item's text in place.
    Update {
        /// Path to the `.mnemo` file, then the item's ULID. With one
        /// argument it's the ULID, and the brain is this project's (v0.17).
        #[arg(value_name = "PATH")]
        path: String,
        /// ULID of the section item to update (when PATH is given).
        #[arg(value_name = "ID")]
        id: Option<String>,
        /// New text (≤ 280 bytes).
        #[arg(long)]
        text: String,
        /// Optional replacement refs.
        #[arg(long)]
        refs: Option<String>,
        #[arg(long)]
        passphrase: Option<String>,
    },
    /// Mark a section item resolved (`open → resolved`).
    Resolve {
        /// Path to the `.mnemo` file, then the item's ULID. With one
        /// argument it's the ULID, and the brain is this project's (v0.17).
        #[arg(value_name = "PATH")]
        path: String,
        /// ULID of the section item to resolve (when PATH is given).
        #[arg(value_name = "ID")]
        id: Option<String>,
        #[arg(long)]
        passphrase: Option<String>,
    },
    /// Soft-delete a section item. Compact to reclaim space.
    Remove {
        /// Path to the `.mnemo` file, then the item's ULID. With one
        /// argument it's the ULID, and the brain is this project's (v0.17).
        #[arg(value_name = "PATH")]
        path: String,
        /// ULID of the section item to remove (when PATH is given).
        #[arg(value_name = "ID")]
        id: Option<String>,
        #[arg(long)]
        passphrase: Option<String>,
    },
}

/// Subcommands under `mnemo cache`. Each operates on a `--ns` namespace
/// inside the given `.mnemo` file. Passphrase resolves via `--passphrase`
/// or `MNEMO_PASSPHRASE` (same rules as top-level commands).
#[derive(Subcommand)]
enum CacheOp {
    /// Look up a key; prints the value to stdout on hit, non-zero
    /// exit on miss.
    Get {
        /// Path to the `.mnemo` file.
        path: String,
        /// Cache namespace.
        #[arg(long)]
        ns: String,
        /// Cache key (SHA-256 hashed by the engine).
        #[arg(long)]
        key: String,
        #[arg(long)]
        passphrase: Option<String>,
    },
    /// Insert or overwrite an entry. Either `--value <string>` (UTF-8)
    /// or `--file <path>` (raw bytes) must be provided.
    Put {
        /// Path to the `.mnemo` file.
        path: String,
        #[arg(long)]
        ns: String,
        #[arg(long)]
        key: String,
        /// Inline UTF-8 value. Mutually exclusive with `--file`.
        #[arg(long, conflicts_with = "file")]
        value: Option<String>,
        /// Path to a file whose bytes become the value. Mutually
        /// exclusive with `--value`.
        #[arg(long, conflicts_with = "value")]
        file: Option<String>,
        /// Free-form content-type label recorded on the entry.
        #[arg(long, default_value = "text")]
        content_type: String,
        /// TTL in seconds. Omit for no expiry.
        #[arg(long)]
        ttl: Option<u64>,
        #[arg(long)]
        passphrase: Option<String>,
    },
    /// Tombstone an entry. Space reclaimed by `mnemo compact`.
    Delete {
        /// Path to the `.mnemo` file.
        path: String,
        #[arg(long)]
        ns: String,
        #[arg(long)]
        key: String,
        #[arg(long)]
        passphrase: Option<String>,
    },
    /// Print cache statistics as JSON. `--ns` restricts to one
    /// namespace; without it the whole cache is summarized.
    Stats {
        /// Path to the `.mnemo` file.
        path: String,
        #[arg(long)]
        ns: Option<String>,
        #[arg(long)]
        passphrase: Option<String>,
    },
    /// Tombstone entries in bulk. `--ns` restricts to one namespace.
    /// `--expired` restricts to TTL-expired entries only; otherwise
    /// every live entry in the scope is tombstoned.
    Purge {
        /// Path to the `.mnemo` file.
        path: String,
        #[arg(long)]
        ns: Option<String>,
        #[arg(long)]
        expired: bool,
        #[arg(long)]
        passphrase: Option<String>,
    },
}

/// Resolve the passphrase from (in priority order) the `--passphrase` flag,
/// the `MNEMO_PASSPHRASE` env var, or an interactive TTY prompt without
/// echo. Non-interactive paths (env var, `--passphrase`) keep working so
/// scripts and CI don't break.
///
/// When `--passphrase` is used the passphrase ends up in shell history and
/// process listings; we warn once to stderr to make that obvious.
/// FMT-9f: the hint `info` and `about` print for a v8 file.
/// TOK-1: what to say about a keyword index that isn't tokenizer 2.
fn tokenizer_note(path: &str, k: mnemo_engine::KeywordTokenizer) -> Option<String> {
    match k {
        mnemo_engine::KeywordTokenizer::V2 => None,
        mnemo_engine::KeywordTokenizer::V1 => Some(format!(
            "keywords match whole words as written; `mnemo compact {path}` rebuilds the \
             index so parts of dotted names and possessives match too"
        )),
        mnemo_engine::KeywordTokenizer::Mixed => Some(format!(
            "a build before v0.15 wrote to the keyword index, so parts of words match only \
             some memories; `mnemo compact {path}` rebuilds it"
        )),
    }
}

fn upgrade_hint(path: &str, format_version: u16) -> Option<String> {
    (format_version < 9).then(|| {
        format!(
            "v{format_version} file: run `mnemo compact {path}` to upgrade to v9 \
             (upgrade every tool that reads it first)"
        )
    })
}

fn passphrase(arg: &Option<String>) -> std::result::Result<String, String> {
    if let Some(p) = arg {
        eprintln!(
            "warning: passing the passphrase as `--passphrase` is insecure; \
             it lands in shell history and process listings. Prefer the \
             MNEMO_PASSPHRASE env var, or omit both to be prompted."
        );
        return Ok(p.clone());
    }
    if let Ok(p) = std::env::var("MNEMO_PASSPHRASE") {
        return Ok(p);
    }
    // No flag, no env var. If stdin is a TTY, prompt without echo. If it
    // isn't (e.g. a CI runner without a real terminal), bail with the
    // historical error message so existing scripts that forgot to set
    // MNEMO_PASSPHRASE get the same diagnostic they used to.
    if !std::io::IsTerminal::is_terminal(&std::io::stdin()) {
        return Err("no passphrase: pass --passphrase or set MNEMO_PASSPHRASE".to_string());
    }
    rpassword::prompt_password("Passphrase: ")
        .map_err(|e| format!("failed to read passphrase: {e}"))
}

/// How long a command waits for the brain's lock (`--wait`, default 10 s).
static WAIT: std::sync::OnceLock<std::time::Duration> = std::sync::OnceLock::new();

/// 12.4: the lock layer's options for this command: `--wait` as the
/// deadline.
fn wait_opts() -> mnemo_engine::SharedOptions {
    let mut o = mnemo_engine::SharedOptions::default();
    if let Some(w) = WAIT.get() {
        o.deadline = *w;
    }
    o
}

/// `--wait`'s value: `10s`, `500ms`, `2m`, or a bare number of seconds.
fn parse_wait(s: &str) -> std::result::Result<std::time::Duration, String> {
    let s = s.trim();
    let (num, unit) = match s.find(|c: char| c.is_ascii_alphabetic()) {
        Some(i) => s.split_at(i),
        None => (s, "s"),
    };
    let n: f64 = num
        .trim()
        .parse()
        .map_err(|_| format!("not a duration: {s:?} (try 10s, 500ms or 2m)"))?;
    let secs = match unit.trim() {
        "ms" => n / 1000.0,
        "s" => n,
        "m" => n * 60.0,
        other => return Err(format!("unknown unit {other:?} in {s:?} (use ms, s or m)")),
    };
    if !secs.is_finite() || secs < 0.0 {
        return Err(format!("not a duration: {s:?}"));
    }
    Ok(std::time::Duration::from_secs_f64(secs.min(1e9)))
}

/// 12.4: a read-only open through the lock layer: it waits up to `--wait`
/// for a writer instead of failing at once, and runs alongside other
/// readers.
fn open_r(path: &str, s: &inspect::Secret) -> mnemo_engine::Result<Mnemo> {
    open_ro(path, s)
}

/// 12.4: a read-write open through the lock layer, for one command's
/// write: it waits up to `--wait` with writer preference, and names `op`
/// to a shared caller that times out meanwhile.
fn open_w(path: &str, s: &inspect::Secret, op: &str) -> mnemo_engine::Result<Mnemo> {
    open_rw(path, s, op)
}

/// A started embedder and the vectors it made.
type Embedded = (Box<dyn mnemo_engine::Embedder>, Vec<Vec<f32>>);

/// 12.4 (slow work first, unlocked): start the embedder and embed `texts`
/// before the brain's lock is taken, so a slow embedder (or the built-in's
/// first download) never keeps other sessions waiting. The identity's width
/// comes from the file's header (no key, no lock); when that can't be read
/// (a torn header), `None`, and the caller embeds after its write open, as
/// before.
fn embed_first(
    path: &str,
    cmd: Option<&str>,
    name: Option<&str>,
    normalize: bool,
    timeout: u64,
    query: &str,
    texts: &[&str],
) -> std::result::Result<Option<Embedded>, String> {
    let Ok(dimensions) = Mnemo::peek_dimensions(path) else {
        return Ok(None);
    };
    let embedder = new_embedder(cmd, name, normalize, timeout, query, Some(dimensions))?;
    let vectors = embedder.embed(texts).map_err(fmt)?;
    Ok(Some((embedder, vectors)))
}

/// 12.3 step 5: the global `--model-dir`.
static MODEL_DIR: std::sync::OnceLock<Option<std::path::PathBuf>> = std::sync::OnceLock::new();

/// The embedder a command uses: the `--embed-cmd` protocol when it's given
/// (with `--embed-name`), otherwise the built-in embedder (12.3 step 5).
/// `dimensions` is the file's width: an `--embed-cmd` identity takes it, and
/// the built-in, whose width is its own, is checked against it. `None`
/// (`reembed` to the built-in) skips that check.
fn new_embedder(
    cmd: Option<&str>,
    name: Option<&str>,
    normalize: bool,
    timeout: u64,
    query: &str,
    dimensions: Option<usize>,
) -> std::result::Result<Box<dyn mnemo_engine::Embedder>, String> {
    let Some(cmd) = cmd else {
        if name.is_some() {
            return Err("--embed-name needs --embed-cmd".into());
        }
        let builtin = builtin_embedder()?;
        if let Some(d) = dimensions {
            let width = builtin.identity().dimensions;
            if d != width {
                return Err(format!(
                    "this file is {d}-dimensional and the built-in embedder is {width}: pass \
                     the file's own embedder (--embed-cmd and --embed-name), or move the file \
                     to the built-in with `mnemo reembed <file> --embed-dims {width}`"
                ));
            }
        }
        return Ok(builtin);
    };
    let name = name.ok_or_else(|| "--embed-cmd needs --embed-name".to_string())?;
    let identity = mnemo_engine::EmbedderIdentity {
        name: name.to_string(),
        dimensions: dimensions.unwrap_or_default(),
        normalize,
        query_convention: query.to_string(),
    };
    Ok(Box::new(
        mnemo_engine::EmbedCmd::new(cmd, identity)
            .map_err(fmt)?
            .with_timeout(std::time::Duration::from_secs(timeout)),
    ))
}

/// 12.3 step 5: the built-in embedder, from `--model-dir`, or from the cache
/// (downloaded on first use, with the size said on stderr first).
#[cfg(feature = "embed-candle")]
fn builtin_embedder() -> std::result::Result<Box<dyn mnemo_engine::Embedder>, String> {
    let e = match MODEL_DIR.get().and_then(Option::as_deref) {
        Some(dir) => mnemo_engine::BuiltinEmbedder::from_dir(dir),
        None => mnemo_engine::BuiltinEmbedder::load_or_install(&mut |m| eprintln!("{m}")),
    }
    .map_err(fmt)?;
    Ok(Box::new(e))
}

/// Without `embed-candle` there's no built-in embedder.
#[cfg(not(feature = "embed-candle"))]
fn builtin_embedder() -> std::result::Result<Box<dyn mnemo_engine::Embedder>, String> {
    Err("this build of mnemo has no built-in embedder: pass --embed-cmd and --embed-name".into())
}

/// 12.3 step 5: `mnemo embedder install` and `mnemo embedder status`.
#[cfg(feature = "embed-candle")]
fn run_embedder(cmd: EmbedderCmd) -> std::result::Result<(), String> {
    use mnemo_engine::builtin;
    use mnemo_engine::Embedder;
    let dir = builtin::model_dir().map_err(fmt)?;
    let size = builtin::human_size(builtin::download_size());
    match cmd {
        EmbedderCmd::Install => {
            if MODEL_DIR.get().is_some_and(Option::is_some) {
                return Err(
                    "--model-dir loads a model of your own; there's nothing to install".into(),
                );
            }
            println!(
                "the built-in embedder: {}@{} ({size}), into {}",
                builtin::MODEL,
                builtin::REVISION,
                dir.display()
            );
            // `install` hashes the files there and replaces any that don't
            // match (RB-010.4 item 2).
            let mut fetched = false;
            builtin::install(&mut |m| {
                fetched = true;
                eprintln!("{m}")
            })
            .map_err(fmt)?;
            builtin::BuiltinEmbedder::load().map_err(fmt)?;
            println!(
                "{}",
                if fetched {
                    "installed"
                } else {
                    "already installed"
                }
            );
        }
        EmbedderCmd::Status => {
            println!("model:      {}", builtin::MODEL);
            println!("revision:   {}", builtin::REVISION);
            match MODEL_DIR.get().and_then(Option::as_deref) {
                Some(d) => {
                    let e = builtin::BuiltinEmbedder::from_dir(d).map_err(fmt)?;
                    println!("model dir:  {} (--model-dir)", d.display());
                    println!(
                        "files:      {}",
                        if e.is_builtin() {
                            "the pinned files (the built-in embedder)"
                        } else {
                            "not the pinned files (an identity of their own)"
                        }
                    );
                    println!("identity:   {}", e.identity().name);
                }
                None => {
                    println!("identity:   {}", builtin::identity().name);
                    println!("cache:      {}", dir.display());
                    // The hashes, not just the sizes (RB-010.4 item 1).
                    println!(
                        "installed:  {}",
                        if !builtin::is_installed() {
                            format!(
                                "no ({size} to fetch on first use, or `mnemo embedder install`)"
                            )
                        } else {
                            match builtin::verify_installed() {
                                Ok(()) => "yes (every file matches its pinned SHA-256)".into(),
                                Err(mnemo_engine::MnemoError::Invalid(why)) => {
                                    format!("no ({why})")
                                }
                                Err(e) => format!("no ({e})"),
                            }
                        }
                    );
                }
            }
        }
    }
    Ok(())
}

/// Without `embed-candle` there's no built-in embedder.
#[cfg(not(feature = "embed-candle"))]
fn run_embedder(_: EmbedderCmd) -> std::result::Result<(), String> {
    Err("this build of mnemo has no built-in embedder (pass --embed-cmd and --embed-name)".into())
}

/// 12.3 step 5: `serve --mcp` with no `--embed-cmd` serves with the
/// built-in embedder, in a build that has it.
fn serve_builtin(
    p: &std::path::Path,
    shared: Option<mnemo_engine::SharedOptions>,
) -> mnemo_engine::Result<()> {
    #[cfg(feature = "embed-candle")]
    {
        let dir = MODEL_DIR.get().and_then(Option::as_deref);
        mnemo_engine::mcp::serve_stdio_with_builtin(p, dir, shared)
    }
    #[cfg(not(feature = "embed-candle"))]
    {
        mnemo_engine::mcp::serve_stdio_with_spec(p, None, shared)
    }
}

/// 12.3 step 5: whether the built-in embedder loads without a download
/// (`--model-dir`, or the model already in the cache).
fn builtin_ready() -> bool {
    #[cfg(feature = "embed-candle")]
    {
        MODEL_DIR.get().is_some_and(Option::is_some) || mnemo_engine::builtin::is_installed()
    }
    #[cfg(not(feature = "embed-candle"))]
    {
        false
    }
}

/// 12.3 step 5: the pinned built-in identity, in a build that has it.
fn builtin_identity() -> Option<mnemo_engine::EmbedderIdentity> {
    #[cfg(feature = "embed-candle")]
    {
        Some(mnemo_engine::builtin::identity())
    }
    #[cfg(not(feature = "embed-candle"))]
    {
        None
    }
}

/// A read-only open with either secret (waiting, as [`open_r`]).
fn open_ro(path: &str, s: &inspect::Secret) -> mnemo_engine::Result<Mnemo> {
    match s {
        inspect::Secret::Passphrase(p) => Mnemo::open_read_only_waiting(path, p, wait_opts()),
        inspect::Secret::Key(k) => Mnemo::open_read_only_waiting_with_key(path, k, wait_opts()),
    }
    .map(warn_notices)
}

/// 12.3: say what the handle has to tell its owner (a passphrase on raw-key
/// KDF parameters), once, on stderr.
fn warn_notices(db: Mnemo) -> Mnemo {
    for n in db.notices() {
        eprintln!("warning: {n}");
    }
    db
}

/// 12.3: where this command's secret came from, and the next source of the
/// same kind that's present, for `info` and for a wrong secret's error.
static SOURCE: std::sync::OnceLock<(String, Option<String>)> = std::sync::OnceLock::new();

/// 12.3 (the keys note, section 6): the secret for the existing brain at
/// `path`. A flag names its source outright. Otherwise the chain picks by
/// the file's kind: `MNEMO_KEY`, `MNEMO_KEY_FILE`, `MNEMO_KEY_COMMAND` or
/// the key store for a key; `MNEMO_PASSPHRASE` or the key store for a
/// passphrase, then the prompt at a terminal.
fn secret_for(
    path: &str,
    pp: &Option<String>,
    key_file: &Option<String>,
) -> std::result::Result<inspect::Secret, String> {
    use mnemo_engine::keys::{self, Resolution, SecretKind};
    if let Some(k) = key_file {
        let _ = SOURCE.set((format!("--key-file ({k})"), None));
        return Ok(inspect::Secret::Key(inspect::read_key_file(k)?));
    }
    if pp.is_some() {
        let _ = SOURCE.set(("--passphrase".into(), None));
        return Ok(inspect::Secret::Passphrase(zeroize::Zeroizing::new(
            passphrase(pp)?,
        )));
    }
    let store = keys::default_store();
    match keys::resolve(path, store.as_deref(), keys::CLI_COMMAND_TIMEOUT).map_err(fmt)? {
        Resolution::Found(r) => {
            for n in &r.notes {
                eprintln!("note: {n}");
            }
            let _ = SOURCE.set((r.source.to_string(), r.next.map(|s| s.to_string())));
            Ok(r.secret)
        }
        Resolution::NoSource { kind, notes } => {
            for n in &notes {
                eprintln!("note: {n}");
            }
            match kind {
                SecretKind::Passphrase => {
                    let p = passphrase(&None)?;
                    let _ = SOURCE.set(("the prompt".into(), None));
                    Ok(inspect::Secret::Passphrase(zeroize::Zeroizing::new(p)))
                }
                SecretKind::Key => Err(format!(
                    "no key for {path}: it uses a key, and none of MNEMO_KEY, MNEMO_KEY_FILE, \
                     MNEMO_KEY_COMMAND or {} has one; pass --key-file, or --passphrase if it \
                     was given a passphrase",
                    store
                        .as_deref()
                        .map(|s| s.describe())
                        .unwrap_or_else(|| "a key store (none in this build yet)".into())
                )),
            }
        }
    }
}

/// A read-write open with either secret (waiting, as [`open_w`]).
fn open_rw(path: &str, s: &inspect::Secret, op: &str) -> mnemo_engine::Result<Mnemo> {
    match s {
        inspect::Secret::Passphrase(p) => Mnemo::open_exclusive(path, p, op, wait_opts()),
        inspect::Secret::Key(k) => Mnemo::open_exclusive_with_key(path, k, op, wait_opts()),
    }
    .map(warn_notices)
    .map(|mut db| {
        // 13a: what this command writes carries its agent's name.
        db.set_author(env_identity().0);
        db
    })
}

/// 13a: this process's agent id and role, from `MNEMO_AGENT` and
/// `MNEMO_ROLE` (each 1 to 64 of letters, digits, `.`, `_`, `-`). One that
/// isn't valid is left out, with a note on stderr the first time.
pub(crate) fn env_identity() -> (Option<String>, Option<String>) {
    static NOTED: std::sync::Once = std::sync::Once::new();
    let read = |name: &str| -> Option<String> {
        let v = std::env::var(name).ok()?;
        let v = v.trim().to_string();
        if v.is_empty() {
            return None;
        }
        if mnemo_engine::valid_agent_id(&v) {
            Some(v)
        } else {
            NOTED.call_once(|| {
                eprintln!(
                    "mnemo: note: {name} isn't 1 to 64 of letters, digits, '.', '_' and '-'; \
                     it's ignored"
                )
            });
            None
        }
    };
    (read("MNEMO_AGENT"), read("MNEMO_ROLE"))
}

/// 13a (R-010.9): who a coordination command runs as. Each falls back to
/// `MNEMO_AGENT` and `MNEMO_ROLE`.
#[derive(clap::Args, Debug, Default)]
struct AsArgs {
    /// The agent you are (default `MNEMO_AGENT`).
    #[arg(long = "as", value_name = "AGENT", global = true)]
    agent: Option<String>,
    /// Your role (default `MNEMO_ROLE`): `inbox` shows what's sent to
    /// `role:<role>`.
    #[arg(long, value_name = "ROLE", global = true)]
    role: Option<String>,
}

impl AsArgs {
    /// RB-013.4: [`AsArgs::resolve`] for a write (`post`, `task add`, the
    /// claim writes): an invalid `MNEMO_AGENT` or `MNEMO_ROLE` is an error,
    /// not a note, since the write would go out from nobody.
    fn resolve_for_write(&self) -> std::result::Result<(Option<String>, Option<String>), String> {
        for (name, given) in [("MNEMO_AGENT", &self.agent), ("MNEMO_ROLE", &self.role)] {
            if given.is_some() {
                continue;
            }
            if let Ok(v) = std::env::var(name) {
                let v = v.trim();
                if !v.is_empty() && !mnemo_engine::valid_agent_id(v) {
                    return Err(format!(
                        "{name} isn't 1 to 64 of letters, digits, '.', '_' and '-'; fix it, or \
                         give --as/--role"
                    ));
                }
            }
        }
        self.resolve()
    }

    /// The agent and role, checked.
    fn resolve(&self) -> std::result::Result<(Option<String>, Option<String>), String> {
        let (env_agent, env_role) = env_identity();
        let check = |flag: &str, v: &Option<String>| -> std::result::Result<(), String> {
            match v {
                Some(x) if !mnemo_engine::valid_agent_id(x) => Err(format!(
                    "{flag} {x:?}: 1 to 64 of letters, digits, '.', '_' and '-'"
                )),
                _ => Ok(()),
            }
        };
        check("--as", &self.agent)?;
        check("--role", &self.role)?;
        Ok((
            self.agent.clone().or(env_agent),
            self.role.clone().or(env_role),
        ))
    }
}

/// RB-013.1: the line that says coordination records are tagged as facts
/// (an older mnemo rewrote this brain), when any are.
fn mistagged_line(db: &mut mnemo_engine::Mnemo) -> Option<String> {
    let n = db.mistagged_coordination().ok()?;
    (n > 0).then(|| {
        format!(
            "{n} coordination record{} tagged as facts (an older mnemo rewrote this brain); \
             `mnemo compact` fixes it",
            if n == 1 { " is" } else { "s are" }
        )
    })
}

/// RB-013.1: the same, once per process, on stderr, for the coordination
/// commands.
fn note_mistagged(db: &mut mnemo_engine::Mnemo) {
    static ONCE: std::sync::Once = std::sync::Once::new();
    if let Some(line) = mistagged_line(db) {
        ONCE.call_once(|| eprintln!("mnemo: warning: {line}"));
    }
}

/// 13a: a lease: seconds, or a number with `s`, `m`, `h` or `d`.
fn parse_ttl(s: &str) -> std::result::Result<i64, String> {
    let s = s.trim();
    let bad = || format!("--ttl {s:?}: seconds, or 90s, 15m, 2h");
    let (n, mult) = match s.char_indices().last() {
        Some((i, 's')) => (&s[..i], 1),
        Some((i, 'm')) => (&s[..i], 60),
        Some((i, 'h')) => (&s[..i], 3_600),
        Some((i, 'd')) => (&s[..i], 86_400),
        _ => (s, 1),
    };
    n.parse::<i64>()
        .ok()
        .and_then(|n| n.checked_mul(mult))
        .ok_or_else(bad)
}

/// One message as a table row: its id, sender, recipient and subject, then
/// its body, indented.
fn print_message(m: &mnemo_engine::Message) {
    println!(
        "{}  {} -> {}  [{}{}]  {}",
        m.id,
        m.from,
        m.to,
        m.status,
        if m.hops > 0 {
            format!(", hop {}", m.hops)
        } else {
            String::new()
        },
        m.subject
    );
    for l in m.body.lines() {
        println!("    {l}");
    }
    if !m.refs.is_empty() {
        println!("    refs: {}", m.refs.join(", "));
    }
}

fn message_json(m: &mnemo_engine::Message) -> serde_json::Value {
    serde_json::json!({
        "id": m.id.to_string(), "to": m.to, "from": m.from, "subject": m.subject,
        "body": m.body, "refs": m.refs, "conversation": m.conversation, "hops": m.hops,
        "status": m.status, "delivery": m.delivery, "created_at": m.created_at,
        "acked_at": m.acked_at,
    })
}

/// 13a: visibility and freshness on a write (`remember`, `update`).
#[derive(clap::Args, Debug, Default)]
struct FreshArgs {
    /// `public`, `team` (the default) or `private`: a filter, not a
    /// security boundary, until per-agent keys.
    #[arg(long, value_parser = ["public", "team", "private"])]
    visibility: Option<String>,
    /// When to look at it again: `30d`, `12h`, `2w`, a date
    /// (`2026-12-01`), or unix seconds.
    #[arg(long, value_name = "WHEN")]
    review_by: Option<String>,
    /// When the content was true: `3d` (ago), a date, or unix seconds.
    /// Left out, it's when it was written.
    #[arg(long, value_name = "WHEN")]
    as_of: Option<String>,
}

impl FreshArgs {
    /// The caller keys these set, checked.
    fn keys(&self) -> std::result::Result<serde_json::Map<String, serde_json::Value>, String> {
        let mut m = serde_json::Map::new();
        if let Some(v) = &self.visibility {
            m.insert(mnemo_engine::MNEMO_META_VISIBILITY.into(), v.clone().into());
        }
        if let Some(w) = &self.review_by {
            m.insert(
                mnemo_engine::MNEMO_META_REVIEW_BY.into(),
                parse_when(w, true)
                    .map_err(|e| format!("--review-by: {e}"))?
                    .into(),
            );
        }
        if let Some(w) = &self.as_of {
            m.insert(
                mnemo_engine::MNEMO_META_AS_OF.into(),
                parse_when(w, false)
                    .map_err(|e| format!("--as-of: {e}"))?
                    .into(),
            );
        }
        Ok(m)
    }
}

/// A time as unix seconds: a duration from now (`30d`, `12h`, `2w`, `90m`,
/// `45s`; ahead when `ahead`, else ago), a date (`YYYY-MM-DD`, midnight UTC),
/// or a whole number of unix seconds.
fn parse_when(s: &str, ahead: bool) -> std::result::Result<i64, String> {
    let s = s.trim();
    if let Ok(n) = s.parse::<i64>() {
        return if n >= 0 {
            Ok(n)
        } else {
            Err(format!("{s:?} is before 1970"))
        };
    }
    let bad = || format!("{s:?} isn't a duration (30d, 12h), a date (2026-12-01) or unix seconds");
    if let Some((_, mult)) = [
        ('w', 604_800),
        ('d', 86_400),
        ('h', 3_600),
        ('m', 60),
        ('s', 1),
    ]
    .iter()
    .find(|(u, _)| s.ends_with(*u))
    {
        let n: i64 = s[..s.len() - 1].parse().map_err(|_| bad())?;
        let now = std::time::SystemTime::now()
            .duration_since(std::time::UNIX_EPOCH)
            .map_or(0, |d| d.as_secs() as i64);
        let d = n.checked_mul(*mult).ok_or_else(bad)?;
        return Ok(if ahead { now + d } else { (now - d).max(0) });
    }
    let parts: Vec<&str> = s.split('-').collect();
    if let [y, m, d] = parts[..] {
        let (y, m, d): (i64, i64, i64) = (
            y.parse().map_err(|_| bad())?,
            m.parse().map_err(|_| bad())?,
            d.parse().map_err(|_| bad())?,
        );
        if !(1..=12).contains(&m) || !(1..=31).contains(&d) || y < 1970 {
            return Err(bad());
        }
        // Days from 1970-01-01 to the date (the civil-from-days inverse).
        let (yy, mm) = if m <= 2 { (y - 1, m + 9) } else { (y, m - 3) };
        let era = yy.div_euclid(400);
        let yoe = yy - era * 400;
        let doy = (153 * mm + 2) / 5 + d - 1;
        let doe = yoe * 365 + yoe / 4 - yoe / 100 + doy;
        let days = era * 146_097 + doe - 719_468;
        return Ok(days * 86_400);
    }
    Err(bad())
}

/// Like [`passphrase`] but for *new* passphrases on `init` / `rekey`:
/// double-prompts and rejects mismatches. Non-interactive paths (`--flag`,
/// env var) skip the double-prompt and use the value directly.
fn new_passphrase(arg: &Option<String>, env_var: &str) -> std::result::Result<String, String> {
    if let Some(p) = arg {
        eprintln!(
            "warning: passing the passphrase as a flag is insecure; it lands \
             in shell history and process listings. Prefer the {env_var} env \
             var, or omit both to be prompted twice."
        );
        return Ok(p.clone());
    }
    if let Ok(p) = std::env::var(env_var) {
        return Ok(p);
    }
    if !std::io::IsTerminal::is_terminal(&std::io::stdin()) {
        return Err(format!("no passphrase: pass the flag or set {env_var}"));
    }
    prompt_new_passphrase()
}

/// 12.3 step 3: the brain `serve --mcp` opens. A relative path is resolved
/// against `CLAUDE_PROJECT_DIR` when Claude Code set it (absolute) in the
/// server's environment, else against the working directory. Claude Code's
/// docs (code.claude.com/docs/en/mcp, 2026-11-14): "This variable is set in
/// the server's environment, not in Claude Code's own environment, so
/// referencing it via `${VAR}` expansion in the `command` or `args` of a
/// project-scoped `.mcp.json` entry … requires a default such as
/// `${CLAUDE_PROJECT_DIR:-.}`", and the variable is there "so your server can
/// resolve project-relative paths without depending on the working
/// directory". So `mcp install`'s `${CLAUDE_PROJECT_DIR:-.}/<path>` reaches
/// the server as `./<path>`, and is resolved here. A missing brain is an
/// error: the server never creates one.
fn serve_path(path: &str) -> std::result::Result<std::path::PathBuf, String> {
    let given = std::path::Path::new(path);
    let project = std::env::var_os("CLAUDE_PROJECT_DIR")
        .map(std::path::PathBuf::from)
        .filter(|d| d.is_absolute());
    let resolved = match (&project, given.is_relative()) {
        (Some(dir), true) => {
            let r = dir.join(given);
            eprintln!(
                "mnemo mcp: {path} is relative to CLAUDE_PROJECT_DIR: {}",
                r.display()
            );
            r
        }
        _ => given.to_path_buf(),
    };
    if !resolved.is_file() {
        return Err(format!(
            "no brain at {}; the MCP server never creates one (make one with `mnemo init`)",
            resolved.display()
        ));
    }
    Ok(resolved)
}

/// Ask for a new passphrase twice, without echo (`init --ask-passphrase`,
/// and `new_passphrase` at a terminal).
fn prompt_new_passphrase() -> std::result::Result<String, String> {
    let first = rpassword::prompt_password("New passphrase: ")
        .map_err(|e| format!("failed to read passphrase: {e}"))?;
    let second = rpassword::prompt_password("Confirm passphrase: ")
        .map_err(|e| format!("failed to read passphrase: {e}"))?;
    if first != second {
        return Err("passphrases do not match".to_string());
    }
    Ok(first)
}

/// 12.3 (the keys note, section 7): show a new key's recovery code under the
/// display rule, or say why it wasn't shown and how to see it later.
fn show_recovery_code(path: &str, key: &[u8; 32]) {
    use mnemo_engine::keys;
    match keys::display::refusal_reason() {
        None => {
            if let Err(e) = keys::display::show(&keys::recovery::encode(key)) {
                eprintln!(
                    "note: the recovery code couldn't be shown ({e}); run `mnemo recovery-code \
                     {path}` in a terminal of your own"
                );
            }
        }
        Some(why) => eprintln!(
            "note: {} ({why})",
            keys::display::REFUSAL.replace("<file>", path)
        ),
    }
}

/// Resolve a query vector from CLI input, accepting exactly one of:
///
/// - `inline`: comma-separated floats from `--query`
/// - `file`: path to a file (or `-` for stdin) from `--query-file`,
///   containing a JSON array, comma-separated floats, or whitespace /
///   newline-separated floats (auto-detected)
///
/// Clap's `conflicts_with` enforces the "not both" half; this fn enforces
/// the "at least one" half. Wrap the `(query, query_file)` pair from any
/// CLI variant in one call: `let vec = resolve_query(query, query_file)?;`
fn resolve_query(
    inline: Option<String>,
    file: Option<String>,
) -> std::result::Result<Vec<f32>, String> {
    let text = match (inline, file) {
        (Some(s), None) => s,
        (None, Some(p)) => {
            if p == "-" {
                use std::io::Read;
                let mut buf = String::new();
                std::io::stdin()
                    .read_to_string(&mut buf)
                    .map_err(|e| format!("reading stdin: {e}"))?;
                buf
            } else {
                std::fs::read_to_string(&p).map_err(|e| format!("reading {p}: {e}"))?
            }
        }
        (Some(_), Some(_)) => {
            // Clap's conflicts_with should catch this before we get here.
            return Err("pass only one of --query or --query-file".into());
        }
        (None, None) => {
            return Err("missing query: pass --query <floats> or --query-file <path|->".into());
        }
    };
    parse_query_text(&text)
}

/// Parse a query vector from a text blob. Tries JSON-array form first if
/// the input starts with `[`; otherwise splits on commas, whitespace, and
/// newlines and parses each non-empty token as `f32`.
fn parse_query_text(text: &str) -> std::result::Result<Vec<f32>, String> {
    let trimmed = text.trim();
    if trimmed.is_empty() {
        return Err("query text was empty".into());
    }
    if trimmed.starts_with('[') {
        return serde_json::from_str::<Vec<f32>>(trimmed)
            .map_err(|e| format!("invalid JSON array of floats: {e}"));
    }
    trimmed
        .split(|c: char| c == ',' || c.is_whitespace())
        .filter(|s| !s.is_empty())
        .map(|t| {
            t.parse::<f32>()
                .map_err(|e| format!("bad float '{t}': {e}"))
        })
        .collect()
}

fn parse_ulid(s: &str) -> std::result::Result<Ulid, String> {
    Ulid::from_string(s.trim()).map_err(|e| format!("bad ULID '{s}': {e}"))
}

/// Phase 12.6: parse one `--filter` expression and append it to `f`.
///
/// Grammar (left-to-right first match wins):
///
/// * `key:exists`           → [`FilterTerm::Exists`]
/// * `key:in=a,b,c`         → [`FilterTerm::In`] over the comma-split values
/// * `key:gte=NUM`          → [`FilterTerm::Range`] with `min = Some(NUM)`
/// * `key:lte=NUM`          → [`FilterTerm::Range`] with `max = Some(NUM)`
/// * `key=value`            → [`FilterTerm::Eq`] with the value parsed below
///
/// Values are tried as JSON first (so numbers, booleans, null, arrays
/// and quoted strings round-trip through serde cleanly); anything else
/// is treated as a plain string.
fn parse_filter_expr(
    expr: &str,
    f: mnemo_engine::Filter,
) -> std::result::Result<mnemo_engine::Filter, String> {
    // `key:exists` — no `=` at all.
    if let Some(key) = expr.strip_suffix(":exists") {
        if key.is_empty() {
            return Err(format!("empty key in --filter '{expr}'"));
        }
        return Ok(f.metadata_exists(key.to_string()));
    }
    // Everything else needs a `=`.
    let (lhs, rhs) = expr
        .split_once('=')
        .ok_or_else(|| format!("bad --filter '{expr}': expected key=value or key:op=value"))?;

    // Split off a `:op` suffix on the lhs (e.g. `score:gte`).
    let (key, op) = match lhs.split_once(':') {
        Some((k, o)) => (k, Some(o)),
        None => (lhs, None),
    };
    if key.is_empty() {
        return Err(format!("empty key in --filter '{expr}'"));
    }

    match op {
        Some("in") => {
            let values: Vec<serde_json::Value> = rhs
                .split(',')
                .map(|s| parse_filter_value(s.trim()))
                .collect();
            Ok(f.metadata_in(key.to_string(), values))
        }
        Some("gte") => {
            let n: f64 = rhs
                .parse()
                .map_err(|e| format!("bad :gte number in --filter '{expr}': {e}"))?;
            Ok(f.metadata_range(key.to_string(), Some(n), None))
        }
        Some("lte") => {
            let n: f64 = rhs
                .parse()
                .map_err(|e| format!("bad :lte number in --filter '{expr}': {e}"))?;
            Ok(f.metadata_range(key.to_string(), None, Some(n)))
        }
        Some(other) => Err(format!(
            "unknown operator ':{other}' in --filter '{expr}' (want :exists, :in, :gte, :lte)"
        )),
        None => Ok(f.metadata_eq(key.to_string(), parse_filter_value(rhs))),
    }
}

/// Parse one filter value. Try JSON first so numbers, booleans, null and
/// quoted strings deserialize cleanly; otherwise fall back to a plain
/// string.
fn parse_filter_value(s: &str) -> serde_json::Value {
    if let Ok(v) = serde_json::from_str::<serde_json::Value>(s) {
        v
    } else {
        serde_json::Value::String(s.to_string())
    }
}

fn parse_memory_types(s: &str) -> std::result::Result<Vec<MemoryType>, String> {
    s.split(',')
        .map(|t| t.trim())
        .filter(|t| !t.is_empty())
        .map(|t| MemoryType::parse(t).ok_or_else(|| format!("unknown memory type '{t}'")))
        .collect()
}

fn parse_metric(s: &str) -> std::result::Result<Metric, String> {
    match s.trim().to_ascii_lowercase().as_str() {
        "cosine" | "cos" => Ok(Metric::Cosine),
        "l2" | "euclidean" => Ok(Metric::L2),
        "dot" | "ip" => Ok(Metric::Dot),
        other => Err(format!("unknown metric '{other}' (use cosine, l2, or dot)")),
    }
}

/// Output format shared by the exploration commands.
#[derive(Copy, Clone, Debug, PartialEq, Eq, ValueEnum)]
#[clap(rename_all = "lowercase")]
enum OutputFormat {
    /// Human-readable text rows.
    Table,
    /// One JSON document per response.
    Json,
    /// JSON Lines (one record per line) — pipeline-friendly.
    Jsonl,
}

impl std::fmt::Display for OutputFormat {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.write_str(match self {
            OutputFormat::Table => "table",
            OutputFormat::Json => "json",
            OutputFormat::Jsonl => "jsonl",
        })
    }
}

/// Truncate a string to `max` chars (not bytes), suffixing `…` when cut.
fn truncate(s: &str, max: usize) -> String {
    if s.chars().count() <= max {
        return s.to_string();
    }
    let mut out: String = s.chars().take(max.saturating_sub(1)).collect();
    out.push('…');
    out
}

/// Serialize a memory as JSON, optionally stripping the embedding.
fn memory_to_json(m: &Memory, include_vector: bool) -> serde_json::Value {
    let mut v = serde_json::to_value(m).unwrap_or_else(|_| serde_json::json!({}));
    if !include_vector {
        if let Some(obj) = v.as_object_mut() {
            obj.remove("vector");
        }
    }
    v
}

/// Print a single memory in the requested format.
/// `whole` prints a table row's content in full (one `get`); lists cut it
/// at 80 characters.
fn print_memory(
    m: &Memory,
    format: OutputFormat,
    verbose: bool,
    include_vector: bool,
    whole: bool,
) {
    match format {
        OutputFormat::Table => {
            let id = m.id.to_string();
            let imp = format!("imp={:.2}", m.importance);
            if verbose {
                println!(
                    "{}  [{}]  agent={}  {}",
                    id,
                    m.memory_type.as_str(),
                    m.agent_id,
                    imp
                );
                println!("  content : {}", m.content);
                if let Some(sid) = &m.session_id {
                    println!("  session : {sid}");
                }
                println!(
                    "  scope   : {}",
                    match m.scope {
                        mnemo_engine::Scope::Private => "private",
                        mnemo_engine::Scope::Shared => "shared",
                    }
                );
                println!(
                    "  times   : created={}  accessed={}  access_count={}",
                    m.created_at, m.accessed_at, m.access_count
                );
                if let Some(ttl) = m.ttl_secs {
                    println!("  ttl_secs: {ttl}");
                }
                if !m.metadata.is_empty() {
                    let meta = serde_json::Value::Object(m.metadata.clone());
                    println!("  meta    : {meta}");
                }
            } else {
                println!(
                    "{}  [{}]  agent={}  {}  {}",
                    id,
                    m.memory_type.as_str(),
                    m.agent_id,
                    imp,
                    if whole {
                        m.content.clone()
                    } else {
                        truncate(&m.content, 80)
                    },
                );
            }
        }
        OutputFormat::Json => {
            let v = memory_to_json(m, include_vector);
            println!(
                "{}",
                serde_json::to_string_pretty(&v).unwrap_or_else(|_| "{}".into())
            );
        }
        OutputFormat::Jsonl => {
            let v = memory_to_json(m, include_vector);
            println!(
                "{}",
                serde_json::to_string(&v).unwrap_or_else(|_| "{}".into())
            );
        }
    }
}

/// Print a list of memories with a header line in table mode.
fn print_memories(items: &[Memory], total: usize, format: OutputFormat, include_vector: bool) {
    match format {
        OutputFormat::Table => {
            if items.is_empty() {
                println!("no memories");
                return;
            }
            println!("showing {} of {} memories", items.len(), total);
            for m in items {
                print_memory(m, OutputFormat::Table, false, false, false);
            }
        }
        OutputFormat::Json => {
            let arr: Vec<_> = items
                .iter()
                .map(|m| memory_to_json(m, include_vector))
                .collect();
            let doc = serde_json::json!({ "total": total, "count": arr.len(), "memories": arr });
            println!(
                "{}",
                serde_json::to_string_pretty(&doc).unwrap_or_else(|_| "{}".into())
            );
        }
        OutputFormat::Jsonl => {
            for m in items {
                println!(
                    "{}",
                    serde_json::to_string(&memory_to_json(m, include_vector))
                        .unwrap_or_else(|_| "{}".into())
                );
            }
        }
    }
}

/// Print recall hits with the score/similarity columns up front.
fn print_recall_hits(hits: &[RecallResult], format: OutputFormat) {
    match format {
        OutputFormat::Table => {
            if hits.is_empty() {
                println!("no results");
                return;
            }
            for h in hits {
                println!(
                    "score={:.3}  sim={:.3}  [{}]  {}  {}",
                    h.score,
                    h.similarity,
                    h.memory.memory_type.as_str(),
                    h.memory.id,
                    truncate(&h.memory.content, 80),
                );
            }
        }
        OutputFormat::Json => {
            let arr: Vec<_> = hits
                .iter()
                .map(|h| {
                    serde_json::json!({
                        "score": h.score,
                        "similarity": h.similarity,
                        "memory": memory_to_json(&h.memory, false),
                    })
                })
                .collect();
            let doc = serde_json::json!({ "count": arr.len(), "hits": arr });
            println!(
                "{}",
                serde_json::to_string_pretty(&doc).unwrap_or_else(|_| "{}".into())
            );
        }
        OutputFormat::Jsonl => {
            for h in hits {
                let line = serde_json::json!({
                    "score": h.score,
                    "similarity": h.similarity,
                    "memory": memory_to_json(&h.memory, false),
                });
                println!(
                    "{}",
                    serde_json::to_string(&line).unwrap_or_else(|_| "{}".into())
                );
            }
        }
    }
}

fn run() -> std::result::Result<(), String> {
    // RB-011.3: `mnemo hook` reads its own command line, so no usage error
    // and no missing `-C` directory can make it exit with anything but 0.
    let argv: Vec<std::ffi::OsString> = std::env::args_os().collect();
    if let Some(a) = hook::parse_args(&argv) {
        match a.wait.as_deref().map(parse_wait) {
            Some(Ok(w)) => {
                let _ = WAIT.set(w);
            }
            Some(Err(e)) => eprintln!("mnemo: hook: --wait: {e}; the default was used"),
            None => {}
        }
        let _ = MODEL_DIR.set(a.model_dir.clone());
        hook::run_args(a);
        return Ok(());
    }
    let mut cli = Cli::parse();
    let _ = WAIT.set(cli.wait);
    let _ = MODEL_DIR.set(cli.model_dir.clone());
    if let Some(dir) = &cli.dir {
        std::env::set_current_dir(dir).map_err(|e| format!("-C {}: {e}", dir.display()))?;
    }
    shift_get_args(&mut cli.command)?;
    let project_brain = resolve_brain_arg(&mut cli.command, cli.dir.is_some())?;
    let moved = cli.dir.is_some();
    match cli.command {
        Command::Init {
            path,
            dimensions,
            no_manifest,
            passphrase: pp,
            ask_passphrase,
            key_file,
        } => {
            use mnemo_engine::keys;
            let cfg = MnemoConfig {
                dimensions,
                ..Default::default()
            };
            let mut write_manifest = |db: &mut Mnemo| -> Result<()> {
                if !no_manifest {
                    db.remember(Memory::scaffold_manifest(dimensions))?;
                    db.flush()?;
                }
                Ok(())
            };
            let env_pp = std::env::var("MNEMO_PASSPHRASE").is_ok_and(|v| !v.is_empty());
            let how = if pp.is_some() || ask_passphrase || env_pp {
                // A passphrase, as before v0.15. The double prompt catches
                // a typo, which would make the file unopenable; the flag and
                // the env var trust the caller.
                let pp = if ask_passphrase {
                    prompt_new_passphrase()?
                } else {
                    new_passphrase(&pp, "MNEMO_PASSPHRASE")?
                };
                let mut db = Mnemo::create(&path, &pp, cfg).map_err(fmt)?;
                write_manifest(&mut db).map_err(fmt)?;
                db.close().map_err(fmt)?;
                "encrypted with a passphrase".to_string()
            } else if let Some(kf) = &key_file {
                // 12.3: a generated key, in a new file the user named.
                if std::fs::symlink_metadata(kf).is_ok() {
                    return Err(format!("{kf} already exists; nothing was created"));
                }
                let mut persist =
                    |_salt: &[u8; 16], key: &[u8; 32]| keys::write_new_key_file(kf, key);
                keys::create_generated(&path, cfg, &mut write_manifest, &mut persist)
                    .map_err(fmt)?;
                format!("encrypted with a generated key, written to {kf} (mode 0600)")
            } else {
                // 12.3: a generated key, kept in the key store.
                let no_keychain = |why: String| {
                    format!(
                        "no keychain is available here{why}, so `mnemo init` can't keep a \
                         generated key, and nothing was created. To protect {path} with a \
                         passphrase, as v0.14 did: `mnemo init --ask-passphrase {path}` (or set \
                         MNEMO_PASSPHRASE). To write a generated key to a new file (mode 0600): \
                         `mnemo init --key-file <PATH> {path}`"
                    )
                };
                let Some(store) = keys::default_store() else {
                    return Err(no_keychain(String::new()));
                };
                store
                    .check_available()
                    .map_err(|e| no_keychain(format!(" ({e})")))?;
                let label = path.clone();
                let mut persist = |salt: &[u8; 16], key: &[u8; 32]| {
                    let entry = keys::StoredSecret::Key(zeroize::Zeroizing::new(*key));
                    keys::store_and_check(&*store, salt, &entry, &label)
                };
                let key = keys::create_generated(&path, cfg, &mut write_manifest, &mut persist)
                    .map_err(fmt)?;
                println!(
                    "created {path} ({dimensions} dimensions), encrypted with a generated key"
                );
                println!("  → the key is in {}", store.describe());
                show_recovery_code(&path, &key);
                if !no_manifest {
                    println!("  → run `mnemo about {path}` to view its scaffold manifest");
                }
                return Ok(());
            };
            if no_manifest {
                println!("created {path} ({dimensions} dimensions, {how}, no manifest)");
            } else {
                println!("created {path} ({dimensions} dimensions, {how}) with scaffold manifest");
                println!("  → run `mnemo about {path}` to view it");
                println!("  → replace it with one that records your embedder and conventions");
            }
        }
        Command::Unlock { path } => {
            use mnemo_engine::keys::{self, StoredSecret};
            let nowhere = "there's nowhere to keep the key, so set MNEMO_KEY to the recovery \
                           code, or use --key-file";
            let store = keys::default_store()
                .ok_or_else(|| format!("no keychain is available here; {nowhere}"))?;
            store
                .check_available()
                .map_err(|e| format!("{e}; {nowhere}"))?;
            let info = keys::file_info(&path).map_err(fmt)?;
            // 12.3 (the keys note, section 5): from a prompt at a terminal,
            // or from stdin; never from the command line.
            let typed =
                zeroize::Zeroizing::new(if std::io::IsTerminal::is_terminal(&std::io::stdin()) {
                    rpassword::prompt_password("Recovery code: ")
                        .map_err(|e| format!("reading the recovery code: {e}"))?
                } else {
                    let mut line = String::new();
                    std::io::Read::read_to_string(
                        &mut std::io::Read::take(std::io::stdin(), 256),
                        &mut line,
                    )
                    .map_err(|e| format!("reading the recovery code: {e}"))?;
                    line.lines().next().unwrap_or("").to_string()
                });
            let key = keys::recovery::parse(&typed).map_err(|e| e.to_string())?;
            if !info.kdf.below_passphrase_floor() {
                return Err(format!(
                    "{path} is protected by a passphrase, not a key, so a recovery code can't \
                     open it; nothing was stored"
                ));
            }
            if !Mnemo::key_opens(&path, &key).map_err(fmt)? {
                return Err(format!(
                    "that recovery code is well formed but doesn't open {path}; nothing was \
                     stored"
                ));
            }
            match store.get(&info.salt).map_err(fmt)? {
                Some(StoredSecret::Key(k)) if *k == *key => {
                    println!(
                        "{path} is already unlocked on this machine ({})",
                        store.describe()
                    );
                    return Ok(());
                }
                Some(_) => eprintln!(
                    "note: {} had another entry for {path}, which doesn't open it; replacing it",
                    store.describe()
                ),
                None => {}
            }
            keys::store_and_check(&*store, &info.salt, &StoredSecret::Key(key), &path)
                .map_err(fmt)?;
            println!("unlocked {path}: its key is in {}", store.describe());
        }
        Command::RecoveryCode { path } => {
            use mnemo_engine::keys::{self, StoredSecret};
            let store = keys::default_store().ok_or_else(|| {
                "no keychain is available here, so there's no stored key to show".to_string()
            })?;
            let info = keys::file_info(&path).map_err(fmt)?;
            let entry = store
                .get(&info.salt)
                .map_err(fmt)?
                .ok_or_else(|| format!("{} has no entry for {path}", store.describe()))?;
            let key = match entry {
                StoredSecret::Key(k) => k,
                StoredSecret::Passphrase(_) => {
                    return Err(format!(
                        "{path} uses a passphrase; there's no recovery code"
                    ))
                }
            };
            if !Mnemo::key_opens(&path, &key).map_err(fmt)? {
                return Err(format!(
                    "the key {} holds for {path} doesn't open it, so its code isn't shown",
                    store.describe()
                ));
            }
            if let Some(why) = keys::display::refusal_reason() {
                return Err(format!(
                    "{} ({why})",
                    keys::display::REFUSAL.replace("<file>", &path)
                ));
            }
            keys::display::show(&keys::recovery::encode(&key))
                .map_err(|e| format!("showing the recovery code: {e}"))?;
        }
        Command::Info {
            path,
            key_file,
            passphrase: pp,
        } => {
            // Build info first — printed before the file open so it's
            // visible even if the open fails (common when verifying a
            // fresh install of mnemo). Mirrors the Python
            // `mnemo.build_info()` shape.
            let bi = mnemo_engine::build_info();
            println!("mnemo:       v{} ({})", bi.version, bi.target);
            println!("aes:         {}", bi.aes_backend);
            println!("polyval:     {}", bi.polyval_backend);
            let secret = secret_for(&path, &pp, &key_file)?;
            let mut db = open_ro(&path, &secret).map_err(fmt)?;
            let s = db.stats().map_err(fmt)?;
            println!("path:        {path}");
            // 12.3: where the secret came from, and the KDF's grade.
            if let Some((src, _)) = SOURCE.get() {
                println!("key source:  {src}");
            }
            if let Some(note) = mnemo_engine::keys::kdf_grade_note(db.kdf_params(), secret.kind()) {
                println!("kdf:         {note}");
            }
            println!("format:      v{}", s.format_version);
            if let Some(hint) = upgrade_hint(&path, s.format_version) {
                println!("             {hint}");
            }
            println!("memories:    {}", s.memories);
            println!("tombstoned:  {}", s.deleted);
            println!("dimensions:  {}", s.dimensions);
            println!("file bytes:  {}", s.file_bytes);
            println!("encrypted:   {}", s.encrypted);
            println!(
                "wal region:  {} pages ({} KiB)",
                s.wal_pages,
                s.wal_pages * 8
            );
            println!("recall:      {}", s.recall_mode.as_str());
            if let Some(k) = s.keyword_tokenizer {
                println!("keywords:    tokenizer {}", k.as_str());
                if let Some(note) = tokenizer_note(&path, k) {
                    println!("             {note}");
                }
            }
            println!("created at:  {}", s.created_at);
            println!("agents:      {}", s.agents.join(", "));
            // INSP-1 (RB-001.25): what a restore can reach right now.
            match s.oldest_restorable_at {
                Some(t) => println!(
                    "snapshots:   {} retained, oldest {} ({} bytes pinned)",
                    s.snapshots_retained,
                    export::rfc3339(t),
                    s.snapshot_pinned_bytes
                ),
                None => println!("snapshots:   none"),
            }
            // Phase 6 instrumentation: how many fsyncs the most recent
            // flush issued. `0` on a read-only open since open() never
            // flushes; shown as a dash in that case for clarity.
            if s.fsyncs_last_flush == 0 {
                println!("fsyncs/flush: — (no flush seen on this handle)");
            } else {
                println!("fsyncs/flush: {}", s.fsyncs_last_flush);
            }
            // Phase 10.1 result-cache summary — one line even when
            // the cache is empty, for symmetry with the other fields.
            {
                let cs = db.cache_stats(None);
                println!(
                    "cache:       {} entries, {} bytes (hits {}, misses {}, evict {})",
                    cs.entries, cs.bytes, cs.hits, cs.misses, cs.evictions
                );
            }
            match s.index {
                Some(ix) => {
                    println!(
                        "ann index:   {} vectors, {} partitions, {} PQ subspaces",
                        ix.vectors, ix.partitions, ix.subspaces
                    );
                    println!(
                        "  defaults:  n_probe={}, n_rerank={}",
                        ix.n_probe, ix.n_rerank
                    );
                }
                None => println!("ann index:   none (recall uses exact scan)"),
            }
        }
        Command::Rekey {
            path,
            key_file,
            passphrase: pp,
            new_passphrase: new,
            new_key,
            store: keep,
            new_key_file,
            rotate,
        } => {
            use mnemo_engine::keys::{self, Secret};
            let old = secret_for(&path, &pp, &key_file)?;
            let new: Secret = if new_key {
                Secret::Key(zeroize::Zeroizing::new(Mnemo::generate_key()))
            } else {
                Secret::Passphrase(zeroize::Zeroizing::new(new_passphrase(
                    &new,
                    "MNEMO_NEW_PASSPHRASE",
                )?))
            };
            // 12.4 (RB-007.4): through the lock layer, so shared handles'
            // calls can't keep the rekey out, and theirs see "rekey".
            let mut db = open_rw(&path, &old, "rekey").map_err(fmt)?;
            // RB-005.4 item 4: REKEY-1 makes an error leave the old secret in
            // force, so say so. The one exception (the old header couldn't
            // be written back) says "may open with either secret" itself.
            let old_word = match old.kind() {
                keys::SecretKind::Passphrase => "passphrase",
                keys::SecretKind::Key => "key",
            };
            let not_changed = |msg: String| {
                if msg.contains("may open with either secret") {
                    msg
                } else {
                    format!("{msg}; the {old_word} was not changed")
                }
            };
            let mut stored_note = None;
            if new_key || keep {
                // 12.3 (the keys note, section 4): the new secret goes into
                // the key store before the commit.
                let Some(store) = keys::default_store() else {
                    return Err(
                        "--new-key and --store keep the new secret in a keychain, and none \
                         is available here; nothing was changed"
                            .into(),
                    );
                };
                store
                    .check_available()
                    .map_err(|e| format!("{e}; nothing was changed"))?;
                // 12.3 (the keys note, section 4): no OS keychain promises its
                // write is on disk when it returns, so a new key must also be
                // shown or written to a file before the commit.
                let refused = keys::display::refusal_reason();
                if new_key && !store.durable() && refused.is_some() && new_key_file.is_none() {
                    return Err(format!(
                        "{} doesn't promise its write is on disk before the rekey commits, and \
                         the new key's recovery code can't be shown here ({}); a power cut \
                         could leave the key nowhere. Run it at a terminal of your own, or add \
                         --new-key-file <PATH> to write the key to a new file too. Nothing was \
                         changed",
                        store.describe(),
                        refused.unwrap_or_default()
                    ));
                }
                if let Some(f) = &new_key_file {
                    if std::fs::symlink_metadata(f).is_ok() {
                        return Err(format!("{f} already exists; nothing was changed"));
                    }
                }
                let mut before_commit = || -> Result<()> {
                    if let Secret::Key(k) = &new {
                        show_recovery_code(&path, k);
                        if let Some(f) = &new_key_file {
                            keys::write_new_key_file(f, k)?;
                        }
                    }
                    Ok(())
                };
                match keys::rekey_stored(&mut db, &new, &*store, &path, &mut before_commit) {
                    Ok(note) => stored_note = Some(note),
                    Err(e) => {
                        if e.new_secret_dropped {
                            if let Some(f) = &new_key_file {
                                let _ = std::fs::remove_file(f);
                            }
                        }
                        return Err(format!("{}; {}", not_changed(fmt(e.error)), e.entries));
                    }
                }
            } else if let Secret::Passphrase(p) = &new {
                // 12.3 (the keys note, section 1, rule 1): never below
                // `secure()`, nor below what the file had.
                let kdf = db.kdf_params().for_passphrase();
                db.rekey(p, kdf).map_err(|e| not_changed(fmt(e)))?;
            }
            // REKEY-1: the rekey took effect; part of the old wrap's cleanup
            // didn't. `--rotate` rewrites the file, which covers it.
            let left = db.rekey_cleanup_error().map(str::to_owned);
            db.close().map_err(fmt)?;
            if let (Some(left), false) = (&left, rotate) {
                eprintln!(
                    "warning: the new secret is in force, but part of the old key \
                     wrap's cleanup failed ({left}); run `mnemo rekey --rotate` to be sure \
                     the old secret opens nothing"
                );
            }
            if let Some(note) = stored_note {
                println!("  → {note}");
            }
            if rotate {
                let r = match &new {
                    Secret::Passphrase(p) => Mnemo::compact_file_waiting(&path, p, wait_opts()),
                    Secret::Key(k) => Mnemo::compact_file_waiting_with_key(&path, k, wait_opts()),
                }
                .map_err(fmt)?;
                println!(
                    "rekeyed and rotated {path}: a fresh data key, {} memories kept",
                    r.after
                );
            } else {
                println!("rekeyed {path}");
                println!(
                    "note: the data key is unchanged; after a leak, run \
                     `mnemo rekey --rotate` to revoke the old secret"
                );
            }
        }
        Command::Compact {
            path,
            key_file,
            passphrase: pp,
        } => {
            let secret = secret_for(&path, &pp, &key_file)?;
            let report = match &secret {
                inspect::Secret::Passphrase(p) => {
                    Mnemo::compact_file_waiting(&path, p, wait_opts())
                }
                inspect::Secret::Key(k) => {
                    Mnemo::compact_file_waiting_with_key(&path, k, wait_opts())
                }
            }
            .map_err(fmt)?;
            println!(
                "compacted {path} (v9): {} -> {} live memories",
                report.before, report.after
            );
            if report.zero_vector_manifests + report.zero_vector_memories > 0 {
                println!(
                    "  all-zero vectors: {} legacy manifest memories given the sentinel \
                     vector, {} other memories carried unchanged",
                    report.zero_vector_manifests, report.zero_vector_memories
                );
            }
        }
        Command::Reembed {
            path,
            embed_cmd,
            embed_name,
            embed_normalize,
            embed_query,
            embed_dims,
            embed_timeout,
            key_file,
            passphrase: pp,
        } => {
            let secret = secret_for(&path, &pp, &key_file)?;
            // The built-in has its own width; `--embed-dims` only has to
            // agree with it.
            let dims = match (&embed_cmd, embed_dims) {
                (_, Some(d)) => Some(d),
                (Some(_), None) => Some(Mnemo::peek_dimensions(&path).map_err(fmt)?),
                (None, None) => None,
            };
            let embedder = new_embedder(
                embed_cmd.as_deref(),
                embed_name.as_deref(),
                embed_normalize,
                embed_timeout,
                embed_query.as_deref().unwrap_or_default(),
                dims,
            )?;
            let report = match &secret {
                inspect::Secret::Passphrase(p) => {
                    Mnemo::reembed_file_waiting(&path, p, &embedder, wait_opts())
                }
                inspect::Secret::Key(k) => {
                    Mnemo::reembed_file_waiting_with_key(&path, k, &embedder, wait_opts())
                }
            }
            .map_err(fmt)?;
            let from = report
                .from
                .as_ref()
                .map_or_else(|| "no recorded embedder".to_string(), |i| i.name.clone());
            println!(
                "re-embedded {path}: {} memories, {from} -> {} ({} dimensions)",
                report.memories, report.to.name, report.to.dimensions
            );
            println!(
                "  (facts, superseded versions, essence and thread turns; {} manifest and {} \
                 thread links kept on their sentinel vector)",
                report.manifests, report.thread_links
            );
            if report.cache_dropped > 0 {
                println!(
                    "  {} semantic cache entries dropped (their vectors have the old width)",
                    report.cache_dropped
                );
            }
        }
        Command::Verify {
            path,
            key_file,
            passphrase: pp,
        } => {
            let secret = secret_for(&path, &pp, &key_file)?;
            let mut db = open_ro(&path, &secret).map_err(fmt)?;
            let report = db.verify_report().map_err(fmt)?;
            println!(
                "verified {} records — all pages decrypt and decode",
                report.records
            );
            if report.zero_vector_memories > 0 {
                eprintln!(
                    "warning: {} memories have an all-zero vector (written before v0.5's \
                     zero-vector rule); they score 0.0 on every vector query. `mnemo compact` \
                     carries them and gives a legacy manifest the sentinel vector.",
                    report.zero_vector_memories
                );
            }
            if let Some(note) = report
                .keyword_tokenizer
                .filter(|k| *k == mnemo_engine::KeywordTokenizer::Mixed)
                .and_then(|k| tokenizer_note(&path, k))
            {
                eprintln!("note: {note}");
            }
            // RB-013.1: coordination records an older mnemo re-tagged.
            if let Some(line) = mistagged_line(&mut db) {
                eprintln!("warning: {line}");
            }
        }
        Command::Import {
            path,
            file,
            passphrase: pp,
        } => {
            let pp = secret_for(&path, &pp, &None)?;
            // Read the input before taking the lock, then one exclusive hold
            // through the lock layer (12.4, RB-007.4) for the whole import.
            let text =
                std::fs::read_to_string(&file).map_err(|e| format!("cannot read {file}: {e}"))?;
            let mut db = open_w(&path, &pp, "import").map_err(fmt)?;
            let mut count = 0usize;
            for (lineno, line) in text.lines().enumerate() {
                let line = line.trim();
                if line.is_empty() {
                    continue;
                }
                let m = memory_from_json(line).map_err(|e| format!("line {}: {e}", lineno + 1))?;
                db.remember(m).map_err(fmt)?;
                count += 1;
            }
            db.flush().map_err(fmt)?;
            println!("imported {count} memories into {path}");
        }
        Command::Remember {
            path,
            text,
            r#type,
            importance,
            agent,
            metadata,
            fresh,
            key,
            supersedes,
            embed_cmd,
            embed_name,
            embed_normalize,
            embed_query,
            embed_timeout,
            passphrase: pp,
        } => {
            // RB-013.4: a new write's agent is checked as every agent id is.
            if let Some(a) = &agent {
                if !mnemo_engine::valid_agent_id(a) {
                    return Err(format!(
                        "--agent {a:?}: 1 to 64 of letters, digits, '.', '_' and '-'"
                    ));
                }
            }
            let pp = secret_for(&path, &pp, &None)?;
            let mt = parse_memory_types(&r#type)?
                .pop()
                .ok_or_else(|| format!("unknown memory type: {type:?}", r#type = r#type))?;
            // 12.4: embed first, then take the write lock (the embedder can
            // take seconds; other sessions shouldn't wait behind it). The
            // identity check and the width check still run under the lock,
            // before anything is written.
            let (mut db, vector) = match embed_first(
                &path,
                embed_cmd.as_deref(),
                embed_name.as_deref(),
                embed_normalize,
                embed_timeout,
                embed_query.as_deref().unwrap_or_default(),
                &[text.as_str()],
            )? {
                Some((embedder, mut vectors)) => {
                    let vector = vectors
                        .pop()
                        .ok_or_else(|| "embedder returned no vector".to_string())?;
                    let mut db = open_w(&path, &pp, "remember").map_err(fmt)?;
                    db.set_embedder(embedder).map_err(fmt)?;
                    (db, vector)
                }
                // The header couldn't be read: the old order.
                None => {
                    let mut db = open_w(&path, &pp, "remember").map_err(fmt)?;
                    let embedder = new_embedder(
                        embed_cmd.as_deref(),
                        embed_name.as_deref(),
                        embed_normalize,
                        embed_timeout,
                        embed_query.as_deref().unwrap_or_default(),
                        Some(db.dimensions()),
                    )?;
                    db.set_embedder(embedder).map_err(fmt)?;
                    let vector = {
                        let embedder_ref = db
                            .embedder()
                            .ok_or_else(|| "no embedder registered".to_string())?;
                        let mut vectors = embedder_ref.embed(&[text.as_str()]).map_err(fmt)?;
                        vectors
                            .pop()
                            .ok_or_else(|| "embedder returned no vector".to_string())?
                    };
                    (db, vector)
                }
            };
            let mut memory = Memory::new(text, mt, vector);
            if let Some(i) = importance {
                memory = memory.with_importance(i);
            }
            // 13a (AGENT-DEFAULT): no `--agent`, the brain's default agent.
            let agent = match agent {
                Some(a) => Some(a),
                None => db.default_agent().map_err(fmt)?,
            };
            if let Some(a) = agent {
                memory = memory.with_agent(a);
            }
            if let Some(meta_str) = metadata {
                let parsed: serde_json::Value = serde_json::from_str(&meta_str)
                    .map_err(|e| format!("invalid --metadata JSON: {e}"))?;
                let obj = parsed
                    .as_object()
                    .ok_or_else(|| "--metadata must be a JSON object".to_string())?;
                for (k, v) in obj {
                    memory.metadata.insert(k.clone(), v.clone());
                }
            }
            memory.metadata.extend(fresh.keys()?);
            // (Scope defaults to Private; add `--shared` later if the
            // CLI needs to opt into Scope::Shared.)
            //
            // Phase 12.1: when `--key` is given, take the keyed-upsert
            // path (supersede / no-op / add), and print `id\toutcome`
            // so scripts can distinguish the three states. Without
            // `--key`, keep the original single-ULID stdout for
            // backward compatibility.
            match key {
                None => {
                    let id = db.remember(memory).map_err(fmt)?;
                    db.flush().map_err(fmt)?;
                    println!("{id}");
                }
                Some(k) => {
                    let (id, outcome) = match &supersedes {
                        Some(old) => {
                            let old = parse_ulid(old)?;
                            db.remember_keyed_superseding(memory, &k, &old)
                        }
                        None => db.remember_keyed(memory, &k),
                    }
                    .map_err(fmt)?;
                    db.flush().map_err(fmt)?;
                    let outcome_str = match outcome {
                        mnemo_engine::WriteOutcome::Added => "added",
                        mnemo_engine::WriteOutcome::Superseded => "superseded",
                        mnemo_engine::WriteOutcome::Unchanged => "unchanged",
                        // `Updated`: `--supersedes` adopted a memory with the
                        // same content as the slot's live record.
                        mnemo_engine::WriteOutcome::Updated => "updated",
                    };
                    // RB-013.2: say when a keyed write changed the level.
                    let change = match outcome {
                        mnemo_engine::WriteOutcome::Superseded => db
                            .superseded_level_change(&id)
                            .map_err(fmt)?
                            .map(|(a, b)| format!(" ({a} → {b})"))
                            .unwrap_or_default(),
                        _ => String::new(),
                    };
                    println!("{id}\t{outcome_str}{change}");
                }
            }
        }
        Command::Index {
            path,
            passphrase: pp,
            drop,
            rebuild,
            partitions,
            subspaces,
            n_probe,
            n_rerank,
        } => {
            let pp = secret_for(&path, &pp, &None)?;
            let mut db = open_w(&path, &pp, "index").map_err(fmt)?;
            if drop {
                db.drop_index();
                db.flush().map_err(fmt)?;
                println!("dropped ANN index on {path}");
            } else if rebuild {
                // BP.1: re-cluster + retrain under the current
                // `IndexConfig::default()` (the ANN-1.1 auto-formulas).
                // Explicit `--partitions` / `--subspaces` / `--n-probe`
                // / `--n-rerank` are rejected here so this flag has one
                // clear behavior — "give me the shipped defaults for
                // the file's current size". Users who want custom
                // parameters should use `mnemo index <file>` (without
                // --rebuild) with the per-flag overrides.
                if partitions != 0 || subspaces != 0 || n_probe != 0 || n_rerank != 0 {
                    return Err(fmt(mnemo_engine::MnemoError::Invalid(
                        "--rebuild uses the auto-defaults; drop \
                         --partitions / --subspaces / --n-probe / \
                         --n-rerank, or build without --rebuild to pin \
                         explicit values"
                            .into(),
                    )));
                }
                let info = db.rebuild_index().map_err(fmt)?;
                db.flush().map_err(fmt)?;
                println!(
                    "rebuilt ANN index on {path}: {} vectors, {} partitions, {} PQ subspaces",
                    info.vectors, info.partitions, info.subspaces
                );
            } else {
                let cfg = mnemo_engine::IndexConfig {
                    n_partitions: partitions,
                    pq_subspaces: subspaces,
                    n_probe,
                    n_rerank,
                    ..Default::default()
                };
                let info = db.build_index_with(cfg).map_err(fmt)?;
                db.flush().map_err(fmt)?;
                println!(
                    "built ANN index on {path}: {} vectors, {} partitions, {} PQ subspaces",
                    info.vectors, info.partitions, info.subspaces
                );
            }
        }
        Command::Search {
            path,
            query,
            query_file,
            top_k,
            visibility,
            passphrase: pp,
        } => {
            let vis = mnemo_engine::VisibilitySet::parse(&visibility).map_err(fmt)?;
            // Search is a pure catalog scan — no access-tracking, no
            // catalog writes. Safe on a read-only handle.
            let pp = secret_for(&path, &pp, &None)?;
            let q = resolve_query(query, query_file)?;
            let mut db = open_r(&path, &pp).map_err(fmt)?;
            let hits = db
                .search_in(&q, top_k, mnemo_engine::Metric::Cosine, vis)
                .map_err(fmt)?;
            if hits.is_empty() {
                println!("no results");
            }
            for (m, sim) in hits {
                println!("{sim:.4}  [{}]  {}", m.memory_type.as_str(), m.content);
            }
        }
        Command::About {
            path,
            format,
            manifest_only,
            visibility,
            key_file,
            passphrase: pp,
        } => {
            let vis = mnemo_engine::VisibilitySet::parse(&visibility).map_err(fmt)?;
            let secret = secret_for(&path, &pp, &key_file)?;
            let mut db = open_ro(&path, &secret).map_err(fmt)?;
            let stats = db.stats().map_err(fmt)?;
            let snapshots = db.snapshots().len();
            let counts = db.kind_counts();
            let now = db.coordination_now();
            let mut entries = db.about_in(vis).map_err(fmt)?;
            // 12.7d: the project essence follows the manifest and the
            // onboarding memories (skipped with --manifest-only).
            let essence = if manifest_only {
                None
            } else {
                db.about_essence().map_err(fmt)?
            };
            let print_essence = || {
                if let Some(render) = &essence {
                    println!();
                    println!("## Project essence");
                    println!();
                    print!("{render}");
                }
            };
            if manifest_only {
                entries.retain(|m| {
                    m.metadata
                        .get("topic")
                        .and_then(|v| v.as_str())
                        .map(|s| s.eq_ignore_ascii_case("manifest"))
                        .unwrap_or(false)
                });
            }
            match format {
                OutputFormat::Json | OutputFormat::Jsonl => {
                    let manifest = entries.iter().find(|m| {
                        m.metadata
                            .get("topic")
                            .and_then(|v| v.as_str())
                            .map(|s| s.eq_ignore_ascii_case("manifest"))
                            .unwrap_or(false)
                    });
                    let doc = serde_json::json!({
                        "path": path,
                        "stats": {
                            "format_version": stats.format_version,
                            "upgrade_hint": upgrade_hint(&path, stats.format_version),
                            "memories": stats.memories,
                            "counts": {
                                "facts": counts.facts,
                                "turns": counts.turns,
                                "essence": counts.essence,
                                "coordination": counts.coordination,
                            },
                            "dimensions": stats.dimensions,
                            "file_bytes": stats.file_bytes,
                            "encrypted": stats.encrypted,
                            "snapshots": snapshots,
                            "has_index": stats.index.is_some(),
                        },
                        "manifest": manifest.map(|m| memory_to_json(m, false)),
                        "onboarding": entries
                            .iter()
                            .map(|m| memory_to_json(m, false))
                            .collect::<Vec<_>>(),
                        "essence": essence.as_deref(),
                    });
                    println!(
                        "{}",
                        serde_json::to_string_pretty(&doc).unwrap_or_else(|_| "{}".into())
                    );
                }
                OutputFormat::Table => {
                    // One-line stats header — what kind of file you're looking at.
                    println!(
                        "# {}  ({} memories: {} facts, {} turns, {} essence, {} coordination · {}-dim · {} · {} snapshots{})",
                        path,
                        stats.memories,
                        counts.facts,
                        counts.turns,
                        counts.essence,
                        counts.coordination,
                        stats.dimensions,
                        if stats.encrypted {
                            "encrypted"
                        } else {
                            "plaintext"
                        },
                        snapshots,
                        if stats.index.is_some() {
                            " · ANN index built"
                        } else {
                            ""
                        },
                    );
                    if let Some(line) = mistagged_line(&mut db) {
                        println!("# {line}");
                    }
                    if let Some(hint) = upgrade_hint(&path, stats.format_version) {
                        println!("# {hint}");
                    }
                    if entries.is_empty() {
                        println!();
                        println!(
                            "(no onboarding memories — this database has no self-description.)"
                        );
                        println!("To make a database self-describing, store a memory with");
                        println!(
                            "  metadata = {{\"area\": \"onboarding\", \"topic\": \"manifest\"}}"
                        );
                        println!("that introduces the project, embedder, and conventions.");
                        print_essence();
                    } else {
                        println!();
                        println!(
                            "## Onboarding briefing ({} entries, most important first)",
                            entries.len()
                        );
                        for m in &entries {
                            let topic = m
                                .metadata
                                .get("topic")
                                .and_then(|v| v.as_str())
                                .unwrap_or("");
                            let is_scaffold = m
                                .metadata
                                .get("scaffold")
                                .and_then(|v| v.as_bool())
                                .unwrap_or(false);
                            let head = if topic.eq_ignore_ascii_case("manifest") {
                                if is_scaffold {
                                    format!(
                                        "MANIFEST (scaffold — please replace)  (importance={:.2})",
                                        m.importance
                                    )
                                } else {
                                    format!("MANIFEST  (importance={:.2})", m.importance)
                                }
                            } else if topic.is_empty() {
                                format!("(importance={:.2})", m.importance)
                            } else {
                                format!("[{}]  (importance={:.2})", topic, m.importance)
                            };
                            // 13a (13.6): past its review date.
                            let head = match mnemo_engine::stale_since(m, now) {
                                Some(t) => {
                                    format!("{head}  [stale since {}]", mnemo_engine::date_of(t))
                                }
                                None => head,
                            };
                            println!();
                            println!("### {head}");
                            println!("{}", m.content);
                        }
                        print_essence();
                        println!();
                        println!("## Quick start");
                        println!(
                            "  mnemo list   {path}                 # browse all live memories"
                        );
                        println!("  mnemo recall {path} --query VEC     # multi-signal recall");
                        println!("  mnemo get    {path} <ulid> --verbose # fetch one memory");
                    }
                }
            }
        }
        Command::Get {
            path,
            id,
            format,
            verbose,
            vector,
            passphrase: pp,
        } => {
            // `get` is a plain catalog lookup + record read — no writes.
            let pp = secret_for(&path, &pp, &None)?;
            let ulid = parse_ulid(id.as_deref().unwrap_or_default())?;
            let mut db = open_r(&path, &pp).map_err(fmt)?;
            let m = db.get(&ulid).map_err(fmt)?;
            // One memory: its whole content, even in the table.
            print_memory(&m, format, verbose, vector, true);
        }
        Command::List {
            path,
            format,
            r#type,
            agent,
            limit,
            offset,
            sort,
            vector,
            visibility,
            key_file,
            passphrase: pp,
        } => {
            let vis = mnemo_engine::VisibilitySet::parse(&visibility).map_err(fmt)?;
            let secret = secret_for(&path, &pp, &key_file)?;
            let types = match r#type {
                Some(s) => Some(parse_memory_types(&s)?),
                None => None,
            };
            let sort = sort.trim().to_ascii_lowercase();
            if !matches!(sort.as_str(), "created" | "importance" | "id") {
                return Err(format!(
                    "unknown sort '{sort}' (use created, importance, or id)"
                ));
            }
            // `list` is a bulk read of the catalog + record bodies — no writes.
            let mut db = open_ro(&path, &secret).map_err(fmt)?;
            let mut all = db.memories().map_err(fmt)?;

            // Filter. 13a (RB-013.2): private records only when asked.
            all.retain(|m| vis.shows(m));
            if let Some(ts) = &types {
                all.retain(|m| ts.contains(&m.memory_type));
            }
            if let Some(a) = &agent {
                all.retain(|m| &m.agent_id == a);
            }
            let total_after_filter = all.len();

            // Friendly nudge for unbounded browses on large stores.
            if limit.is_none() && total_after_filter > 10_000 {
                eprintln!(
                    "warning: {} memories — consider --limit; printing all anyway",
                    total_after_filter
                );
            }

            // Sort.
            match sort.as_str() {
                "created" => all.sort_by_key(|m| m.created_at),
                "importance" => {
                    all.sort_by(|a, b| b.importance.total_cmp(&a.importance));
                }
                "id" => all.sort_by_key(|m| m.id),
                _ => unreachable!(),
            }

            // Paginate.
            let start = offset.min(all.len());
            let end = match limit {
                Some(n) => (start + n).min(all.len()),
                None => all.len(),
            };
            let mut page: Vec<Memory> = all[start..end].to_vec();
            // Asked for private records: mark them in the table, as
            // `inspect` badges them.
            if vis.private && matches!(format, OutputFormat::Table) {
                for m in page.iter_mut() {
                    if mnemo_engine::visibility_of(m) == "private" {
                        m.content = format!("[private] {}", m.content);
                    }
                }
            }
            print_memories(&page, total_after_filter, format, vector);
        }
        Command::Export {
            path,
            format,
            r#type,
            agent,
            git,
            visibility,
            output,
            key_file,
            passphrase: pp,
        } => {
            let secret = secret_for(&path, &pp, &key_file)?;
            let types = match r#type {
                Some(s) => Some(parse_memory_types(&s)?),
                None => None,
            };
            if let Some(o) = &output {
                if let (Ok(a), Ok(b)) = (std::fs::canonicalize(o), std::fs::canonicalize(&path)) {
                    if a == b {
                        return Err(format!("refusing to write the export over {path} itself"));
                    }
                }
            }
            let mut db = open_ro(&path, &secret).map_err(fmt)?;
            let summary = db.stats_summary();
            let facts = export::FileFacts {
                format_version: summary.format_version,
                dimensions: summary.dimensions,
            };
            let mut all = db.memories().map_err(fmt)?;
            drop(db);
            // 13a (13.5): private records only when asked, never with --git.
            let vis = mnemo_engine::VisibilitySet::parse(&visibility).map_err(fmt)?;
            let vis = if git {
                mnemo_engine::VisibilitySet {
                    private: false,
                    ..vis
                }
            } else {
                vis
            };
            let before = all.len();
            let private = all
                .iter()
                .filter(|m| mnemo_engine::visibility_of(m) == "private")
                .count();
            all.retain(|m| vis.shows(m));
            if vis.private && private > 0 {
                eprintln!(
                    "mnemo: the export includes {private} private record{}",
                    if private == 1 { "" } else { "s" }
                );
            } else if private > 0 && before != all.len() {
                eprintln!(
                    "mnemo: {private} private record{} left out{}",
                    if private == 1 { " was" } else { "s were" },
                    if git {
                        " (`--git` never writes them)"
                    } else {
                        " (`--visibility all` includes them)"
                    }
                );
            }
            let opts = export::ExportOptions {
                format,
                git,
                types,
                agent,
            };
            let selected = export::select(all, &opts);
            let body = export::render(&selected, &opts, &facts);
            eprintln!(
                "warning: the export is plaintext, not encrypted; keep it as safe as \
                 the file's passphrase"
            );
            match output {
                Some(p) => {
                    export::write_private(&p, &body)?;
                    eprintln!("exported {} memories to {p}", selected.len());
                }
                None => {
                    use std::io::Write;
                    // A closed pipe (`| head`) isn't an error worth a panic.
                    let _ = std::io::stdout().lock().write_all(body.as_bytes());
                }
            }
        }
        Command::Inspect {
            path,
            port,
            open,
            idle_timeout,
            key_file,
            passphrase: pp,
        } => {
            let idle = inspect::parse_idle(&idle_timeout)?;
            let secret = secret_for(&path, &pp, &key_file)?;
            let loaded = inspect::load(&path, &secret)?;
            let listener = inspect::bind(port).map_err(|e| format!("binding 127.0.0.1: {e}"))?;
            let port = listener
                .local_addr()
                .map_err(|e| format!("binding 127.0.0.1: {e}"))?
                .port();
            let token = inspect::new_token();
            // The link carries a one-time code; the page exchanges it for
            // the token on its first load.
            let code = inspect::new_token();
            let url = format!("http://127.0.0.1:{port}/?c={code}");
            println!("inspecting {path} (read-only; the file is read once and closed)");
            println!("{url}");
            println!("the link opens one tab (it works once); press Ctrl-C to stop");
            {
                use std::io::Write;
                let _ = std::io::stdout().flush();
            }
            let watch = inspect::Watch::new();
            if open {
                if let Err(e) = inspect::open_browser(&url, watch.clone()) {
                    eprintln!("warning: couldn't open a browser ({e}); open the URL above");
                } else if cfg!(target_os = "linux") {
                    // RB-004.5 item 5: a snap or flatpak browser can't read
                    // the forwarding page under /tmp (tested: snap Firefox).
                    eprintln!(
                        "note: if the browser says the file can't be found (a snap or \
                         flatpak browser can't read /tmp), copy the link above instead"
                    );
                }
            }
            let state = std::sync::Arc::new(std::sync::Mutex::new(inspect::State::new(
                path, secret, loaded,
            )));
            inspect::serve(listener, token, code, state, watch, idle)
                .map_err(|e| format!("serving: {e}"))?;
        }
        Command::Recall {
            path,
            query,
            query_file,
            text,
            keywords,
            no_keywords,
            top_k,
            visibility,
            format,
            r#type,
            agent,
            metric,
            n_probe,
            n_rerank,
            no_track,
            session,
            filter,
            max_bytes,
            embed_cmd,
            embed_name,
            embed_normalize,
            embed_query,
            embed_timeout,
            key_file,
            passphrase: pp,
        } => {
            let secret = secret_for(&path, &pp, &key_file)?;
            if query.is_none() && query_file.is_none() && text.is_none() && keywords.is_none() {
                return Err(
                    "recall requires one of --query / --query-file / --text / --keywords".into(),
                );
            }

            // Open the `.mnemo` file for recall:
            //
            // * `--no-track` → `open_read_only` (shared flock,
            //   `track_access=false` on the request). Compatible with
            //   other readers, blocked only by exclusive writers.
            //
            // * default (tracking) → try `open` (exclusive flock) so
            //   recall can bump `accessed_at` / `access_count` in the
            //   catalog. If that fails because another holder has the
            //   shared or exclusive lock, print one line to stderr
            //   and fall back to `open_read_only` + `track_access=false`.
            //
            // Returns `(db, effective_no_track)` so the caller can
            // decide whether to flush after `recall`.
            let open_recall =
                |path: &str,
                 secret: &inspect::Secret,
                 no_track: bool|
                 -> std::result::Result<(Mnemo, bool), mnemo_engine::MnemoError> {
                    if no_track {
                        return open_ro(path, secret).map(|db| (db, true));
                    }
                    match open_rw(path, secret, "recall") {
                        Ok(db) => Ok((db, false)),
                        Err(mnemo_engine::MnemoError::Locked { .. }) => {
                            // R-004.4: open read-only first and print the
                            // notice only if that worked. An exclusive
                            // holder blocks the read-only open too, and
                            // then the `Locked` error is the whole story.
                            // One try (12.4): the write open already
                            // waited `--wait`, and a holder that kept it
                            // out almost always keeps a read out too, so a
                            // second full wait would double the delay.
                            let db = match secret {
                                inspect::Secret::Passphrase(p) => Mnemo::open_read_only(path, p),
                                inspect::Secret::Key(k) => Mnemo::open_read_only_with_key(path, k),
                            }?;
                            eprintln!(
                                "mnemo: another process holds the lock on {path}; \
                                 running recall read-only with --no-track"
                            );
                            Ok((db, true))
                        }
                        // The v8 sunset: a v8 file recalls read-only.
                        Err(mnemo_engine::MnemoError::FormatTooOld { version: 8 }) => {
                            let db = open_ro(path, secret)?;
                            eprintln!(
                                "mnemo: {path} is a v8 file, which opens read-only; running \
                                 recall with --no-track (`mnemo compact` converts it to v9)"
                            );
                            Ok((db, true))
                        }
                        Err(e) => Err(e),
                    }
                };

            // Resolve the query vector. The `--text` branch opens the
            // database up front so it can register an embedder on the
            // handle (`set_embedder`) and run it; it uses the same
            // lock-fallback as the vector branch. The vector branches
            // defer the open until after we've built `req`.
            // FMT-9d: `--keywords` adds a BM25 term; `--text` without an
            // embedder is keyword-only on v9.
            // 12.3 step 4: `--no-keywords` is `--keywords ""`, vector only.
            let mut keyword: Option<String> = if no_keywords {
                Some(String::new())
            } else {
                keywords
            };
            // The query text, for keyword matching (hybrid by default).
            let mut query_text: Option<String> = None;
            let (q, mut db_opt, mut effective_no_track) = match text {
                Some(text) => {
                    // 12.3 step 5: `--embed-cmd`, or else the built-in
                    // embedder, loaded (or fetched) before the open so no lock
                    // is held meanwhile. The built-in is used only on a file
                    // that records its identity, so a recall never records
                    // one; otherwise (and offline, or in a build without it)
                    // `--text` is matched by keyword only on a v9 file.
                    let mut builtin =
                        (embed_cmd.is_none() && builtin_ready()).then(builtin_embedder);
                    let (mut db, mut effective_no_track) =
                        open_recall(&path, &secret, no_track).map_err(fmt)?;
                    if embed_cmd.is_none() && builtin.is_none() {
                        let recorded = db.embedder_identity().map_err(fmt)?;
                        if recorded.is_some() && recorded == builtin_identity() {
                            // The first use on a file the built-in wrote: fetch
                            // the model with the file closed, then open again.
                            drop(db);
                            builtin = Some(builtin_embedder());
                            (db, effective_no_track) =
                                open_recall(&path, &secret, no_track).map_err(fmt)?;
                        }
                    }
                    let embedder = if embed_cmd.is_some() {
                        Ok(new_embedder(
                            embed_cmd.as_deref(),
                            embed_name.as_deref(),
                            embed_normalize,
                            embed_timeout,
                            embed_query.as_deref().unwrap_or_default(),
                            Some(db.dimensions()),
                        )?)
                    } else {
                        let recorded = db.embedder_identity().map_err(fmt)?;
                        match builtin {
                            Some(Ok(b)) if recorded.as_ref() == Some(&b.identity()) => Ok(b),
                            Some(Err(e)) => Err(e),
                            _ => Err(match recorded {
                                Some(r) => format!(
                                    "this file's embedder is {:?}, not the built-in (pass \
                                     --embed-cmd and --embed-name for it)",
                                    r.name
                                ),
                                None if builtin_identity().is_none() => {
                                    "this build has no built-in embedder".to_string()
                                }
                                None => "this file records no embedder yet".to_string(),
                            }),
                        }
                    };
                    match embedder {
                        Ok(embedder) => {
                            db.set_embedder(embedder).map_err(fmt)?;
                            let vector = {
                                let embedder_ref = db.embedder().ok_or_else(|| {
                                    "embedder vanished after set_embedder".to_string()
                                })?;
                                // 12.3 step 4: the query side.
                                let mut vs =
                                    embedder_ref.embed_query(&[text.as_str()]).map_err(fmt)?;
                                vs.pop()
                                    .ok_or_else(|| "embedder returned no vector".to_string())?
                            };
                            query_text = Some(text);
                            (vector, Some(db), effective_no_track)
                        }
                        Err(why) => {
                            if no_keywords {
                                return Err(format!(
                                    "--no-keywords with --text needs an embedder: {why}"
                                ));
                            }
                            // No embedder: keyword-only recall, which needs v9.
                            if db.stats_summary().format_version < 9 {
                                return Err(format!(
                                    "--text needs an embedder on a v8 file (or a v9 file, \
                                     which can recall by keyword): {why}"
                                ));
                            }
                            eprintln!("mnemo: recalling by keywords only: {why}");
                            if keyword.is_none() {
                                keyword = Some(text);
                            }
                            (Vec::new(), Some(db), effective_no_track)
                        }
                    }
                }
                None if query.is_none() && query_file.is_none() => (Vec::new(), None, no_track),
                None => (resolve_query(query, query_file)?, None, no_track),
            };

            let metric = parse_metric(&metric)?;
            let mut req = RecallRequest::new(q)
                .top_k(top_k)
                .metric(metric)
                .visibility(mnemo_engine::VisibilitySet::parse(&visibility).map_err(fmt)?);
            if let Some(k) = keyword {
                req = req.keywords(k);
            }
            if let Some(t) = query_text {
                req = req.text(t);
            }
            if let Some(s) = r#type {
                req = req.types(parse_memory_types(&s)?);
            }
            if let Some(a) = agent {
                req = req.agent(a);
            }
            if let Some(n) = n_probe {
                req = req.n_probe(n);
            }
            if let Some(n) = n_rerank {
                req = req.n_rerank(n);
            }
            // Phase 12.6: parse --session and the repeatable --filter
            // expressions into a single `Filter`. Empty filter == no
            // constraints.
            let mut f = mnemo_engine::Filter::default();
            if let Some(s) = session {
                f = f.with_session(s);
            }
            for expr in filter {
                f = parse_filter_expr(&expr, f)?;
            }
            req = req.filter(f);
            if let Some(b) = max_bytes {
                req = req.max_bytes(b);
            }

            // If the vector branch didn't pre-open, open now with the
            // same fallback semantics.
            let mut db = match db_opt.take() {
                Some(db) => db,
                None => {
                    let (db, eff_no_track) = open_recall(&path, &secret, no_track).map_err(fmt)?;
                    effective_no_track = eff_no_track;
                    db
                }
            };
            if effective_no_track {
                req = req.track_access(false);
            }
            let resp = db.recall_budgeted(&req).map_err(fmt)?;
            // R-001.4: a tracking recall mutates the catalog's
            // `accessed_at` / `access_count` in memory. Flush before
            // exit so the bumps reach disk — otherwise the usage
            // saturation signal is reset to zero on the next CLI
            // invocation. The read-only / fallback path doesn't
            // mutate, so skip the flush and avoid the needless
            // `ReadOnly` error from a read-only handle.
            if !effective_no_track {
                db.flush().map_err(fmt)?;
            }
            print_recall_hits(&resp.hits, format);
            // Phase 12.8: if the max_bytes budget cut anything, say
            // so on stderr so pipelines / scripts know the result is
            // bounded. The stdout format stays unchanged so existing
            // parsers keep working.
            if resp.truncated {
                eprintln!(
                    "(truncated: hits dropped by --max-bytes; rerun with a larger \
                     budget or smaller --top-k to see more)"
                );
            }
        }
        Command::Stale {
            path,
            mine,
            visibility,
            format,
            who,
            passphrase: pp,
        } => {
            let vis = mnemo_engine::VisibilitySet::parse(&visibility).map_err(fmt)?;
            let (agent, _) = who.resolve()?;
            if mine && agent.is_none() {
                return Err("--mine needs --as or MNEMO_AGENT".into());
            }
            let pp = secret_for(&path, &pp, &None)?;
            let mut db = open_ro(&path, &pp).map_err(fmt)?;
            note_mistagged(&mut db);
            let mut rows = db.stale().map_err(fmt)?;
            if mine {
                rows.retain(|r| r.whose == agent);
            }
            // RB-013.2: private records only when asked.
            rows.retain(|r| vis.shows_level(&r.visibility));
            let json = |r: &mnemo_engine::Stale| {
                serde_json::json!({
                    "id": r.id.to_string(), "what": r.what, "since": r.since,
                    "text": r.text, "whose": r.whose,
                })
            };
            match format {
                OutputFormat::Json => println!(
                    "{}",
                    serde_json::Value::Array(rows.iter().map(json).collect())
                ),
                OutputFormat::Jsonl => rows.iter().for_each(|r| println!("{}", json(r))),
                OutputFormat::Table => {
                    if rows.is_empty() {
                        println!("nothing stale");
                    }
                    for r in &rows {
                        println!(
                            "{}  {}  stale since {}{}  {}",
                            r.id,
                            r.what,
                            mnemo_engine::date_of(r.since),
                            r.whose
                                .as_deref()
                                .map(|w| format!(" ({w})"))
                                .unwrap_or_default(),
                            r.text
                        );
                    }
                }
            }
        }
        Command::Wake {
            cmd,
            who,
            brain: path,
            passphrase: pp,
        } => {
            let (agent, _) = who.resolve()?;
            let pp = secret_for(&path, &pp, &None)?;
            let mut db = open_w(&path, &pp, "wake").map_err(fmt)?;
            if agent.is_some() {
                db.set_author(agent);
            }
            match cmd {
                WakeCmd::Pause | WakeCmd::Resume => {
                    let pause = matches!(cmd, WakeCmd::Pause);
                    let o = db.set_wake_paused(pause).map_err(fmt)?;
                    db.flush().map_err(fmt)?;
                    let word = if pause { "paused" } else { "resumed" };
                    match o {
                        mnemo_engine::WriteOutcome::Unchanged => {
                            println!("wake-ups were already {word}")
                        }
                        _ => println!("wake-ups {word} for every session of this brain"),
                    }
                }
                WakeCmd::Status => {
                    match db.wake_paused().map_err(fmt)? {
                        Some((by, at)) => {
                            println!("wake-ups: paused (by {by}, {})", export::rfc3339(at))
                        }
                        None => println!("wake-ups: on"),
                    }
                    if std::env::var("MNEMO_WAKE").is_ok_and(|v| v.eq_ignore_ascii_case("off")) {
                        println!("MNEMO_WAKE=off: this session wakes for nothing");
                    }
                    let cwd = std::env::current_dir().unwrap_or_default();
                    let dir = project::toplevel(&cwd).unwrap_or(cwd);
                    let found = cross_session_inbound(&dir);
                    if found.is_empty() {
                        println!(
                            "crossSessionInbound: not set in the settings files found (keep it \
                             `accept` for this project's sessions)"
                        );
                    }
                    for (f, v) in found {
                        let note = if v == "accept" {
                            ""
                        } else {
                            " (wake-ups through a session's socket need `accept`)"
                        };
                        println!("crossSessionInbound: {v} in {f}{note}");
                    }
                }
            }
        }
        Command::Task {
            cmd,
            who,
            brain: path,
            passphrase: pp,
        } => {
            let (agent, role) = if matches!(cmd, TaskCmd::Add { .. }) {
                who.resolve_for_write()?
            } else {
                who.resolve()?
            };
            let pp = secret_for(&path, &pp, &None)?;
            let mut db = open_w(&path, &pp, "task").map_err(fmt)?;
            note_mistagged(&mut db);
            if agent.is_some() {
                db.set_author(agent.clone());
            }
            if agent.is_some()
                && matches!(
                    cmd,
                    TaskCmd::Add { .. } | TaskCmd::Next | TaskCmd::Update { .. }
                )
            {
                let _ = db.touch_presence(role.as_deref(), Some("cli"));
            }
            let task_json = |t: &mnemo_engine::Task| {
                serde_json::json!({
                    "slug": t.slug, "title": t.title, "body": t.body, "role": t.role,
                    "status": t.status, "owner": t.owner, "creator": t.creator,
                    "after": t.after, "pre_approved": t.pre_approved,
                    "created_at": t.created_at, "history": t.history,
                })
            };
            let row = |t: &mnemo_engine::Task| {
                format!(
                    "{}  [{}{}]  {}{}",
                    t.slug,
                    t.status,
                    t.owner
                        .as_deref()
                        .map(|o| format!(", {o}"))
                        .unwrap_or_default(),
                    t.title,
                    t.role
                        .as_deref()
                        .map(|r| format!("  (for {r})"))
                        .unwrap_or_default()
                )
            };
            let out: std::result::Result<(), String> = match &cmd {
                TaskCmd::Add {
                    title,
                    body,
                    for_role,
                    after,
                    pre_approved,
                    slug,
                } => {
                    let spec = mnemo_engine::TaskSpec {
                        title: title.clone(),
                        body: body.clone(),
                        role: for_role.clone(),
                        after: after.clone(),
                        pre_approved: *pre_approved,
                        slug: slug.clone(),
                    };
                    let (t, o) = db.task_add(&spec).map_err(fmt)?;
                    let o = match o {
                        mnemo_engine::WriteOutcome::Added => "added",
                        mnemo_engine::WriteOutcome::Unchanged => "unchanged",
                        _ => "updated",
                    };
                    println!("{}\t{o}\t{}", t.slug, t.status);
                    Ok(())
                }
                TaskCmd::Next => match db.task_next(role.as_deref()).map_err(fmt)? {
                    Some(t) => {
                        println!(
                            "{}\t{}\t{}\t{}",
                            t.task.slug,
                            t.token,
                            export::rfc3339(t.expires_at),
                            t.task.title
                        );
                        if let Some(o) = &t.reclaimed_from {
                            eprintln!("mnemo: taken back from {o}, whose claim lapsed");
                        }
                        Ok(())
                    }
                    None => Err(format!(
                        "nothing to take for {}",
                        role.as_deref()
                            .map(|r| format!("role {r}"))
                            .unwrap_or("no role".into())
                    )),
                },
                TaskCmd::Update {
                    slug,
                    status,
                    note,
                    token,
                } => {
                    match db
                        .task_update(slug, status.as_deref(), note.as_deref(), token.as_deref())
                        .map_err(fmt)?
                    {
                        mnemo_engine::TaskOutcome::Updated(t, claim) => {
                            match claim {
                                // RB-012.1: the claim the owner now holds.
                                Some(c) => {
                                    println!(
                                        "{}\t{}\t{}\t{}",
                                        t.slug,
                                        t.status,
                                        c.token,
                                        export::rfc3339(c.expires_at)
                                    );
                                    if c.retaken {
                                        eprintln!(
                                            "mnemo: your claim had lapsed and nobody took {}, so \
                                             it's yours again, with a new token",
                                            t.slug
                                        );
                                    }
                                }
                                None => println!("{}\t{}", t.slug, t.status),
                            }
                            Ok(())
                        }
                        mnemo_engine::TaskOutcome::Lost(mnemo_engine::TaskLost::TakenBack) => {
                            Err(format!(
                                "lost: another agent took {slug} back after your claim lapsed; \
                                 nothing changed"
                            ))
                        }
                        mnemo_engine::TaskOutcome::Lost(mnemo_engine::TaskLost::OtherToken) => {
                            Err(format!(
                                "lost: that token isn't {slug}'s claim's (another session of \
                                 yours may hold it); nothing changed"
                            ))
                        }
                    }
                }
                TaskCmd::List {
                    status,
                    for_role,
                    format,
                } => {
                    let ts = db
                        .tasks(status.as_deref(), for_role.as_deref())
                        .map_err(fmt)?;
                    match format {
                        OutputFormat::Json => println!(
                            "{}",
                            serde_json::Value::Array(ts.iter().map(task_json).collect())
                        ),
                        OutputFormat::Jsonl => ts.iter().for_each(|t| println!("{}", task_json(t))),
                        OutputFormat::Table => {
                            if ts.is_empty() {
                                println!("no tasks");
                            }
                            ts.iter().for_each(|t| println!("{}", row(t)));
                        }
                    }
                    Ok(())
                }
                TaskCmd::Get { slug, format } => match db.task(slug).map_err(fmt)? {
                    None => Err(format!("no task {slug:?}")),
                    Some(t) => {
                        match format {
                            OutputFormat::Table => {
                                println!("{}", row(&t));
                                for l in t.body.lines() {
                                    println!("    {l}");
                                }
                                if !t.after.is_empty() {
                                    println!("    after: {}", t.after.join(", "));
                                }
                                for h in &t.history {
                                    println!(
                                        "    {} {} -> {} by {}{}",
                                        export::rfc3339(h["at"].as_i64().unwrap_or(0)),
                                        h["from"].as_str().unwrap_or(""),
                                        h["to"].as_str().unwrap_or(""),
                                        h["by"].as_str().unwrap_or(""),
                                        h["note"]
                                            .as_str()
                                            .map(|n| format!(": {n}"))
                                            .unwrap_or_default()
                                    );
                                }
                            }
                            _ => println!("{}", task_json(&t)),
                        }
                        Ok(())
                    }
                },
            };
            db.flush().map_err(fmt)?;
            out?;
        }
        Command::Claim {
            cmd,
            who,
            brain: path,
            passphrase: pp,
        } => {
            let (agent, role) = if matches!(
                cmd,
                ClaimCmd::Take { .. } | ClaimCmd::Renew { .. } | ClaimCmd::Release { .. }
            ) {
                who.resolve_for_write()?
            } else {
                who.resolve()?
            };
            let pp = secret_for(&path, &pp, &None)?;
            let mut db = open_w(&path, &pp, "claim").map_err(fmt)?;
            note_mistagged(&mut db);
            if agent.is_some() {
                db.set_author(agent.clone());
            }
            let writes = matches!(
                cmd,
                ClaimCmd::Take { .. } | ClaimCmd::Renew { .. } | ClaimCmd::Release { .. }
            );
            if writes {
                let _ = db.touch_presence(role.as_deref(), Some("cli"));
            }
            let ttl = |t: &Option<String>| t.as_deref().map(parse_ttl).transpose();
            let lost = |topic: &str| {
                format!(
                    "lost: the claim on {topic:?} lapsed or another agent holds it; don't take                      an irreversible step on it"
                )
            };
            let when = |t: i64| export::rfc3339(t);
            let out: std::result::Result<(), String> = match &cmd {
                ClaimCmd::Take { topic, ttl: t } => match db.claim(topic, ttl(t)?).map_err(fmt)? {
                    mnemo_engine::ClaimOutcome::Claimed { token, expires_at } => {
                        println!("claimed\t{token}\t{}", when(expires_at));
                        Ok(())
                    }
                    mnemo_engine::ClaimOutcome::HeldBy {
                        agent: a,
                        expires_at,
                    } => Err(format!(
                        "{topic:?} is held by {a} until {}",
                        when(expires_at)
                    )),
                },
                ClaimCmd::Renew {
                    topic,
                    token,
                    ttl: t,
                } => match db.renew(topic, token, ttl(t)?).map_err(fmt)? {
                    mnemo_engine::ClaimStatus::Held { expires_at } => {
                        println!("held until {}", when(expires_at));
                        Ok(())
                    }
                    _ => Err(lost(topic)),
                },
                ClaimCmd::Release { topic, token } => {
                    match db.release(topic, token).map_err(fmt)? {
                        mnemo_engine::ClaimStatus::Released => {
                            println!("released");
                            Ok(())
                        }
                        _ => Err(lost(topic)),
                    }
                }
                ClaimCmd::Check { topic, token } => {
                    match db.check_claim(topic, token).map_err(fmt)? {
                        mnemo_engine::ClaimStatus::Held { expires_at } => {
                            println!("held until {}", when(expires_at));
                            Ok(())
                        }
                        _ => Err(lost(topic)),
                    }
                }
                ClaimCmd::Who { format } => {
                    let rows = db.who().map_err(fmt)?;
                    let alive = |a: mnemo_engine::Alive| match a {
                        mnemo_engine::Alive::Yes => "yes",
                        mnemo_engine::Alive::No => "no",
                        mnemo_engine::Alive::Unknown => "unknown",
                    };
                    let json = |p: &mnemo_engine::Presence| {
                        serde_json::json!({
                            "agent": p.agent, "role": p.role, "tool": p.tool,
                            "last_active": p.last_active, "alive": alive(p.alive),
                            "claims": p.claims,
                        })
                    };
                    match format {
                        OutputFormat::Json => println!(
                            "{}",
                            serde_json::Value::Array(rows.iter().map(json).collect())
                        ),
                        OutputFormat::Jsonl => {
                            for p in &rows {
                                println!("{}", json(p));
                            }
                        }
                        OutputFormat::Table => {
                            if rows.is_empty() {
                                println!("no agents yet");
                            }
                            for p in &rows {
                                println!(
                                    "{}  role {}  {}  alive {}  last active {}{}",
                                    p.agent,
                                    p.role.as_deref().unwrap_or("-"),
                                    p.tool.as_deref().unwrap_or("-"),
                                    alive(p.alive),
                                    when(p.last_active),
                                    if p.claims.is_empty() {
                                        String::new()
                                    } else {
                                        format!("  holds {}", p.claims.join(", "))
                                    }
                                );
                            }
                        }
                    }
                    Ok(())
                }
            };
            db.flush().map_err(fmt)?;
            out?;
        }
        Command::Post {
            to,
            subject,
            body,
            refs,
            conversation,
            who,
            brain: path,
            passphrase: pp,
        } => {
            let (agent, role) = who.resolve_for_write()?;
            let pp = secret_for(&path, &pp, &None)?;
            let mut db = open_w(&path, &pp, "post").map_err(fmt)?;
            note_mistagged(&mut db);
            if agent.is_some() {
                db.set_author(agent.clone());
                let _ = db.touch_presence(role.as_deref(), Some("cli"));
            }
            let m = db
                .post(
                    &to,
                    &subject,
                    &body,
                    &refs,
                    conversation.as_deref(),
                    agent.as_deref(),
                    role.as_deref(),
                )
                .map_err(fmt)?;
            db.flush().map_err(fmt)?;
            println!("{}\thop {}", m.id, m.hops);
        }
        Command::Inbox {
            path,
            all,
            visibility,
            prune,
            days,
            format,
            who,
            passphrase: pp,
        } => {
            let (agent, role) = who.resolve()?;
            let pp = secret_for(&path, &pp, &None)?;
            let mut db = open_w(&path, &pp, "inbox").map_err(fmt)?;
            note_mistagged(&mut db);
            if agent.is_some() {
                db.set_author(agent.clone());
                let _ = db.touch_presence(role.as_deref(), Some("cli"));
            }
            if prune {
                let n = db.prune_messages(i64::from(days) * 86_400).map_err(fmt)?;
                db.flush().map_err(fmt)?;
                println!("pruned {n} acked message{}", if n == 1 { "" } else { "s" });
                return Ok(());
            }
            if agent.is_none() && role.is_none() {
                eprintln!("mnemo: no MNEMO_AGENT or --as: showing only messages to `all`");
            }
            let msgs = db
                .inbox_in(
                    agent.as_deref(),
                    role.as_deref(),
                    !all,
                    mnemo_engine::VisibilitySet::parse(&visibility).map_err(fmt)?,
                )
                .map_err(fmt)?;
            let unseen: Vec<mnemo_engine::Ulid> = msgs.iter().map(|m| m.id).collect();
            db.mark_seen(&unseen).map_err(fmt)?;
            db.flush().map_err(fmt)?;
            match format {
                OutputFormat::Json => println!(
                    "{}",
                    serde_json::Value::Array(msgs.iter().map(message_json).collect())
                ),
                OutputFormat::Jsonl => {
                    for m in &msgs {
                        println!("{}", message_json(m));
                    }
                }
                OutputFormat::Table => {
                    if msgs.is_empty() {
                        println!("no messages");
                    }
                    for m in &msgs {
                        print_message(m);
                    }
                }
            }
        }
        Command::Ack {
            path,
            id,
            note,
            who,
            passphrase: pp,
        } => {
            let (agent, role) = who.resolve()?;
            let id = id.unwrap_or_default();
            let ulid = parse_ulid(&id)?;
            let pp = secret_for(&path, &pp, &None)?;
            let mut db = open_w(&path, &pp, "ack").map_err(fmt)?;
            note_mistagged(&mut db);
            if agent.is_some() {
                db.set_author(agent.clone());
                let _ = db.touch_presence(role.as_deref(), Some("cli"));
            }
            let outcome = db
                .ack(&ulid, note.as_deref(), agent.as_deref())
                .map_err(fmt)?;
            db.flush().map_err(fmt)?;
            let s = match outcome {
                mnemo_engine::WriteOutcome::Unchanged => "unchanged",
                _ => "acked",
            };
            println!("{id}\t{s}");
        }
        Command::DefaultAgent {
            path,
            set,
            clear,
            passphrase: pp,
        } => {
            let pp = secret_for(&path, &pp, &None)?;
            if set.is_none() && !clear {
                let mut db = open_r(&path, &pp).map_err(fmt)?;
                match db.default_agent().map_err(fmt)? {
                    Some(a) => println!("{a}"),
                    None => println!("(none: writes that name no agent go to `default`)"),
                }
            } else {
                let mut db = open_w(&path, &pp, "default-agent").map_err(fmt)?;
                let outcome = db.set_default_agent(set.as_deref()).map_err(fmt)?;
                db.flush().map_err(fmt)?;
                let what = set.as_deref().unwrap_or("(none)");
                match outcome {
                    mnemo_engine::WriteOutcome::Unchanged => println!("{what}\tunchanged"),
                    _ => println!("{what}\tupdated"),
                }
            }
        }
        Command::Demo { path } => demo(&path).map_err(fmt)?,
        Command::Update {
            path,
            id,
            text,
            fresh,
            importance,
            metadata,
            ttl_secs,
            clear_ttl,
            embed_cmd,
            embed_name,
            embed_normalize,
            embed_query,
            embed_timeout,
            passphrase: pp,
        } => {
            use mnemo_engine::{MemoryPatch, WriteOutcome};
            let pp = secret_for(&path, &pp, &None)?;
            let id = id.unwrap_or_default();
            let ulid = parse_ulid(&id)?;

            let mut patch = MemoryPatch::default();
            if let Some(i) = importance {
                patch.importance = Some(i);
            }
            let keys = fresh.keys()?;
            if !keys.is_empty() {
                patch.caller_keys = Some(keys);
            }
            if let Some(meta_str) = metadata {
                let parsed: serde_json::Value = serde_json::from_str(&meta_str)
                    .map_err(|e| format!("invalid --metadata JSON: {e}"))?;
                let obj = parsed
                    .as_object()
                    .ok_or_else(|| "--metadata must be a JSON object".to_string())?;
                patch.metadata = Some(obj.clone());
            }
            if clear_ttl {
                patch.ttl_secs = Some(None);
            } else if let Some(ttl) = ttl_secs {
                patch.ttl_secs = Some(Some(ttl));
            }

            let (mut db, outcome) = match text {
                Some(t) => {
                    // 12.4: embed first, then take the write lock. 12.3 step
                    // 5: with no `--embed-cmd`, the built-in embedder.
                    match embed_first(
                        &path,
                        embed_cmd.as_deref(),
                        embed_name.as_deref(),
                        embed_normalize,
                        embed_timeout,
                        embed_query.as_deref().unwrap_or_default(),
                        &[t.as_str()],
                    )? {
                        Some((embedder, mut vectors)) => {
                            let vector = vectors.pop().ok_or_else(|| {
                                "embedder returned no vector for the input text".to_string()
                            })?;
                            let mut db = open_w(&path, &pp, "update").map_err(fmt)?;
                            db.set_embedder(embedder).map_err(fmt)?;
                            // As `update_text` does, with the vector already made.
                            if vector.len() != db.dimensions() {
                                return Err(fmt(mnemo_engine::MnemoError::DimensionMismatch {
                                    expected: db.dimensions(),
                                    got: vector.len(),
                                }));
                            }
                            patch.content = Some(t);
                            patch.vector = Some(vector);
                            let outcome = db.update(&ulid, patch).map_err(fmt)?;
                            (db, outcome)
                        }
                        None => {
                            let mut db = open_w(&path, &pp, "update").map_err(fmt)?;
                            let embedder = new_embedder(
                                embed_cmd.as_deref(),
                                embed_name.as_deref(),
                                embed_normalize,
                                embed_timeout,
                                embed_query.as_deref().unwrap_or_default(),
                                Some(db.dimensions()),
                            )?;
                            db.set_embedder(embedder).map_err(fmt)?;
                            let outcome = db.update_text(&ulid, &t, patch).map_err(fmt)?;
                            (db, outcome)
                        }
                    }
                }
                None => {
                    let mut db = open_w(&path, &pp, "update").map_err(fmt)?;
                    let outcome = db.update(&ulid, patch).map_err(fmt)?;
                    (db, outcome)
                }
            };
            db.flush().map_err(fmt)?;
            let outcome_str = match outcome {
                WriteOutcome::Updated => "updated",
                WriteOutcome::Unchanged => "unchanged",
                // Not reachable on `update`, but keep the match total.
                WriteOutcome::Added => "updated",
                WriteOutcome::Superseded => "updated",
            };
            println!("{id}\t{outcome_str}");
        }
        Command::History {
            path,
            key,
            agent,
            shared,
            format,
            visibility,
            passphrase: pp,
        } => {
            let vis = mnemo_engine::VisibilitySet::parse(&visibility).map_err(fmt)?;
            use mnemo_engine::KeyScope;
            let pp = secret_for(&path, &pp, &None)?;
            let mut db = open_r(&path, &pp).map_err(fmt)?;
            // v0.8.1 bugfix: default slot matches keyed remember with
            // the same arguments. No `--shared`, no `--agent` → default
            // agent's private slot.
            let scope = if shared {
                KeyScope::Shared
            } else {
                // 13a (AGENT-DEFAULT): no `--agent`, the brain's default.
                match agent.or(db.default_agent().map_err(fmt)?) {
                    Some(a) => KeyScope::Private(a),
                    None => KeyScope::private_default(),
                }
            };
            // RB-013.2: each version's state first, then the levels shown,
            // so a hidden live version never makes an older one look live.
            let chain: Vec<(&str, Memory)> = db
                .history_in(&key, scope)
                .map_err(fmt)?
                .into_iter()
                .enumerate()
                .map(|(i, m)| (if i == 0 { "live" } else { "superseded" }, m))
                .filter(|(_, m)| vis.shows(m))
                .collect();
            match format {
                OutputFormat::Table => {
                    if chain.is_empty() {
                        println!("no history for key={key}");
                    } else {
                        for (state, m) in chain.iter() {
                            println!(
                                "{state:<10} {id}  created_at={ct}  {content}",
                                id = m.id,
                                ct = m.created_at,
                                content = truncate(&m.content, 80),
                            );
                        }
                    }
                }
                OutputFormat::Json => {
                    let arr: Vec<_> = chain
                        .iter()
                        .map(|(state, m)| {
                            let mut v = memory_to_json(m, false);
                            if let Some(obj) = v.as_object_mut() {
                                obj.insert(
                                    "state".into(),
                                    serde_json::Value::String((*state).into()),
                                );
                            }
                            v
                        })
                        .collect();
                    println!(
                        "{}",
                        serde_json::to_string_pretty(
                            &serde_json::json!({ "count": arr.len(), "chain": arr }),
                        )
                        .unwrap_or_else(|_| "{}".into())
                    );
                }
                OutputFormat::Jsonl => {
                    for (state, m) in chain.iter() {
                        let mut v = memory_to_json(m, false);
                        if let Some(obj) = v.as_object_mut() {
                            obj.insert("state".into(), serde_json::Value::String((*state).into()));
                        }
                        println!(
                            "{}",
                            serde_json::to_string(&v).unwrap_or_else(|_| "{}".into())
                        );
                    }
                }
            }
        }
        Command::Thread { cmd } => handle_thread_cmd(cmd)?,
        Command::Essence { cmd } => handle_essence_cmd(cmd)?,
        Command::Snapshots {
            path,
            passphrase: pp,
        } => {
            let pp = secret_for(&path, &pp, &None)?;
            let db = open_r(&path, &pp).map_err(fmt)?;
            let snaps = db.snapshots();
            if snaps.is_empty() {
                println!("no snapshots yet (nothing has been flushed)");
            } else {
                println!("{:<8}  {:<12}  committed (unix)", "txn", "memories");
                for s in snaps {
                    println!("{:<8}  {:<12}  {}", s.txn_id, s.memory_count, s.created_at);
                }
            }
        }
        Command::Restore {
            path,
            to_txn,
            to_time,
            passphrase: pp,
        } => {
            let pp = secret_for(&path, &pp, &None)?;
            let mut db = open_w(&path, &pp, "restore").map_err(fmt)?;
            let info = match (to_txn, to_time) {
                (Some(txn), _) => db.restore_to(txn).map_err(fmt)?,
                (None, Some(t)) => db.restore_to_time(t).map_err(fmt)?,
                (None, None) => return Err("restore needs --to-txn or --to-time".to_string()),
            };
            println!(
                "restored {path} to snapshot txn {} ({} memories)",
                info.txn_id, info.memory_count
            );
        }
        Command::Serve {
            path,
            mcp,
            embed_cmd,
            embed_name,
            embed_normalize,
            embed_query,
            embed_timeout,
            shared,
            allow_network_fs,
        } => {
            if !mcp {
                return Err("serve requires --mcp today (other transports may come later)".into());
            }
            // The MCP server finds its secret itself, through the key-source
            // chain with no prompt (12.3) — passing `passphrase()` here would
            // open a TTY prompt and break the
            // stdio JSON-RPC handshake. Stderr is safe for diagnostics.
            let resolved = serve_path(&path)?;
            let p = resolved.as_path();
            let shared = shared.then(|| {
                let mut o = wait_opts();
                o.allow_network_fs = allow_network_fs;
                o
            });
            match (embed_cmd, embed_name) {
                (Some(c), Some(n)) => {
                    let spec = mnemo_engine::mcp::EmbedSpec {
                        command: c,
                        name: n,
                        normalize: embed_normalize,
                        timeout: std::time::Duration::from_secs(embed_timeout),
                        query_convention: embed_query.unwrap_or_default(),
                    };
                    mnemo_engine::mcp::serve_stdio_with_spec(p, Some(spec), shared)
                }
                (None, None) => serve_builtin(p, shared),
                _ => return Err("--embed-cmd and --embed-name go together".into()),
            }
            .map_err(fmt)?;
        }
        Command::Onboard {
            guide,
            format,
            client,
            scope,
            hook_budget,
            yes,
            print,
            no_model,
            undo,
            plugin,
            wake,
        } => {
            if !guide {
                return onboard::run(onboard::Opts {
                    clients: client,
                    scope,
                    hook_budget,
                    yes,
                    print,
                    no_model,
                    undo,
                    plugin,
                    moved,
                    wake,
                });
            }
            let text = match format {
                GuideFormat::Markdown => mnemo_engine::guide::markdown(),
                GuideFormat::LlmsTxt => mnemo_engine::guide::llms_txt(),
                GuideFormat::LlmsFull => mnemo_engine::guide::llms_full(),
                GuideFormat::PluginSkill => mnemo_engine::guide::plugin_skill_md(),
            };
            print!("{text}");
        }
        Command::Hook {
            event,
            client,
            budget,
        } => hook::run(hook::Opts {
            event,
            client,
            budget,
            moved,
        }),
        Command::Embedder { cmd } => run_embedder(cmd)?,
        Command::Cache { op } => run_cache_op(op)?,
        Command::Mcp {
            cmd:
                McpCmd::Install {
                    client,
                    scope,
                    name,
                    print,
                    yes,
                    path,
                },
        } => mcp_install::run(mcp_install::Install {
            client,
            file: path,
            project: project_brain,
            scope,
            name,
            print,
            yes,
        })?,
    }
    Ok(())
}

/// Dispatch a `mnemo cache …` subcommand. Kept out of `run()` to hold
/// the main match down to one line per subcommand.
fn run_cache_op(op: CacheOp) -> std::result::Result<(), String> {
    use mnemo_engine::CachePutOpts;

    match op {
        CacheOp::Get {
            path,
            ns,
            key,
            passphrase: pp,
        } => {
            let pp = secret_for(&path, &pp, &None)?;
            // Get on a cache is a mutation (bumps access stats) unless
            // the handle is read-only. Use read-write here so the stats
            // update lands durably on the next user-driven flush. A v8
            // file opens read-only (the v8 sunset), so its stats stay.
            let mut db = match open_w(&path, &pp, "cache get") {
                Err(mnemo_engine::MnemoError::FormatTooOld { version: 8 }) => {
                    open_r(&path, &pp).map_err(fmt)?
                }
                other => other.map_err(fmt)?,
            };
            match db.cache_get(&ns, &key).map_err(fmt)? {
                Some(v) => {
                    // Print value to stdout verbatim. If the caller
                    // asked for binary content-type, they can pipe;
                    // the CLI does not decode.
                    use std::io::Write;
                    std::io::stdout()
                        .write_all(&v.value)
                        .map_err(|e| e.to_string())?;
                    // A trailing newline for terminal ergonomics when
                    // the content is text; skip if the value already
                    // ends in one to avoid double-newlines in scripts.
                    if !v.value.ends_with(b"\n") {
                        println!();
                    }
                    // Persist the access-stats bump.
                    db.flush().map_err(fmt)?;
                }
                None => {
                    return Err(format!("cache miss on ({ns}, {key})"));
                }
            }
        }
        CacheOp::Put {
            path,
            ns,
            key,
            value,
            file,
            content_type,
            ttl,
            passphrase: pp,
        } => {
            let pp = secret_for(&path, &pp, &None)?;
            let bytes = match (value, file) {
                (Some(v), None) => v.into_bytes(),
                (None, Some(f)) => std::fs::read(&f).map_err(|e| format!("read {f}: {e}"))?,
                (Some(_), Some(_)) => {
                    return Err("--value and --file are mutually exclusive".into())
                }
                (None, None) => {
                    return Err("cache put needs --value <string> or --file <path>".into())
                }
            };
            let opts = CachePutOpts {
                content_type,
                ttl_secs: ttl,
                cost_hint_ms: None,
            };
            let mut db = open_w(&path, &pp, "cache put").map_err(fmt)?;
            db.cache_put(&ns, &key, &bytes, opts).map_err(fmt)?;
            db.flush().map_err(fmt)?;
            println!("cached {} bytes at ({ns}, {key})", bytes.len());
        }
        CacheOp::Delete {
            path,
            ns,
            key,
            passphrase: pp,
        } => {
            let pp = secret_for(&path, &pp, &None)?;
            let mut db = open_w(&path, &pp, "cache delete").map_err(fmt)?;
            db.cache_delete(&ns, &key).map_err(fmt)?;
            db.flush().map_err(fmt)?;
            println!("deleted ({ns}, {key}) (space reclaimed on next compact)");
        }
        CacheOp::Stats {
            path,
            ns,
            passphrase: pp,
        } => {
            let pp = secret_for(&path, &pp, &None)?;
            // Read-only handle is fine — stats is a pure scan.
            let db = open_r(&path, &pp).map_err(fmt)?;
            let s = db.cache_stats(ns.as_deref());
            let obj = serde_json::json!({
                "namespace": ns,
                "entries": s.entries,
                "bytes": s.bytes,
                "hits": s.hits,
                "misses": s.misses,
                "hit_rate": s.hit_rate,
                "evictions": s.evictions,
            });
            println!("{}", serde_json::to_string_pretty(&obj).unwrap());
        }
        CacheOp::Purge {
            path,
            ns,
            expired,
            passphrase: pp,
        } => {
            let pp = secret_for(&path, &pp, &None)?;
            let mut db = open_w(&path, &pp, "cache purge").map_err(fmt)?;
            let n = db.cache_purge(ns.as_deref(), expired).map_err(fmt)?;
            db.flush().map_err(fmt)?;
            println!("purged {n} entr{}", if n == 1 { "y" } else { "ies" });
        }
    }
    Ok(())
}

/// Build a [`Memory`] from one JSONL line.
fn memory_from_json(line: &str) -> std::result::Result<Memory, String> {
    use serde_json::Value;
    let v: Value = serde_json::from_str(line).map_err(|e| e.to_string())?;
    let content = v
        .get("content")
        .and_then(Value::as_str)
        .ok_or("missing string field 'content'")?;
    let vec_json = v
        .get("vector")
        .and_then(Value::as_array)
        .ok_or("missing array field 'vector'")?;
    let vector: Vec<f32> = vec_json
        .iter()
        .map(|x| {
            x.as_f64()
                .map(|f| f as f32)
                .ok_or("vector element not a number")
        })
        .collect::<std::result::Result<_, _>>()?;
    let mt = v
        .get("memory_type")
        .and_then(Value::as_str)
        .and_then(MemoryType::parse)
        .unwrap_or(MemoryType::Semantic);
    let mut m = Memory::new(content, mt, vector);
    if let Some(a) = v.get("agent_id").and_then(Value::as_str) {
        m = m.with_agent(a);
    }
    if let Some(i) = v.get("importance").and_then(Value::as_f64) {
        m = m.with_importance(i as f32);
    }
    Ok(m)
}

fn fmt(e: mnemo_engine::MnemoError) -> String {
    // 12.3: a wrong secret names where it came from, and the next source of
    // the same kind that's present (no fall-through).
    if matches!(e, mnemo_engine::MnemoError::WrongPassphrase) {
        if let Some((src, next)) = SOURCE.get() {
            return match next {
                Some(n) => format!("{e} (the secret came from {src}; without it, {n} comes next)"),
                None => format!("{e} (the secret came from {src})"),
            };
        }
    }
    e.to_string()
}

/// Phase 12.7a: handle `mnemo thread {ingest|export|forget}`. Split
/// into its own function because the three subcommands share nothing
/// with the top-level dispatch beyond passphrase resolution.
/// 12.4: ingest `turns` into `thread`: plan under a short read (which turns
/// are new, and the chunk texts), embed them with no lock held, then write
/// the vectors under the write lock. If another process ingested in
/// between, the plan is made again under the lock and only the texts that
/// weren't embedded yet are embedded there. `make_embedder` gets the
/// brain's width. Used by `thread ingest` and the hooks (12.2).
fn ingest_turns(
    path: &str,
    pp: &inspect::Secret,
    thread: &str,
    turns: &[mnemo_engine::ThreadTurn],
    op: &str,
    make_embedder: impl FnOnce(usize) -> std::result::Result<Box<dyn mnemo_engine::Embedder>, String>,
) -> std::result::Result<mnemo_engine::IngestReport, String> {
    // 12.4: plan under a short read (which turns are new, and the
    // chunk texts), embed them with no lock held, then write the
    // vectors under the write lock. If another process ingested in
    // between, the plan is made again under the lock and only the
    // texts that weren't embedded yet are embedded there.
    let (texts, dimensions) = {
        let mut db = open_r(path, pp).map_err(fmt)?;
        (
            db.ingest_thread_texts(thread, turns).map_err(fmt)?,
            db.dimensions(),
        )
    };
    let embedder = make_embedder(dimensions)?;
    let pre: Vec<Vec<f32>> = if texts.is_empty() {
        Vec::new()
    } else {
        use mnemo_engine::Embedder;
        let refs: Vec<&str> = texts.iter().map(String::as_str).collect();
        embedder.embed(&refs).map_err(fmt)?
    };
    let mut db = open_w(path, pp, op).map_err(fmt)?;
    db.set_embedder(embedder).map_err(fmt)?;
    let now = db.ingest_thread_texts(thread, turns).map_err(fmt)?;
    let report = if now == texts {
        db.ingest_thread_with_vectors(thread, turns, &pre)
            .map_err(fmt)?
    } else {
        let mut have: std::collections::HashMap<&str, &Vec<f32>> =
            texts.iter().map(String::as_str).zip(pre.iter()).collect();
        let missing: Vec<&str> = now
            .iter()
            .map(String::as_str)
            .filter(|t| !have.contains_key(t))
            .collect();
        let extra = if missing.is_empty() {
            Vec::new()
        } else {
            db.embedder()
                .ok_or_else(|| "no embedder registered".to_string())?
                .embed(&missing)
                .map_err(fmt)?
        };
        for (t, v) in missing.iter().zip(extra.iter()) {
            have.insert(t, v);
        }
        let vectors = now
            .iter()
            .map(|t| have.get(t.as_str()).map(|v| (*v).clone()))
            .collect::<Option<Vec<_>>>()
            .ok_or_else(|| "embedder returned too few vectors".to_string())?;
        db.ingest_thread_with_vectors(thread, turns, &vectors)
            .map_err(fmt)?
    };
    db.flush().map_err(fmt)?;
    Ok(report)
}

fn handle_thread_cmd(cmd: ThreadCmd) -> std::result::Result<(), String> {
    use mnemo_engine::{read_transcript_with, TranscriptFormat};
    use std::io::{Read, Write};
    match cmd {
        ThreadCmd::Ingest {
            path,
            thread,
            transcript,
            format,
            tool_results,
            redact,
            embed_cmd,
            embed_name,
            embed_normalize,
            embed_query,
            embed_timeout,
            passphrase: pp,
        } => {
            let pp = secret_for(&path, &pp, &None)?;
            let fmt_enum = TranscriptFormat::parse(&format).ok_or_else(|| {
                format!("unknown --format '{format}' (want 'jsonl' or 'claude-code-jsonl')")
            })?;
            // Read the transcript (stdin with `-`, else the file).
            let opts = mnemo_engine::TranscriptOptions {
                tool_results: tool_results.into(),
                lenient: false,
            };
            let mut turns = if transcript == "-" {
                let mut buf = Vec::new();
                std::io::stdin()
                    .read_to_end(&mut buf)
                    .map_err(|e| format!("reading stdin: {e}"))?;
                read_transcript_with(&buf[..], fmt_enum, opts).map_err(fmt)?
            } else {
                let file = std::fs::File::open(&transcript)
                    .map_err(|e| format!("opening {transcript}: {e}"))?;
                read_transcript_with(file, fmt_enum, opts).map_err(fmt)?
            };
            if redact {
                let counts = hook::redact_turns(&mut turns);
                if let Some(line) = hook::redaction_note(&counts) {
                    eprintln!("{line}");
                }
            }

            let report =
                ingest_turns(&path, &pp, &thread, &turns, "thread ingest", |dimensions| {
                    new_embedder(
                        embed_cmd.as_deref(),
                        embed_name.as_deref(),
                        embed_normalize,
                        embed_timeout,
                        embed_query.as_deref().unwrap_or_default(),
                        Some(dimensions),
                    )
                })?;
            println!(
                "thread {thread}: added {added} record(s) ({chunked} chunked, {truncated} truncated); \
                 skipped {skipped} already-stored turn(s)",
                added = report.added_records,
                chunked = report.chunked_turns,
                truncated = report.truncated_turns,
                skipped = report.skipped_existing_turns,
            );
            Ok(())
        }
        ThreadCmd::Export {
            path,
            thread,
            output,
            passphrase: pp,
        } => {
            let pp = secret_for(&path, &pp, &None)?;
            let mut db = open_r(&path, &pp).map_err(fmt)?;
            // 12.7d: the shared ingest-shape export (seq order, chunks
            // joined), so the JSONL matches Python and MCP `thread_export`
            // and re-ingests cleanly.
            let turns = db.thread_export_turns(&thread).map_err(fmt)?;
            let lines: Vec<String> = turns
                .iter()
                .map(|t| serde_json::to_string(&t.to_json()).unwrap_or_else(|_| "{}".into()))
                .collect();
            let body = lines.join("\n") + "\n";
            match output {
                Some(p) => {
                    let mut f =
                        std::fs::File::create(&p).map_err(|e| format!("opening {p}: {e}"))?;
                    f.write_all(body.as_bytes())
                        .map_err(|e| format!("writing {p}: {e}"))?;
                    println!(
                        "exported {} turn(s) from thread '{thread}' to {p}",
                        turns.len()
                    );
                }
                None => {
                    print!("{body}");
                }
            }
            Ok(())
        }
        ThreadCmd::Forget {
            path,
            thread,
            passphrase: pp,
        } => {
            let pp = secret_for(&path, &pp, &None)?;
            let mut db = open_w(&path, &pp, "thread forget").map_err(fmt)?;
            let n = db.thread_forget(&thread).map_err(fmt)?;
            db.flush().map_err(fmt)?;
            println!(
                "forgot {n} record(s) in thread '{thread}' (run `mnemo compact {path}` to reclaim space)"
            );
            Ok(())
        }
        ThreadCmd::Start {
            path,
            new,
            from,
            passphrase: pp,
        } => {
            let new = new.unwrap_or_default();
            let pp = secret_for(&path, &pp, &None)?;
            let mut db = open_w(&path, &pp, "thread start").map_err(fmt)?;
            let id = db.thread_start(&new, &from).map_err(fmt)?;
            db.flush().map_err(fmt)?;
            println!(
                "thread '{new}' continues from '{from}' (link record {id}; try `mnemo essence {path} --thread {new}`)"
            );
            Ok(())
        }
    }
}

/// Phase 12.7b: handle `mnemo essence {render|add|append|update|resolve|remove}`.
fn handle_essence_cmd(cmd: EssenceCmd) -> std::result::Result<(), String> {
    use mnemo_engine::{EssenceScope, EssenceSection};
    let parse_refs = |s: Option<String>| -> Option<Vec<String>> {
        s.map(|raw| {
            raw.split(',')
                .map(|p| p.trim().to_string())
                .filter(|p| !p.is_empty())
                .collect::<Vec<_>>()
        })
    };
    let resolve_scope =
        |thread: Option<String>, project: bool| -> std::result::Result<EssenceScope, String> {
            match (thread, project) {
                (Some(t), false) => Ok(EssenceScope::Thread(t)),
                (None, true) => Ok(EssenceScope::Project),
                (None, false) => {
                    Err("pass either --thread <id> or --project (clap also enforces this).".into())
                }
                (Some(_), true) => Err("--thread and --project are mutually exclusive.".into()),
            }
        };
    match cmd {
        EssenceCmd::Render {
            path,
            thread,
            project,
            budget,
            passphrase: pp,
        } => {
            let pp = secret_for(&path, &pp, &None)?;
            let scope = resolve_scope(thread, project)?;
            let mut db = open_r(&path, &pp).map_err(fmt)?;
            let out = db.essence(scope, budget).map_err(fmt)?;
            print!("{out}");
            Ok(())
        }
        EssenceCmd::Add {
            path,
            section,
            text,
            thread,
            project,
            refs,
            passphrase: pp,
        } => {
            let pp = secret_for(&path, &pp, &None)?;
            let section = EssenceSection::parse(&section).ok_or_else(|| {
                format!(
                    "unknown section '{section}' (want intent, conventions, decisions, state, open, next, lessons)"
                )
            })?;
            if section == EssenceSection::Timeline {
                return Err("use `mnemo essence append` for timeline entries".into());
            }
            let scope = resolve_scope(thread, project)?;
            let mut db = open_w(&path, &pp, "essence add").map_err(fmt)?;
            let id = db
                .essence_add(scope, section, &text, parse_refs(refs))
                .map_err(fmt)?;
            db.flush().map_err(fmt)?;
            println!("{id}\tadded");
            Ok(())
        }
        EssenceCmd::Append {
            path,
            text,
            thread,
            project,
            refs,
            passphrase: pp,
        } => {
            let pp = secret_for(&path, &pp, &None)?;
            let scope = resolve_scope(thread, project)?;
            let mut db = open_w(&path, &pp, "essence append").map_err(fmt)?;
            let id = db
                .essence_append_timeline(scope, &text, parse_refs(refs))
                .map_err(fmt)?;
            db.flush().map_err(fmt)?;
            println!("{id}\tappended");
            Ok(())
        }
        EssenceCmd::Update {
            path,
            id,
            text,
            refs,
            passphrase: pp,
        } => {
            let pp = secret_for(&path, &pp, &None)?;
            let id = id.unwrap_or_default();
            let ulid = parse_ulid(&id)?;
            let mut db = open_w(&path, &pp, "essence update").map_err(fmt)?;
            let outcome = db
                .essence_update(&ulid, &text, parse_refs(refs))
                .map_err(fmt)?;
            db.flush().map_err(fmt)?;
            let s = match outcome {
                mnemo_engine::WriteOutcome::Updated => "updated",
                mnemo_engine::WriteOutcome::Unchanged => "unchanged",
                _ => "updated",
            };
            println!("{id}\t{s}");
            Ok(())
        }
        EssenceCmd::Resolve {
            path,
            id,
            passphrase: pp,
        } => {
            let pp = secret_for(&path, &pp, &None)?;
            let id = id.unwrap_or_default();
            let ulid = parse_ulid(&id)?;
            let mut db = open_w(&path, &pp, "essence resolve").map_err(fmt)?;
            let outcome = db.essence_resolve(&ulid).map_err(fmt)?;
            db.flush().map_err(fmt)?;
            let s = match outcome {
                mnemo_engine::WriteOutcome::Updated => "resolved",
                mnemo_engine::WriteOutcome::Unchanged => "already-resolved",
                _ => "resolved",
            };
            println!("{id}\t{s}");
            Ok(())
        }
        EssenceCmd::Remove {
            path,
            id,
            passphrase: pp,
        } => {
            let pp = secret_for(&path, &pp, &None)?;
            let id = id.unwrap_or_default();
            let ulid = parse_ulid(&id)?;
            let mut db = open_w(&path, &pp, "essence remove").map_err(fmt)?;
            db.essence_remove(&ulid).map_err(fmt)?;
            db.flush().map_err(fmt)?;
            println!("{id}\tremoved");
            Ok(())
        }
    }
}

/// Self-contained end-to-end demonstration.
fn demo(path: &str) -> Result<()> {
    let _ = std::fs::remove_file(path);
    let pp = "demo-passphrase";
    let cfg = MnemoConfig {
        dimensions: 4,
        ..Default::default()
    };

    println!("creating encrypted database at {path} ...");
    let mut db = Mnemo::create(path, pp, cfg)?;

    let seeds = [
        (
            "user prefers concise answers",
            MemoryType::Semantic,
            [0.9, 0.1, 0.0, 0.1],
            0.9,
        ),
        (
            "user is based in Berlin",
            MemoryType::Semantic,
            [0.8, 0.2, 0.1, 0.0],
            0.7,
        ),
        (
            "ran the deploy script at 14:00",
            MemoryType::Episodic,
            [0.1, 0.9, 0.1, 0.0],
            0.4,
        ),
        (
            "to reset state, call clear() then reload",
            MemoryType::Procedural,
            [0.0, 0.1, 0.9, 0.2],
            0.6,
        ),
        (
            "scratch: temp calculation result",
            MemoryType::Working,
            [0.2, 0.2, 0.2, 0.9],
            0.2,
        ),
    ];
    for (content, mt, v, imp) in seeds {
        db.remember(
            Memory::new(content, mt, v.to_vec())
                .with_agent("assistant")
                .with_importance(imp),
        )?;
    }
    db.flush()?;
    println!("stored {} memories, flushed to disk\n", db.len());

    let info = db.build_index()?;
    db.flush()?;
    println!(
        "built ANN index: {} vectors, {} partitions, {} PQ subspaces",
        info.vectors, info.partitions, info.subspaces
    );

    println!("\nrecall for a query close to 'user preferences' (index-accelerated):");
    let req = RecallRequest::new(vec![0.85, 0.15, 0.05, 0.05]).top_k(3);
    for h in db.recall(&req)? {
        println!(
            "  score={:.3}  sim={:.3}  [{}]  {}",
            h.score,
            h.similarity,
            h.memory.memory_type.as_str(),
            h.memory.content
        );
    }

    println!("\nreopening to confirm persistence and encryption ...");
    // `close` consumes the handle and releases the file and its lock.
    db.close()?;
    let db = Mnemo::open(path, pp)?;
    println!("reopened: {} memories survive the round-trip", db.len());

    let raw = std::fs::read(path).unwrap_or_default();
    let needle = b"user prefers concise answers";
    let leaked = raw.windows(needle.len()).any(|w| w == needle);
    println!("plaintext 'user prefers concise answers' present in file bytes: {leaked}");

    println!("\ndemo complete.");
    Ok(())
}

/// EPIPE-1: the exit code when stdout's reader went away (`mnemo list |
/// head`): what a process killed by SIGPIPE reports on Unix.
#[cfg(unix)]
const EXIT_BROKEN_PIPE: i32 = 141;
#[cfg(not(unix))]
const EXIT_BROKEN_PIPE: i32 = 1;

/// EPIPE-1: Rust ignores SIGPIPE, so `println!` to a closed pipe panics
/// ("failed printing to stdout: Broken pipe"). That panic exits quietly
/// instead, as a SIGPIPE would; every other panic goes to the default hook.
fn quiet_broken_pipe() {
    let default = std::panic::take_hook();
    std::panic::set_hook(Box::new(move |info| {
        let msg = info
            .payload()
            .downcast_ref::<String>()
            .map(String::as_str)
            .or_else(|| info.payload().downcast_ref::<&str>().copied())
            .unwrap_or("");
        let pipe = msg.contains("Broken pipe")
            || msg.contains("os error 32)")
            || msg.contains("os error 232)")
            || msg.contains("pipe is being closed");
        if msg.starts_with("failed printing to stdout") && pipe {
            std::process::exit(EXIT_BROKEN_PIPE);
        }
        default(info);
    }));
}

fn main() -> ExitCode {
    quiet_broken_pipe();
    // Windows' default main-thread stack is 1 MiB, and this CLI's
    // `run()` is a single ~600-line match whose debug-mode frame
    // reserves space for every variant's locals at once. Rust 1.95 +
    // the extra `embed_timeout` field on three subcommands pushed us
    // over the edge on `windows-latest` (stack overflow in every CLI
    // test, exit code 0xC00000FD). Running the dispatch on a worker
    // thread with 8 MiB of stack sidesteps the whole class — portable,
    // no linker flags, no cfg guards. The spawn + join overhead is
    // ~1 ms, invisible against disk I/O.
    const RUN_STACK: usize = 8 * 1024 * 1024;
    let handle = match std::thread::Builder::new()
        .name("mnemo-cli".into())
        .stack_size(RUN_STACK)
        .spawn(run)
    {
        Ok(h) => h,
        Err(e) => {
            eprintln!("error: could not start cli worker thread: {e}");
            return ExitCode::FAILURE;
        }
    };
    let result = match handle.join() {
        Ok(r) => r,
        Err(_) => {
            eprintln!("error: cli worker thread panicked");
            return ExitCode::FAILURE;
        }
    };
    match result {
        Ok(()) => ExitCode::SUCCESS,
        Err(e) => {
            eprintln!("error: {e}");
            ExitCode::FAILURE
        }
    }
}