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
#![allow(dead_code)]
mod cli;
mod codex;
mod commit;
mod content_ops;
mod convert;
mod display;
mod embeddings;
mod engage;
mod github;
mod helpers;
mod index;
mod knowledge;
pub mod paths;
mod session;
mod state;
mod store;
mod surreal_db;
mod sync;
mod tensor;
mod types;
mod wake_chunk;
mod wake_ritual;
mod wake_token;
use anyhow::{Context, Result, bail};
use clap::Parser;
use crate::index::{
IndexConfig, export_csv, export_jsonl, export_markdown, import_jsonl, rebuild_index,
};
use cli::*;
use display::*;
use helpers::*;
fn main() -> Result<()> {
paths::emit_mx_home_note();
let cli = Cli::parse();
match cli.command {
Commands::Memory { command } => handle_memory(command, cli.verbose),
Commands::Commit {
message,
all,
push,
encode_only,
title,
body,
show_encoded,
} => {
if encode_only {
// PR-style encoding: encode title and body, print to stdout.
// `--encode-only` is its own print path and is deliberately
// left alone — its entire purpose is to emit encoded output.
if let (Some(t), Some(b)) = (title, body) {
let encoded_message = commit::encode_commit_message(&t, &b)?;
println!("{}", encoded_message);
} else {
// This shouldn't happen due to clap validation, but handle gracefully
bail!("--encode-only requires both --title and --body");
}
} else {
// Normal commit workflow
let msg =
message.ok_or_else(|| anyhow::anyhow!("message is required for commit"))?;
commit::upload_commit(&msg, all, push, show_encoded)?;
}
Ok(())
}
Commands::Pr { command } => handle_pr(command),
Commands::Sync { command } => sync::handle_sync(command),
Commands::Github { command } => handle_github(command),
Commands::Wiki { command } => handle_wiki(command),
Commands::Session { command } => handle_session(command),
Commands::Codex { command } => handle_codex(command),
Commands::Convert { command } => handle_convert(command),
Commands::Heartbeat { since, reset } => handle_heartbeat(since, reset),
Commands::Log { count, full, args } => handle_log(count, full, args),
Commands::State { command } => handle_state(command),
}
}
/// Heartbeat - calming co-regulation prompt
/// Call and response - send a heart, get one back with BPM feedback
fn handle_heartbeat(since: Option<u64>, reset: bool) -> Result<()> {
use rand::Rng;
use std::thread;
use std::time::Duration;
let hearts = [
'❤', '🧡', '💛', '💚', '💙', '💜', '🩷', '🩵', '🤍', '💗', '💖', '💕',
];
let mut rng = rand::rng();
// Random delay 50-150ms to feel organic
let delay = rng.random_range(50..150);
thread::sleep(Duration::from_millis(delay));
// Pick a random heart
let heart = hearts[rng.random_range(0..hearts.len())];
if reset {
println!("{} Session reset. Breathe, Q.", heart);
return Ok(());
}
match since {
None => {
// First call - just start
println!("{}", heart);
println!("Heartbeat started. Call again with --since <ms> to begin.");
}
Some(ms) => {
// Calculate BPM: 60000ms / interval = beats per minute
let bpm = 60000_u64.checked_div(ms).unwrap_or(999);
let message = match bpm {
0..=59 => "Nice and slow. You're safe.",
60..=80 => "There you are. Resting.",
81..=100 => "Getting there. Keep breathing.",
101..=120 => "Still quick. Let the interval stretch.",
_ => "Too fast, Q. Breathe. Slow down.",
};
println!("{} {} bpm", heart, bpm);
println!("{}", message);
}
}
Ok(())
}
/// Handle emotional state tensor commands
fn handle_state(cmd: StateCommands) -> Result<()> {
use std::io::{self, Read as IoRead};
use std::path::PathBuf;
// Helper to load tensor schema by ID or path
let load_tensor_schema = |schema_arg: Option<String>| -> Result<tensor::TensorSchema> {
match schema_arg {
Some(s) if s.contains('/') || s.contains('.') => {
// Looks like a path
tensor::TensorSchema::load(&PathBuf::from(s))
}
Some(id) => tensor::TensorSchema::load_by_id(&id),
None => tensor::TensorSchema::load_default(),
}
};
// Helper to load legacy state schema
let load_legacy_schema = |custom_path: Option<String>| -> Result<state::StateSchema> {
match custom_path {
Some(p) => state::load_schema(&PathBuf::from(p)),
None => state::load_default_schema(),
}
};
match cmd {
// === NEW TENSOR-BASED COMMANDS ===
StateCommands::Encode {
values,
dimensions,
file,
schema,
guided,
format,
runes,
} => {
let schema = load_tensor_schema(schema)?;
let tensor = if guided {
// Interactive guided mode
tensor::guided_capture(&schema)?
} else if let Some(dims_str) = dimensions {
// Parse named dimensions
tensor::StateTensor::parse_named_dimensions(&schema, &dims_str)?
} else if let Some(file_path) = file {
// Read from file
let content = std::fs::read_to_string(&file_path)
.with_context(|| format!("Failed to read file: {}", file_path))?;
// Try pipe-separated first, then newline-separated
let values_str = if content.contains('|') {
content.trim().to_string()
} else {
content
.lines()
.map(|l| l.trim())
.filter(|l| !l.is_empty())
.collect::<Vec<_>>()
.join("|")
};
tensor::StateTensor::parse_values(&schema, &values_str)?
} else if let Some(values_str) = values {
// Parse from argument
tensor::StateTensor::parse_values(&schema, &values_str)?
} else {
// Default tensor
tensor::StateTensor::default_from_schema(&schema)
};
// Output in requested format
match format.as_str() {
"json" => println!("{}", serde_json::to_string_pretty(&tensor)?),
"human" => {
println!("{}", tensor.describe(&schema));
if let Some((mood_name, mood, distance)) = tensor.nearest_mood(&schema) {
println!("\nNearest mood: {} (distance: {:.3})", mood_name, distance);
println!(" {}", mood.description);
}
}
"bootstrap" => {
// Self-documenting bootstrap format
println!("{}", tensor.format_bootstrap(&schema)?);
}
_ => {
// tensor format
if runes {
println!("{}", tensor.encode_with_runes(&schema));
} else {
println!("{}", tensor.encode());
}
}
}
}
StateCommands::Decode {
input,
schema,
format,
} => {
// Get input from arg or stdin
let input_str = match input {
Some(s) => s,
None => {
let mut buf = String::new();
io::stdin().read_to_string(&mut buf)?;
buf.trim().to_string()
}
};
// Decode the tensor (schema ID is embedded in the string)
let tensor = tensor::StateTensor::decode(&input_str)?;
// Load schema (use argument if provided, otherwise use ID from tensor)
let schema = match schema {
Some(s) => load_tensor_schema(Some(s))?,
None => tensor::TensorSchema::load_by_id(&tensor.schema_id)?,
};
match format.as_str() {
"json" => println!("{}", serde_json::to_string_pretty(&tensor)?),
"tensor" => println!("{}", tensor.encode()),
"mood" => {
if let Some((mood_name, mood, distance)) = tensor.nearest_mood(&schema) {
println!("{}", mood_name);
println!(" Description: {}", mood.description);
println!(" Distance: {:.3}", distance);
} else {
println!("(unnamed region)");
}
}
_ => {
// human format
println!("{}", tensor.describe(&schema));
if let Some((mood_name, mood, distance)) = tensor.nearest_mood(&schema) {
println!("\nNearest mood: {} (distance: {:.3})", mood_name, distance);
println!(" {}", mood.description);
}
}
}
}
StateCommands::Schemas { json } => {
let schemas = tensor::TensorSchema::list_available()?;
if json {
let schema_list: Vec<serde_json::Value> = schemas
.iter()
.filter_map(|schema_id| {
tensor::TensorSchema::load_by_id(schema_id).ok().map(|s| {
serde_json::json!({
"id": s.id,
"name": s.name,
"dimensions": s.dimensions.len(),
"moods": s.moods.len(),
})
})
})
.collect();
println!("{}", serde_json::to_string_pretty(&schema_list)?);
} else if schemas.is_empty() {
println!("No schemas found (checked $MX_HOME/schemas/)");
println!("\nCreate a schema file (YAML or JSON) to get started.");
} else {
println!("Available schemas:\n");
for schema_id in schemas {
match tensor::TensorSchema::load_by_id(&schema_id) {
Ok(schema) => {
println!(
" {} - {} ({} dimensions, {} moods)",
schema.id,
schema.name,
schema.dimensions.len(),
schema.moods.len()
);
}
Err(_) => {
println!(" {} - (failed to load)", schema_id);
}
}
}
}
}
StateCommands::Moods { schema, mood, json } => {
let schema = load_tensor_schema(schema)?;
if let Some(mood_name) = mood {
// Show specific mood
match schema.moods.get(&mood_name) {
Some(mood_def) => {
if json {
println!("{}", serde_json::to_string_pretty(&mood_def)?);
} else {
println!("Mood: {}", mood_name);
println!("Description: {}", mood_def.description);
println!("Tolerance: {:.2}", mood_def.tolerance);
println!("\nTensor values:");
for (i, value) in mood_def.tensor.iter().enumerate() {
let dim_name = schema
.dimensions
.get(i)
.map(|d| d.name.as_str())
.unwrap_or("?");
let weight = mood_def
.weights
.as_ref()
.and_then(|w| w.get(i))
.copied()
.unwrap_or(1.0);
println!(" {}: {:.2} (weight: {:.2})", dim_name, value, weight);
}
}
}
None => {
bail!(
"Unknown mood '{}'. Available moods: {}",
mood_name,
schema.moods.keys().cloned().collect::<Vec<_>>().join(", ")
);
}
}
} else {
// List all moods
if json {
println!("{}", serde_json::to_string_pretty(&schema.moods)?);
} else {
println!("Moods for schema '{}' ({}):\n", schema.id, schema.name);
for (name, mood_def) in &schema.moods {
let tensor_str: Vec<String> = mood_def
.tensor
.iter()
.map(|v| format!("{:.2}", v))
.collect();
println!(" {:12} [{}]", name, tensor_str.join("|"));
println!(" {}", mood_def.description);
}
}
}
}
StateCommands::Info { schema, json } => {
let schema = load_tensor_schema(schema)?;
if json {
println!("{}", serde_json::to_string_pretty(&schema)?);
} else {
println!("Schema: {} ({})", schema.name, schema.id);
println!("Version: {}", schema.version);
println!();
println!("Dimensions ({}):", schema.dimensions.len());
for dim in &schema.dimensions {
let rune = dim
.rune
.as_ref()
.map(|r| format!(" {}", r))
.unwrap_or_default();
println!(" {}{}:", dim.name, rune);
println!(" Low: {}", dim.anchors.low);
if let Some(mid) = &dim.anchors.mid {
println!(" Mid: {}", mid);
}
println!(" High: {}", dim.anchors.high);
println!(" Default: {:.2}", dim.default);
}
println!();
println!("Moods ({}):", schema.moods.len());
for (name, mood) in &schema.moods {
println!(
" {:12} - {} (tol: {:.2})",
name, mood.description, mood.tolerance
);
}
}
}
// === LEGACY COMMANDS (backward compatibility) ===
StateCommands::LegacyEncode {
mode,
interactive,
format,
schema,
} => {
let schema = load_legacy_schema(schema)?;
let dynamic_state = if interactive {
state::DynamicState::interactive_capture(&schema)?
} else if let Some(mode_name) = mode {
state::DynamicState::from_mode(&mode_name, &schema)?
} else {
state::DynamicState::from_mode("default", &schema)?
};
match format.as_str() {
"json" => println!("{}", serde_json::to_string_pretty(&dynamic_state)?),
"human" => println!("{}", dynamic_state.describe(&schema)),
_ => println!("{}", dynamic_state.encode_stele(&schema)),
}
}
StateCommands::Parse {
file,
preference,
format,
schema,
} => {
// Strip leading markdown bold markers (**/__) so "**Wake State:** ..."
// matches the same as plain "Wake State: ...". Only used in the predicate;
// the original line is kept for value extraction.
fn strip_md_bold(line: &str) -> &str {
line.trim_start()
.trim_start_matches("**")
.trim_start_matches("__")
.trim_start()
}
// Extract the @state:... fragment from a matched line, stripping any
// leading label ("Wake State:", "**Wake State:**", etc.) and trailing
// markdown bold close ("**") that pocket inserts around the label.
fn extract_stele_fragment(line: &str) -> &str {
// Find the @state token wherever it appears in the line
if let Some(pos) = line.find("@state") {
line[pos..]
.trim_end_matches('*')
.trim_end_matches('_')
.trim()
} else {
line.trim()
}
}
let legacy_schema = load_legacy_schema(schema.clone())?;
let raw_line = if let Some(pref) = preference {
pref
} else {
let path = file.unwrap_or_else(|| {
crate::paths::swap_dir()
.join("session-bootstrap.md")
.to_string_lossy()
.to_string()
});
let content = std::fs::read_to_string(&path)
.with_context(|| format!("Failed to read file: {}", path))?;
content
.lines()
.find(|line| {
let stripped = strip_md_bold(line);
stripped.starts_with("Wake Preference:")
|| stripped.starts_with("Wake State:")
|| stripped.starts_with(&legacy_schema.stele.header)
})
.map(|s| s.to_string())
.unwrap_or_else(|| String::from("default"))
};
// Detect tensor format: @state:<namespace>|... (has colon after @state)
let stele_fragment = extract_stele_fragment(&raw_line);
let is_tensor_format =
stele_fragment.starts_with("@state:") && stele_fragment.contains('|');
if is_tensor_format {
// Decode via tensor path which handles positional numeric values
let tensor_schema = load_tensor_schema(schema)?;
let tensor = tensor::StateTensor::decode(stele_fragment).with_context(|| {
format!("Failed to decode tensor stele: {}", stele_fragment)
})?;
match format.as_str() {
"json" => println!("{}", serde_json::to_string_pretty(&tensor.values)?),
"stele" => println!("{}", tensor.encode()),
_ => {
println!("Parsed: {}", stele_fragment);
println!();
println!("{}", tensor.describe(&tensor_schema));
}
}
} else {
// Legacy path: mode names or rune-prefixed stele
let dynamic_state =
state::parse_wake_preference_dynamic(&raw_line, &legacy_schema)?;
match format.as_str() {
"json" => println!("{}", serde_json::to_string_pretty(&dynamic_state)?),
"stele" => println!("{}", dynamic_state.encode_stele(&legacy_schema)),
"mode" => {
println!("Mode calculation not yet implemented for DynamicState");
}
_ => {
println!("Parsed: {}", raw_line.trim());
println!();
println!("{}", dynamic_state.describe(&legacy_schema));
}
}
}
}
}
Ok(())
}
fn handle_memory(cmd: MemoryCommands, verbose: bool) -> Result<()> {
let config = IndexConfig::default();
match cmd {
MemoryCommands::Rebuild => {
println!("Rebuilding Memory index...");
let stats = rebuild_index(&config)?;
println!("{}", stats);
}
MemoryCommands::Search {
query,
filter,
semantic,
} => {
let db = store::create_store_with_verbose(&config.db_path, verbose)?;
let ctx = resolve_agent_context(filter.mine, filter.include_private);
// Note: Search doesn't activate facts - discovery != engagement
// Build filter for database query (resonance and category)
let db_filter = store::KnowledgeFilter {
min_resonance: filter.min_resonance,
max_resonance: filter.max_resonance,
categories: filter.category.clone(),
};
// Get results from database with resonance filtering
let entries = if semantic {
use crate::embeddings::{EmbeddingProvider, FastEmbedProvider};
eprintln!("Initializing semantic search...");
let mut provider = FastEmbedProvider::new()?;
let query_embedding = provider.embed(&query)?;
// When --tags is present the in-memory filter will thin the DB results,
// so we over-fetch to ensure enough candidates survive the tag filter.
// Tradeoff: 5x multiplier works well at typical limits (10-50) but does
// not scale for very large limits. The cap (limit + 200) prevents runaway
// fetches when the caller requests hundreds of entries.
let requested_limit = filter.limit.unwrap_or(20);
let db_limit = if filter.tags.is_some() {
(requested_limit * 5).min(requested_limit + 200)
} else {
requested_limit
};
db.semantic_search(&query_embedding, &ctx, &db_filter, db_limit)?
} else {
db.search(&query, &ctx, &db_filter)?
};
// Apply in-memory field presence filters
let entries = apply_entry_filters(entries, &filter);
if filter.json {
println!("{}", serde_json::to_string_pretty(&entries)?);
} else if entries.is_empty() {
println!("No results for '{}'", query);
} else {
println!("Found {} results:\n", entries.len());
for entry in entries {
print_entry_summary(&entry);
}
}
}
MemoryCommands::List { filter } => {
let db = store::create_store_with_verbose(&config.db_path, verbose)?;
let ctx = resolve_agent_context(filter.mine, filter.include_private);
// Validate categories if provided
if let Some(ref cats) = filter.category {
for cat in cats {
if db.get_category(cat)?.is_none() {
let categories = db.list_categories()?;
let valid_ids: Vec<&str> =
categories.iter().map(|c| c.id.as_str()).collect();
bail!(
"Unknown category '{}'. Valid categories: {}",
cat,
valid_ids.join(", ")
);
}
}
}
// Build filter for database query (resonance only - category handled below)
let db_filter = store::KnowledgeFilter {
min_resonance: filter.min_resonance,
max_resonance: filter.max_resonance,
categories: None,
};
// Get results from database with resonance filtering
let entries = if let Some(ref cats) = filter.category {
let mut all = Vec::new();
for cat in cats {
all.extend(db.list_by_category(cat, &ctx, &db_filter)?);
}
all
} else {
// List all categories from database
let mut all = Vec::new();
let categories = db.list_categories()?;
for cat in categories {
all.extend(db.list_by_category(&cat.id, &ctx, &db_filter)?);
}
all
};
// Apply in-memory field presence filters
let entries = apply_entry_filters(entries, &filter);
if filter.json {
println!("{}", serde_json::to_string_pretty(&entries)?);
} else if entries.is_empty() {
println!("No entries found");
} else {
println!("Found {} entries:\n", entries.len());
for entry in entries {
print_entry_summary(&entry);
}
}
}
MemoryCommands::Show {
id,
json,
content_only,
} => {
let db = store::create_store_with_verbose(&config.db_path, verbose)?;
let id = normalize_id(&id);
// For Show, we need to respect privacy but use current agent context
// If the user has MX_CURRENT_AGENT set, they can see their own private entries
let ctx = match std::env::var("MX_CURRENT_AGENT") {
Ok(agent) if !agent.is_empty() => store::AgentContext::for_agent(agent),
_ => store::AgentContext::public_only(),
};
match db.get(&id, &ctx)? {
Some(entry) => {
// Activate fact when viewing details
if entry.id.starts_with("kn-")
&& let Err(e) = db.update_activations(std::slice::from_ref(&entry.id))
{
eprintln!("Warning: failed to update activation: {}", e);
}
if content_only {
if let Some(body) = &entry.body {
print!("{}", body);
}
} else if json {
println!("{}", serde_json::to_string_pretty(&entry)?);
} else {
print_entry_full(&entry);
}
}
None => {
bail!("Entry '{}' not found", id);
}
}
}
MemoryCommands::Stats { json } => {
let db = store::create_store_with_verbose(&config.db_path, verbose)?;
// For stats, show counts for current agent's perspective
let ctx = match std::env::var("MX_CURRENT_AGENT") {
Ok(agent) if !agent.is_empty() => store::AgentContext::for_agent(agent),
_ => store::AgentContext::public_only(),
};
let total = db.count()?;
let categories = db.list_categories()?;
let filter = store::KnowledgeFilter::default();
if json {
let mut cat_counts = serde_json::Map::new();
for cat in categories {
let count = db.count_by_category(&cat.id, &ctx, &filter)?;
cat_counts.insert(cat.id, serde_json::Value::Number(count.into()));
}
println!(
"{}",
serde_json::to_string_pretty(&serde_json::json!({
"total": total,
"categories": cat_counts,
}))?
);
} else {
println!("Memory Index Statistics\n");
println!("Total entries: {}", total);
println!();
for cat in categories {
let count = db.count_by_category(&cat.id, &ctx, &filter)?;
println!(" {:12} {}", cat.id, count);
}
}
}
MemoryCommands::Health { json } => {
let db = open_surreal(&config, verbose)?;
let health = db.graph_health()?;
if json {
println!("{}", serde_json::to_string_pretty(&health)?);
} else {
let total = health["total"].as_i64().unwrap_or(0);
let embedded_pct = health["embedded_pct"].as_i64().unwrap_or(0);
let anchored_pct = health["anchored_pct"].as_i64().unwrap_or(0);
let stale_pct = health["stale_high_res_pct"].as_i64().unwrap_or(0);
println!("Graph Health\n");
println!(" Total entries: {}", total);
println!(" {:3}% embedded", embedded_pct);
println!(" {:3}% anchored", anchored_pct);
println!(" {:3}% stale (high-res, >30d)", stale_pct);
}
}
MemoryCommands::Growth { json } => {
let db = open_surreal(&config, verbose)?;
let counts = db.growth_sparkline()?;
if json {
println!("{}", serde_json::to_string_pretty(&counts)?);
} else {
// Human-readable: label + bar
println!("Growth (last 8 weeks)");
if let Some(arr) = counts.as_array() {
for (i, v) in arr.iter().enumerate() {
println!(" week -{}: {}", 7 - i, v.as_i64().unwrap_or(0));
}
}
}
}
MemoryCommands::OpenThreads { json } => {
let db = open_surreal(&config, verbose)?;
let threads = db.open_threads()?;
if json {
println!("{}", serde_json::to_string_pretty(&threads)?);
} else {
let arr = threads.as_array().map(|v| v.as_slice()).unwrap_or(&[]);
if arr.is_empty() {
println!("No open threads.");
} else {
println!("Open threads ({})\n", arr.len());
for t in arr {
let id = t["id"].as_str().unwrap_or("");
let resonance = t["resonance"].as_i64().unwrap_or(0);
let created_at = t["created_at"].as_str().unwrap_or("");
let body = t["body"]
.as_str()
.unwrap_or("")
.chars()
.take(80)
.collect::<String>();
println!(" [r{}] {} {} {}", resonance, id, created_at, body);
}
}
}
}
MemoryCommands::Delete { id, json } => {
let db = store::create_store_with_verbose(&config.db_path, verbose)?;
let id = normalize_id(&id);
// Respect visibility: agents can only delete entries they can see
let current_agent = std::env::var("MX_CURRENT_AGENT")
.ok()
.filter(|s| !s.is_empty());
let ctx = match ¤t_agent {
Some(agent) => store::AgentContext::for_agent(agent),
None => store::AgentContext::public_only(),
};
// Backup before delete (Issue #206)
if let Some(entry) = db.get(&id, &ctx)? {
let _ = db
.backup_content(&entry, "delete", current_agent.as_deref())
.map_err(|e| eprintln!("Warning: failed to create backup: {}", e));
}
if db.delete(&id, &ctx)? {
if json {
println!(
"{}",
serde_json::to_string_pretty(&serde_json::json!({
"deleted": true,
"id": id,
}))?
);
} else {
println!("Deleted entry '{}'", id);
}
} else {
bail!("Entry '{}' not found", id);
}
}
MemoryCommands::Import { path } => {
let db = store::create_store_with_verbose(&config.db_path, verbose)?;
let import_path = path
.map(std::path::PathBuf::from)
.unwrap_or_else(|| config.jsonl_path.clone());
let count = import_jsonl(db.as_ref(), &import_path)?;
println!("Imported {} entries from {:?}", count, import_path);
}
MemoryCommands::Add {
category,
title,
content,
file,
tags,
applicability,
project,
source_agent,
source_type,
entry_type,
session_id,
ephemeral,
domain,
content_type,
private,
visibility,
owner,
json,
resonance,
resonance_type,
wake_phrase,
wake_phrases,
wake_order,
anchors,
r#type,
session,
thread_id,
} => {
use anyhow::Context;
use std::fs;
let db = store::create_store_with_verbose(&config.db_path, verbose)?;
// Get content from either --content or --file
let body = if let Some(text) = content {
text
} else if let Some(file_path) = file {
fs::read_to_string(&file_path)
.with_context(|| format!("Failed to read file: {}", file_path))?
} else {
bail!("Either --content or --file must be provided");
};
// Determine agent - use source_agent or env var (no longer required)
let agent_id = match source_agent {
Some(ref sa) if !sa.is_empty() => sa.clone(),
_ => match std::env::var("MX_CURRENT_AGENT") {
Ok(agent) if !agent.is_empty() => agent,
_ => {
bail!("--source-agent not provided and MX_CURRENT_AGENT not set");
}
},
};
// Resolve visibility: --private flag is sugar for --visibility private
let is_private = private || visibility.as_deref() == Some("private");
if let Some(ref vis) = visibility
&& vis != "public"
&& vis != "private"
{
bail!("--visibility must be 'public' or 'private'");
}
// Handle fact type routing mode (--type flag)
if let Some(ref fact_type) = r#type {
// Handle thread_closed specially - updates existing thread
if fact_type == "thread_closed" {
let tid = if let Some(id) = thread_id {
id
} else {
// Find by content match (fragile fallback)
find_open_thread_by_content(&*db, &body, &agent_id)?
};
// Update existing thread to closed state
if let Some(thread_entry) =
db.get(&tid, &store::AgentContext::for_agent(&agent_id))?
{
let mut meta: serde_json::Value = thread_entry
.summary
.as_deref()
.map(|s| {
serde_json::from_str(s).unwrap_or_else(|_| serde_json::json!({}))
})
.unwrap_or_else(|| serde_json::json!({}));
if let Some(obj) = meta.as_object_mut() {
obj.insert(
"state".to_string(),
serde_json::Value::String("closed".to_string()),
);
}
let new_summary = meta.to_string();
if db.update_summary(
&tid,
&new_summary,
&store::AgentContext::for_agent(&agent_id),
)? {
println!("Closed thread: {}", tid);
} else {
bail!("Entry '{}' not found", tid);
}
return Ok(());
} else {
bail!("Thread not found: {}", tid);
}
}
// Route fact type to category and tags
let routing = route_fact_type(fact_type)?;
// Build fact entry
let now = chrono::Utc::now().to_rfc3339();
let truncated_title = safe_truncate(&body, 60);
let fact_title = format!("{}: {}", fact_type, truncated_title);
// Generate ID using session if provided
let session_hint = session.as_deref().unwrap_or("fact");
let id = knowledge::KnowledgeEntry::generate_id(session_hint, &fact_title);
// Build metadata JSON
let mut metadata = serde_json::Map::new();
metadata.insert(
"fact_type".to_string(),
serde_json::Value::String(fact_type.clone()),
);
metadata.insert(
"agent".to_string(),
serde_json::Value::String(agent_id.clone()),
);
metadata.insert(
"date".to_string(),
serde_json::Value::String(chrono::Local::now().format("%Y-%m-%d").to_string()),
);
// Add state field for threads
if routing.category == "thread" {
metadata.insert(
"state".to_string(),
serde_json::Value::String("open".to_string()),
);
}
let summary_json = serde_json::Value::Object(metadata).to_string();
// Merge routed tags with any user-provided tags
let mut tag_list: Vec<String> =
routing.tags.iter().map(|s| s.to_string()).collect();
if let Some(t) = tags {
tag_list.extend(
t.split(',')
.map(|s| s.trim().to_string())
.filter(|s| !s.is_empty()),
);
}
// Build the knowledge entry
let entry = knowledge::KnowledgeEntry {
id: id.clone(),
category_id: routing.category.to_string(),
title: fact_title.clone(),
body: Some(body.clone()),
summary: Some(summary_json),
applicability: vec![],
source_project_id: project,
source_agent_id: Some(format!("agent:{}", agent_id)),
file_path: None,
tags: tag_list.clone(),
created_at: Some(now.clone()),
updated_at: Some(now),
content_hash: Some(knowledge::KnowledgeEntry::compute_hash(&body)),
source_type_id: Some("source_type:agent_session".to_string()),
entry_type_id: Some("entry_type:primary".to_string()),
session_id: session.clone(),
ephemeral: true,
content_type_id: Some("content_type:text".to_string()),
owner: Some(format!("agent:{}", agent_id)),
visibility: "public".to_string(),
resonance: resonance.unwrap_or(3),
resonance_type: Some("ephemeral".to_string()),
last_activated: None,
activation_count: 0,
decay_rate: 0.0,
anchors: vec![],
wake_phrases: vec![],
wake_order: None,
wake_phrase: None,
embedding: None,
embedding_model: None,
embedded_at: None,
format: "markdown".to_string(),
effective_resonance: None,
};
// Insert the fact
db.upsert_knowledge(&entry)?;
// Create EXTRACTED_FROM relationship to session if provided
if let Some(ref sess) = session {
let session_ref = if sess.starts_with("kn-") {
sess.clone()
} else {
format!("kn-{}", sess)
};
let ctx = crate::store::AgentContext::public_only();
if db.get(&session_ref, &ctx)?.is_none() {
eprintln!(
"Warning: Session {} not found - relationship not created",
session_ref
);
} else {
db.add_relationship(&id, &session_ref, "extracted_from")?;
}
}
println!("Added fact: {}", id);
println!(" Type: {}", fact_type);
println!(" Category: {}", routing.category);
println!(" Content: {}", body);
// Auto-generate embedding if in network SurrealDB mode
auto_embed(&id, db.as_ref())?;
return Ok(());
}
// Standard memory add mode (no --type flag)
let category = category.expect("category required when --type not provided");
let title = title.expect("title required when --type not provided");
// Validate category against database
if db.get_category(&category)?.is_none() {
let categories = db.list_categories()?;
let valid_ids: Vec<&str> = categories.iter().map(|c| c.id.as_str()).collect();
bail!(
"Invalid category '{}'. Valid categories: {}",
category,
valid_ids.join(", ")
);
}
// Parse tags
let tag_list: Vec<String> = tags
.map(|t| {
t.split(',')
.map(|s| s.trim().to_string())
.filter(|s| !s.is_empty())
.collect()
})
.unwrap_or_default();
// Parse applicability CSV
let applicability_list: Vec<String> = applicability
.map(|a| {
a.split(',')
.map(|s| s.trim().to_string())
.filter(|s| !s.is_empty())
.collect()
})
.unwrap_or_default();
// Parse anchors CSV
let anchor_list: Vec<String> = anchors
.map(|a| {
a.split(',')
.map(|s| s.trim().to_string())
.filter(|s| !s.is_empty())
.collect()
})
.unwrap_or_default();
// Parse wake_phrases CSV or use single wake_phrase
let wake_phrase_list: Vec<String> = if let Some(phrases) = wake_phrases {
phrases
.split(',')
.map(|s| s.trim().to_string())
.filter(|s| !s.is_empty())
.collect()
} else if let Some(ref single_phrase) = wake_phrase {
vec![single_phrase.clone()]
} else {
vec![]
};
// Determine visibility and owner
// FIX #123: Ensure owner matches the format expected by visibility filter.
// The visibility filter compares `owner = $current_agent` where $current_agent
// comes from MX_CURRENT_AGENT. Owner must be stored in the same format.
let entry_visibility = if is_private {
"private".to_string()
} else {
"public".to_string()
};
let entry_owner = if is_private {
// Owner defaults to agent_id (already resolved from --source-agent or MX_CURRENT_AGENT)
Some(owner.unwrap_or_else(|| agent_id.clone()))
} else {
owner
};
// Validate resonance_type if provided
if let Some(ref rtype) = resonance_type {
let valid_types = [
"foundational",
"transformative",
"relational",
"operational",
"ephemeral",
"session",
];
if !valid_types.contains(&rtype.as_str()) {
bail!(
"Invalid resonance type '{}'. Valid types: {}",
rtype,
valid_types.join(", ")
);
}
}
// Generate ID
let path_hint = domain.unwrap_or_else(|| category.clone());
let id = knowledge::KnowledgeEntry::generate_id(&path_hint, &title);
// Create entry
let now = chrono::Utc::now().to_rfc3339();
let entry = knowledge::KnowledgeEntry {
id: id.clone(),
category_id: category.clone(),
title: title.clone(),
body: Some(body),
summary: None,
applicability: applicability_list.clone(),
source_project_id: project,
source_agent_id: Some(agent_id.clone()),
file_path: None,
tags: tag_list,
created_at: Some(now.clone()),
updated_at: Some(now),
content_hash: Some(knowledge::KnowledgeEntry::compute_hash(&title)),
source_type_id: Some(source_type),
entry_type_id: Some(entry_type),
session_id: session_id.clone(),
ephemeral,
content_type_id: Some(content_type),
owner: entry_owner.clone(),
visibility: entry_visibility.clone(),
resonance: resonance.unwrap_or(0),
resonance_type,
last_activated: None,
activation_count: 0,
decay_rate: 0.0,
anchors: anchor_list,
wake_phrases: wake_phrase_list,
wake_order,
wake_phrase,
embedding: None,
embedding_model: None,
embedded_at: None,
format: "markdown".to_string(),
effective_resonance: None,
};
// Insert into database (applicability already set in struct)
db.upsert_knowledge(&entry)?;
// Create EXTRACTED_FROM edge when --session-id is provided.
// Standard mode stores session_id as a field but the for-session query
// traverses the relates_to edge — wire both paths for consistency.
if let Some(ref sess_id) = session_id {
let session_ref = normalize_id(sess_id);
let ctx = crate::store::AgentContext::public_only();
if db.get(&session_ref, &ctx)?.is_none() {
eprintln!(
"Warning: Session {} not found - EXTRACTED_FROM edge not created",
session_ref
);
} else {
db.add_relationship(&id, &session_ref, "extracted_from")?;
}
}
// Auto-generate embedding if in network SurrealDB mode
auto_embed(&id, db.as_ref())?;
// Auto-generate anchors if in network SurrealDB mode
auto_anchor(&id, db.as_ref(), None)?;
if json {
println!(
"{}",
serde_json::to_string_pretty(&serde_json::json!({
"id": id,
"category": category,
"title": title,
"visibility": entry_visibility,
"owner": entry_owner,
"resonance": entry.resonance,
"resonance_type": entry.resonance_type,
"tags": entry.tags,
"applicability": entry.applicability,
"anchors": entry.anchors,
"wake_phrase": entry.wake_phrase,
"wake_phrases": entry.wake_phrases,
}))?
);
} else {
println!("Added entry: {}", id);
println!(" Category: {}", category);
println!(" Title: {}", title);
println!(" Visibility: {}", entry_visibility);
if let Some(ref o) = entry_owner {
println!(" Owner: {}", o);
}
if entry.resonance > 0 {
println!(" Resonance: {}", entry.resonance);
}
if let Some(ref rtype) = entry.resonance_type {
println!(" Resonance Type: {}", rtype);
}
if !entry.tags.is_empty() {
println!(" Tags: {}", entry.tags.join(", "));
}
if !entry.applicability.is_empty() {
println!(" Applicability: {}", entry.applicability.join(", "));
}
if !entry.anchors.is_empty() {
println!(" Anchors: {}", entry.anchors.join(", "));
}
if let Some(ref phrase) = entry.wake_phrase {
println!(" Wake Phrase: {}", phrase);
}
}
}
MemoryCommands::Update {
id,
title,
content,
file,
append_content,
append_file,
prepend_content,
prepend_file,
find,
replace,
replace_all,
nth,
category,
tags,
add_tag,
remove_tag,
applicability,
content_type,
resonance,
resonance_type,
anchors,
add_anchor,
remove_anchor,
wake_phrase,
wake_phrases,
add_wake_phrase,
remove_wake_phrase,
wake_order,
private,
visibility,
owner,
session_id,
force,
json,
} => {
use anyhow::Context;
use std::fs;
let db = store::create_store_with_verbose(&config.db_path, verbose)?;
let id = normalize_id(&id);
// For Update, use current agent context to allow updating own private entries
// #10: read MX_CURRENT_AGENT once, reuse for both ctx and backup
let current_agent = std::env::var("MX_CURRENT_AGENT")
.ok()
.filter(|s| !s.is_empty());
let ctx = match ¤t_agent {
Some(agent) => store::AgentContext::for_agent(agent),
None => store::AgentContext::public_only(),
};
// Fetch existing entry
let mut entry = db
.get(&id, &ctx)?
.ok_or_else(|| anyhow::anyhow!("Entry not found: {}", id))?;
// Resolve --private as sugar for --visibility private
let visibility = if private && visibility.is_none() {
Some("private".to_string())
} else {
visibility
};
let mut changes = Vec::new();
// Backup before body mutation (Issue #206)
let will_change_body = content.is_some()
|| file.is_some()
|| append_content.is_some()
|| append_file.is_some()
|| prepend_content.is_some()
|| prepend_file.is_some()
|| find.is_some();
if will_change_body {
let _ = db
.backup_content(&entry, "update", current_agent.as_deref())
.map_err(|e| eprintln!("Warning: failed to create backup: {}", e));
}
// Update title if provided
if let Some(new_title) = title {
changes.push(format!("title: {} -> {}", entry.title, new_title));
entry.title = new_title;
}
// Track if body was changed for hash update
let mut body_changed = false;
// Update content - supports multiple modes:
// 1. Full replacement via --content or --file
// 2. Append via --append-content or --append-file
// 3. Prepend via --prepend-content or --prepend-file
// 4. Find/replace via --find/--replace
if let Some(text) = content {
changes.push("content: updated (inline)".to_string());
entry.body = Some(text);
body_changed = true;
} else if let Some(file_path) = file {
let text = fs::read_to_string(&file_path)
.with_context(|| format!("Failed to read file: {}", file_path))?;
changes.push(format!("content: updated from {}", file_path));
entry.body = Some(text);
body_changed = true;
} else if let Some(ref append_text) = append_content {
let new_body = content_ops::append_content(entry.body.as_deref(), append_text);
changes.push(format!("content: appended {} bytes", append_text.len()));
entry.body = Some(new_body);
body_changed = true;
} else if let Some(ref file_path) = append_file {
let append_text = fs::read_to_string(file_path)
.with_context(|| format!("Failed to read file: {}", file_path))?;
let new_body = content_ops::append_content(entry.body.as_deref(), &append_text);
changes.push(format!(
"content: appended {} bytes from {}",
append_text.len(),
file_path
));
entry.body = Some(new_body);
body_changed = true;
} else if let Some(ref prepend_text) = prepend_content {
let new_body = content_ops::prepend_content(entry.body.as_deref(), prepend_text);
changes.push(format!("content: prepended {} bytes", prepend_text.len()));
entry.body = Some(new_body);
body_changed = true;
} else if let Some(ref file_path) = prepend_file {
let prepend_text = fs::read_to_string(file_path)
.with_context(|| format!("Failed to read file: {}", file_path))?;
let new_body = content_ops::prepend_content(entry.body.as_deref(), &prepend_text);
changes.push(format!(
"content: prepended {} bytes from {}",
prepend_text.len(),
file_path
));
entry.body = Some(new_body);
body_changed = true;
} else if let Some(ref find_text) = find {
let replace_text = replace.as_deref().unwrap_or("");
let body_text = entry
.body
.as_deref()
.ok_or_else(|| anyhow::anyhow!("Entry has no body content to edit"))?;
let result = content_ops::edit_content(
body_text,
find_text,
replace_text,
replace_all,
nth,
)?;
changes.push(format!(
"content: {} replacement{}",
result.replacements,
if result.replacements == 1 { "" } else { "s" }
));
entry.body = Some(result.new_content);
body_changed = true;
}
// Update category if provided
if let Some(new_category) = category {
// Validate category
if db.get_category(&new_category)?.is_none() {
let categories = db.list_categories()?;
let valid_ids: Vec<&str> = categories.iter().map(|c| c.id.as_str()).collect();
bail!(
"Invalid category '{}'. Valid categories: {}",
new_category,
valid_ids.join(", ")
);
}
changes.push(format!(
"category: {} -> {}",
entry.category_id, new_category
));
entry.category_id = new_category;
}
// Update resonance if provided
if let Some(new_resonance) = resonance {
changes.push(format!(
"resonance: {} -> {}",
entry.resonance, new_resonance
));
entry.resonance = new_resonance;
}
// Update resonance type if provided
if let Some(ref new_type) = resonance_type {
let valid_types = [
"foundational",
"transformative",
"relational",
"operational",
"ephemeral",
"session",
];
if !valid_types.contains(&new_type.as_str()) {
bail!(
"Invalid resonance type '{}'. Valid types: {}",
new_type,
valid_types.join(", ")
);
}
changes.push(format!(
"resonance_type: {:?} -> {}",
entry.resonance_type, new_type
));
entry.resonance_type = Some(new_type.clone());
}
// Update anchors if provided (replace all)
// Track explicitly removed anchors so auto_anchor won't re-add them
let mut explicitly_removed_anchors: Vec<String> = Vec::new();
if let Some(ref new_anchors) = anchors {
let anchor_list: Vec<String> = new_anchors
.split(',')
.map(|s| normalize_id(s.trim()))
.filter(|s| !s.is_empty())
.collect();
// Anchors in old set but not in new set were explicitly removed
for old_anchor in &entry.anchors {
if !anchor_list.contains(old_anchor) {
explicitly_removed_anchors.push(old_anchor.clone());
}
}
changes.push(format!("anchors: {:?} -> {:?}", entry.anchors, anchor_list));
entry.anchors = anchor_list;
}
// Add a single anchor
if let Some(ref new_anchor) = add_anchor {
let normalized = normalize_id(new_anchor);
if !entry.anchors.contains(&normalized) {
entry.anchors.push(normalized.clone());
changes.push(format!("anchors: added '{}'", normalized));
}
}
// Remove a specific anchor
if let Some(ref anchor_to_remove) = remove_anchor {
let normalized = normalize_id(anchor_to_remove);
if let Some(pos) = entry.anchors.iter().position(|a| *a == normalized) {
entry.anchors.remove(pos);
changes.push(format!("anchors: removed '{}'", normalized));
}
}
// Update wake phrase if provided
if let Some(ref new_phrase) = wake_phrase {
changes.push(format!(
"wake_phrase: {:?} -> {}",
entry.wake_phrase, new_phrase
));
entry.wake_phrase = Some(new_phrase.clone());
}
// Update wake_phrases (replaces all)
if let Some(ref phrases_str) = wake_phrases {
let phrase_list: Vec<String> = phrases_str
.split(',')
.map(|s| s.trim().to_string())
.filter(|s| !s.is_empty())
.collect();
changes.push(format!(
"wake_phrases: {:?} -> {:?}",
entry.wake_phrases, phrase_list
));
entry.wake_phrases = phrase_list;
}
// Add a single wake phrase
if let Some(ref new_phrase) = add_wake_phrase
&& !entry.wake_phrases.contains(new_phrase)
{
entry.wake_phrases.push(new_phrase.clone());
changes.push(format!("wake_phrases: added '{}'", new_phrase));
}
// Remove a specific wake phrase
if let Some(ref phrase_to_remove) = remove_wake_phrase
&& let Some(pos) = entry
.wake_phrases
.iter()
.position(|p| p == phrase_to_remove)
{
entry.wake_phrases.remove(pos);
changes.push(format!("wake_phrases: removed '{}'", phrase_to_remove));
}
// Update wake_order (use '-' to clear)
if let Some(ref order_str) = wake_order {
if order_str == "-" {
changes.push("wake_order: cleared".to_string());
entry.wake_order = None;
} else if let Ok(order_value) = order_str.parse::<i32>() {
changes.push(format!(
"wake_order: {:?} -> {}",
entry.wake_order, order_value
));
entry.wake_order = Some(order_value);
} else {
bail!(
"Invalid wake_order value '{}' (use number or '-' to clear)",
order_str
);
}
}
// Update visibility if provided
if let Some(ref new_vis) = visibility {
// Validate value
if new_vis != "public" && new_vis != "private" {
bail!("--visibility must be 'public' or 'private'");
}
let old_vis = entry.visibility.clone();
// Bloom protection: warn when making blooms public
if new_vis == "public" && entry.category_id == "bloom" && !force {
bail!(
"Making bloom '{}' public will expose identity data. Use --force to confirm.",
entry.id
);
}
// Handle public -> private: require owner
if new_vis == "private" && old_vis == "public" {
let new_owner = owner.clone().or_else(|| {
std::env::var("MX_CURRENT_AGENT")
.ok()
.filter(|s| !s.is_empty())
});
if new_owner.is_none() {
bail!(
"Cannot make entry private without an owner. Provide --owner or set MX_CURRENT_AGENT."
);
}
entry.owner = new_owner;
}
// Handle private -> public: clear owner
if new_vis == "public" && old_vis == "private" {
entry.owner = None;
}
changes.push(format!("visibility: {} -> {}", old_vis, new_vis));
entry.visibility = new_vis.clone();
}
// Update owner if provided (only for private entries)
if let Some(ref new_owner) = owner {
// Only allow owner update if entry is or will be private
let is_private =
visibility.as_deref() == Some("private") || entry.visibility == "private";
if !is_private {
bail!(
"Cannot set owner on public entry. Use --visibility private to make entry private first."
);
}
changes.push(format!("owner: {:?} -> {}", entry.owner, new_owner));
entry.owner = Some(new_owner.clone());
}
// Update session_id if provided
if let Some(ref new_session_id) = session_id {
let normalized = normalize_id(new_session_id);
changes.push(format!(
"session_id: {:?} -> {}",
entry.session_id, normalized
));
entry.session_id = Some(normalized.clone());
// Create EXTRACTED_FROM edge, mirroring the add path logic.
// The for-session query traverses the relates_to edge, so we
// need both the field AND the edge for consistency.
let session_ref = normalized;
let edge_ctx = crate::store::AgentContext::public_only();
if db.get(&session_ref, &edge_ctx)?.is_none() {
eprintln!(
"Warning: Session {} not found - EXTRACTED_FROM edge not created",
session_ref
);
} else {
db.add_relationship(&id, &session_ref, "extracted_from")?;
}
}
// Update timestamp
entry.updated_at = Some(chrono::Utc::now().to_rfc3339());
// Update content hash if body was changed
if body_changed && let Some(body) = entry.body.as_ref() {
entry.content_hash = Some(knowledge::KnowledgeEntry::compute_hash(body));
}
// Update tags if provided - set on entry BEFORE upsert
if let Some(tags_str) = tags {
let tag_list: Vec<String> = tags_str
.split(',')
.map(|s| s.trim().to_string())
.filter(|s| !s.is_empty())
.collect();
changes.push(format!("tags: {}", tag_list.join(", ")));
entry.tags = tag_list;
}
// Add a single tag
if let Some(ref new_tag) = add_tag {
let tag = new_tag.trim().to_string();
if !tag.is_empty() && !entry.tags.contains(&tag) {
entry.tags.push(tag.clone());
changes.push(format!("tags: added '{}'", tag));
}
}
// Remove a specific tag
if let Some(ref tag_to_remove) = remove_tag {
let tag = tag_to_remove.trim().to_string();
if let Some(pos) = entry.tags.iter().position(|t| *t == tag) {
entry.tags.remove(pos);
changes.push(format!("tags: removed '{}'", tag));
}
}
// Upsert entry (now includes updated tags)
db.upsert_knowledge(&entry)?;
// Update applicability if provided
if let Some(applicability_str) = applicability {
let applicability_list: Vec<String> = applicability_str
.split(',')
.map(|s| s.trim().to_string())
.filter(|s| !s.is_empty())
.collect();
changes.push(format!("applicability: {}", applicability_list.join(", ")));
entry.applicability = applicability_list;
db.upsert_knowledge(&entry)?;
}
// Update content type if provided
if let Some(new_content_type) = content_type {
changes.push(format!(
"content_type: {} -> {}",
entry.content_type_id.as_deref().unwrap_or("none"),
new_content_type
));
entry.content_type_id = Some(new_content_type);
// Re-upsert to update content_type_id
db.upsert_knowledge(&entry)?;
}
// Auto-generate embedding if in network SurrealDB mode
auto_embed(&id, db.as_ref())?;
// Auto-generate anchors if in network SurrealDB mode
// Pass explicitly removed anchors so auto_anchor respects user intent:
// if the user did --anchors (full replacement) and removed some anchors,
// auto_anchor should not re-add them.
let removed = if explicitly_removed_anchors.is_empty() {
None
} else {
Some(explicitly_removed_anchors.as_slice())
};
auto_anchor(&id, db.as_ref(), removed)?;
if json {
println!(
"{}",
serde_json::to_string_pretty(&serde_json::json!({
"id": id,
"changes": changes,
}))?
);
} else {
println!("Updated entry: {}", id);
if changes.is_empty() {
println!(" No changes specified");
} else {
for change in &changes {
println!(" {}", change);
}
}
}
}
MemoryCommands::Edit {
id,
find,
replace,
replace_all,
nth,
json,
} => {
let db = store::create_store_with_verbose(&config.db_path, verbose)?;
let id = normalize_id(&id);
// Use current agent context for private entry access
let current_agent = std::env::var("MX_CURRENT_AGENT")
.ok()
.filter(|s| !s.is_empty());
let ctx = match ¤t_agent {
Some(agent) => store::AgentContext::for_agent(agent),
None => store::AgentContext::public_only(),
};
// Backup before edit (Issue #206)
if let Some(entry) = db.get(&id, &ctx)? {
let _ = db
.backup_content(&entry, "edit", current_agent.as_deref())
.map_err(|e| eprintln!("Warning: failed to create backup: {}", e));
}
let result = db.edit_content(&id, &ctx, &find, &replace, replace_all, nth)?;
// Auto-generate embedding if in network SurrealDB mode
auto_embed(&id, db.as_ref())?;
// Auto-generate anchors if in network SurrealDB mode
auto_anchor(&id, db.as_ref(), None)?;
if json {
println!(
"{}",
serde_json::to_string_pretty(&serde_json::json!({
"id": id,
"replacements": result.replacements,
}))?
);
} else {
println!("Edited entry: {}", id);
println!(
" {} replacement{}",
result.replacements,
if result.replacements == 1 { "" } else { "s" }
);
}
}
MemoryCommands::Append {
id,
content,
file,
json,
} => {
use std::io::{self, Read};
let db = store::create_store_with_verbose(&config.db_path, verbose)?;
let id = normalize_id(&id);
// Use current agent context for private entry access
let current_agent = std::env::var("MX_CURRENT_AGENT")
.ok()
.filter(|s| !s.is_empty());
let ctx = match ¤t_agent {
Some(agent) => store::AgentContext::for_agent(agent),
None => store::AgentContext::public_only(),
};
// Get content from argument, file, or stdin
let text = if let Some(c) = content {
c
} else if let Some(file_path) = file {
std::fs::read_to_string(&file_path)
.with_context(|| format!("Failed to read file: {}", file_path))?
} else {
let mut buffer = String::new();
io::stdin()
.read_to_string(&mut buffer)
.context("Failed to read from stdin")?;
buffer.trim_end().to_string()
};
if text.is_empty() {
bail!("No content provided");
}
// Backup before append (Issue #206)
if let Some(entry) = db.get(&id, &ctx)? {
let _ = db
.backup_content(&entry, "append", current_agent.as_deref())
.map_err(|e| eprintln!("Warning: failed to create backup: {}", e));
}
db.append_content(&id, &ctx, &text)?;
// Auto-generate embedding if in network SurrealDB mode
auto_embed(&id, db.as_ref())?;
// Auto-generate anchors if in network SurrealDB mode
auto_anchor(&id, db.as_ref(), None)?;
if json {
println!(
"{}",
serde_json::to_string_pretty(&serde_json::json!({
"id": id,
"bytes_added": text.len(),
}))?
);
} else {
println!("Appended to entry: {}", id);
println!(" {} bytes added", text.len());
}
}
MemoryCommands::Prepend {
id,
content,
file,
json,
} => {
use std::io::{self, Read};
let db = store::create_store_with_verbose(&config.db_path, verbose)?;
let id = normalize_id(&id);
// Use current agent context for private entry access
let current_agent = std::env::var("MX_CURRENT_AGENT")
.ok()
.filter(|s| !s.is_empty());
let ctx = match ¤t_agent {
Some(agent) => store::AgentContext::for_agent(agent),
None => store::AgentContext::public_only(),
};
// Get content from argument, file, or stdin
let text = if let Some(c) = content {
c
} else if let Some(file_path) = file {
std::fs::read_to_string(&file_path)
.with_context(|| format!("Failed to read file: {}", file_path))?
} else {
let mut buffer = String::new();
io::stdin()
.read_to_string(&mut buffer)
.context("Failed to read from stdin")?;
buffer.trim_end().to_string()
};
if text.is_empty() {
bail!("No content provided");
}
// Backup before prepend (Issue #206)
if let Some(entry) = db.get(&id, &ctx)? {
let _ = db
.backup_content(&entry, "prepend", current_agent.as_deref())
.map_err(|e| eprintln!("Warning: failed to create backup: {}", e));
}
db.prepend_content(&id, &ctx, &text)?;
// Auto-generate embedding if in network SurrealDB mode
auto_embed(&id, db.as_ref())?;
// Auto-generate anchors if in network SurrealDB mode
auto_anchor(&id, db.as_ref(), None)?;
if json {
println!(
"{}",
serde_json::to_string_pretty(&serde_json::json!({
"id": id,
"bytes_added": text.len(),
}))?
);
} else {
println!("Prepended to entry: {}", id);
println!(" {} bytes added", text.len());
}
}
MemoryCommands::Restore { id, list, json } => {
let db = store::create_store_with_verbose(&config.db_path, verbose)?;
let id = normalize_id(&id);
// Shared agent context (#10: read MX_CURRENT_AGENT once)
let current_agent = std::env::var("MX_CURRENT_AGENT")
.ok()
.filter(|s| !s.is_empty());
let ctx = match ¤t_agent {
Some(agent) => store::AgentContext::for_agent(agent),
None => store::AgentContext::public_only(),
};
if list {
// List available backups
// #7: filter by visibility — only show backups for entries the agent can see
if db.get(&id, &ctx)?.is_none() {
if json {
println!("{}", serde_json::to_string_pretty(&serde_json::json!([]))?);
} else {
println!("No entry or backups found for {}", id);
}
} else {
let backups = db.list_backups(&id)?;
if json {
println!("{}", serde_json::to_string_pretty(&backups)?);
} else if backups.is_empty() {
println!("No backups found for {}", id);
} else {
println!("Backups for {}:", id);
for b in &backups {
let body_len = b.body.as_ref().map(|s| s.len()).unwrap_or(0);
println!(
" {} | {} | {} | {} bytes",
b.id,
b.created_at.as_deref().unwrap_or("unknown"),
b.operation,
body_len,
);
}
}
}
} else {
let backup = db
.latest_backup(&id)?
.ok_or_else(|| anyhow::anyhow!("No backups found for {}", id))?;
// #5: single fetch, #6: better error for deleted entries
let mut entry = match db.get(&id, &ctx)? {
Some(entry) => {
// Backup current state before restoring
if let Err(e) =
db.backup_content(&entry, "update", current_agent.as_deref())
{
eprintln!(
"Warning: failed to backup current state before restore: {}",
e
);
}
entry
}
None => {
bail!(
"Entry '{}' not found (may have been deleted). \
Restore from backup after deletion is not yet supported.",
id
);
}
};
// Restore body from backup
entry.body = backup.body.clone();
// #4: set updated_at
entry.updated_at = Some(chrono::Utc::now().to_rfc3339());
// Recompute content hash
let hash_body = entry.body.as_deref().unwrap_or("").to_string();
entry.content_hash = Some(knowledge::KnowledgeEntry::compute_hash(&hash_body));
db.upsert_knowledge(&entry)?;
// #3: update embeddings and anchors like all other mutation paths
auto_embed(&id, db.as_ref())?;
auto_anchor(&id, db.as_ref(), None)?;
if json {
println!(
"{}",
serde_json::to_string_pretty(&serde_json::json!({
"restored": true,
"id": id,
"from_backup": backup.id,
"backup_created": backup.created_at,
"operation": backup.operation,
}))?
);
} else {
println!("Restored entry: {}", id);
println!(" from backup: {}", backup.id);
println!(
" backup created: {}",
backup.created_at.as_deref().unwrap_or("unknown")
);
println!(" original operation: {}", backup.operation);
}
}
}
MemoryCommands::Embed { id, all } => {
use crate::embeddings::{EmbeddingProvider, FastEmbedProvider};
let db = store::create_store_with_verbose(&config.db_path, verbose)?;
// Use current agent context for private entry access
let ctx = match std::env::var("MX_CURRENT_AGENT") {
Ok(agent) if !agent.is_empty() => store::AgentContext::for_agent(agent),
_ => store::AgentContext::public_only(),
};
// Initialize embedding provider once
println!("Initializing FastEmbed model...");
let mut provider = FastEmbedProvider::new()?;
if all {
// Embed ALL entries
let entries = db.list_all(&ctx)?;
let total = entries.len();
println!("Found {} entries to embed", total);
for (idx, mut entry) in entries.into_iter().enumerate() {
// Construct embedding text from title + summary/body + tags
let mut parts = vec![entry.title.clone()];
if let Some(summary) = &entry.summary {
parts.push(summary.clone());
} else if let Some(body) = &entry.body {
parts.push(body.chars().take(2000).collect());
}
if !entry.tags.is_empty() {
parts.push(format!("Tags: {}", entry.tags.join(", ")));
}
let embedding_text = parts.join("\n\n");
// Generate embedding
println!("Embedded {}/{}: {}", idx + 1, total, entry.title);
let embedding = provider.embed(&embedding_text)?;
// Update entry with embedding
entry.embedding = Some(embedding);
entry.embedding_model = Some(provider.model_id().to_string());
entry.embedded_at = Some(chrono::Utc::now().to_rfc3339());
entry.updated_at = Some(chrono::Utc::now().to_rfc3339());
// Save to database
db.upsert_knowledge(&entry)?;
}
println!("✓ All {} entries embedded successfully!", total);
println!(" Model: {}", provider.model_id());
println!(" Dimensions: {}", provider.dimensions());
} else {
// Embed single entry
let entry_id = id.ok_or_else(|| {
anyhow::anyhow!("Entry ID required (use --all to embed all entries)")
})?;
// Fetch entry
let mut entry = db
.get(&entry_id, &ctx)?
.ok_or_else(|| anyhow::anyhow!("Entry not found: {}", entry_id))?;
// Construct embedding text from title + summary/body + tags
let mut parts = vec![entry.title.clone()];
if let Some(summary) = &entry.summary {
parts.push(summary.clone());
} else if let Some(body) = &entry.body {
parts.push(body.chars().take(2000).collect());
}
if !entry.tags.is_empty() {
parts.push(format!("Tags: {}", entry.tags.join(", ")));
}
let embedding_text = parts.join("\n\n");
// Generate embedding
println!("Generating embedding for '{}'...", entry.title);
let embedding = provider.embed(&embedding_text)?;
// Update entry with embedding
entry.embedding = Some(embedding);
entry.embedding_model = Some(provider.model_id().to_string());
entry.embedded_at = Some(chrono::Utc::now().to_rfc3339());
entry.updated_at = Some(chrono::Utc::now().to_rfc3339());
// Save to database
db.upsert_knowledge(&entry)?;
println!("✓ Embedding generated and saved!");
println!(" Entry: {}", entry_id);
println!(" Model: {}", provider.model_id());
println!(" Dimensions: {}", provider.dimensions());
}
}
MemoryCommands::AutoAnchor {
id,
threshold,
max_anchors,
dry_run,
verbose,
} => {
let db = store::create_store_with_verbose(&config.db_path, verbose)?;
// Use current agent context for private entry access
let ctx = match std::env::var("MX_CURRENT_AGENT") {
Ok(agent) if !agent.is_empty() => store::AgentContext::for_agent(agent),
_ => store::AgentContext::public_only(),
};
// Get entries to process
let entries = if let Some(entry_id) = id {
// Process single entry
let entry = db
.get(&entry_id, &ctx)?
.ok_or_else(|| anyhow::anyhow!("Entry not found: {}", entry_id))?;
if entry.embedding.is_none() {
anyhow::bail!(
"Entry {} has no embedding. Run `mx memory embed {}` first.",
entry_id,
entry_id
);
}
vec![entry]
} else {
// Get all entries with embeddings
let all_entries = db.list_all(&ctx)?;
all_entries
.into_iter()
.filter(|e| e.embedding.is_some())
.collect()
};
if entries.is_empty() {
println!("No entries with embeddings found.");
return Ok(());
}
println!("Processing {} entries...", entries.len());
// Get ALL entries with embeddings for similarity comparison
let all_candidates = db.list_all(&ctx)?;
let candidates: Vec<_> = all_candidates
.into_iter()
.filter(|e| e.embedding.is_some())
.collect();
let mut total_added = 0;
let entries_count = entries.len();
for entry in entries {
let entry_embedding = entry.embedding.as_ref().unwrap();
// Calculate similarities
let mut similarities: Vec<(String, String, f32)> = Vec::new();
for candidate in &candidates {
// Skip self
if candidate.id == entry.id {
continue;
}
// Skip if already an anchor
if entry.anchors.contains(&candidate.id) {
continue;
}
// Privacy check
let can_anchor = if entry.visibility == "private" {
// Private can anchor to same-owner private OR public
candidate.visibility == "public"
|| (candidate.visibility == "private" && candidate.owner == entry.owner)
} else {
// Public can only anchor to public
candidate.visibility == "public"
};
if !can_anchor {
continue;
}
// Calculate cosine similarity
let candidate_embedding = candidate.embedding.as_ref().unwrap();
let similarity = cosine_similarity(entry_embedding, candidate_embedding);
// Filter by threshold, skip near-duplicates
if similarity >= threshold && similarity <= 0.95 {
similarities.push((
candidate.id.clone(),
candidate.title.clone(),
similarity,
));
}
}
// Sort by similarity (descending) and take top N
similarities
.sort_by(|a, b| b.2.partial_cmp(&a.2).unwrap_or(std::cmp::Ordering::Equal));
let top_matches: Vec<_> = similarities.into_iter().take(max_anchors).collect();
if top_matches.is_empty() {
if verbose {
println!(
" {} \"{}\" - No similar entries found",
entry.id, entry.title
);
}
continue;
}
println!("Processing {} \"{}\"...", entry.id, entry.title);
for (match_id, match_title, score) in &top_matches {
if verbose {
println!(" → {} \"{}\" ({:.2})", match_id, match_title, score);
} else {
println!(" → {} \"{}\"", match_id, match_title);
}
}
if dry_run {
println!(
"[DRY RUN] Would add {} anchors to {}",
top_matches.len(),
entry.id
);
} else {
// Update the entry with new anchors
let new_anchor_ids: Vec<String> =
top_matches.iter().map(|(id, _, _)| id.clone()).collect();
// Merge with existing anchors
let mut updated_anchors = entry.anchors.clone();
updated_anchors.extend(new_anchor_ids);
updated_anchors.sort();
updated_anchors.dedup();
// Create updated entry
let mut updated_entry = entry.clone();
updated_entry.anchors = updated_anchors;
updated_entry.updated_at = Some(chrono::Utc::now().to_rfc3339());
// Save to database
db.upsert_knowledge(&updated_entry)?;
println!("Added {} anchors", top_matches.len());
total_added += top_matches.len();
}
}
if dry_run {
println!("\n[DRY RUN] Complete. No changes written.");
} else {
println!(
"\n✓ Added {} total anchors across {} entries",
total_added, entries_count
);
}
}
MemoryCommands::Agents { command } => handle_agents(command, &config)?,
MemoryCommands::Projects { command } => handle_projects(command, &config)?,
MemoryCommands::Applicability { command } => handle_applicability(command, &config)?,
MemoryCommands::Sessions { command } => handle_sessions(command, &config)?,
MemoryCommands::Categories { command } => handle_categories(command, &config)?,
MemoryCommands::Tags { command } => handle_tags(command, &config)?,
MemoryCommands::SourceTypes { command } => handle_source_types(command, &config)?,
MemoryCommands::EntryTypes { command } => handle_entry_types(command, &config)?,
MemoryCommands::SessionTypes { command } => handle_session_types(command, &config)?,
MemoryCommands::RelationshipTypes { command } => {
handle_relationship_types(command, &config)?
}
MemoryCommands::Relationships { command } => handle_relationships(command, &config)?,
MemoryCommands::ContentTypes { command } => handle_content_types(command, &config)?,
MemoryCommands::Export { format, output } => {
let db = store::create_store(&config.db_path)?;
match format.as_str() {
"md" | "markdown" => {
// Markdown exports to directory
let output_dir = output.as_deref().unwrap_or("./memory-export");
let dir_path = std::path::PathBuf::from(output_dir);
export_markdown(db.as_ref(), &dir_path)?;
println!("Exported to directory: {}", output_dir);
}
"jsonl" => {
// JSONL exports to file or stdout
if let Some(ref path) = output {
export_jsonl(db.as_ref(), &std::path::PathBuf::from(path))?;
println!("Exported to {}", path);
} else {
export_jsonl(db.as_ref(), &std::path::PathBuf::from("/dev/stdout"))?;
}
}
"csv" => {
// CSV exports to file or stdout
if let Some(ref path) = output {
export_csv(db.as_ref(), &std::path::PathBuf::from(path))?;
println!("Exported to {}", path);
} else {
export_csv(db.as_ref(), &std::path::PathBuf::from("/dev/stdout"))?;
}
}
_ => {
bail!("Invalid format '{}'. Valid formats: md, jsonl, csv", format);
}
}
}
MemoryCommands::Wake {
limit,
min_resonance,
days,
json,
ritual,
index,
no_activate,
engage,
set_missing,
begin,
bloom_id,
respond,
skip,
session,
} => {
let db = store::create_store(&config.db_path)?;
// Get current agent context - required for wake
let current_agent = match std::env::var("MX_CURRENT_AGENT") {
Ok(agent) if !agent.is_empty() => agent,
_ => {
bail!("MX_CURRENT_AGENT not set. Cannot wake without identity.");
}
};
let ctx = store::AgentContext::for_agent(current_agent.clone());
// Run cascade
let cascade = db.wake_cascade(&ctx, limit, min_resonance, days)?;
// Increment activation counts for wake cascade entries.
// We do NOT reset last_activated here — wake surfacing is passive, not
// intentional access, and resetting the decay clock would create a feedback
// loop where frequently-surfaced entries never decay.
if !no_activate {
let ids = cascade.all_ids();
if !ids.is_empty() {
db.increment_activation_count(&ids)?;
}
}
// Output
if begin {
// Start session-based ritual (state stored in DB)
let output = wake_ritual::begin_ritual(db.as_ref(), &cascade)?;
println!("{}", output);
} else if let Some(phrase) = respond {
// Submit wake phrase response
let session_token =
session.ok_or_else(|| anyhow::anyhow!("--session required with --respond"))?;
let id = bloom_id
.ok_or_else(|| anyhow::anyhow!("--bloom-id required with --respond"))?;
let output =
wake_ritual::respond_ritual(db.as_ref(), &ctx, &id, &phrase, &session_token)?;
println!("{}", output);
} else if skip {
// Skip a bloom
let session_token =
session.ok_or_else(|| anyhow::anyhow!("--session required with --skip"))?;
let id =
bloom_id.ok_or_else(|| anyhow::anyhow!("--bloom-id required with --skip"))?;
let output = wake_ritual::skip_ritual(db.as_ref(), &ctx, &id, &session_token)?;
println!("{}", output);
} else if engage {
// Interactive engage mode
engage::run_engage_ritual(&cascade, db.as_ref(), set_missing)?;
} else if json {
println!("{}", serde_json::to_string_pretty(&cascade)?);
} else if index {
print_wake_index(&cascade);
} else if ritual {
print_wake_ritual(&cascade, ¤t_agent);
} else {
print_wake_cascade(&cascade);
}
}
MemoryCommands::Recent {
days,
json,
format,
resonance_type,
all_types,
sort,
limit,
} => {
let db = store::create_store_with_verbose(&config.db_path, verbose)?;
// Note: Listing doesn't activate facts - bulk view != focused access
// Auto-enable all_types when --resonance-type is set, otherwise the
// default ephemeral-only query would silently return nothing for
// non-ephemeral types (e.g. `--resonance-type foundational`).
let all_types = all_types || resonance_type.is_some();
// Decide which query to use:
// --all-types (or --resonance-type) => query all resonance types
// (default) => ephemeral only (backwards compatible)
// --resonance-type filter is applied post-query in both cases.
let mut facts = if all_types {
db.query_recent_facts_all_types(days)?
} else {
db.query_recent_facts(days)?
};
// Filter by resonance_type if provided (works with both code paths)
if let Some(ref rtype) = resonance_type {
facts.retain(|f| f.resonance_type.as_deref() == Some(rtype.as_str()));
}
// Apply sort: "resonance" sorts by effective_resonance (decay-adjusted) highest-first.
// DB already returns entries ORDER BY effective_resonance DESC; the default path
// preserves that ordering rather than re-sorting, so a resonance-9 from 6 months
// ago does not outrank a resonance-7 from yesterday.
if matches!(sort, RecentSortOrder::Resonance) {
facts.sort_by(|a, b| {
// Sort by effective_resonance (decay-adjusted) when available;
// fall back to raw resonance for entries that lack it.
let a_val = a.effective_resonance.unwrap_or(a.resonance as f64);
let b_val = b.effective_resonance.unwrap_or(b.resonance as f64);
b_val
.partial_cmp(&a_val)
.unwrap_or(std::cmp::Ordering::Equal)
});
}
// Default: preserve DB ordering (effective_resonance DESC). No re-sort needed.
// Apply limit
facts.truncate(limit);
// Support both --json flag and legacy --format json
if json || format == "json" {
let json_facts: Vec<serde_json::Value> = facts
.iter()
.map(|f| {
let fact_type = f
.summary
.as_ref()
.and_then(|s| serde_json::from_str::<serde_json::Value>(s).ok())
.and_then(|v: serde_json::Value| {
v.get("fact_type")
.and_then(|t| t.as_str())
.map(String::from)
});
serde_json::json!({
"id": f.id,
"type": fact_type,
"content": f.body.as_ref().unwrap_or(&"".to_string()),
"created_at": f.created_at.as_ref().unwrap_or(&"".to_string()),
"resonance": f.resonance,
})
})
.collect();
println!("{}", serde_json::to_string_pretty(&json_facts)?);
} else {
for fact in facts {
let summary_json = fact
.summary
.as_ref()
.and_then(|s| serde_json::from_str::<serde_json::Value>(s).ok());
let fact_type = summary_json
.as_ref()
.and_then(|v: &serde_json::Value| {
v.get("fact_type")
.and_then(|t| t.as_str())
.map(String::from)
})
.unwrap_or_else(|| "unknown".to_string());
let state = fact.get_summary_state();
let date = fact
.created_at
.as_ref()
.and_then(|dt_str: &String| {
chrono::DateTime::parse_from_rfc3339(dt_str).ok()
})
.map(|dt| dt.format("%Y-%m-%d").to_string())
.unwrap_or_else(|| "unknown".to_string());
let content = fact.body.as_deref().unwrap_or("");
let preview = safe_truncate(content, 60);
if let Some(state) = state {
println!(
"[{}] {} ({}): {} ({}, resonance {})",
date, fact_type, state, preview, fact.id, fact.resonance
);
} else {
println!(
"[{}] {}: {} ({}, resonance {})",
date, fact_type, preview, fact.id, fact.resonance
);
}
}
}
}
MemoryCommands::WakeFetch { days, limit } => {
if days <= 0 {
bail!("--days must be a positive integer (got {days})");
}
let db = store::create_store_with_verbose(&config.db_path, verbose)?;
let mut facts = db.query_recent_facts_all_types(days)?;
// Filter to resonance >= 3 AND extract fact_type in a single pass.
// Collect (entry, fact_type) pairs so we don't re-parse summary JSON later.
let mut typed_facts: Vec<(crate::knowledge::KnowledgeEntry, String)> = facts
.drain(..)
.filter(|f| f.resonance >= 3)
.filter_map(|f| {
let ft = f
.summary
.as_ref()
.and_then(|s| serde_json::from_str::<serde_json::Value>(s).ok())
.and_then(|v| v.get("fact_type")?.as_str().map(String::from))?;
Some((f, ft))
})
.collect();
// Sort by effective resonance (decay-adjusted), highest first
typed_facts.sort_by(|(a, _), (b, _)| {
let a_val = a.effective_resonance.unwrap_or(a.resonance as f64);
let b_val = b.effective_resonance.unwrap_or(b.resonance as f64);
b_val
.partial_cmp(&a_val)
.unwrap_or(std::cmp::Ordering::Equal)
});
// Apply limit
typed_facts.truncate(limit);
if typed_facts.is_empty() {
println!("(no memory entries returned)");
return Ok(());
}
println!("<facts>");
for (i, (fact, fact_type)) in typed_facts.iter().enumerate() {
if i > 0 {
println!();
}
let date = fact
.created_at
.as_ref()
.and_then(|dt_str| chrono::DateTime::parse_from_rfc3339(dt_str).ok())
.map(|dt| dt.format("%Y-%m-%d").to_string())
.unwrap_or_else(|| "unknown".to_string());
let content = fact.body.as_deref().unwrap_or("");
println!(
"[{}] {} (resonance {}) {}",
date, fact_type, fact.resonance, fact.id
);
let escaped = content.replace("]]>", "]]]]><![CDATA[>");
println!("<![CDATA[{}]]>", escaped);
}
println!("</facts>");
}
MemoryCommands::ForSession {
session_id,
json,
format,
} => {
let db = store::create_store_with_verbose(&config.db_path, verbose)?;
// Normalize session ID
let session_ref = normalize_id(&session_id);
// Get fact IDs
let fact_ids = db.get_facts_for_session(&session_ref)?;
if fact_ids.is_empty() {
println!("No facts found for session: {}", session_ref);
return Ok(());
}
// Increment activation counts for session facts — viewing a session is
// passive bulk access, not intentional recall of any single entry.
// Do NOT reset last_activated so decay continues normally.
if !fact_ids.is_empty()
&& let Err(e) = db.increment_activation_count(&fact_ids)
{
eprintln!("Warning: failed to update activation counts: {}", e);
}
// Fetch full entries for each fact
let ctx = match std::env::var("MX_CURRENT_AGENT") {
Ok(agent) if !agent.is_empty() => store::AgentContext::for_agent(agent),
_ => store::AgentContext::public_only(),
};
// Support both --json flag and legacy --format json
if json || format == "json" {
let mut json_facts = Vec::new();
for fact_id in &fact_ids {
if let Some(fact) = db.get(fact_id, &ctx)? {
let fact_type = fact
.summary
.as_ref()
.and_then(|s| serde_json::from_str::<serde_json::Value>(s).ok())
.and_then(|v: serde_json::Value| {
v.get("fact_type")
.and_then(|t| t.as_str())
.map(String::from)
});
json_facts.push(serde_json::json!({
"id": fact.id,
"type": fact_type,
"content": fact.body.as_ref().unwrap_or(&"".to_string()),
"created_at": fact.created_at.as_ref().unwrap_or(&"".to_string()),
"resonance": fact.resonance,
}));
}
}
println!("{}", serde_json::to_string_pretty(&json_facts)?);
} else {
println!("Facts for session {}:", session_ref);
for fact_id in fact_ids {
if let Some(fact) = db.get(&fact_id, &ctx)? {
let fact_type = fact
.summary
.as_ref()
.and_then(|s| serde_json::from_str::<serde_json::Value>(s).ok())
.and_then(|v: serde_json::Value| {
v.get("fact_type")
.and_then(|t| t.as_str())
.map(String::from)
})
.unwrap_or_else(|| "unknown".to_string());
let date = fact
.created_at
.as_ref()
.and_then(|dt_str: &String| {
chrono::DateTime::parse_from_rfc3339(dt_str).ok()
})
.map(|dt| dt.format("%Y-%m-%d").to_string())
.unwrap_or_else(|| "unknown".to_string());
let content = fact.body.as_deref().unwrap_or("");
let preview = safe_truncate(content, 60);
println!(
"[{}] {}: {} ({}, resonance {})",
date, fact_type, preview, fact.id, fact.resonance
);
}
}
}
}
MemoryCommands::FactSession {
fact_id,
json,
format,
} => {
let db = store::create_store_with_verbose(&config.db_path, verbose)?;
// Normalize fact ID
let fact_ref = normalize_id(&fact_id);
// Activate fact when fetching its session (going deeper)
if let Err(e) = db.update_activations(std::slice::from_ref(&fact_ref)) {
eprintln!("Warning: failed to update activation: {}", e);
}
// Get session ID
// Support both --json flag and legacy --format json
let use_json = json || format == "json";
match db.get_session_for_fact(&fact_ref)? {
Some(session_id) => {
if use_json {
println!(
"{}",
serde_json::to_string_pretty(&serde_json::json!({
"fact_id": fact_ref,
"session_id": session_id,
}))?
);
} else {
println!(
"Fact {} was extracted from session: {}",
fact_ref, session_id
);
}
}
None => {
if use_json {
println!(
"{}",
serde_json::to_string_pretty(&serde_json::json!({
"fact_id": fact_ref,
"session_id": null,
}))?
);
} else {
println!("No session found for fact: {}", fact_ref);
}
}
}
}
MemoryCommands::Reinforce {
id,
amount,
cap,
json,
format,
} => {
let db = store::create_store_with_verbose(&config.db_path, verbose)?;
// Normalize ID
let normalized_id = normalize_id(&id);
// Respect visibility: agents can only reinforce entries they can see
let ctx = match std::env::var("MX_CURRENT_AGENT") {
Ok(agent) if !agent.is_empty() => store::AgentContext::for_agent(agent),
_ => store::AgentContext::public_only(),
};
// Call reinforce on the store
if let Some(result) = db.reinforce(&normalized_id, amount, Some(cap), &ctx)? {
// Output result - support both --json flag and legacy --format json
if json || format == "json" {
println!("{}", serde_json::to_string_pretty(&result)?);
} else {
println!("Reinforced entry: {}", result.id);
println!(" Old resonance: {}", result.old_resonance);
println!(" New resonance: {}", result.new_resonance);
println!(" Amount added: {}", result.amount_added);
if result.capped {
println!(" (Capped at {})", cap);
}
println!(" Last activated: {}", result.last_activated);
println!(" Activation count: {}", result.activation_count);
}
} else {
bail!("Entry '{}' not found", normalized_id);
}
}
}
Ok(())
}
fn handle_agents(cmd: AgentsCommands, config: &IndexConfig) -> Result<()> {
let db = store::create_store(&config.db_path)?;
match cmd {
AgentsCommands::List { json } => {
let agents = db.list_agents()?;
if json {
println!("{}", serde_json::to_string_pretty(&agents)?);
} else if agents.is_empty() {
println!("No agents registered");
} else {
println!("Registered agents:\n");
for agent in agents {
println!(
" {} - {}",
agent.id,
agent.description.as_deref().unwrap_or("")
);
if let Some(domain) = &agent.domain {
println!(" Domain: {}", domain);
}
}
}
}
AgentsCommands::Add {
id,
description,
domain,
} => {
let now = chrono::Utc::now().to_rfc3339();
let agent = types::Agent {
id: id.clone(),
description: Some(description.clone()),
domain: Some(domain.clone()),
created_at: Some(now.clone()),
updated_at: Some(now),
};
db.upsert_agent(&agent)?;
println!("Added agent: {}", id);
println!(" Description: {}", description);
println!(" Domain: {}", domain);
}
AgentsCommands::Show { id } => match db.get_agent(&id)? {
Some(agent) => {
println!("Agent: {}", agent.id);
if let Some(desc) = &agent.description {
println!("Description: {}", desc);
}
if let Some(domain) = &agent.domain {
println!("Domain: {}", domain);
}
if let Some(created) = &agent.created_at {
println!("Created: {}", created);
}
if let Some(updated) = &agent.updated_at {
println!("Updated: {}", updated);
}
}
None => {
bail!("Agent '{}' not found", id);
}
},
AgentsCommands::Seed { path } => {
use anyhow::Context;
use std::fs;
use std::path::PathBuf;
// Determine agents directory
let agents_dir = if let Some(p) = path {
PathBuf::from(p)
} else {
// Default: $MX_HOME/agents/
crate::paths::agents_dir()
};
if !agents_dir.exists() {
bail!("Agents directory does not exist: {:?}", agents_dir);
}
// Scan for .md files
let entries = fs::read_dir(&agents_dir)
.with_context(|| format!("Failed to read directory: {:?}", agents_dir))?;
let mut seeded = Vec::new();
let now = chrono::Utc::now().to_rfc3339();
for entry in entries {
let entry = entry?;
let path = entry.path();
// Skip if not a markdown file
if path.extension().and_then(|s| s.to_str()) != Some("md") {
continue;
}
// Skip files starting with _
if let Some(name) = path.file_name().and_then(|n| n.to_str())
&& name.starts_with('_')
{
continue;
}
// Read file
let content = fs::read_to_string(&path)
.with_context(|| format!("Failed to read file: {:?}", path))?;
// Parse frontmatter
if let Some((frontmatter, _body)) = parse_frontmatter(&content)
&& let Ok(agent_data) = serde_yaml::from_str::<AgentFrontmatter>(&frontmatter)
{
let agent = types::Agent {
id: agent_data.name.clone(),
description: Some(agent_data.description.clone()),
domain: agent_data.domain,
created_at: Some(now.clone()),
updated_at: Some(now.clone()),
};
db.upsert_agent(&agent)?;
seeded.push(agent_data.name);
}
}
if seeded.is_empty() {
println!("No agents seeded from {:?}", agents_dir);
} else {
println!("Seeded {} agents:", seeded.len());
for name in &seeded {
println!(" {}", name);
}
}
}
}
Ok(())
}
fn handle_projects(cmd: ProjectsCommands, config: &IndexConfig) -> Result<()> {
let db = store::create_store(&config.db_path)?;
match cmd {
ProjectsCommands::List { json } => {
let projects = db.list_projects(false)?;
if json {
println!("{}", serde_json::to_string_pretty(&projects)?);
} else if projects.is_empty() {
println!("No projects registered");
} else {
println!("Registered projects:\n");
for project in projects {
println!(" {} - {}", project.id, project.name);
if let Some(path) = &project.path {
println!(" Path: {}", path);
}
if let Some(url) = &project.repo_url {
println!(" Repo: {}", url);
}
if let Some(desc) = &project.description {
println!(" Description: {}", desc);
}
println!();
}
}
}
ProjectsCommands::Add {
id,
name,
path,
repo_url,
description,
} => {
let now = chrono::Utc::now().to_rfc3339();
let project = types::Project {
id: id.clone(),
name: name.clone(),
path,
repo_url,
description,
active: true,
created_at: now.clone(),
updated_at: now,
};
db.upsert_project(&project)?;
println!("Added project: {}", id);
println!(" Name: {}", name);
}
}
Ok(())
}
fn handle_applicability(cmd: ApplicabilityCommands, config: &IndexConfig) -> Result<()> {
let db = store::create_store(&config.db_path)?;
match cmd {
ApplicabilityCommands::List => {
let types = db.list_applicability_types()?;
if types.is_empty() {
println!("No applicability types registered");
} else {
println!("Registered applicability types:\n");
for atype in types {
println!(" {} - {}", atype.id, atype.description);
if let Some(scope) = &atype.scope {
println!(" Scope: {}", scope);
}
println!();
}
}
}
ApplicabilityCommands::Add {
id,
description,
scope,
} => {
let now = chrono::Utc::now().to_rfc3339();
let atype = types::ApplicabilityType {
id: id.clone(),
description: description.clone(),
scope,
created_at: now,
};
db.upsert_applicability_type(&atype)?;
println!("Added applicability type: {}", id);
println!(" Description: {}", description);
}
}
Ok(())
}
fn handle_sessions(cmd: SessionsCommands, config: &IndexConfig) -> Result<()> {
let db = store::create_store(&config.db_path)?;
match cmd {
SessionsCommands::List { project, json } => {
let sessions = db.list_sessions(project.as_deref())?;
if json {
println!("{}", serde_json::to_string_pretty(&sessions)?);
} else if sessions.is_empty() {
println!("No sessions found");
} else {
println!("Sessions:\n");
for session in sessions {
println!(" ID: {}", session.id);
println!(" Type: {}", session.session_type_id);
if let Some(proj) = &session.project_id {
println!(" Project: {}", proj);
}
println!(" Started: {}", session.started_at);
if let Some(ended) = &session.ended_at {
println!(" Ended: {}", ended);
}
println!();
}
}
}
SessionsCommands::Create {
session_type,
project,
} => {
let now = chrono::Utc::now().to_rfc3339();
let id = format!("sess-{}", chrono::Utc::now().format("%Y%m%d-%H%M%S"));
let session = types::Session {
id: id.clone(),
session_type_id: session_type,
project_id: project,
started_at: now,
ended_at: None,
metadata: None,
};
db.upsert_session(&session)?;
println!("Created session: {}", id);
}
SessionsCommands::Close { id } => {
if let Some(mut session) = db.get_session(&id)? {
session.ended_at = Some(chrono::Utc::now().to_rfc3339());
db.upsert_session(&session)?;
println!("Closed session: {}", id);
} else {
bail!("Session '{}' not found", id);
}
}
}
Ok(())
}
fn handle_categories(cmd: CategoriesCommands, config: &IndexConfig) -> Result<()> {
let db = store::create_store(&config.db_path)?;
match cmd {
CategoriesCommands::List { json } => {
let categories = db.list_categories()?;
if json {
println!("{}", serde_json::to_string_pretty(&categories)?);
} else if categories.is_empty() {
println!("No categories registered");
} else {
println!("Registered categories:\n");
for category in categories {
println!(" {} - {}", category.id, category.description);
}
}
}
CategoriesCommands::Add { id, description } => {
// Check if category already exists
if db.get_category(&id)?.is_some() {
bail!("Category '{}' already exists", id);
}
let now = chrono::Utc::now().to_rfc3339();
let category = types::Category {
id: id.clone(),
description: description.clone(),
created_at: now,
};
db.upsert_category(&category)?;
println!("Added category: {}", id);
println!(" Description: {}", description);
}
CategoriesCommands::Remove { id } => {
// Check if category exists
if db.get_category(&id)?.is_none() {
bail!("Category '{}' not found", id);
}
// delete_category will check if entries use it and error if so
match db.delete_category(&id) {
Ok(true) => {
println!("Deleted category: {}", id);
}
Ok(false) => {
bail!("Category '{}' not found", id);
}
Err(e) => {
return Err(e);
}
}
}
}
Ok(())
}
fn handle_tags(cmd: TagsCommands, config: &IndexConfig) -> Result<()> {
let db = store::create_store(&config.db_path)?;
match cmd {
TagsCommands::List { category, json } => {
// Validate category if provided
if let Some(ref cat) = category
&& db.get_category(cat)?.is_none()
{
let categories = db.list_categories()?;
let valid_ids: Vec<&str> = categories.iter().map(|c| c.id.as_str()).collect();
bail!(
"Unknown category '{}'. Valid categories: {}",
cat,
valid_ids.join(", ")
);
}
let tags = db.list_all_tags(category.as_deref())?;
if json {
println!("{}", serde_json::to_string_pretty(&tags)?);
} else if tags.is_empty() {
if let Some(cat) = &category {
println!("No tags found in category '{}'", cat);
} else {
println!("No tags found");
}
} else {
if let Some(cat) = &category {
println!("Tags in category '{}':\n", cat);
} else {
println!("All tags:\n");
}
for tag in tags {
println!(" {}", tag);
}
}
}
}
Ok(())
}
fn handle_source_types(cmd: SourceTypesCommands, config: &IndexConfig) -> Result<()> {
let db = store::create_store(&config.db_path)?;
match cmd {
SourceTypesCommands::List { json } => {
let types = db.list_source_types()?;
if json {
println!("{}", serde_json::to_string_pretty(&types)?);
} else if types.is_empty() {
println!("No source types registered");
} else {
println!("Registered source types:\n");
for stype in types {
println!(" {} - {}", stype.id, stype.description);
}
}
}
}
Ok(())
}
fn handle_entry_types(cmd: EntryTypesCommands, config: &IndexConfig) -> Result<()> {
let db = store::create_store(&config.db_path)?;
match cmd {
EntryTypesCommands::List { json } => {
let types = db.list_entry_types()?;
if json {
println!("{}", serde_json::to_string_pretty(&types)?);
} else if types.is_empty() {
println!("No entry types registered");
} else {
println!("Registered entry types:\n");
for etype in types {
println!(" {} - {}", etype.id, etype.description);
}
}
}
}
Ok(())
}
fn handle_session_types(cmd: SessionTypesCommands, config: &IndexConfig) -> Result<()> {
let db = store::create_store(&config.db_path)?;
match cmd {
SessionTypesCommands::List { json } => {
let types = db.list_session_types()?;
if json {
println!("{}", serde_json::to_string_pretty(&types)?);
} else if types.is_empty() {
println!("No session types registered");
} else {
println!("Registered session types:\n");
for stype in types {
println!(" {} - {}", stype.id, stype.description);
}
}
}
}
Ok(())
}
fn handle_relationship_types(cmd: RelationshipTypesCommands, config: &IndexConfig) -> Result<()> {
let db = store::create_store(&config.db_path)?;
match cmd {
RelationshipTypesCommands::List { json } => {
let types = db.list_relationship_types()?;
if json {
println!("{}", serde_json::to_string_pretty(&types)?);
} else if types.is_empty() {
println!("No relationship types registered");
} else {
println!("Registered relationship types:\n");
for rtype in types {
let directional = if rtype.directional {
"(directional)"
} else {
"(bidirectional)"
};
println!(" {} - {} {}", rtype.id, rtype.description, directional);
}
}
}
}
Ok(())
}
fn handle_relationships(cmd: RelationshipsCommands, config: &IndexConfig) -> Result<()> {
let db = store::create_store(&config.db_path)?;
match cmd {
RelationshipsCommands::List { id, json } => {
let relationships = db.list_relationships_for_entry(&id)?;
if json {
println!("{}", serde_json::to_string_pretty(&relationships)?);
} else if relationships.is_empty() {
println!("No relationships found for '{}'", id);
} else {
println!("Relationships for '{}':\n", id);
for rel in relationships {
let direction = if rel.from_entry_id == id {
format!("-> {} ({})", rel.to_entry_id, rel.relationship_type)
} else {
format!("<- {} ({})", rel.from_entry_id, rel.relationship_type)
};
println!(" {} {}", rel.id, direction);
}
}
}
RelationshipsCommands::Add { from, to, r#type } => {
let id = db.add_relationship(&from, &to, &r#type)?;
println!("Added relationship: {}", id);
println!(" From: {}", from);
println!(" To: {}", to);
println!(" Type: {}", r#type);
}
RelationshipsCommands::Delete { id } => {
if db.delete_relationship(&id)? {
println!("Deleted relationship: {}", id);
} else {
bail!("Relationship '{}' not found", id);
}
}
}
Ok(())
}
fn handle_content_types(cmd: ContentTypesCommands, config: &IndexConfig) -> Result<()> {
let db = store::create_store(&config.db_path)?;
match cmd {
ContentTypesCommands::List { json } => {
let types = db.list_content_types()?;
if json {
println!("{}", serde_json::to_string_pretty(&types)?);
} else if types.is_empty() {
println!("No content types registered");
} else {
println!("Registered content types:\n");
for ctype in types {
println!(" {} - {}", ctype.id, ctype.description);
if let Some(exts) = &ctype.file_extensions {
println!(" Extensions: {}", exts);
}
}
}
}
}
Ok(())
}
fn handle_pr(cmd: PrCommands) -> Result<()> {
match cmd {
PrCommands::Merge {
number,
rebase,
merge_commit,
} => {
commit::pr_merge(number, rebase, merge_commit)?;
Ok(())
}
}
}
fn handle_github(cmd: GithubCommands) -> Result<()> {
match cmd {
GithubCommands::Cleanup {
repo,
issues,
discussions,
dry_run,
} => {
github::cleanup(&repo, issues, discussions, dry_run)?;
Ok(())
}
GithubCommands::Comment { command } => {
handle_comment(command)?;
Ok(())
}
}
}
fn handle_comment(cmd: CommentCommands) -> Result<()> {
match cmd {
CommentCommands::Issue {
repo,
number,
message,
identity,
} => {
let url = github::post_issue_comment(&repo, number, &message, identity.as_deref())?;
println!("Comment posted: {}", url);
}
CommentCommands::Discussion {
repo,
number,
message,
identity,
} => {
let url =
github::post_discussion_comment(&repo, number, &message, identity.as_deref())?;
println!("Comment posted: {}", url);
}
}
Ok(())
}
fn handle_session(cmd: SessionCommands) -> Result<()> {
match cmd {
SessionCommands::Export { path, output } => {
session::export_session(path, output)?;
Ok(())
}
}
}
fn handle_codex(cmd: CodexCommands) -> Result<()> {
match cmd {
CodexCommands::Save {
path,
all,
clean,
include_agents,
} => {
codex::save_session(path, all, clean, include_agents)?;
Ok(())
}
CodexCommands::List { all, json } => {
codex::list_sessions(all, json)?;
Ok(())
}
CodexCommands::Read {
id,
human,
agents,
grep,
json,
clean,
} => {
let clean_agents = clean && agents;
codex::read_session(id, human, grep, agents, json, clean, clean_agents)?;
Ok(())
}
CodexCommands::Search { pattern, json } => {
codex::search_archives(pattern, json)?;
Ok(())
}
CodexCommands::Migrate {
dry_run,
verbose,
clean,
include_agents,
} => {
codex::migrate_archives(dry_run, verbose, clean, include_agents)?;
Ok(())
}
}
}
fn handle_convert(cmd: ConvertCommands) -> Result<()> {
use std::path::PathBuf;
match cmd {
ConvertCommands::Md2yaml {
input,
output,
dry_run,
} => {
let input_path = PathBuf::from(&input);
let output_dir = output
.map(PathBuf::from)
.unwrap_or_else(|| std::env::current_dir().unwrap());
if input_path.is_file() {
convert::convert_file(&input_path, &output_dir, dry_run)?;
} else if input_path.is_dir() {
convert::convert_directory(&input_path, &output_dir, dry_run)?;
} else {
bail!("Input path does not exist: {:?}", input_path);
}
Ok(())
}
ConvertCommands::Yaml2md {
input,
output,
repo,
dry_run,
} => {
let input_path = PathBuf::from(&input);
let output_dir = output
.map(PathBuf::from)
.unwrap_or_else(|| std::env::current_dir().unwrap());
if input_path.is_file() {
convert::yaml_to_markdown_file(&input_path, &output_dir, repo.as_deref(), dry_run)?;
} else if input_path.is_dir() {
convert::yaml_to_markdown_directory(
&input_path,
&output_dir,
repo.as_deref(),
dry_run,
)?;
} else {
bail!("Input path does not exist: {:?}", input_path);
}
Ok(())
}
}
}
fn handle_wiki(cmd: WikiCommands) -> Result<()> {
match cmd {
WikiCommands::Sync {
repo,
source,
page_name,
dry_run,
} => {
sync::wiki::sync(&repo, &source, page_name.as_deref(), dry_run)?;
Ok(())
}
}
}
/// Handle mx log - decoded git log
fn handle_log(count: usize, full: bool, extra_args: Vec<String>) -> Result<()> {
use std::process::Command;
// Build git log command
let format = if full {
// Full format: hash, author, date, subject, body
"%H%n%an <%ae>%n%ad%n%s%n%b%n---END---"
} else {
// Compact format: short hash, subject, body (for decoding)
"%h%n%s%n%b%n---END---"
};
let mut cmd = Command::new("git");
cmd.args([
"log",
&format!("-{}", count),
&format!("--format={}", format),
]);
// Add any extra arguments
for arg in &extra_args {
cmd.arg(arg);
}
let output = cmd.output().context("Failed to run git log")?;
if !output.status.success() {
bail!(
"git log failed: {}",
String::from_utf8_lossy(&output.stderr)
);
}
let log_output = String::from_utf8_lossy(&output.stdout);
// Parse and decode each commit
for commit_block in log_output.split("---END---") {
let commit_block = commit_block.trim();
if commit_block.is_empty() {
continue;
}
let lines: Vec<&str> = commit_block.lines().collect();
if full {
// Full format: hash, author, date, subject, body...
if lines.len() >= 4 {
let hash = lines[0];
let author = lines[1];
let date = lines[2];
let subject = lines[3];
let body: String = lines[4..].join("\n");
println!("\x1b[33mcommit {}\x1b[0m", hash);
println!("Author: {}", author);
println!("Date: {}", date);
println!();
// Try to decode the subject (title)
println!(" {}", subject);
// Try to decode the body
if !body.trim().is_empty() {
let decoded = try_decode_commit_body(&body);
println!();
for line in decoded.lines() {
println!(" {}", line);
}
}
println!();
}
} else {
// Compact format: short hash, subject, body...
if lines.len() >= 2 {
let hash = lines[0];
let subject = lines[1];
let body: String = lines[2..].join("\n");
// Try to decode the body
let decoded = try_decode_commit_body(&body);
let display = if decoded != body.trim() {
decoded
} else {
// Not encoded, show original subject
subject.to_string()
};
// Truncate for display
let display_truncated = safe_truncate(&display, 72);
println!("\x1b[33m{}\x1b[0m {}", hash, display_truncated);
}
}
}
Ok(())
}
/// Try to decode an encoded commit body, return original if decoding fails
fn try_decode_commit_body(body: &str) -> String {
let body = body.trim();
if body.is_empty() {
return body.to_string();
}
// Look for footer pattern [algo:dict|algo:dict]
let lines: Vec<&str> = body.lines().collect();
// Find the footer (last line starting with '[' and containing '|')
let footer_line = lines
.iter()
.rev()
.find(|l| l.trim().starts_with('[') && l.contains('|'));
let footer = match footer_line {
Some(f) => *f,
None => return body.to_string(), // No footer, not encoded
};
// Find the encoded body (everything before footer, excluding "whoa.")
let body_lines: Vec<&str> = lines
.iter()
.take_while(|l| !l.trim().starts_with('['))
.filter(|l| l.trim() != "whoa.")
.copied()
.collect();
if body_lines.is_empty() {
return body.to_string();
}
let encoded_body = body_lines.join("\n");
// Try to decode
match commit::decode_body(&encoded_body, footer) {
Ok(decoded) => decoded,
Err(_) => body.to_string(), // Decoding failed, return original
}
}
#[derive(serde::Deserialize)]
struct AgentFrontmatter {
name: String,
description: String,
#[serde(default)]
domain: Option<String>,
}
fn parse_frontmatter(content: &str) -> Option<(String, String)> {
let lines: Vec<&str> = content.lines().collect();
// Check if starts with ---
if lines.first()? != &"---" {
return None;
}
// Find closing ---
let end_idx = lines.iter().skip(1).position(|&line| line == "---")?;
let frontmatter = lines[1..=end_idx].join("\n");
let body = lines[end_idx + 2..].join("\n");
Some((frontmatter, body))
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_safe_truncate_short_string() {
// String shorter than limit - no truncation
assert_eq!(safe_truncate("hello", 10), "hello");
}
#[test]
fn test_safe_truncate_exact_length() {
// String exactly at limit - no truncation
assert_eq!(safe_truncate("hello", 5), "hello");
}
#[test]
fn test_safe_truncate_long_string() {
// String longer than limit - truncated with "..."
assert_eq!(safe_truncate("hello world", 8), "hello...");
}
#[test]
fn test_safe_truncate_emoji() {
// Emoji (multi-byte UTF-8) - should not panic
let emoji_string = "Hello! A fox for you 5 times";
let result = safe_truncate(emoji_string, 15);
// Should truncate by character count, not bytes
assert!(result.ends_with("..."));
assert_eq!(result.chars().count(), 15); // 12 chars + 3 for "..."
}
#[test]
fn test_safe_truncate_all_emoji() {
// All emoji string - should handle gracefully
let result = safe_truncate("aaaaaaaaaa", 5);
assert_eq!(result, "aa...");
}
#[test]
fn test_safe_truncate_empty() {
// Empty string
assert_eq!(safe_truncate("", 10), "");
}
#[test]
fn test_safe_truncate_very_small_limit() {
// Limit smaller than "..." length
let result = safe_truncate("hello world", 3);
// Should handle gracefully (saturating_sub prevents underflow)
assert_eq!(result, "...");
}
// =====================================================================
// Regression tests for unicode boundary panic fix (PR #162)
//
// These tests exercise the CALL SITES that previously used raw byte-index
// slicing (&s[..N]) and would have panicked on multi-byte UTF-8 characters.
// The fix replaced those with safe_truncate() which counts characters.
// =====================================================================
#[test]
fn test_log_display_emoji_would_panic_at_byte_69() {
// Regression: handle_log used `&display[..69]` which panics if byte 69
// lands inside a multi-byte character.
//
// 73 fish emoji (U+1F41F, 4 bytes each) = 73 chars, 292 bytes.
// Old code: `&display[..69]` slices at byte 69, inside the 18th emoji
// (bytes 68..71). This panics with "byte index 69 is not a char boundary".
let emoji_str: String = "\u{1F41F}".repeat(73);
assert_eq!(emoji_str.chars().count(), 73);
assert!(emoji_str.len() > 72);
let result = safe_truncate(&emoji_str, 72);
assert!(result.ends_with("..."));
assert_eq!(result.chars().count(), 72);
assert!(std::str::from_utf8(result.as_bytes()).is_ok());
}
#[test]
fn test_log_display_cjk_mixed_would_panic_at_byte_69() {
// Mixed ASCII + CJK where byte 69 falls inside a CJK character.
// 2 ASCII bytes + 24 CJK chars (72 bytes) = 26 chars, 74 bytes.
// Old code: &display[..69] = byte 69 = 2 + 67, and 67 is NOT divisible
// by 3, so byte 69 lands inside the 23rd CJK char. PANIC!
let mut s = "ab".to_string();
s.push_str(&"\u{4E16}".repeat(24));
assert_eq!(s.chars().count(), 26);
assert!(s.len() > 72);
// Verify byte 69 is NOT a char boundary (the actual panic trigger)
assert!(!s.is_char_boundary(69));
let result = safe_truncate(&s, 72);
// 26 chars < 72 limit, no truncation needed
assert_eq!(result, s);
}
#[test]
fn test_entry_summary_emoji_would_panic_at_byte_77() {
// Regression: print_entry_summary used `&summary[..77]` which panics
// if byte 77 lands inside a multi-byte character.
//
// 81 fish emoji = 81 chars, 324 bytes.
// Old code: `&summary[..77]` = byte 77, inside the 20th emoji
// (bytes 76..79). Panics with "byte index 77 is not a char boundary".
let emoji_summary: String = "\u{1F41F}".repeat(81);
assert_eq!(emoji_summary.chars().count(), 81);
let result = safe_truncate(&emoji_summary, 80);
assert!(result.ends_with("..."));
assert_eq!(result.chars().count(), 80);
assert!(std::str::from_utf8(result.as_bytes()).is_ok());
}
#[test]
fn test_entry_summary_cjk_would_panic_at_byte_77() {
// 81 CJK chars (U+4E16) = 243 bytes.
// Old code: &summary[..77]. 77 / 3 = 25.67 -> byte 77 is NOT on a
// character boundary (char boundaries at 75, 78...). PANIC!
let cjk_summary: String = "\u{4E16}".repeat(81);
assert_eq!(cjk_summary.chars().count(), 81);
// Verify byte 77 is indeed NOT a char boundary
assert!(!cjk_summary.is_char_boundary(77));
let result = safe_truncate(&cjk_summary, 80);
assert!(result.ends_with("..."));
assert_eq!(result.chars().count(), 80);
}
#[test]
fn test_entry_summary_mixed_ascii_emoji_would_panic_at_byte_77() {
// 75 ASCII + 6 emoji (4 bytes each) = 81 chars, 99 bytes.
// Old code: &summary[..77] = byte 77 = 75 + 2, which is 2 bytes into
// the first emoji. PANIC!
let mut mixed = "x".repeat(75);
for _ in 0..6 {
mixed.push('\u{1F41F}');
}
assert_eq!(mixed.chars().count(), 81);
// Verify byte 77 is NOT a char boundary (inside first emoji)
assert!(!mixed.is_char_boundary(77));
let result = safe_truncate(&mixed, 80);
assert!(result.ends_with("..."));
assert_eq!(result.chars().count(), 80);
}
#[test]
fn test_fact_title_truncation_emoji_at_60_boundary() {
// memory add --type uses safe_truncate(&body, 60) for fact titles.
// 61 emoji = 244 bytes. Old byte-slicing would have panicked.
let emoji_body: String = "\u{1F41F}".repeat(61);
let result = safe_truncate(&emoji_body, 60);
assert!(result.ends_with("..."));
assert_eq!(result.chars().count(), 60);
}
#[test]
fn test_recent_preview_cjk_at_60_boundary() {
// memory recent uses safe_truncate(content, 60).
// 61 CJK chars = 183 bytes.
let long_cjk: String = "\u{4E16}".repeat(61);
let result = safe_truncate(&long_cjk, 60);
assert!(result.ends_with("..."));
assert_eq!(result.chars().count(), 60);
}
}