vtcode-core 0.98.1

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

use crate::config::loader::VTCodeConfig;
use crate::config::types::AgentConfig as RuntimeAgentConfig;
use crate::config::{ConfigManager, PersistentMemoryConfig, get_config_dir};
use crate::llm::factory::infer_provider_from_model;
use crate::llm::provider::{LLMProvider, LLMRequest, Message, MessageRole};
use crate::llm::{
    LightweightFeature, collect_single_response, create_provider_for_model_route,
    resolve_lightweight_route,
};

pub const MEMORY_FILENAME: &str = "MEMORY.md";
pub const MEMORY_SUMMARY_FILENAME: &str = "memory_summary.md";
pub const ROLLOUT_SUMMARIES_DIRNAME: &str = "rollout_summaries";
pub const NOTES_DIRNAME: &str = "notes";

const MEMORY_LOCK_FILENAME: &str = ".memory.lock";
const PREFERENCES_FILENAME: &str = "preferences.md";
const REPOSITORY_FACTS_FILENAME: &str = "repository-facts.md";
const DEFAULT_FACT_LIMIT: usize = 24;
const MEMORY_HIGHLIGHT_LIMIT: usize = 10;
const TOPIC_FACT_LIMIT: usize = 32;
const LOCK_RETRY_ATTEMPTS: usize = 40;
const LOCK_RETRY_DELAY_MS: u64 = 50;

#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
pub struct GroundedFactRecord {
    pub fact: String,
    pub source: String,
}

#[derive(Debug, Clone, Serialize, PartialEq, Eq)]
pub struct PersistentMemoryStatus {
    pub enabled: bool,
    pub auto_write: bool,
    pub directory: PathBuf,
    pub summary_file: PathBuf,
    pub memory_file: PathBuf,
    pub preferences_file: PathBuf,
    pub repository_facts_file: PathBuf,
    pub notes_dir: PathBuf,
    pub rollout_summaries_dir: PathBuf,
    pub summary_exists: bool,
    pub registry_exists: bool,
    pub pending_rollout_summaries: usize,
    pub cleanup_status: MemoryCleanupStatus,
}

#[derive(Debug, Clone, Serialize)]
pub struct PersistentMemoryExcerpt {
    pub status: PersistentMemoryStatus,
    pub contents: String,
    pub truncated: bool,
    pub bytes_read: usize,
    pub lines_read: usize,
}

#[derive(Debug, Clone, Serialize)]
pub struct PersistentMemoryWriteReport {
    pub directory: PathBuf,
    pub summary_file: PathBuf,
    pub memory_file: PathBuf,
    pub rollout_summary_file: Option<PathBuf>,
    pub created_files: Vec<PathBuf>,
    pub added_facts: usize,
    pub pending_rollout_summaries: usize,
}

#[derive(Debug, Clone, Serialize, PartialEq, Eq)]
pub struct PersistentMemoryMatch {
    pub source: String,
    pub fact: String,
}

#[derive(Debug, Clone, Serialize, PartialEq, Eq)]
pub struct PersistentMemoryForgetReport {
    pub directory: PathBuf,
    pub summary_file: PathBuf,
    pub memory_file: PathBuf,
    pub removed_facts: usize,
    pub pending_rollout_summaries: usize,
}

#[derive(Debug, Clone, Serialize, PartialEq, Eq)]
pub struct MemoryCleanupStatus {
    pub needed: bool,
    pub suspicious_facts: usize,
    pub suspicious_summary_lines: usize,
}

#[derive(Debug, Clone, Serialize)]
pub struct PersistentMemoryCleanupReport {
    pub directory: PathBuf,
    pub summary_file: PathBuf,
    pub memory_file: PathBuf,
    pub rewritten_facts: usize,
    pub removed_rollout_files: usize,
}

pub fn extract_memory_highlights(contents: &str, limit: usize) -> Vec<String> {
    if limit == 0 {
        return Vec::new();
    }

    let mut highlights = Vec::with_capacity(limit);
    for line in contents.lines() {
        let trimmed = line.trim();
        if trimmed.is_empty() || trimmed.starts_with('#') {
            continue;
        }

        let normalized = trimmed
            .strip_prefix("- ")
            .or_else(|| trimmed.strip_prefix("* "))
            .or_else(|| trimmed.strip_prefix("+ "))
            .unwrap_or(trimmed);
        if normalized.is_empty() || highlights.iter().any(|existing| existing == normalized) {
            continue;
        }

        highlights.push(normalized.to_string());
        if highlights.len() == limit {
            break;
        }
    }

    highlights
}

#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
#[serde(rename_all = "snake_case")]
pub enum MemoryOpKind {
    Remember,
    Forget,
    AskMissing,
    Noop,
}

#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
pub struct MemoryOpCandidate {
    pub id: usize,
    pub source: String,
    pub fact: String,
}

#[derive(Debug, Clone, Copy, Serialize, Deserialize, PartialEq, Eq)]
#[serde(rename_all = "snake_case")]
pub enum MemoryPlannedTopic {
    Preferences,
    RepositoryFacts,
}

#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
pub struct MemoryPlannedFact {
    pub topic: MemoryPlannedTopic,
    pub fact: String,
    #[serde(default)]
    pub source: String,
}

#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
pub struct MemoryMissingField {
    pub field: String,
    pub prompt: String,
}

#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
pub struct MemoryOpPlan {
    pub kind: MemoryOpKind,
    #[serde(default)]
    pub facts: Vec<MemoryPlannedFact>,
    #[serde(default)]
    pub selected_ids: Vec<usize>,
    #[serde(default)]
    pub missing: Option<MemoryMissingField>,
    #[serde(default)]
    pub message: Option<String>,
}

#[derive(Debug, Clone, Copy, PartialEq, Eq)]
enum MemoryTopic {
    Preferences,
    RepositoryFacts,
}

impl MemoryTopic {
    fn title(self) -> &'static str {
        match self {
            Self::Preferences => "Preferences",
            Self::RepositoryFacts => "Repository Facts",
        }
    }

    fn description(self) -> &'static str {
        match self {
            Self::Preferences => "Durable user preferences and workflow notes.",
            Self::RepositoryFacts => "Grounded repository facts and recurring tooling notes.",
        }
    }

    fn slug(self) -> &'static str {
        match self {
            Self::Preferences => "preferences",
            Self::RepositoryFacts => "repository_facts",
        }
    }

    fn from_slug(value: &str) -> Option<Self> {
        match value {
            "preferences" => Some(Self::Preferences),
            "repository_facts" => Some(Self::RepositoryFacts),
            _ => None,
        }
    }
}

#[derive(Debug)]
struct PersistentMemoryFiles {
    directory: PathBuf,
    summary_file: PathBuf,
    memory_file: PathBuf,
    preferences_file: PathBuf,
    repository_facts_file: PathBuf,
    notes_dir: PathBuf,
    rollout_summaries_dir: PathBuf,
    lock_file: PathBuf,
}

impl PersistentMemoryFiles {
    fn new(directory: PathBuf) -> Self {
        Self {
            summary_file: directory.join(MEMORY_SUMMARY_FILENAME),
            memory_file: directory.join(MEMORY_FILENAME),
            preferences_file: directory.join(PREFERENCES_FILENAME),
            repository_facts_file: directory.join(REPOSITORY_FACTS_FILENAME),
            notes_dir: directory.join(NOTES_DIRNAME),
            rollout_summaries_dir: directory.join(ROLLOUT_SUMMARIES_DIRNAME),
            lock_file: directory.join(MEMORY_LOCK_FILENAME),
            directory,
        }
    }
}

#[derive(Debug, Clone)]
struct ClassifiedFacts {
    preferences: Vec<GroundedFactRecord>,
    repository_facts: Vec<GroundedFactRecord>,
}

impl ClassifiedFacts {
    fn total(&self) -> usize {
        self.preferences.len() + self.repository_facts.len()
    }
}

#[derive(Debug, Deserialize)]
struct MemorySummaryResponse {
    #[serde(default)]
    bullets: Vec<String>,
}

#[derive(Debug, Clone)]
struct MemoryModelRoute {
    provider_name: String,
    model: String,
    temperature: f32,
}

#[derive(Debug, Clone)]
struct ResolvedMemoryRoutes {
    primary: MemoryModelRoute,
    fallback: Option<MemoryModelRoute>,
    warning: Option<String>,
}

#[derive(Debug, Deserialize)]
struct MemoryClassificationItem {
    id: usize,
    topic: MemoryPlannedTopic,
    #[serde(default)]
    fact: Option<String>,
}

#[derive(Debug, Deserialize)]
struct MemoryClassificationPlan {
    #[serde(default)]
    keep: Vec<MemoryClassificationItem>,
}

pub fn normalize_whitespace(text: &str) -> String {
    text.split_whitespace().collect::<Vec<_>>().join(" ")
}

pub fn truncate_for_fact(text: &str, max_chars: usize) -> String {
    let trimmed = text.trim();
    if trimmed.chars().count() <= max_chars {
        return trimmed.to_string();
    }

    let truncated = trimmed
        .chars()
        .take(max_chars.saturating_sub(3))
        .collect::<String>();
    format!("{truncated}...")
}

fn memory_supports_native_json(provider: &dyn LLMProvider, route: &MemoryModelRoute) -> bool {
    provider.supports_structured_output(&route.model)
}

fn build_memory_json_request(
    provider: &dyn LLMProvider,
    route: &MemoryModelRoute,
    prompt: String,
    schema_name: &str,
    schema: &serde_json::Value,
) -> Result<LLMRequest> {
    let supports_native_json = memory_supports_native_json(provider, route);
    let prompt = if supports_native_json {
        prompt
    } else {
        let schema = serde_json::to_string_pretty(schema)
            .context("failed to serialize persistent memory JSON schema")?;
        format!(
            "{prompt}\n\nReturn JSON only. Do not add markdown fences or explanatory text. The response must be a single JSON object that matches this schema:\n{schema}"
        )
    };

    Ok(LLMRequest {
        model: route.model.clone(),
        temperature: Some(route.temperature),
        output_format: supports_native_json.then(|| {
            json!({
                "type": "json_schema",
                "json_schema": {
                    "name": schema_name,
                    "schema": schema,
                }
            })
        }),
        messages: vec![Message::user(prompt)],
        ..Default::default()
    })
}

fn parse_memory_json_response<T>(text: &str, context: &str) -> Result<T>
where
    T: DeserializeOwned,
{
    let trimmed = text.trim();
    if trimmed.is_empty() {
        bail!("{context} returned empty content");
    }

    if let Ok(parsed) = serde_json::from_str::<T>(trimmed) {
        return Ok(parsed);
    }

    if let Some(json_block) = extract_first_json_block(trimmed) {
        return serde_json::from_str::<T>(json_block)
            .with_context(|| format!("failed to parse {context} response"));
    }

    serde_json::from_str::<T>(trimmed)
        .with_context(|| format!("failed to parse {context} response"))
}

fn extract_first_json_block(text: &str) -> Option<&str> {
    let (start, opening) = text
        .char_indices()
        .find(|(_, ch)| matches!(ch, '{' | '['))?;
    let mut stack = vec![opening];
    let mut in_string = false;
    let mut escaped = false;

    for (offset, ch) in text[start + opening.len_utf8()..].char_indices() {
        if in_string {
            if escaped {
                escaped = false;
            } else if ch == '\\' {
                escaped = true;
            } else if ch == '"' {
                in_string = false;
            }
            continue;
        }

        match ch {
            '"' => in_string = true,
            '{' | '[' => stack.push(ch),
            '}' => {
                if stack.pop() != Some('{') {
                    return None;
                }
                if stack.is_empty() {
                    let end = start + opening.len_utf8() + offset + ch.len_utf8();
                    return Some(&text[start..end]);
                }
            }
            ']' => {
                if stack.pop() != Some('[') {
                    return None;
                }
                if stack.is_empty() {
                    let end = start + opening.len_utf8() + offset + ch.len_utf8();
                    return Some(&text[start..end]);
                }
            }
            _ => {}
        }
    }

    None
}

pub fn maybe_extract_tool_fact(message: &Message) -> Option<GroundedFactRecord> {
    if message.role != MessageRole::Tool {
        return None;
    }

    let tool_name = message.origin_tool.as_deref().unwrap_or("tool");
    let text = message.content.as_text();
    let raw = text.trim();
    if raw.is_empty() {
        return None;
    }

    let candidate = serde_json::from_str::<serde_json::Value>(raw)
        .ok()
        .and_then(|value| {
            if value.get("error").is_some()
                || value.get("success") == Some(&serde_json::Value::Bool(false))
            {
                return None;
            }

            for key in ["summary", "message", "result", "output", "stdout"] {
                if let Some(value) = value.get(key) {
                    if let Some(text) = value.as_str() {
                        let normalized = normalize_whitespace(text);
                        if !normalized.is_empty() {
                            return Some(normalized);
                        }
                    } else if !value.is_null() {
                        let normalized = normalize_whitespace(&value.to_string());
                        if !normalized.is_empty() {
                            return Some(normalized);
                        }
                    }
                }
            }

            let compact = normalize_whitespace(&value.to_string());
            (!compact.is_empty()).then_some(compact)
        })
        .or_else(|| {
            let lowered = raw.to_ascii_lowercase();
            if lowered.contains("error")
                || lowered.contains("failed")
                || lowered.contains("denied")
                || lowered.contains("timeout")
            {
                return None;
            }
            Some(normalize_whitespace(raw))
        })?;

    Some(GroundedFactRecord {
        fact: truncate_for_fact(&candidate, 180),
        source: format!("tool:{tool_name}"),
    })
}

pub fn maybe_extract_user_fact(message: &Message) -> Option<GroundedFactRecord> {
    if message.role != MessageRole::User {
        return None;
    }

    let text = normalize_whitespace(message.content.as_text().as_ref());
    if text.is_empty() {
        return None;
    }

    let candidate_text = strip_user_memory_candidate_prefixes(&text);
    let (candidate_text, looks_authored_note) = strip_user_memory_note_marker(candidate_text)
        .map(|fact| (fact, true))
        .unwrap_or((candidate_text, false));
    let lowered = candidate_text.to_ascii_lowercase();
    let looks_durable_self_fact = [
        "my name is ",
        "i prefer ",
        "my preferred ",
        "my pronouns are ",
        "my timezone is ",
    ]
    .iter()
    .any(|prefix| lowered.starts_with(prefix));

    let should_extract = looks_authored_note || looks_durable_self_fact;
    should_extract.then(|| GroundedFactRecord {
        fact: truncate_for_fact(candidate_text, 180),
        source: "user_assertion".to_string(),
    })
}

fn strip_user_memory_candidate_prefixes(text: &str) -> &str {
    const PREFIXES: &[&str] = &[
        "please ",
        "please, ",
        "can you ",
        "could you ",
        "would you ",
        "vt code, ",
        "vt code ",
    ];

    let mut trimmed = text.trim();
    loop {
        let lowered = trimmed.to_ascii_lowercase();
        let Some(prefix) = PREFIXES.iter().find(|prefix| lowered.starts_with(**prefix)) else {
            return trimmed;
        };
        trimmed = trimmed
            .get(prefix.len()..)
            .unwrap_or("")
            .trim_start_matches([',', ':', '-', ' '])
            .trim_start();
    }
}

fn strip_user_memory_note_marker(text: &str) -> Option<&str> {
    const NOTE_PREFIXES: &[&str] = &["note that ", "important:"];

    let lowered = text.to_ascii_lowercase();
    NOTE_PREFIXES.iter().find_map(|prefix| {
        lowered.starts_with(prefix).then(|| {
            text.get(prefix.len()..)
                .unwrap_or("")
                .trim_start_matches([',', ':', '-', ' '])
                .trim_start()
        })
    })
}

pub fn dedup_latest_facts(history: &[Message], limit: usize) -> Vec<GroundedFactRecord> {
    let mut facts = Vec::new();
    for message in history {
        if let Some(fact) =
            maybe_extract_tool_fact(message).or_else(|| maybe_extract_user_fact(message))
        {
            let normalized = normalize_whitespace(&fact.fact).to_ascii_lowercase();
            if let Some(existing_idx) = facts.iter().position(|entry: &GroundedFactRecord| {
                normalize_whitespace(&entry.fact).to_ascii_lowercase() == normalized
            }) {
                facts.remove(existing_idx);
            }
            facts.push(fact);
        }
    }

    let keep_from = facts.len().saturating_sub(limit);
    facts.into_iter().skip(keep_from).collect()
}

pub fn resolve_persistent_memory_dir(
    config: &PersistentMemoryConfig,
    workspace_root: &Path,
) -> Result<Option<PathBuf>> {
    let project_name = persistent_memory_project_name(workspace_root);
    let directory = persistent_memory_base_dir(config)?
        .join("projects")
        .join(sanitize_project_name(&project_name))
        .join("memory");
    migrate_legacy_persistent_memory_dir_if_needed(config, &project_name, &directory)?;
    Ok(Some(directory))
}

pub fn persistent_memory_status(
    config: &PersistentMemoryConfig,
    workspace_root: &Path,
) -> Result<PersistentMemoryStatus> {
    let directory = resolve_persistent_memory_dir(config, workspace_root)?.unwrap_or_else(|| {
        dirs::home_dir()
            .map(|home| home.join(".vtcode"))
            .unwrap_or_else(|| PathBuf::from(".vtcode"))
            .join("projects")
            .join("workspace")
            .join("memory")
    });
    let files = PersistentMemoryFiles::new(directory);
    let pending_rollout_summaries = count_pending_rollout_summaries(&files.rollout_summaries_dir)?;
    let cleanup_status = detect_memory_cleanup_status(&files)?;

    Ok(PersistentMemoryStatus {
        enabled: config.enabled,
        auto_write: config.auto_write,
        summary_exists: files.summary_file.exists(),
        registry_exists: files.memory_file.exists(),
        pending_rollout_summaries,
        cleanup_status,
        directory: files.directory,
        summary_file: files.summary_file,
        memory_file: files.memory_file,
        preferences_file: files.preferences_file,
        repository_facts_file: files.repository_facts_file,
        notes_dir: files.notes_dir,
        rollout_summaries_dir: files.rollout_summaries_dir,
    })
}

pub async fn read_persistent_memory_excerpt(
    config: &PersistentMemoryConfig,
    workspace_root: &Path,
) -> Result<Option<PersistentMemoryExcerpt>> {
    if !config.enabled {
        return Ok(None);
    }

    let status = persistent_memory_status(config, workspace_root)?;
    if !status.summary_file.exists() {
        return Ok(None);
    }

    let raw = tokio::fs::read_to_string(&status.summary_file)
        .await
        .with_context(|| {
            format!(
                "Failed to read persistent memory summary {}",
                status.summary_file.display()
            )
        })?;

    let (contents, truncated, bytes_read, lines_read) =
        truncate_memory_excerpt(&raw, config.startup_line_limit, config.startup_byte_limit);

    Ok(Some(PersistentMemoryExcerpt {
        status,
        contents,
        truncated,
        bytes_read,
        lines_read,
    }))
}

pub async fn finalize_persistent_memory(
    runtime_config: &RuntimeAgentConfig,
    vt_cfg: Option<&VTCodeConfig>,
    history: &[Message],
) -> Result<Option<PersistentMemoryWriteReport>> {
    let config = vt_cfg
        .map(|cfg| cfg.agent.persistent_memory.clone())
        .unwrap_or_default();
    if !config.enabled || !config.auto_write {
        return Ok(None);
    }
    if persistent_memory_status(&config, runtime_config.workspace.as_path())?
        .cleanup_status
        .needed
    {
        return Ok(None);
    }

    let facts = dedup_latest_facts(history, DEFAULT_FACT_LIMIT);
    persist_memory_internal(
        &config,
        runtime_config.workspace.as_path(),
        Some(runtime_config),
        vt_cfg,
        &facts,
        true,
        false,
    )
    .await
}

pub async fn rebuild_persistent_memory_summary(
    runtime_config: &RuntimeAgentConfig,
    vt_cfg: Option<&VTCodeConfig>,
) -> Result<Option<PersistentMemoryWriteReport>> {
    let config = vt_cfg
        .map(|cfg| cfg.agent.persistent_memory.clone())
        .unwrap_or_default();
    if !config.enabled {
        return Ok(None);
    }
    if persistent_memory_status(&config, runtime_config.workspace.as_path())?
        .cleanup_status
        .needed
    {
        bail!("persistent memory cleanup is required before rebuilding the summary");
    }

    persist_memory_internal(
        &config,
        runtime_config.workspace.as_path(),
        Some(runtime_config),
        vt_cfg,
        &[],
        false,
        true,
    )
    .await
}

pub async fn rebuild_generated_memory_files(
    config: &PersistentMemoryConfig,
    workspace_root: &Path,
) -> Result<()> {
    let directory = resolve_persistent_memory_dir(config, workspace_root)?
        .expect("persistent memory directory should resolve");
    let files = PersistentMemoryFiles::new(directory);
    let mut created_files = Vec::new();
    ensure_memory_layout(&files, &mut created_files).await?;
    let _lock = MemoryLock::acquire(&files.lock_file).await?;
    let _ = consolidate_memory_files(None, None, workspace_root, &files).await?;
    Ok(())
}

pub async fn scaffold_persistent_memory(
    config: &PersistentMemoryConfig,
    workspace_root: &Path,
) -> Result<Option<PersistentMemoryStatus>> {
    let status = persistent_memory_status(config, workspace_root)?;
    let files = PersistentMemoryFiles::new(status.directory.clone());
    let mut created_files = Vec::new();
    ensure_memory_layout(&files, &mut created_files).await?;
    Ok(Some(persistent_memory_status(config, workspace_root)?))
}

pub async fn cleanup_persistent_memory(
    runtime_config: &RuntimeAgentConfig,
    vt_cfg: Option<&VTCodeConfig>,
    include_summary_only_signals: bool,
) -> Result<Option<PersistentMemoryCleanupReport>> {
    let config = vt_cfg
        .map(|cfg| cfg.agent.persistent_memory.clone())
        .unwrap_or_default();
    if !config.enabled {
        return Ok(None);
    }

    let directory = resolve_persistent_memory_dir(&config, runtime_config.workspace.as_path())?
        .expect("persistent memory directory should resolve when enabled");
    let files = PersistentMemoryFiles::new(directory);
    let mut created_files = Vec::new();
    ensure_memory_layout(&files, &mut created_files).await?;

    let status = detect_memory_cleanup_status(&files)?;
    if !status.needed && !include_summary_only_signals {
        return Ok(Some(PersistentMemoryCleanupReport {
            directory: files.directory,
            summary_file: files.summary_file,
            memory_file: files.memory_file,
            rewritten_facts: 0,
            removed_rollout_files: 0,
        }));
    }

    let _lock = MemoryLock::acquire(&files.lock_file).await?;
    let candidates = collect_cleanup_candidates(&files).await?;
    let classified = if candidates.is_empty() {
        ClassifiedFacts {
            preferences: Vec::new(),
            repository_facts: Vec::new(),
        }
    } else {
        classify_facts_strict(
            Some(runtime_config),
            vt_cfg,
            runtime_config.workspace.as_path(),
            &candidates,
        )
        .await?
    };

    let removed_rollout_files = remove_rollout_markdown_files(&files.rollout_summaries_dir).await?;
    let notes = read_note_summaries(&files.notes_dir).await?;
    let mut created_files = Vec::new();
    write_topic_file(
        &files.preferences_file,
        MemoryTopic::Preferences,
        &classified.preferences,
        &mut created_files,
    )
    .await?;
    write_topic_file(
        &files.repository_facts_file,
        MemoryTopic::RepositoryFacts,
        &classified.repository_facts,
        &mut created_files,
    )
    .await?;
    write_memory_index(
        &files.memory_file,
        &classified.preferences,
        &classified.repository_facts,
        &notes,
        0,
        &mut created_files,
    )
    .await?;
    write_memory_summary(
        &files.summary_file,
        Some(runtime_config),
        vt_cfg,
        runtime_config.workspace.as_path(),
        &classified.preferences,
        &classified.repository_facts,
        &notes,
        &mut created_files,
    )
    .await?;

    Ok(Some(PersistentMemoryCleanupReport {
        directory: files.directory,
        summary_file: files.summary_file,
        memory_file: files.memory_file,
        rewritten_facts: classified.total(),
        removed_rollout_files,
    }))
}

pub async fn list_persistent_memory_candidates(
    config: &PersistentMemoryConfig,
    workspace_root: &Path,
) -> Result<Option<Vec<PersistentMemoryMatch>>> {
    if !config.enabled {
        return Ok(None);
    }

    let directory = resolve_persistent_memory_dir(config, workspace_root)?
        .expect("persistent memory directory should resolve when enabled");
    if !directory.exists() {
        return Ok(Some(Vec::new()));
    }

    let files = PersistentMemoryFiles::new(directory);
    collect_all_memory_matches(&files).await.map(Some)
}

pub async fn find_persistent_memory_matches(
    config: &PersistentMemoryConfig,
    workspace_root: &Path,
    query: &str,
) -> Result<Option<Vec<PersistentMemoryMatch>>> {
    if !config.enabled {
        return Ok(None);
    }
    let Some(normalized_query) = normalize_memory_query(query) else {
        return Ok(Some(Vec::new()));
    };
    let directory = resolve_persistent_memory_dir(config, workspace_root)?
        .expect("persistent memory directory should resolve when enabled");
    if !directory.exists() {
        return Ok(Some(Vec::new()));
    }

    let files = PersistentMemoryFiles::new(directory);
    collect_memory_matches(&files, &normalized_query)
        .await
        .map(Some)
}

pub async fn plan_remember_persistent_memory(
    runtime_config: &RuntimeAgentConfig,
    vt_cfg: Option<&VTCodeConfig>,
    request: &str,
    supplemental_answer: Option<&str>,
) -> Result<Option<MemoryOpPlan>> {
    let config = vt_cfg
        .map(|cfg| cfg.agent.persistent_memory.clone())
        .unwrap_or_default();
    if !config.enabled {
        return Ok(None);
    }

    let plan = plan_memory_operation(
        runtime_config,
        vt_cfg,
        runtime_config.workspace.as_path(),
        MemoryOpKind::Remember,
        request,
        supplemental_answer,
        &[],
    )
    .await?;
    Ok(Some(plan))
}

pub async fn persist_remembered_memory_plan(
    runtime_config: &RuntimeAgentConfig,
    vt_cfg: Option<&VTCodeConfig>,
    plan: &MemoryOpPlan,
) -> Result<Option<PersistentMemoryWriteReport>> {
    let config = vt_cfg
        .map(|cfg| cfg.agent.persistent_memory.clone())
        .unwrap_or_default();
    if !config.enabled || plan.kind != MemoryOpKind::Remember {
        return Ok(None);
    }

    let facts = memory_plan_facts(plan)?;
    persist_preclassified_memory_internal(
        &config,
        runtime_config.workspace.as_path(),
        Some(runtime_config),
        vt_cfg,
        &facts,
        true,
        false,
    )
    .await
}

pub async fn plan_forget_persistent_memory(
    runtime_config: &RuntimeAgentConfig,
    vt_cfg: Option<&VTCodeConfig>,
    request: &str,
    candidates: &[MemoryOpCandidate],
) -> Result<Option<MemoryOpPlan>> {
    let config = vt_cfg
        .map(|cfg| cfg.agent.persistent_memory.clone())
        .unwrap_or_default();
    if !config.enabled {
        return Ok(None);
    }

    let plan = plan_memory_operation(
        runtime_config,
        vt_cfg,
        runtime_config.workspace.as_path(),
        MemoryOpKind::Forget,
        request,
        None,
        candidates,
    )
    .await?;
    Ok(Some(plan))
}

pub async fn forget_planned_persistent_memory_matches(
    runtime_config: &RuntimeAgentConfig,
    vt_cfg: Option<&VTCodeConfig>,
    candidates: &[MemoryOpCandidate],
    plan: &MemoryOpPlan,
) -> Result<Option<PersistentMemoryForgetReport>> {
    let config = vt_cfg
        .map(|cfg| cfg.agent.persistent_memory.clone())
        .unwrap_or_default();
    if !config.enabled || plan.kind != MemoryOpKind::Forget {
        return Ok(None);
    }

    let selected = selected_memory_candidates(candidates, &plan.selected_ids)?;
    let directory = resolve_persistent_memory_dir(&config, runtime_config.workspace.as_path())?
        .expect("persistent memory directory should resolve when enabled");
    let files = PersistentMemoryFiles::new(directory);
    if !files.directory.exists() {
        return Ok(Some(PersistentMemoryForgetReport {
            directory: files.directory,
            summary_file: files.summary_file,
            memory_file: files.memory_file,
            removed_facts: 0,
            pending_rollout_summaries: 0,
        }));
    }

    let _lock = MemoryLock::acquire(&files.lock_file).await?;
    let mut removed_facts = 0usize;
    removed_facts += rewrite_topic_without_selected(
        &files.preferences_file,
        MemoryTopic::Preferences,
        &selected,
    )
    .await?;
    removed_facts += rewrite_topic_without_selected(
        &files.repository_facts_file,
        MemoryTopic::RepositoryFacts,
        &selected,
    )
    .await?;

    let rollout_files = list_rollout_markdown_files(&files.rollout_summaries_dir).await?;
    for path in rollout_files {
        removed_facts += scrub_rollout_file_by_selection(&path, &selected).await?;
    }

    if removed_facts > 0 {
        let _ = consolidate_memory_files(
            Some(runtime_config),
            vt_cfg,
            runtime_config.workspace.as_path(),
            &files,
        )
        .await?;
    }

    Ok(Some(PersistentMemoryForgetReport {
        directory: files.directory,
        summary_file: files.summary_file,
        memory_file: files.memory_file,
        removed_facts,
        pending_rollout_summaries: count_pending_rollout_summaries(&files.rollout_summaries_dir)?,
    }))
}

async fn persist_preclassified_memory_internal(
    config: &PersistentMemoryConfig,
    workspace_root: &Path,
    runtime_config: Option<&RuntimeAgentConfig>,
    vt_cfg: Option<&VTCodeConfig>,
    facts: &[GroundedFactRecord],
    write_rollout: bool,
    force_rebuild: bool,
) -> Result<Option<PersistentMemoryWriteReport>> {
    let directory = resolve_persistent_memory_dir(config, workspace_root)?
        .expect("persistent memory directory should resolve when enabled");
    let files = PersistentMemoryFiles::new(directory);
    let mut created_files = Vec::new();
    ensure_memory_layout(&files, &mut created_files).await?;
    if detect_memory_cleanup_status(&files)?.needed && (write_rollout || !facts.is_empty()) {
        bail!("persistent memory cleanup is required before mutating memory");
    }

    let _lock = MemoryLock::acquire(&files.lock_file).await?;
    let existing_lines = read_existing_memory_lines(&files.directory).await?;
    let deduped_facts = facts
        .iter()
        .filter(|fact| {
            let normalized = normalize_whitespace(&fact.fact).to_ascii_lowercase();
            !existing_lines.contains(&normalized)
        })
        .cloned()
        .collect::<Vec<_>>();
    let classified = classified_facts_from_records(&deduped_facts);

    let staged_rollout = if write_rollout && classified.total() > 0 {
        Some(
            write_rollout_summary_pending(&files.rollout_summaries_dir, &classified)
                .await
                .with_context(|| {
                    format!(
                        "Failed to write rollout summary under {}",
                        files.rollout_summaries_dir.display()
                    )
                })?,
        )
    } else {
        None
    };

    let pending_before = list_pending_rollout_files(&files.rollout_summaries_dir).await?;
    let should_consolidate = force_rebuild
        || staged_rollout.is_some()
        || !pending_before.is_empty()
        || !files.summary_file.exists()
        || !files.memory_file.exists();
    if !should_consolidate {
        return Ok(None);
    }

    let consolidated =
        consolidate_memory_files(runtime_config, vt_cfg, workspace_root, &files).await?;
    created_files.extend(consolidated.created_files);
    created_files.sort();
    created_files.dedup();

    Ok(Some(PersistentMemoryWriteReport {
        directory: files.directory,
        summary_file: files.summary_file,
        memory_file: files.memory_file,
        rollout_summary_file: staged_rollout.map(finalize_rollout_summary_path),
        created_files,
        added_facts: consolidated.added_facts,
        pending_rollout_summaries: count_pending_rollout_summaries(&files.rollout_summaries_dir)?,
    }))
}

async fn persist_memory_internal(
    config: &PersistentMemoryConfig,
    workspace_root: &Path,
    runtime_config: Option<&RuntimeAgentConfig>,
    vt_cfg: Option<&VTCodeConfig>,
    candidate_facts: &[GroundedFactRecord],
    write_rollout: bool,
    force_rebuild: bool,
) -> Result<Option<PersistentMemoryWriteReport>> {
    let directory = resolve_persistent_memory_dir(config, workspace_root)?
        .expect("persistent memory directory should resolve when enabled");
    let files = PersistentMemoryFiles::new(directory);
    let mut created_files = Vec::new();
    ensure_memory_layout(&files, &mut created_files).await?;
    if detect_memory_cleanup_status(&files)?.needed
        && (write_rollout || !candidate_facts.is_empty())
    {
        bail!("persistent memory cleanup is required before mutating memory");
    }

    let _lock = MemoryLock::acquire(&files.lock_file).await?;
    let existing_lines = read_existing_memory_lines(&files.directory).await?;

    let deduped_candidates = candidate_facts
        .iter()
        .filter(|fact| {
            let normalized = normalize_whitespace(&fact.fact).to_ascii_lowercase();
            !existing_lines.contains(&normalized)
        })
        .cloned()
        .collect::<Vec<_>>();

    let staged_rollout = if write_rollout && !deduped_candidates.is_empty() {
        let classified =
            classify_facts_strict(runtime_config, vt_cfg, workspace_root, &deduped_candidates)
                .await?;
        if classified.total() == 0 {
            None
        } else {
            Some(
                write_rollout_summary_pending(&files.rollout_summaries_dir, &classified)
                    .await
                    .with_context(|| {
                        format!(
                            "Failed to write rollout summary under {}",
                            files.rollout_summaries_dir.display()
                        )
                    })?,
            )
        }
    } else {
        None
    };

    let pending_before = list_pending_rollout_files(&files.rollout_summaries_dir).await?;
    let should_consolidate = force_rebuild
        || staged_rollout.is_some()
        || !pending_before.is_empty()
        || !files.summary_file.exists()
        || !files.memory_file.exists();
    if !should_consolidate {
        return Ok(None);
    }

    let consolidated =
        consolidate_memory_files(runtime_config, vt_cfg, workspace_root, &files).await?;
    created_files.extend(consolidated.created_files);
    created_files.sort();
    created_files.dedup();

    let pending_rollout_summaries = count_pending_rollout_summaries(&files.rollout_summaries_dir)?;

    Ok(Some(PersistentMemoryWriteReport {
        directory: files.directory,
        summary_file: files.summary_file,
        memory_file: files.memory_file,
        rollout_summary_file: staged_rollout.map(finalize_rollout_summary_path),
        created_files,
        added_facts: consolidated.added_facts,
        pending_rollout_summaries,
    }))
}

fn classified_facts_from_records(records: &[GroundedFactRecord]) -> ClassifiedFacts {
    let mut preferences = Vec::new();
    let mut repository_facts = Vec::new();
    for fact in records {
        match decode_topic_source(&fact.source)
            .0
            .unwrap_or_else(|| classify_fact(fact))
        {
            MemoryTopic::Preferences => preferences.push(fact.clone()),
            MemoryTopic::RepositoryFacts => repository_facts.push(fact.clone()),
        }
    }

    ClassifiedFacts {
        preferences: merge_topic_facts(preferences),
        repository_facts: merge_topic_facts(repository_facts),
    }
}

async fn ensure_memory_layout(
    files: &PersistentMemoryFiles,
    created_files: &mut Vec<PathBuf>,
) -> Result<()> {
    tokio::fs::create_dir_all(&files.directory)
        .await
        .with_context(|| {
            format!(
                "Failed to create persistent memory directory {}",
                files.directory.display()
            )
        })?;
    tokio::fs::create_dir_all(&files.rollout_summaries_dir)
        .await
        .with_context(|| {
            format!(
                "Failed to create rollout summaries directory {}",
                files.rollout_summaries_dir.display()
            )
        })?;
    tokio::fs::create_dir_all(&files.notes_dir)
        .await
        .with_context(|| {
            format!(
                "Failed to create notes directory {}",
                files.notes_dir.display()
            )
        })?;

    ensure_file(
        &files.preferences_file,
        render_topic_file(MemoryTopic::Preferences, &[]),
        created_files,
    )
    .await?;
    ensure_file(
        &files.repository_facts_file,
        render_topic_file(MemoryTopic::RepositoryFacts, &[]),
        created_files,
    )
    .await?;
    ensure_file(
        &files.memory_file,
        render_memory_index(&[], &[], &[], 0),
        created_files,
    )
    .await?;
    ensure_file(
        &files.summary_file,
        render_memory_summary(&[], &[], &[]),
        created_files,
    )
    .await?;

    Ok(())
}

async fn ensure_file(
    path: &Path,
    contents: String,
    created_files: &mut Vec<PathBuf>,
) -> Result<()> {
    if path.exists() {
        return Ok(());
    }

    tokio::fs::write(path, contents)
        .await
        .with_context(|| format!("Failed to write {}", path.display()))?;
    created_files.push(path.to_path_buf());
    Ok(())
}

fn persistent_memory_base_dir(config: &PersistentMemoryConfig) -> Result<PathBuf> {
    if let Some(override_dir) = config.directory_override.as_deref() {
        if let Some(stripped) = override_dir.strip_prefix("~/") {
            let home = dirs::home_dir().context("Could not resolve home directory")?;
            return Ok(home.join(stripped));
        }
        return Ok(PathBuf::from(override_dir));
    }

    dirs::home_dir()
        .map(|home| home.join(".vtcode"))
        .context("Could not resolve VT Code home directory")
}

fn persistent_memory_project_name(workspace_root: &Path) -> String {
    ConfigManager::current_project_name(workspace_root)
        .or_else(|| {
            workspace_root
                .file_name()
                .and_then(|value| value.to_str())
                .map(|value| value.to_string())
        })
        .unwrap_or_else(|| "workspace".to_string())
}

fn migrate_legacy_persistent_memory_dir_if_needed(
    config: &PersistentMemoryConfig,
    project_name: &str,
    target_dir: &Path,
) -> Result<()> {
    if config.directory_override.is_some() {
        return Ok(());
    }

    let Some(legacy_dir) = legacy_persistent_memory_dir(project_name)? else {
        return Ok(());
    };
    if legacy_dir == target_dir || !legacy_dir.exists() {
        return Ok(());
    }

    migrate_legacy_memory_dir(&legacy_dir, target_dir)
}

fn migrate_legacy_memory_dir(legacy_dir: &Path, target_dir: &Path) -> Result<()> {
    if target_dir.exists() && memory_directory_has_stored_content(target_dir)? {
        if !memory_directory_has_stored_content(legacy_dir)? {
            remove_empty_legacy_memory_hierarchy(legacy_dir)?;
        }
        return Ok(());
    }

    if target_dir.exists() {
        std::fs::remove_dir_all(target_dir)
            .with_context(|| format!("Failed to clear {}", target_dir.display()))?;
    }

    let target_parent = target_dir
        .parent()
        .context("Persistent memory directory is missing a parent")?;
    std::fs::create_dir_all(target_parent)
        .with_context(|| format!("Failed to create {}", target_parent.display()))?;

    std::fs::rename(legacy_dir, target_dir).with_context(|| {
        format!(
            "Failed to migrate persistent memory from {} to {}",
            legacy_dir.display(),
            target_dir.display()
        )
    })?;
    remove_empty_legacy_memory_hierarchy(legacy_dir)?;
    Ok(())
}

fn legacy_persistent_memory_dir(project_name: &str) -> Result<Option<PathBuf>> {
    let Some(legacy_base) = get_config_dir() else {
        return Ok(None);
    };
    let current_base = dirs::home_dir()
        .map(|home| home.join(".vtcode"))
        .context("Could not resolve VT Code home directory")?;
    if legacy_base == current_base {
        return Ok(None);
    }

    Ok(Some(
        legacy_base
            .join("projects")
            .join(sanitize_project_name(project_name))
            .join("memory"),
    ))
}

fn memory_directory_has_stored_content(directory: &Path) -> Result<bool> {
    if !directory.exists() {
        return Ok(false);
    }

    for path in [
        directory.join(PREFERENCES_FILENAME),
        directory.join(REPOSITORY_FACTS_FILENAME),
    ] {
        if !path.exists() {
            continue;
        }

        let contents = std::fs::read_to_string(&path)
            .with_context(|| format!("Failed to read {}", path.display()))?;
        if !parse_topic_file(&contents).is_empty() {
            return Ok(true);
        }
    }

    let rollout_dir = directory.join(ROLLOUT_SUMMARIES_DIRNAME);
    if !rollout_dir.exists() {
        return Ok(false);
    }

    for entry in std::fs::read_dir(&rollout_dir)
        .with_context(|| format!("Failed to list {}", rollout_dir.display()))?
    {
        let path = entry?.path();
        if path.extension().and_then(|value| value.to_str()) != Some("md") {
            continue;
        }
        let contents = std::fs::read_to_string(&path)
            .with_context(|| format!("Failed to read {}", path.display()))?;
        if !parse_topic_file(&contents).is_empty() {
            return Ok(true);
        }
    }

    Ok(false)
}

fn remove_empty_legacy_memory_hierarchy(legacy_memory_dir: &Path) -> Result<()> {
    let mut current = legacy_memory_dir.parent();
    for _ in 0..3 {
        let Some(path) = current else {
            break;
        };
        match std::fs::remove_dir(path) {
            Ok(()) => current = path.parent(),
            Err(err) if err.kind() == std::io::ErrorKind::NotFound => current = path.parent(),
            Err(err) if err.kind() == std::io::ErrorKind::DirectoryNotEmpty => break,
            Err(err) => {
                return Err(err).with_context(|| format!("Failed to remove {}", path.display()));
            }
        }
    }

    Ok(())
}

fn sanitize_project_name(project_name: &str) -> String {
    let sanitized = project_name
        .chars()
        .map(|ch| match ch {
            '/' | '\\' | ':' => '_',
            other => other,
        })
        .collect::<String>();
    let trimmed = sanitized.trim();
    if trimmed.is_empty() {
        "workspace".to_string()
    } else {
        trimmed.to_string()
    }
}

fn truncate_memory_excerpt(
    contents: &str,
    line_limit: usize,
    byte_limit: usize,
) -> (String, bool, usize, usize) {
    let all_lines = contents.lines().collect::<Vec<_>>();
    let mut selected = String::new();
    let mut bytes_read = 0usize;
    let mut lines_read = 0usize;
    let mut truncated = false;

    for (index, line) in all_lines.iter().enumerate() {
        if lines_read >= line_limit {
            truncated = true;
            break;
        }

        let line_bytes = line.len();
        let trailing_newline = usize::from(index + 1 < all_lines.len());
        if bytes_read + line_bytes + trailing_newline > byte_limit {
            truncated = true;
            break;
        }

        selected.push_str(line);
        selected.push('\n');
        bytes_read += line_bytes + trailing_newline;
        lines_read += 1;
    }

    if !truncated && contents.len() > bytes_read {
        truncated = true;
    }

    (
        selected.trim_end().to_string(),
        truncated,
        bytes_read,
        lines_read,
    )
}

async fn read_existing_memory_lines(directory: &Path) -> Result<BTreeSet<String>> {
    let mut lines = BTreeSet::new();
    if !directory.exists() {
        return Ok(lines);
    }

    let mut stack = vec![directory.to_path_buf()];
    while let Some(next_dir) = stack.pop() {
        let mut entries = tokio::fs::read_dir(&next_dir)
            .await
            .with_context(|| format!("Failed to list {}", next_dir.display()))?;
        while let Some(entry) = entries.next_entry().await? {
            let path = entry.path();
            let metadata = entry.metadata().await?;
            if metadata.is_dir() {
                stack.push(path);
                continue;
            }
            if path.extension().and_then(|value| value.to_str()) != Some("md") {
                continue;
            }
            let content = tokio::fs::read_to_string(&path).await.unwrap_or_default();
            for line in content.lines() {
                let Some((_, fact)) = parse_fact_line(line) else {
                    continue;
                };
                lines.insert(normalize_whitespace(&fact).to_ascii_lowercase());
            }
        }
    }

    Ok(lines)
}

fn default_cleanup_status() -> MemoryCleanupStatus {
    MemoryCleanupStatus {
        needed: false,
        suspicious_facts: 0,
        suspicious_summary_lines: 0,
    }
}

fn detect_memory_cleanup_status(files: &PersistentMemoryFiles) -> Result<MemoryCleanupStatus> {
    if !files.directory.exists() {
        return Ok(default_cleanup_status());
    }

    let mut suspicious_facts = 0usize;
    for path in [
        &files.preferences_file,
        &files.repository_facts_file,
        &files.memory_file,
    ] {
        suspicious_facts += count_suspicious_facts_in_file(path)?;
    }
    suspicious_facts += count_suspicious_rollout_facts(&files.rollout_summaries_dir)?;

    let suspicious_summary_lines = count_suspicious_summary_lines(&files.summary_file)?;
    Ok(MemoryCleanupStatus {
        needed: suspicious_facts > 0 || suspicious_summary_lines > 0,
        suspicious_facts,
        suspicious_summary_lines,
    })
}

fn count_suspicious_facts_in_file(path: &Path) -> Result<usize> {
    if !path.exists() {
        return Ok(0);
    }

    let content = std::fs::read_to_string(path)
        .with_context(|| format!("Failed to read {}", path.display()))?;
    Ok(parse_topic_file(&content)
        .into_iter()
        .filter(is_legacy_polluted_fact)
        .count())
}

fn count_suspicious_rollout_facts(rollout_dir: &Path) -> Result<usize> {
    if !rollout_dir.exists() {
        return Ok(0);
    }

    let mut count = 0usize;
    for entry in std::fs::read_dir(rollout_dir)
        .with_context(|| format!("Failed to list {}", rollout_dir.display()))?
    {
        let path = entry?.path();
        if path.extension().and_then(|value| value.to_str()) != Some("md") {
            continue;
        }
        count += count_suspicious_facts_in_file(&path)?;
    }
    Ok(count)
}

fn count_suspicious_summary_lines(path: &Path) -> Result<usize> {
    if !path.exists() {
        return Ok(0);
    }

    let content = std::fs::read_to_string(path)
        .with_context(|| format!("Failed to read {}", path.display()))?;
    Ok(content
        .lines()
        .map(str::trim)
        .filter(|line| line.starts_with("- "))
        .map(|line| line.trim_start_matches("- ").trim())
        .filter(|line| looks_like_legacy_prompt(line) || looks_like_serialized_payload(line))
        .count())
}

fn is_legacy_polluted_fact(fact: &GroundedFactRecord) -> bool {
    looks_like_legacy_prompt(&fact.fact) || looks_like_serialized_payload(&fact.fact)
}

fn looks_like_legacy_prompt(text: &str) -> bool {
    let mut lowered = normalize_whitespace(text).to_ascii_lowercase();
    while let Some(stripped) = [
        "please ",
        "can you ",
        "could you ",
        "would you ",
        "vt code, ",
        "vt code ",
    ]
    .iter()
    .find_map(|prefix| lowered.strip_prefix(prefix))
    {
        lowered = stripped.trim_start().to_string();
    }
    remember_markers_for_cleanup()
        .iter()
        .chain(forget_markers_for_cleanup())
        .any(|marker| lowered.starts_with(marker))
}

fn looks_like_serialized_payload(text: &str) -> bool {
    let trimmed = text.trim();
    trimmed.starts_with('{')
        || trimmed.starts_with('[')
        || trimmed.contains("\"query\":")
        || trimmed.contains("\"matches\":")
        || trimmed.contains("\"path\":")
        || trimmed.contains("</parameter>")
        || trimmed.contains("</invoke>")
        || trimmed.contains("<</invoke>")
}

fn remember_markers_for_cleanup() -> &'static [&'static str] {
    &[
        "save to memory",
        "remember that",
        "remember my",
        "remember ",
        "add to memory",
        "store in memory",
    ]
}

fn forget_markers_for_cleanup() -> &'static [&'static str] {
    &["forget ", "remove from memory", "delete from memory"]
}

fn normalize_memory_query(query: &str) -> Option<String> {
    let normalized = normalize_whitespace(query).to_ascii_lowercase();
    (!normalized.is_empty()).then_some(normalized)
}

async fn collect_memory_matches(
    files: &PersistentMemoryFiles,
    normalized_query: &str,
) -> Result<Vec<PersistentMemoryMatch>> {
    Ok(collect_all_memory_matches(files)
        .await?
        .into_iter()
        .filter(|record| {
            let normalized_fact = normalize_whitespace(&record.fact).to_ascii_lowercase();
            let normalized_source = normalize_whitespace(&record.source).to_ascii_lowercase();
            normalized_fact.contains(normalized_query)
                || normalized_source.contains(normalized_query)
        })
        .collect())
}

async fn collect_all_memory_matches(
    files: &PersistentMemoryFiles,
) -> Result<Vec<PersistentMemoryMatch>> {
    let preferences = read_topic_records(&files.preferences_file, MemoryTopic::Preferences).await?;
    let repository_facts =
        read_topic_records(&files.repository_facts_file, MemoryTopic::RepositoryFacts).await?;
    let rollout_records = read_rollout_records(&files.rollout_summaries_dir).await?;
    let notes = read_note_summaries(&files.notes_dir).await?;

    let mut matches = Vec::new();
    for record in preferences
        .into_iter()
        .chain(repository_facts)
        .chain(rollout_records.0)
        .chain(rollout_records.1)
    {
        let (_topic, source) = decode_topic_source(&record.source);
        matches.push(PersistentMemoryMatch {
            source,
            fact: record.fact,
        });
    }
    for note in notes {
        for highlight in note.highlights {
            matches.push(PersistentMemoryMatch {
                source: note.relative_path.clone(),
                fact: highlight,
            });
        }
    }

    let mut deduped = Vec::new();
    for record in matches {
        let normalized = normalize_whitespace(&record.fact).to_ascii_lowercase();
        if let Some(existing_idx) = deduped.iter().position(|entry: &PersistentMemoryMatch| {
            normalize_whitespace(&entry.fact).to_ascii_lowercase() == normalized
        }) {
            deduped.remove(existing_idx);
        }
        deduped.push(record);
    }
    Ok(deduped)
}

async fn collect_cleanup_candidates(
    files: &PersistentMemoryFiles,
) -> Result<Vec<GroundedFactRecord>> {
    let preferences = read_topic_records(&files.preferences_file, MemoryTopic::Preferences).await?;
    let repository_facts =
        read_topic_records(&files.repository_facts_file, MemoryTopic::RepositoryFacts).await?;
    let rollout_records = read_rollout_records(&files.rollout_summaries_dir).await?;

    Ok(preferences
        .into_iter()
        .chain(repository_facts)
        .chain(rollout_records.0)
        .chain(rollout_records.1)
        .collect())
}

async fn write_rollout_summary_pending(
    rollout_dir: &Path,
    classified: &ClassifiedFacts,
) -> Result<PathBuf> {
    tokio::fs::create_dir_all(rollout_dir)
        .await
        .with_context(|| format!("Failed to create {}", rollout_dir.display()))?;

    let file_name = format!("{}.pending.md", unique_rollout_id());
    let path = rollout_dir.join(file_name);
    let contents = render_rollout_summary(classified);
    tokio::fs::write(&path, contents)
        .await
        .with_context(|| format!("Failed to write {}", path.display()))?;
    Ok(path)
}

fn finalize_rollout_summary_path(path: PathBuf) -> PathBuf {
    if let Some(name) = path.file_name().and_then(|value| value.to_str()) {
        path.with_file_name(name.trim_end_matches(".pending.md").to_string() + ".md")
    } else {
        path
    }
}

async fn list_pending_rollout_files(rollout_dir: &Path) -> Result<Vec<PathBuf>> {
    if !rollout_dir.exists() {
        return Ok(Vec::new());
    }

    let mut entries = tokio::fs::read_dir(rollout_dir)
        .await
        .with_context(|| format!("Failed to list {}", rollout_dir.display()))?;
    let mut paths = Vec::new();
    while let Some(entry) = entries.next_entry().await? {
        let path = entry.path();
        if path
            .file_name()
            .and_then(|value| value.to_str())
            .is_some_and(|name| name.ends_with(".pending.md"))
        {
            paths.push(path);
        }
    }
    paths.sort();
    Ok(paths)
}

async fn list_rollout_markdown_files(rollout_dir: &Path) -> Result<Vec<PathBuf>> {
    if !rollout_dir.exists() {
        return Ok(Vec::new());
    }

    let mut entries = tokio::fs::read_dir(rollout_dir)
        .await
        .with_context(|| format!("Failed to list {}", rollout_dir.display()))?;
    let mut paths = Vec::new();
    while let Some(entry) = entries.next_entry().await? {
        let path = entry.path();
        if path.extension().and_then(|value| value.to_str()) == Some("md") {
            paths.push(path);
        }
    }
    paths.sort();
    Ok(paths)
}

fn count_pending_rollout_summaries(rollout_dir: &Path) -> Result<usize> {
    if !rollout_dir.exists() {
        return Ok(0);
    }

    let mut count = 0usize;
    for entry in std::fs::read_dir(rollout_dir)
        .with_context(|| format!("Failed to list {}", rollout_dir.display()))?
    {
        let path = entry?.path();
        if path
            .file_name()
            .and_then(|value| value.to_str())
            .is_some_and(|name| name.ends_with(".pending.md"))
        {
            count += 1;
        }
    }
    Ok(count)
}

fn list_note_markdown_files(notes_dir: &Path) -> Result<Vec<PathBuf>> {
    fn walk(dir: &Path, files: &mut Vec<PathBuf>) -> Result<()> {
        if !dir.exists() {
            return Ok(());
        }

        for entry in
            std::fs::read_dir(dir).with_context(|| format!("Failed to list {}", dir.display()))?
        {
            let path = entry?.path();
            if path.is_dir() {
                walk(&path, files)?;
            } else if path.extension().and_then(|value| value.to_str()) == Some("md") {
                files.push(path);
            }
        }

        Ok(())
    }

    let mut files = Vec::new();
    walk(notes_dir, &mut files)?;
    files.sort();
    Ok(files)
}

async fn read_note_summaries(notes_dir: &Path) -> Result<Vec<MemoryNoteSummary>> {
    let note_files = list_note_markdown_files(notes_dir)?;
    let mut notes = Vec::with_capacity(note_files.len());
    for path in note_files {
        let content = tokio::fs::read_to_string(&path)
            .await
            .with_context(|| format!("Failed to read {}", path.display()))?;
        let relative = path
            .strip_prefix(notes_dir)
            .with_context(|| format!("Failed to relativize {}", path.display()))?
            .to_string_lossy()
            .replace('\\', "/");
        notes.push(MemoryNoteSummary {
            relative_path: format!("{NOTES_DIRNAME}/{relative}"),
            highlights: extract_memory_highlights(&content, 3),
        });
    }
    Ok(notes)
}

struct ConsolidationResult {
    created_files: Vec<PathBuf>,
    added_facts: usize,
}

#[derive(Debug, Clone, PartialEq, Eq)]
struct MemoryNoteSummary {
    relative_path: String,
    highlights: Vec<String>,
}

async fn consolidate_memory_files(
    runtime_config: Option<&RuntimeAgentConfig>,
    vt_cfg: Option<&VTCodeConfig>,
    workspace_root: &Path,
    files: &PersistentMemoryFiles,
) -> Result<ConsolidationResult> {
    let pending_files = list_pending_rollout_files(&files.rollout_summaries_dir).await?;
    let preferences_existing =
        read_topic_records(&files.preferences_file, MemoryTopic::Preferences).await?;
    let repository_existing =
        read_topic_records(&files.repository_facts_file, MemoryTopic::RepositoryFacts).await?;
    let rollout_records = read_rollout_records(&files.rollout_summaries_dir).await?;
    let notes = read_note_summaries(&files.notes_dir).await?;

    let preferences = merge_topic_facts(
        preferences_existing
            .into_iter()
            .chain(rollout_records.0)
            .collect(),
    );
    let repository_facts = merge_topic_facts(
        repository_existing
            .into_iter()
            .chain(rollout_records.1)
            .collect(),
    );

    let mut created_files = Vec::new();
    write_topic_file(
        &files.preferences_file,
        MemoryTopic::Preferences,
        &preferences,
        &mut created_files,
    )
    .await?;
    write_topic_file(
        &files.repository_facts_file,
        MemoryTopic::RepositoryFacts,
        &repository_facts,
        &mut created_files,
    )
    .await?;

    write_memory_index(
        &files.memory_file,
        &preferences,
        &repository_facts,
        &notes,
        0,
        &mut created_files,
    )
    .await?;
    write_memory_summary(
        &files.summary_file,
        runtime_config,
        vt_cfg,
        workspace_root,
        &preferences,
        &repository_facts,
        &notes,
        &mut created_files,
    )
    .await?;

    let added_facts = pending_files
        .iter()
        .filter_map(|path| std::fs::read_to_string(path).ok())
        .flat_map(|content| {
            content
                .lines()
                .filter_map(parse_fact_line)
                .collect::<Vec<_>>()
        })
        .count();

    for pending in &pending_files {
        let finalized = finalize_rollout_summary_path(pending.clone());
        if !finalized.exists() {
            tokio::fs::rename(pending, &finalized)
                .await
                .with_context(|| {
                    format!("Failed to finalize rollout summary {}", pending.display())
                })?;
        } else {
            tokio::fs::remove_file(pending)
                .await
                .with_context(|| format!("Failed to remove {}", pending.display()))?;
        }
    }

    Ok(ConsolidationResult {
        created_files,
        added_facts,
    })
}

async fn read_topic_records(path: &Path, topic: MemoryTopic) -> Result<Vec<GroundedFactRecord>> {
    if !path.exists() {
        return Ok(Vec::new());
    }

    let contents = tokio::fs::read_to_string(path)
        .await
        .with_context(|| format!("Failed to read {}", path.display()))?;
    Ok(parse_topic_file(&contents)
        .into_iter()
        .map(|record| GroundedFactRecord {
            fact: record.fact,
            source: encode_topic_source(topic, &record.source),
        })
        .collect())
}

async fn read_rollout_records(
    rollout_dir: &Path,
) -> Result<(Vec<GroundedFactRecord>, Vec<GroundedFactRecord>)> {
    if !rollout_dir.exists() {
        return Ok((Vec::new(), Vec::new()));
    }

    let mut entries = tokio::fs::read_dir(rollout_dir)
        .await
        .with_context(|| format!("Failed to list {}", rollout_dir.display()))?;
    let mut preferences = Vec::new();
    let mut repository_facts = Vec::new();
    while let Some(entry) = entries.next_entry().await? {
        let path = entry.path();
        if path.extension().and_then(|value| value.to_str()) != Some("md") {
            continue;
        }
        let contents = tokio::fs::read_to_string(&path).await.unwrap_or_default();
        for record in parse_topic_file(&contents) {
            let (topic, _display_source) = decode_topic_source(&record.source);
            match topic.unwrap_or_else(|| classify_fact(&record)) {
                MemoryTopic::Preferences => preferences.push(record),
                MemoryTopic::RepositoryFacts => repository_facts.push(record),
            }
        }
    }

    Ok((preferences, repository_facts))
}

fn merge_topic_facts(records: Vec<GroundedFactRecord>) -> Vec<GroundedFactRecord> {
    let mut facts = Vec::new();
    for fact in records {
        let normalized = normalize_whitespace(&fact.fact).to_ascii_lowercase();
        if let Some(existing_idx) = facts.iter().position(|entry: &GroundedFactRecord| {
            normalize_whitespace(&entry.fact).to_ascii_lowercase() == normalized
        }) {
            facts.remove(existing_idx);
        }
        facts.push(fact);
    }

    let keep_from = facts.len().saturating_sub(TOPIC_FACT_LIMIT);
    facts.into_iter().skip(keep_from).collect()
}

fn normalized_selection_key(source: &str, fact: &str) -> String {
    format!(
        "{}::{}",
        normalize_whitespace(source).to_ascii_lowercase(),
        normalize_whitespace(fact).to_ascii_lowercase()
    )
}

fn selection_key_for_record(record: &GroundedFactRecord) -> String {
    let (_topic, source) = decode_topic_source(&record.source);
    normalized_selection_key(&source, &record.fact)
}

fn selection_keys(selected: &[MemoryOpCandidate]) -> BTreeSet<String> {
    selected
        .iter()
        .map(|entry| normalized_selection_key(&entry.source, &entry.fact))
        .collect()
}

async fn rewrite_topic_without_selected(
    path: &Path,
    topic: MemoryTopic,
    selected: &[MemoryOpCandidate],
) -> Result<usize> {
    if !path.exists() {
        return Ok(0);
    }

    let selected = selection_keys(selected);
    let facts = read_topic_records(path, topic).await?;
    let removed = facts
        .iter()
        .filter(|fact| selected.contains(&selection_key_for_record(fact)))
        .count();
    if removed == 0 {
        return Ok(0);
    }

    let kept = facts
        .into_iter()
        .filter(|fact| !selected.contains(&selection_key_for_record(fact)))
        .collect::<Vec<_>>();
    tokio::fs::write(path, render_topic_file(topic, &kept))
        .await
        .with_context(|| format!("Failed to write {}", path.display()))?;
    Ok(removed)
}

async fn scrub_rollout_file_by_selection(
    path: &Path,
    selected: &[MemoryOpCandidate],
) -> Result<usize> {
    let contents = tokio::fs::read_to_string(path)
        .await
        .with_context(|| format!("Failed to read {}", path.display()))?;
    let selected = selection_keys(selected);
    let mut removed = 0usize;
    let mut filtered = Vec::new();

    for line in contents.lines() {
        let keep = parse_fact_line(line).is_none_or(|(source, fact)| {
            let record = GroundedFactRecord { source, fact };
            let matches = selected.contains(&selection_key_for_record(&record));
            if matches {
                removed += 1;
            }
            !matches
        });
        if keep {
            filtered.push(line);
        }
    }

    if removed == 0 {
        return Ok(0);
    }

    let mut rewritten = filtered.join("\n");
    if contents.ends_with('\n') {
        rewritten.push('\n');
    }
    tokio::fs::write(path, rewritten)
        .await
        .with_context(|| format!("Failed to write {}", path.display()))?;
    Ok(removed)
}

async fn remove_rollout_markdown_files(rollout_dir: &Path) -> Result<usize> {
    let rollout_files = list_rollout_markdown_files(rollout_dir).await?;
    let count = rollout_files.len();
    for path in rollout_files {
        tokio::fs::remove_file(&path)
            .await
            .with_context(|| format!("Failed to remove {}", path.display()))?;
    }
    Ok(count)
}

async fn write_topic_file(
    path: &Path,
    topic: MemoryTopic,
    facts: &[GroundedFactRecord],
    created_files: &mut Vec<PathBuf>,
) -> Result<()> {
    if !path.exists() {
        created_files.push(path.to_path_buf());
    }
    let contents = render_topic_file(topic, facts);
    tokio::fs::write(path, contents)
        .await
        .with_context(|| format!("Failed to write {}", path.display()))?;
    Ok(())
}

async fn write_memory_index(
    path: &Path,
    preferences: &[GroundedFactRecord],
    repository_facts: &[GroundedFactRecord],
    notes: &[MemoryNoteSummary],
    pending_rollouts: usize,
    created_files: &mut Vec<PathBuf>,
) -> Result<()> {
    if !path.exists() {
        created_files.push(path.to_path_buf());
    }
    let contents = render_memory_index(preferences, repository_facts, notes, pending_rollouts);
    tokio::fs::write(path, contents)
        .await
        .with_context(|| format!("Failed to write {}", path.display()))?;
    Ok(())
}

async fn write_memory_summary(
    path: &Path,
    runtime_config: Option<&RuntimeAgentConfig>,
    vt_cfg: Option<&VTCodeConfig>,
    workspace_root: &Path,
    preferences: &[GroundedFactRecord],
    repository_facts: &[GroundedFactRecord],
    notes: &[MemoryNoteSummary],
    created_files: &mut Vec<PathBuf>,
) -> Result<()> {
    let contents = summarize_memory(
        runtime_config,
        vt_cfg,
        workspace_root,
        preferences,
        repository_facts,
        notes,
    )
    .await
    .unwrap_or_else(|| render_memory_summary(preferences, repository_facts, notes));
    if !path.exists() {
        created_files.push(path.to_path_buf());
    }
    tokio::fs::write(path, contents)
        .await
        .with_context(|| format!("Failed to write {}", path.display()))?;
    Ok(())
}

fn parse_topic_file(contents: &str) -> Vec<GroundedFactRecord> {
    contents
        .lines()
        .filter_map(parse_fact_line)
        .map(|(source, fact)| GroundedFactRecord { source, fact })
        .collect()
}

fn parse_fact_line(line: &str) -> Option<(String, String)> {
    let trimmed = line.trim();
    let remainder = trimmed.strip_prefix("- [")?;
    let (source, fact) = remainder.split_once("] ")?;
    let fact = fact.trim();
    if fact.is_empty() {
        return None;
    }
    Some((source.trim().to_string(), fact.to_string()))
}

fn classify_fact(fact: &GroundedFactRecord) -> MemoryTopic {
    if fact.source == "user_assertion" {
        MemoryTopic::Preferences
    } else {
        MemoryTopic::RepositoryFacts
    }
}

fn encode_topic_source(topic: MemoryTopic, source: &str) -> String {
    format!("{}:{}", topic.slug(), source)
}

fn decode_topic_source(source: &str) -> (Option<MemoryTopic>, String) {
    let Some((topic, display_source)) = source.split_once(':') else {
        return (None, source.to_string());
    };
    (
        MemoryTopic::from_slug(topic),
        display_source.trim().to_string(),
    )
}

async fn classify_facts_strict(
    runtime_config: Option<&RuntimeAgentConfig>,
    vt_cfg: Option<&VTCodeConfig>,
    workspace_root: &Path,
    candidates: &[GroundedFactRecord],
) -> Result<ClassifiedFacts> {
    if candidates.is_empty() {
        return Ok(ClassifiedFacts {
            preferences: Vec::new(),
            repository_facts: Vec::new(),
        });
    }

    classify_facts_with_llm(runtime_config, vt_cfg, workspace_root, candidates).await
}

async fn classify_facts_with_llm(
    runtime_config: Option<&RuntimeAgentConfig>,
    vt_cfg: Option<&VTCodeConfig>,
    workspace_root: &Path,
    candidates: &[GroundedFactRecord],
) -> Result<ClassifiedFacts> {
    let runtime_config = runtime_config
        .ok_or_else(|| anyhow!("runtime config is required for persistent memory LLM routing"))?;
    let routes = resolve_memory_model_routes(runtime_config, vt_cfg);
    log_memory_route_warning(&routes);

    let provider = create_memory_provider(&routes.primary, runtime_config, vt_cfg)?;
    match classify_facts_with_provider(
        provider.as_ref(),
        &routes.primary,
        workspace_root,
        candidates,
    )
    .await
    {
        Ok(result) => Ok(result),
        Err(primary_err) => {
            let Some(fallback) = routes.fallback.as_ref() else {
                return Err(primary_err);
            };

            tracing::warn!(
                model = %routes.primary.model,
                fallback_model = %fallback.model,
                error = %primary_err,
                "persistent memory classification failed on lightweight route; retrying with main model"
            );
            let provider = create_memory_provider(fallback, runtime_config, vt_cfg)?;
            classify_facts_with_provider(provider.as_ref(), fallback, workspace_root, candidates)
                .await
        }
    }
}

async fn classify_facts_with_provider(
    provider: &dyn LLMProvider,
    route: &MemoryModelRoute,
    workspace_root: &Path,
    candidates: &[GroundedFactRecord],
) -> Result<ClassifiedFacts> {
    let payload = candidates
        .iter()
        .enumerate()
        .map(|(index, fact)| {
            json!({
                "id": index,
                "source": fact.source,
                "fact": fact.fact,
            })
        })
        .collect::<Vec<_>>();

    let schema = json!({
        "type": "object",
        "properties": {
            "keep": {
                "type": "array",
                "items": {
                    "type": "object",
                    "properties": {
                        "id": {"type": "integer"},
                        "topic": {
                            "type": "string",
                            "enum": ["preferences", "repository_facts"]
                        },
                        "fact": {"type": "string"}
                    },
                    "required": ["id", "topic", "fact"],
                    "additionalProperties": false
                }
            }
        },
        "required": ["keep"],
        "additionalProperties": false
    });
    let request = build_memory_json_request(
        provider,
        route,
        format!(
            "Classify VT Code memory evidence. Keep only durable reusable preferences or repository facts. Rewrite each kept fact into one concise canonical sentence. Drop transient, conversational, or noisy entries by omitting them.\n\nWorkspace: {}\nCandidates:\n{}",
            workspace_root.display(),
            serde_json::to_string_pretty(&payload)
                .context("failed to serialize memory classification payload")?
        ),
        "memory_classification",
        &schema,
    )?;

    let response = collect_single_response(provider, request)
        .await
        .context("persistent memory classification LLM request failed")?;
    let content = response
        .content
        .context("persistent memory classification returned no content")?;
    let parsed = parse_memory_json_response::<MemoryClassificationPlan>(
        content.trim(),
        "persistent memory classification",
    )?;

    let mut preferences = Vec::new();
    let mut repository_facts = Vec::new();
    for item in parsed.keep {
        let candidate = candidates.get(item.id).ok_or_else(|| {
            anyhow!(
                "memory classification referenced unknown candidate id {}",
                item.id
            )
        })?;
        let normalized_fact = normalize_whitespace(item.fact.as_deref().unwrap_or(&candidate.fact));
        if normalized_fact.is_empty() || looks_like_legacy_prompt(&normalized_fact) {
            continue;
        }
        let topic = match item.topic {
            MemoryPlannedTopic::Preferences => MemoryTopic::Preferences,
            MemoryPlannedTopic::RepositoryFacts => MemoryTopic::RepositoryFacts,
        };
        let record = GroundedFactRecord {
            fact: truncate_for_fact(&normalized_fact, 180),
            source: {
                let (_existing_topic, display_source) = decode_topic_source(&candidate.source);
                encode_topic_source(topic, &display_source)
            },
        };
        match topic {
            MemoryTopic::Preferences => preferences.push(record),
            MemoryTopic::RepositoryFacts => repository_facts.push(record),
        };
    }

    Ok(ClassifiedFacts {
        preferences,
        repository_facts,
    })
}

async fn summarize_memory(
    runtime_config: Option<&RuntimeAgentConfig>,
    vt_cfg: Option<&VTCodeConfig>,
    workspace_root: &Path,
    preferences: &[GroundedFactRecord],
    repository_facts: &[GroundedFactRecord],
    notes: &[MemoryNoteSummary],
) -> Option<String> {
    let runtime_config = runtime_config?;
    let routes = resolve_memory_model_routes(runtime_config, vt_cfg);
    log_memory_route_warning(&routes);

    let provider = create_memory_provider(&routes.primary, runtime_config, vt_cfg).ok()?;
    match summarize_memory_with_provider(
        provider.as_ref(),
        &routes.primary,
        workspace_root,
        preferences,
        repository_facts,
        notes,
    )
    .await
    {
        Ok(summary) => Some(summary),
        Err(primary_err) => {
            let fallback = routes.fallback.as_ref()?;
            tracing::warn!(
                model = %routes.primary.model,
                fallback_model = %fallback.model,
                error = %primary_err,
                "persistent memory summary failed on lightweight route; retrying with main model"
            );
            let provider = create_memory_provider(fallback, runtime_config, vt_cfg).ok()?;
            summarize_memory_with_provider(
                provider.as_ref(),
                fallback,
                workspace_root,
                preferences,
                repository_facts,
                notes,
            )
            .await
            .ok()
        }
    }
}

async fn summarize_memory_with_provider(
    provider: &dyn LLMProvider,
    route: &MemoryModelRoute,
    workspace_root: &Path,
    preferences: &[GroundedFactRecord],
    repository_facts: &[GroundedFactRecord],
    notes: &[MemoryNoteSummary],
) -> Result<String> {
    let schema = json!({
        "type": "object",
        "properties": {
            "bullets": {
                "type": "array",
                "items": {"type": "string"}
            }
        },
        "required": ["bullets"],
        "additionalProperties": false
    });
    let request = build_memory_json_request(
        provider,
        route,
        format!(
            "Write a concise VT Code persistent memory summary for startup injection. Return 4-10 short bullets only. Focus on stable preferences, repository facts, and durable user-authored notes.\n\nWorkspace: {}\nPreferences:\n{}\n\nRepository facts:\n{}\n\nNotes:\n{}",
            workspace_root.display(),
            facts_for_prompt(preferences),
            facts_for_prompt(repository_facts),
            notes_for_prompt(notes),
        ),
        "memory_summary",
        &schema,
    )?;

    let response = collect_single_response(provider, request)
        .await
        .context("persistent memory summary LLM request failed")?
        .content
        .context("persistent memory summary returned no content")?;
    let parsed = parse_memory_json_response::<MemorySummaryResponse>(
        response.trim(),
        "persistent memory summary",
    )?;
    let bullets = parsed
        .bullets
        .into_iter()
        .map(|bullet| normalize_whitespace(&bullet))
        .filter(|bullet| !bullet.is_empty())
        .take(MEMORY_HIGHLIGHT_LIMIT)
        .collect::<Vec<_>>();
    if bullets.is_empty() {
        bail!("persistent memory summary returned no bullets");
    }

    Ok(render_memory_summary_bullets(&bullets))
}

async fn plan_memory_operation(
    runtime_config: &RuntimeAgentConfig,
    vt_cfg: Option<&VTCodeConfig>,
    workspace_root: &Path,
    expected_kind: MemoryOpKind,
    request: &str,
    supplemental_answer: Option<&str>,
    candidates: &[MemoryOpCandidate],
) -> Result<MemoryOpPlan> {
    let routes = resolve_memory_model_routes(runtime_config, vt_cfg);
    log_memory_route_warning(&routes);

    let provider = create_memory_provider(&routes.primary, runtime_config, vt_cfg)?;
    match plan_memory_operation_with_provider(
        provider.as_ref(),
        &routes.primary,
        workspace_root,
        expected_kind.clone(),
        request,
        supplemental_answer,
        candidates,
    )
    .await
    {
        Ok(plan) => Ok(plan),
        Err(primary_err) => {
            let Some(fallback) = routes.fallback.as_ref() else {
                return Err(primary_err);
            };

            tracing::warn!(
                model = %routes.primary.model,
                fallback_model = %fallback.model,
                error = %primary_err,
                "persistent memory planner failed on lightweight route; retrying with main model"
            );
            let provider = create_memory_provider(fallback, runtime_config, vt_cfg)?;
            plan_memory_operation_with_provider(
                provider.as_ref(),
                fallback,
                workspace_root,
                expected_kind,
                request,
                supplemental_answer,
                candidates,
            )
            .await
        }
    }
}

async fn plan_memory_operation_with_provider(
    provider: &dyn LLMProvider,
    route: &MemoryModelRoute,
    workspace_root: &Path,
    expected_kind: MemoryOpKind,
    request: &str,
    supplemental_answer: Option<&str>,
    candidates: &[MemoryOpCandidate],
) -> Result<MemoryOpPlan> {
    let payload = serde_json::to_string_pretty(candidates)
        .context("failed to serialize memory operation candidates")?;
    let supplemental = supplemental_answer.unwrap_or("").trim();
    let schema = json!({
        "type": "object",
        "properties": {
            "kind": {
                "type": "string",
                "enum": ["remember", "forget", "ask_missing", "noop"]
            },
            "facts": {
                "type": "array",
                "items": {
                    "type": "object",
                    "properties": {
                        "topic": {
                            "type": "string",
                            "enum": ["preferences", "repository_facts"]
                        },
                        "fact": {"type": "string"},
                        "source": {"type": "string"}
                    },
                    "required": ["topic", "fact"],
                    "additionalProperties": false
                }
            },
            "selected_ids": {
                "type": "array",
                "items": {"type": "integer"}
            },
            "missing": {
                "type": ["object", "null"],
                "properties": {
                    "field": {"type": "string"},
                    "prompt": {"type": "string"}
                },
                "required": ["field", "prompt"],
                "additionalProperties": false
            },
            "message": {"type": ["string", "null"]}
        },
        "required": ["kind", "facts", "selected_ids", "missing", "message"],
        "additionalProperties": false
    });
    let llm_request = build_memory_json_request(
        provider,
        route,
        format!(
            "Plan a VT Code persistent memory operation.\n\nExpected operation: {:?}\nWorkspace: {}\nUser request: {}\nSupplemental answer: {}\nCurrent candidates:\n{}\n\nRules:\n- Never echo the raw request back as a saved fact.\n- For remember: extract only durable canonical facts. If a required value is missing, return ask_missing.\n- For forget: choose only ids from Current candidates. Do not invent ids.\n- For ask_missing: include one concise field label and one concise human-facing prompt.\n- For noop: do not include facts or selected ids.\n- Saved facts must be standalone sentences, not imperative prompts.",
            expected_kind,
            workspace_root.display(),
            request.trim(),
            if supplemental.is_empty() {
                "(none)"
            } else {
                supplemental
            },
            payload
        ),
        "memory_operation_plan",
        &schema,
    )?;

    let response = collect_single_response(provider, llm_request)
        .await
        .context("persistent memory planner LLM request failed")?;
    let content = response
        .content
        .context("persistent memory planner returned no content")?;
    let plan =
        parse_memory_json_response::<MemoryOpPlan>(content.trim(), "persistent memory planner")?;
    validate_memory_op_plan(&plan, expected_kind, candidates)?;
    Ok(plan)
}

fn validate_memory_op_plan(
    plan: &MemoryOpPlan,
    expected_kind: MemoryOpKind,
    candidates: &[MemoryOpCandidate],
) -> Result<()> {
    match plan.kind {
        MemoryOpKind::Remember => {
            if expected_kind != MemoryOpKind::Remember {
                bail!("memory planner returned remember for a non-remember request");
            }
            if plan.facts.is_empty() {
                bail!("memory planner returned remember with no facts");
            }
            if plan
                .facts
                .iter()
                .any(|fact| normalize_whitespace(&fact.fact).is_empty())
            {
                bail!("memory planner returned an empty fact");
            }
        }
        MemoryOpKind::Forget => {
            if expected_kind != MemoryOpKind::Forget {
                bail!("memory planner returned forget for a non-forget request");
            }
            let valid_ids = candidates
                .iter()
                .map(|candidate| candidate.id)
                .collect::<BTreeSet<_>>();
            if plan.selected_ids.iter().any(|id| !valid_ids.contains(id)) {
                bail!("memory planner selected an unknown memory candidate");
            }
        }
        MemoryOpKind::AskMissing => {
            let missing = plan
                .missing
                .as_ref()
                .ok_or_else(|| anyhow!("memory planner returned ask_missing without a prompt"))?;
            if normalize_whitespace(&missing.field).is_empty()
                || normalize_whitespace(&missing.prompt).is_empty()
            {
                bail!("memory planner returned an incomplete missing-field request");
            }
        }
        MemoryOpKind::Noop => {}
    }

    if matches!(plan.kind, MemoryOpKind::AskMissing | MemoryOpKind::Noop)
        && (!plan.facts.is_empty() || !plan.selected_ids.is_empty())
    {
        bail!("memory planner returned extra mutations for a non-mutating plan");
    }

    Ok(())
}

fn memory_plan_facts(plan: &MemoryOpPlan) -> Result<Vec<GroundedFactRecord>> {
    if plan.kind != MemoryOpKind::Remember {
        bail!("memory plan is not a remember operation");
    }

    Ok(plan
        .facts
        .iter()
        .map(|fact| {
            let topic = match fact.topic {
                MemoryPlannedTopic::Preferences => MemoryTopic::Preferences,
                MemoryPlannedTopic::RepositoryFacts => MemoryTopic::RepositoryFacts,
            };
            let source = if fact.source.trim().is_empty() {
                "manual_memory".to_string()
            } else {
                normalize_whitespace(&fact.source)
            };
            GroundedFactRecord {
                fact: truncate_for_fact(&normalize_whitespace(&fact.fact), 180),
                source: encode_topic_source(topic, &source),
            }
        })
        .filter(|fact| !fact.fact.is_empty())
        .collect())
}

fn selected_memory_candidates(
    candidates: &[MemoryOpCandidate],
    selected_ids: &[usize],
) -> Result<Vec<MemoryOpCandidate>> {
    let selected = selected_ids
        .iter()
        .filter_map(|id| {
            candidates
                .iter()
                .find(|candidate| candidate.id == *id)
                .cloned()
        })
        .collect::<Vec<_>>();
    if selected_ids.len() != selected.len() {
        bail!("memory plan selected a missing candidate");
    }
    Ok(selected)
}

fn facts_for_prompt(facts: &[GroundedFactRecord]) -> String {
    if facts.is_empty() {
        return "- none".to_string();
    }

    facts
        .iter()
        .map(|fact| {
            let (_topic, source) = decode_topic_source(&fact.source);
            format!("- [{}] {}", source, fact.fact)
        })
        .collect::<Vec<_>>()
        .join("\n")
}

fn notes_for_prompt(notes: &[MemoryNoteSummary]) -> String {
    if notes.is_empty() {
        return "- none".to_string();
    }

    notes
        .iter()
        .map(|note| {
            let preview = if note.highlights.is_empty() {
                "no extracted highlights".to_string()
            } else {
                note.highlights.join("; ")
            };
            format!("- [{}] {}", note.relative_path, preview)
        })
        .collect::<Vec<_>>()
        .join("\n")
}

fn resolve_memory_model_routes(
    runtime_config: &RuntimeAgentConfig,
    vt_cfg: Option<&VTCodeConfig>,
) -> ResolvedMemoryRoutes {
    let resolution =
        resolve_lightweight_route(runtime_config, vt_cfg, LightweightFeature::Memory, None);
    let primary = memory_model_route_from_resolution(&resolution.primary, runtime_config, vt_cfg);
    let fallback = resolution
        .fallback
        .as_ref()
        .map(|route| memory_model_route_from_resolution(route, runtime_config, vt_cfg));

    ResolvedMemoryRoutes {
        primary,
        fallback,
        warning: resolution.warning,
    }
}

fn memory_model_route_from_resolution(
    route: &crate::llm::ModelRoute,
    runtime_config: &RuntimeAgentConfig,
    vt_cfg: Option<&VTCodeConfig>,
) -> MemoryModelRoute {
    let temperature = if route.model == runtime_config.model
        && route
            .provider_name
            .eq_ignore_ascii_case(runtime_provider_name(runtime_config).as_str())
    {
        0.0
    } else {
        vt_cfg
            .map(|cfg| cfg.agent.small_model.temperature)
            .unwrap_or(0.0)
    };

    MemoryModelRoute {
        provider_name: route.provider_name.clone(),
        model: route.model.clone(),
        temperature,
    }
}

fn log_memory_route_warning(routes: &ResolvedMemoryRoutes) {
    if let Some(warning) = &routes.warning {
        tracing::warn!(warning = %warning, "persistent memory route adjusted");
    }
}

fn create_memory_provider(
    route: &MemoryModelRoute,
    runtime_config: &RuntimeAgentConfig,
    vt_cfg: Option<&VTCodeConfig>,
) -> Result<Box<dyn LLMProvider>> {
    create_provider_for_model_route(
        &crate::llm::ModelRoute {
            provider_name: route.provider_name.clone(),
            model: route.model.clone(),
        },
        runtime_config,
        vt_cfg,
    )
    .context("Failed to initialize persistent memory LLM provider")
}

fn runtime_provider_name(runtime_config: &RuntimeAgentConfig) -> String {
    if !runtime_config.provider.trim().is_empty() {
        return runtime_config.provider.to_lowercase();
    }

    infer_provider_from_model(&runtime_config.model)
        .map(|provider| provider.to_string().to_lowercase())
        .unwrap_or_else(|| "gemini".to_string())
}

fn render_topic_file(topic: MemoryTopic, facts: &[GroundedFactRecord]) -> String {
    let mut output = String::new();
    output.push_str("# ");
    output.push_str(topic.title());
    output.push_str("\n\n");
    output.push_str(topic.description());
    output.push('\n');

    if facts.is_empty() {
        output.push_str("\n- No saved facts yet.\n");
        return output;
    }

    output.push('\n');
    for fact in facts {
        let (_topic, display_source) = decode_topic_source(&fact.source);
        output.push_str("- [");
        output.push_str(display_source.trim());
        output.push_str("] ");
        output.push_str(&fact.fact);
        output.push('\n');
    }

    output
}

fn render_memory_index(
    preferences: &[GroundedFactRecord],
    repository_facts: &[GroundedFactRecord],
    notes: &[MemoryNoteSummary],
    pending_rollouts: usize,
) -> String {
    let mut highlights = preferences
        .iter()
        .chain(repository_facts.iter())
        .cloned()
        .collect::<Vec<_>>();
    let keep_from = highlights.len().saturating_sub(MEMORY_HIGHLIGHT_LIMIT);
    highlights = highlights.into_iter().skip(keep_from).collect();

    let mut output = String::new();
    output.push_str("# VT Code Memory Registry\n\n");
    output.push_str("## Files\n");
    output.push_str("- `memory_summary.md`: Startup-injected summary for future sessions.\n");
    output.push_str("- `preferences.md`: Durable user preferences and workflow notes.\n");
    output.push_str(
        "- `repository-facts.md`: Grounded repository facts and recurring tooling notes.\n",
    );
    output
        .push_str("- `notes/`: User-authored durable notes available to the native memory tool.\n");
    output.push_str("- `rollout_summaries/`: Per-session evidence summaries.\n");
    output.push_str(&format!(
        "\n## Rollout Status\n- Pending rollout summaries: {}\n",
        pending_rollouts
    ));

    output.push_str("\n## Highlights\n");
    if highlights.is_empty() {
        output.push_str("- No persistent notes yet.\n");
    } else {
        for fact in highlights {
            let (_topic, display_source) = decode_topic_source(&fact.source);
            output.push_str("- [");
            output.push_str(display_source.trim());
            output.push_str("] ");
            output.push_str(&fact.fact);
            output.push('\n');
        }
    }

    if !notes.is_empty() {
        output.push_str("\n## Note Files\n");
        for note in notes {
            output.push_str("- ");
            output.push('`');
            output.push_str(&note.relative_path);
            output.push('`');
            if let Some(first) = note.highlights.first() {
                output.push_str(": ");
                output.push_str(first);
            }
            output.push('\n');
        }
    }

    output
}

fn render_memory_summary(
    preferences: &[GroundedFactRecord],
    repository_facts: &[GroundedFactRecord],
    notes: &[MemoryNoteSummary],
) -> String {
    let mut bullets = preferences
        .iter()
        .chain(repository_facts.iter())
        .map(|fact| fact.fact.clone())
        .collect::<Vec<_>>();
    bullets.extend(notes.iter().filter_map(|note| {
        note.highlights
            .first()
            .map(|highlight| format!("Note ({}): {}", note.relative_path, highlight))
    }));
    let keep_from = bullets.len().saturating_sub(MEMORY_HIGHLIGHT_LIMIT);
    bullets = bullets.into_iter().skip(keep_from).collect();
    if bullets.is_empty() {
        bullets.push("No durable memory notes have been consolidated yet.".to_string());
    }
    render_memory_summary_bullets(&bullets)
}

fn render_memory_summary_bullets(bullets: &[String]) -> String {
    let mut output = String::new();
    output.push_str("# VT Code Memory Summary\n\n");
    for bullet in bullets {
        output.push_str("- ");
        output.push_str(bullet.trim());
        output.push('\n');
    }
    output
}

fn render_rollout_summary(classified: &ClassifiedFacts) -> String {
    let mut output = String::new();
    output.push_str("# Rollout Summary\n\n");
    output.push_str(&format!(
        "- Generated: {}\n",
        chrono::Utc::now().to_rfc3339()
    ));
    output.push('\n');

    if classified.total() == 0 {
        output.push_str("- No durable facts captured.\n");
        return output;
    }

    for fact in classified
        .preferences
        .iter()
        .chain(classified.repository_facts.iter())
    {
        output.push_str("- [");
        output.push_str(&fact.source);
        output.push_str("] ");
        output.push_str(&fact.fact);
        output.push('\n');
    }

    output
}

fn unique_rollout_id() -> String {
    let millis = SystemTime::now()
        .duration_since(UNIX_EPOCH)
        .unwrap_or_default()
        .as_millis();
    format!("rollout-{millis}")
}

struct MemoryLock {
    path: PathBuf,
}

impl MemoryLock {
    async fn acquire(path: &Path) -> Result<Self> {
        for _ in 0..LOCK_RETRY_ATTEMPTS {
            match tokio::fs::OpenOptions::new()
                .create_new(true)
                .write(true)
                .open(path)
                .await
            {
                Ok(_) => {
                    return Ok(Self {
                        path: path.to_path_buf(),
                    });
                }
                Err(err) if err.kind() == std::io::ErrorKind::AlreadyExists => {
                    sleep(Duration::from_millis(LOCK_RETRY_DELAY_MS)).await;
                }
                Err(err) => {
                    return Err(err)
                        .with_context(|| format!("Failed to acquire {}", path.display()));
                }
            }
        }

        Err(anyhow::anyhow!(
            "Timed out waiting for persistent memory lock {}",
            path.display()
        ))
    }
}

impl Drop for MemoryLock {
    fn drop(&mut self) {
        let _ = std::fs::remove_file(&self.path);
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::config::models::ModelId;
    use crate::llm::provider::{
        FinishReason, LLMError, LLMNormalizedStream, LLMProvider, LLMRequest, LLMResponse,
        NormalizedStreamEvent,
    };
    use crate::llm::resolve_api_key_for_model_route;
    use async_trait::async_trait;
    use futures::stream;
    use std::sync::Mutex;
    use tempfile::tempdir;

    struct StaticProvider {
        response: &'static str,
        supports_structured_output: bool,
        last_request: Mutex<Option<LLMRequest>>,
    }

    impl StaticProvider {
        fn new(response: &'static str) -> Self {
            Self {
                response,
                supports_structured_output: true,
                last_request: Mutex::new(None),
            }
        }

        fn prompt_only_json(response: &'static str) -> Self {
            Self {
                response,
                supports_structured_output: false,
                last_request: Mutex::new(None),
            }
        }

        fn last_request(&self) -> LLMRequest {
            self.last_request
                .lock()
                .expect("request lock")
                .clone()
                .expect("request recorded")
        }
    }

    #[async_trait]
    impl LLMProvider for StaticProvider {
        fn name(&self) -> &str {
            "static"
        }

        async fn generate(
            &self,
            request: LLMRequest,
        ) -> std::result::Result<LLMResponse, LLMError> {
            *self.last_request.lock().expect("request lock") = Some(request);
            Ok(LLMResponse::new("stub-model", self.response))
        }

        fn supported_models(&self) -> Vec<String> {
            vec!["stub-model".to_string()]
        }

        fn validate_request(&self, _request: &LLMRequest) -> std::result::Result<(), LLMError> {
            Ok(())
        }

        fn supports_structured_output(&self, _model: &str) -> bool {
            self.supports_structured_output
        }
    }

    fn message_history() -> Vec<Message> {
        vec![
            Message::user("I prefer cargo nextest".to_string()),
            Message::tool_response_with_origin(
                "call-1".to_string(),
                serde_json::json!({"summary":"Tests live under vtcode-core/tests"}).to_string(),
                "unified_search".to_string(),
            ),
        ]
    }

    fn runtime_config(workspace: &Path) -> RuntimeAgentConfig {
        RuntimeAgentConfig {
            model: "gpt-5".to_string(),
            api_key: "test-key".to_string(),
            provider: "openai".to_string(),
            openai_chatgpt_auth: None,
            api_key_env: "OPENAI_API_KEY".to_string(),
            workspace: workspace.to_path_buf(),
            verbose: false,
            quiet: false,
            theme: "ciapre".to_string(),
            reasoning_effort: crate::config::types::ReasoningEffortLevel::None,
            ui_surface: crate::config::types::UiSurfacePreference::Auto,
            prompt_cache: crate::config::PromptCachingConfig::default(),
            model_source: crate::config::types::ModelSelectionSource::WorkspaceConfig,
            custom_api_keys: Default::default(),
            checkpointing_enabled: true,
            checkpointing_storage_dir: None,
            checkpointing_max_snapshots: 10,
            checkpointing_max_age_days: Some(7),
            max_conversation_turns: 10,
            model_behavior: None,
        }
    }

    fn enabled_memory_config() -> PersistentMemoryConfig {
        PersistentMemoryConfig {
            enabled: true,
            ..PersistentMemoryConfig::default()
        }
    }

    fn enabled_memory_config_for(workspace: &Path) -> PersistentMemoryConfig {
        PersistentMemoryConfig {
            enabled: true,
            directory_override: Some(workspace.join(".memory").display().to_string()),
            ..PersistentMemoryConfig::default()
        }
    }

    #[test]
    fn dedup_latest_facts_extracts_user_and_tool_memory() {
        let facts = dedup_latest_facts(&message_history(), 8);
        assert_eq!(facts.len(), 2);
        assert!(facts.iter().any(|fact| fact.source == "user_assertion"));
        assert!(
            facts
                .iter()
                .any(|fact| fact.source == "tool:unified_search")
        );
    }

    #[test]
    fn maybe_extract_user_fact_keeps_durable_self_facts() {
        let name = maybe_extract_user_fact(&Message::user("My name is Vinh Nguyen".to_string()))
            .expect("name should be extracted");
        assert_eq!(name.source, "user_assertion");
        assert_eq!(name.fact, "My name is Vinh Nguyen");

        let preference = maybe_extract_user_fact(&Message::user(
            "I prefer cargo nextest for test runs".to_string(),
        ))
        .expect("preference should be extracted");
        assert_eq!(preference.source, "user_assertion");
        assert_eq!(preference.fact, "I prefer cargo nextest for test runs");
    }

    #[test]
    fn maybe_extract_user_fact_ignores_transient_first_person_task_chatter() {
        assert!(
            maybe_extract_user_fact(&Message::user(
                "I am debugging a failing vtcode-core test".to_string(),
            ))
            .is_none()
        );
        assert!(
            maybe_extract_user_fact(&Message::user(
                "My tests are still failing after the refactor".to_string(),
            ))
            .is_none()
        );
    }

    #[test]
    fn maybe_extract_user_fact_keeps_authored_notes_after_polite_prefixes() {
        let note = maybe_extract_user_fact(&Message::user(
            "Please note that I prefer pnpm in JavaScript workspaces".to_string(),
        ))
        .expect("authored note should be extracted");
        assert_eq!(note.source, "user_assertion");
        assert_eq!(note.fact, "I prefer pnpm in JavaScript workspaces");
    }

    #[test]
    fn maybe_extract_user_fact_ignores_memory_prompts_and_questions() {
        assert!(
            maybe_extract_user_fact(&Message::user(
                "remember that I prefer cargo nextest".to_string(),
            ))
            .is_none()
        );
        assert!(
            maybe_extract_user_fact(&Message::user("do you remember my name?".to_string()))
                .is_none()
        );
        assert!(
            maybe_extract_user_fact(&Message::user(
                "what do you remember about this repo?".to_string(),
            ))
            .is_none()
        );
    }

    #[tokio::test]
    async fn finalize_persistent_memory_ignores_explicit_memory_prompts() {
        let workspace = tempdir().expect("workspace");
        std::fs::write(workspace.path().join(".git"), "gitdir: /tmp/git").expect("git marker");

        let mut runtime = runtime_config(workspace.path());
        runtime.provider = "missing-provider".to_string();

        let mut vt_cfg = VTCodeConfig::default();
        vt_cfg.agent.persistent_memory = enabled_memory_config_for(workspace.path());

        let report = finalize_persistent_memory(
            &runtime,
            Some(&vt_cfg),
            &[Message::user(
                "remember that I prefer cargo nextest".to_string(),
            )],
        )
        .await
        .expect("finalize should skip ignored prompts");

        assert!(report.is_none());
    }

    #[tokio::test]
    async fn finalize_persistent_memory_skips_existing_authored_note_duplicates() {
        let workspace = tempdir().expect("workspace");
        std::fs::write(workspace.path().join(".git"), "gitdir: /tmp/git").expect("git marker");

        let mut runtime = runtime_config(workspace.path());
        runtime.provider = "missing-provider".to_string();

        let mut vt_cfg = VTCodeConfig::default();
        vt_cfg.agent.persistent_memory = enabled_memory_config_for(workspace.path());

        let memory_dir =
            resolve_persistent_memory_dir(&vt_cfg.agent.persistent_memory, workspace.path())
                .expect("memory dir")
                .expect("resolved dir");
        let files = PersistentMemoryFiles::new(memory_dir);
        std::fs::create_dir_all(&files.directory).expect("dir");
        std::fs::write(
            &files.preferences_file,
            "# Preferences\n\n- [user_assertion] I prefer cargo nextest for test runs\n",
        )
        .expect("prefs");

        let report = finalize_persistent_memory(
            &runtime,
            Some(&vt_cfg),
            &[Message::user(
                "Please note that I prefer cargo nextest for test runs".to_string(),
            )],
        )
        .await
        .expect("existing duplicate should skip routing");

        assert!(report.is_none());
    }

    #[tokio::test]
    async fn llm_classification_rewrites_and_routes_candidates() {
        let workspace = tempdir().expect("workspace");
        let provider = StaticProvider::new(
            r#"{
              "keep": [
                {"id": 0, "topic": "preferences", "fact": "Prefer cargo nextest for test runs"},
                {"id": 1, "topic": "repository_facts", "fact": "Tests live under vtcode-core/tests"}
              ]
            }"#,
        );
        let route = MemoryModelRoute {
            provider_name: "stub".to_string(),
            model: "stub-model".to_string(),
            temperature: 0.0,
        };
        let classified = classify_facts_with_provider(
            &provider,
            &route,
            workspace.path(),
            &dedup_latest_facts(&message_history(), 8),
        )
        .await
        .expect("classify");

        assert_eq!(classified.preferences.len(), 1);
        assert_eq!(classified.repository_facts.len(), 1);
        assert_eq!(
            classified.preferences[0].fact,
            "Prefer cargo nextest for test runs"
        );
        assert_eq!(
            classified.repository_facts[0].fact,
            "Tests live under vtcode-core/tests"
        );
    }

    #[tokio::test]
    async fn remember_planner_requests_missing_details() {
        let workspace = tempdir().expect("workspace");
        let provider = StaticProvider::new(
            r#"{
              "kind": "ask_missing",
              "facts": [],
              "selected_ids": [],
              "missing": {"field": "name", "prompt": "What name should VT Code remember?"},
              "message": null
            }"#,
        );
        let route = MemoryModelRoute {
            provider_name: "stub".to_string(),
            model: "stub-model".to_string(),
            temperature: 0.0,
        };
        let plan = plan_memory_operation_with_provider(
            &provider,
            &route,
            workspace.path(),
            MemoryOpKind::Remember,
            "save to memory and remember my name",
            None,
            &[],
        )
        .await
        .expect("plan");

        assert_eq!(plan.kind, MemoryOpKind::AskMissing);
        assert_eq!(
            plan.missing.as_ref().map(|missing| missing.field.as_str()),
            Some("name")
        );
    }

    #[tokio::test]
    async fn forget_planner_selects_exact_candidate_ids() {
        let workspace = tempdir().expect("workspace");
        let provider = StaticProvider::new(
            r#"{
              "kind": "forget",
              "facts": [],
              "selected_ids": [1],
              "missing": null,
              "message": "Remove the pnpm preference."
            }"#,
        );
        let route = MemoryModelRoute {
            provider_name: "stub".to_string(),
            model: "stub-model".to_string(),
            temperature: 0.0,
        };
        let candidates = vec![
            MemoryOpCandidate {
                id: 0,
                source: "manual_memory".to_string(),
                fact: "Prefer cargo nextest".to_string(),
            },
            MemoryOpCandidate {
                id: 1,
                source: "manual_memory".to_string(),
                fact: "Prefer pnpm".to_string(),
            },
        ];
        let plan = plan_memory_operation_with_provider(
            &provider,
            &route,
            workspace.path(),
            MemoryOpKind::Forget,
            "forget my pnpm preference",
            None,
            &candidates,
        )
        .await
        .expect("plan");

        assert_eq!(plan.kind, MemoryOpKind::Forget);
        assert_eq!(plan.selected_ids, vec![1]);
    }

    #[tokio::test]
    async fn classification_falls_back_to_prompt_only_json_when_native_schema_is_unsupported() {
        let workspace = tempdir().expect("workspace");
        let provider = StaticProvider::prompt_only_json(
            "Here is the JSON:\n```json\n{\n  \"keep\": [\n    {\"id\": 0, \"topic\": \"preferences\", \"fact\": \"Prefer cargo nextest for test runs\"}\n  ]\n}\n```",
        );
        let route = MemoryModelRoute {
            provider_name: "stub".to_string(),
            model: "stub-model".to_string(),
            temperature: 0.0,
        };

        let classified = classify_facts_with_provider(
            &provider,
            &route,
            workspace.path(),
            &dedup_latest_facts(&message_history(), 8),
        )
        .await
        .expect("classify");

        assert_eq!(classified.preferences.len(), 1);
        let request = provider.last_request();
        assert!(request.output_format.is_none());
        assert!(
            request.messages[0]
                .content
                .as_text()
                .contains("Return JSON only.")
        );
    }

    #[tokio::test]
    async fn planner_falls_back_to_prompt_only_json_when_native_schema_is_unsupported() {
        let workspace = tempdir().expect("workspace");
        let provider = StaticProvider::prompt_only_json(
            "```json\n{\n  \"kind\": \"ask_missing\",\n  \"facts\": [],\n  \"selected_ids\": [],\n  \"missing\": {\"field\": \"name\", \"prompt\": \"What name should VT Code remember?\"},\n  \"message\": null\n}\n```",
        );
        let route = MemoryModelRoute {
            provider_name: "stub".to_string(),
            model: "stub-model".to_string(),
            temperature: 0.0,
        };

        let plan = plan_memory_operation_with_provider(
            &provider,
            &route,
            workspace.path(),
            MemoryOpKind::Remember,
            "remember my name",
            None,
            &[],
        )
        .await
        .expect("plan");

        assert_eq!(plan.kind, MemoryOpKind::AskMissing);
        let request = provider.last_request();
        assert!(request.output_format.is_none());
        assert!(
            request.messages[0]
                .content
                .as_text()
                .contains("Return JSON only.")
        );
    }

    #[derive(Clone)]
    struct StreamingOnlyMemoryProvider {
        response: &'static str,
    }

    #[async_trait]
    impl LLMProvider for StreamingOnlyMemoryProvider {
        fn name(&self) -> &str {
            "streaming-memory"
        }

        fn supports_streaming(&self) -> bool {
            true
        }

        fn supports_non_streaming(&self, _model: &str) -> bool {
            false
        }

        async fn generate(
            &self,
            _request: LLMRequest,
        ) -> std::result::Result<LLMResponse, LLMError> {
            panic!("generate should not be called for streaming-only provider")
        }

        async fn stream_normalized(
            &self,
            _request: LLMRequest,
        ) -> std::result::Result<LLMNormalizedStream, LLMError> {
            Ok(Box::pin(stream::iter(vec![Ok(
                NormalizedStreamEvent::Done {
                    response: Box::new(LLMResponse {
                        content: Some(self.response.to_string()),
                        model: "stub-model".to_string(),
                        tool_calls: None,
                        usage: None,
                        finish_reason: FinishReason::Stop,
                        reasoning: None,
                        reasoning_details: None,
                        organization_id: None,
                        request_id: None,
                        tool_references: Vec::new(),
                    }),
                },
            )])))
        }

        fn supported_models(&self) -> Vec<String> {
            vec!["stub-model".to_string()]
        }

        fn validate_request(&self, _request: &LLMRequest) -> std::result::Result<(), LLMError> {
            Ok(())
        }
    }

    #[tokio::test]
    async fn planner_supports_streaming_only_provider() {
        let workspace = tempdir().expect("workspace");
        let provider = StreamingOnlyMemoryProvider {
            response: "{\"kind\":\"ask_missing\",\"facts\":[],\"selected_ids\":[],\"missing\":{\"field\":\"name\",\"prompt\":\"What name should VT Code remember?\"},\"message\":null}",
        };
        let route = MemoryModelRoute {
            provider_name: "stub".to_string(),
            model: "stub-model".to_string(),
            temperature: 0.0,
        };

        let plan = plan_memory_operation_with_provider(
            &provider,
            &route,
            workspace.path(),
            MemoryOpKind::Remember,
            "remember my name",
            None,
            &[],
        )
        .await
        .expect("streaming planner should succeed");

        assert_eq!(plan.kind, MemoryOpKind::AskMissing);
    }

    #[tokio::test]
    async fn summary_falls_back_to_prompt_only_json_when_native_schema_is_unsupported() {
        let workspace = tempdir().expect("workspace");
        let provider = StaticProvider::prompt_only_json(
            "Summary:\n{\"bullets\":[\"Prefer cargo nextest\",\"Tests live under vtcode-core/tests\"]}",
        );
        let route = MemoryModelRoute {
            provider_name: "stub".to_string(),
            model: "stub-model".to_string(),
            temperature: 0.0,
        };

        let summary = summarize_memory_with_provider(
            &provider,
            &route,
            workspace.path(),
            &[GroundedFactRecord {
                fact: "Prefer cargo nextest".to_string(),
                source: encode_topic_source(MemoryTopic::Preferences, "manual_memory"),
            }],
            &[GroundedFactRecord {
                fact: "Tests live under vtcode-core/tests".to_string(),
                source: encode_topic_source(MemoryTopic::RepositoryFacts, "tool:unified_search"),
            }],
            &[],
        )
        .await
        .expect("summary");

        assert!(summary.contains("Prefer cargo nextest"));
        let request = provider.last_request();
        assert!(request.output_format.is_none());
    }

    #[tokio::test]
    async fn rebuild_summary_uses_summary_file_not_registry() {
        let workspace = tempdir().expect("workspace");
        std::fs::write(workspace.path().join(".git"), "gitdir: /tmp/git").expect("git marker");
        let memory_config = enabled_memory_config_for(workspace.path());
        let mut vt_cfg = VTCodeConfig::default();
        vt_cfg.agent.persistent_memory = memory_config.clone();

        let memory_dir = resolve_persistent_memory_dir(&memory_config, workspace.path())
            .expect("memory dir")
            .expect("resolved dir");
        let files = PersistentMemoryFiles::new(memory_dir.clone());
        let mut created_files = Vec::new();
        ensure_memory_layout(&files, &mut created_files)
            .await
            .expect("layout");
        tokio::fs::write(
            &files.preferences_file,
            render_topic_file(
                MemoryTopic::Preferences,
                &[GroundedFactRecord {
                    fact: "Prefer cargo nextest".to_string(),
                    source: encode_topic_source(MemoryTopic::Preferences, "manual_memory"),
                }],
            ),
        )
        .await
        .expect("write prefs");

        let excerpt = read_persistent_memory_excerpt(&memory_config, workspace.path())
            .await
            .expect("excerpt")
            .expect("present");
        assert!(excerpt.contents.contains("No durable memory notes"));

        rebuild_persistent_memory_summary(&runtime_config(workspace.path()), Some(&vt_cfg))
            .await
            .expect("rebuild")
            .expect("report");

        let excerpt = read_persistent_memory_excerpt(&memory_config, workspace.path())
            .await
            .expect("excerpt")
            .expect("present");
        assert!(excerpt.contents.contains("Prefer cargo nextest"));
    }

    #[tokio::test]
    async fn scaffold_creates_memory_layout_even_when_disabled() {
        let workspace = tempdir().expect("workspace");
        let config = PersistentMemoryConfig {
            enabled: false,
            directory_override: Some(workspace.path().join(".memory").display().to_string()),
            ..PersistentMemoryConfig::default()
        };

        let status = scaffold_persistent_memory(&config, workspace.path())
            .await
            .expect("scaffold succeeds")
            .expect("status");

        assert!(!status.enabled);
        assert!(status.summary_file.exists());
        assert!(status.memory_file.exists());
        assert!(status.preferences_file.exists());
        assert!(status.repository_facts_file.exists());
        assert!(status.notes_dir.exists());
        assert!(status.rollout_summaries_dir.exists());
    }

    #[tokio::test]
    async fn rebuild_generated_files_include_notes_as_canonical_inputs() {
        let workspace = tempdir().expect("workspace");
        let config = PersistentMemoryConfig {
            enabled: true,
            directory_override: Some(workspace.path().join(".memory").display().to_string()),
            ..PersistentMemoryConfig::default()
        };

        scaffold_persistent_memory(&config, workspace.path())
            .await
            .expect("scaffold")
            .expect("status");
        let memory_dir = resolve_persistent_memory_dir(&config, workspace.path())
            .expect("memory dir")
            .expect("resolved dir");
        let files = PersistentMemoryFiles::new(memory_dir);
        tokio::fs::write(
            files.notes_dir.join("project.md"),
            "# Project Notes\n\n- Keep Anthropic memory backed by shared storage.\n",
        )
        .await
        .expect("write note");

        rebuild_generated_memory_files(&config, workspace.path())
            .await
            .expect("rebuild");

        let summary = tokio::fs::read_to_string(&files.summary_file)
            .await
            .expect("summary");
        let index = tokio::fs::read_to_string(&files.memory_file)
            .await
            .expect("index");

        assert!(summary.contains("Keep Anthropic memory backed by shared storage"));
        assert!(index.contains("## Note Files"), "{index}");
        assert!(index.contains("Keep Anthropic memory backed by shared storage"));
    }

    #[tokio::test]
    async fn remember_plan_persists_normalized_manual_memory_update() {
        let workspace = tempdir().expect("workspace");
        std::fs::write(workspace.path().join(".git"), "gitdir: /tmp/git").expect("git marker");
        let mut vt_cfg = VTCodeConfig::default();
        vt_cfg.agent.persistent_memory = enabled_memory_config_for(workspace.path());
        let plan = MemoryOpPlan {
            kind: MemoryOpKind::Remember,
            facts: vec![MemoryPlannedFact {
                topic: MemoryPlannedTopic::Preferences,
                fact: "Prefer pnpm for workspace package management.".to_string(),
                source: "manual_memory".to_string(),
            }],
            selected_ids: Vec::new(),
            missing: None,
            message: None,
        };

        let report =
            persist_remembered_memory_plan(&runtime_config(workspace.path()), Some(&vt_cfg), &plan)
                .await
                .expect("remember plan")
                .expect("report");

        assert_eq!(report.added_facts, 1);
        let excerpt =
            read_persistent_memory_excerpt(&vt_cfg.agent.persistent_memory, workspace.path())
                .await
                .expect("excerpt")
                .expect("present");
        assert!(excerpt.contents.contains("Prefer pnpm"));
    }

    #[tokio::test]
    async fn forget_planned_matches_remove_notes_from_memory_files() {
        let workspace = tempdir().expect("workspace");
        std::fs::write(workspace.path().join(".git"), "gitdir: /tmp/git").expect("git marker");
        let runtime = runtime_config(workspace.path());
        let mut vt_cfg = VTCodeConfig::default();
        vt_cfg.agent.persistent_memory = enabled_memory_config_for(workspace.path());
        let remember_plan = MemoryOpPlan {
            kind: MemoryOpKind::Remember,
            facts: vec![MemoryPlannedFact {
                topic: MemoryPlannedTopic::Preferences,
                fact: "Prefer pnpm for workspace package management.".to_string(),
                source: "manual_memory".to_string(),
            }],
            selected_ids: Vec::new(),
            missing: None,
            message: None,
        };

        persist_remembered_memory_plan(&runtime, Some(&vt_cfg), &remember_plan)
            .await
            .expect("remember plan")
            .expect("report");

        let matches = find_persistent_memory_matches(
            &vt_cfg.agent.persistent_memory,
            workspace.path(),
            "pnpm",
        )
        .await
        .expect("find matches")
        .expect("enabled");
        assert!(!matches.is_empty());

        let candidates =
            list_persistent_memory_candidates(&vt_cfg.agent.persistent_memory, workspace.path())
                .await
                .expect("list")
                .expect("enabled")
                .into_iter()
                .enumerate()
                .map(|(index, entry)| MemoryOpCandidate {
                    id: index,
                    source: entry.source,
                    fact: entry.fact,
                })
                .collect::<Vec<_>>();
        let plan = MemoryOpPlan {
            kind: MemoryOpKind::Forget,
            facts: Vec::new(),
            selected_ids: vec![0],
            missing: None,
            message: None,
        };

        let report =
            forget_planned_persistent_memory_matches(&runtime, Some(&vt_cfg), &candidates, &plan)
                .await
                .expect("forget plan")
                .expect("report");
        assert!(report.removed_facts >= 1);

        let matches = find_persistent_memory_matches(
            &vt_cfg.agent.persistent_memory,
            workspace.path(),
            "pnpm",
        )
        .await
        .expect("find matches")
        .expect("enabled");
        assert!(matches.is_empty());

        let excerpt =
            read_persistent_memory_excerpt(&vt_cfg.agent.persistent_memory, workspace.path())
                .await
                .expect("excerpt")
                .expect("present");
        assert!(!excerpt.contents.contains("Prefer pnpm"));
    }

    #[test]
    fn cleanup_status_flags_legacy_prompt_lines() {
        let workspace = tempdir().expect("workspace");
        let memory_config = enabled_memory_config_for(workspace.path());
        let memory_dir = resolve_persistent_memory_dir(&memory_config, workspace.path())
            .expect("memory dir")
            .expect("resolved dir");
        let files = PersistentMemoryFiles::new(memory_dir);
        std::fs::create_dir_all(&files.directory).expect("dir");
        std::fs::create_dir_all(&files.rollout_summaries_dir).expect("rollout dir");
        std::fs::write(
            &files.preferences_file,
            "# Preferences\n\n- [user_assertion] save to memory and remember my name\n",
        )
        .expect("prefs");
        std::fs::write(
            &files.summary_file,
            "# VT Code Memory Summary\n\n- {\"query\":\"pnpm\"}\n",
        )
        .expect("summary");

        let status = detect_memory_cleanup_status(&files).expect("status");
        assert!(status.needed);
        assert!(status.suspicious_facts >= 1);
        assert!(status.suspicious_summary_lines >= 1);
    }

    #[test]
    fn cleanup_status_ignores_normalized_user_assertion_fact() {
        let workspace = tempdir().expect("workspace");
        let memory_config = enabled_memory_config_for(workspace.path());
        let memory_dir = resolve_persistent_memory_dir(&memory_config, workspace.path())
            .expect("memory dir")
            .expect("resolved dir");
        let files = PersistentMemoryFiles::new(memory_dir);
        std::fs::create_dir_all(&files.directory).expect("dir");
        std::fs::write(
            &files.preferences_file,
            "# Preferences\n\n- [user_assertion] My name is Vinh Nguyen\n",
        )
        .expect("prefs");

        let status = detect_memory_cleanup_status(&files).expect("status");
        assert!(!status.needed);
        assert_eq!(status.suspicious_facts, 0);
        assert_eq!(status.suspicious_summary_lines, 0);
    }

    #[test]
    fn cleanup_status_ignores_embedded_remember_word_in_fact() {
        let workspace = tempdir().expect("workspace");
        let memory_config = enabled_memory_config_for(workspace.path());
        let memory_dir = resolve_persistent_memory_dir(&memory_config, workspace.path())
            .expect("memory dir")
            .expect("resolved dir");
        let files = PersistentMemoryFiles::new(memory_dir);
        std::fs::create_dir_all(&files.directory).expect("dir");
        std::fs::write(
            &files.repository_facts_file,
            "# Repository Facts\n\n- [repository_fact] The docs remember prior design decisions in AGENTS.md.\n",
        )
        .expect("facts");

        let status = detect_memory_cleanup_status(&files).expect("status");
        assert!(!status.needed);
        assert_eq!(status.suspicious_facts, 0);
    }

    #[test]
    fn resolve_memory_model_route_prefers_explicit_small_model_provider() {
        let workspace = tempdir().expect("workspace");
        let runtime = runtime_config(workspace.path());
        let mut vt_cfg = VTCodeConfig::default();
        vt_cfg.agent.small_model.enabled = true;
        vt_cfg.agent.small_model.use_for_memory = true;
        vt_cfg.agent.small_model.model = "claude-4-5-haiku".to_string();

        let routes = resolve_memory_model_routes(&runtime, Some(&vt_cfg));

        assert_eq!(routes.primary.provider_name, "openai");
        assert_eq!(routes.primary.model, ModelId::GPT5Mini.as_str());
        assert!(routes.warning.is_some());
    }

    #[test]
    fn resolve_memory_route_api_key_uses_runtime_key_for_active_provider() {
        let workspace = tempdir().expect("workspace");
        let route = MemoryModelRoute {
            provider_name: "openai".to_string(),
            model: "gpt-5-mini".to_string(),
            temperature: 0.1,
        };

        let api_key = resolve_api_key_for_model_route(
            &crate::llm::ModelRoute {
                provider_name: route.provider_name.clone(),
                model: route.model.clone(),
            },
            &runtime_config(workspace.path()),
        );

        assert_eq!(api_key.as_deref(), Some("test-key"));
    }

    #[test]
    fn resolves_project_scoped_memory_directory() {
        let workspace = tempdir().expect("workspace");
        std::fs::write(workspace.path().join(".vtcode-project"), "renamed-project")
            .expect("project name");
        let config = enabled_memory_config();
        let directory = resolve_persistent_memory_dir(&config, workspace.path())
            .expect("memory dir")
            .expect("memory dir should resolve");
        assert!(
            directory
                .to_string_lossy()
                .contains(".vtcode/projects/renamed-project/memory")
        );
    }

    #[test]
    fn migrates_legacy_memory_into_empty_target_directory() {
        let root = tempdir().expect("root");
        let legacy_dir = root.path().join("legacy/projects/repo/memory");
        let target_dir = root.path().join("home/.vtcode/projects/repo/memory");
        std::fs::create_dir_all(legacy_dir.join(ROLLOUT_SUMMARIES_DIRNAME)).expect("legacy dir");
        std::fs::write(
            legacy_dir.join(PREFERENCES_FILENAME),
            render_topic_file(
                MemoryTopic::Preferences,
                &[GroundedFactRecord {
                    fact: "Prefer cargo nextest".to_string(),
                    source: encode_topic_source(MemoryTopic::Preferences, "manual_memory"),
                }],
            ),
        )
        .expect("legacy prefs");

        migrate_legacy_memory_dir(&legacy_dir, &target_dir).expect("migrate");

        assert!(!legacy_dir.exists());
        let migrated =
            std::fs::read_to_string(target_dir.join(PREFERENCES_FILENAME)).expect("target prefs");
        assert!(migrated.contains("Prefer cargo nextest"));
    }

    #[test]
    fn migrates_legacy_memory_over_scaffold_only_target() {
        let root = tempdir().expect("root");
        let legacy_dir = root.path().join("legacy/projects/repo/memory");
        let target_dir = root.path().join("home/.vtcode/projects/repo/memory");
        std::fs::create_dir_all(legacy_dir.join(ROLLOUT_SUMMARIES_DIRNAME)).expect("legacy dir");
        std::fs::write(
            legacy_dir.join(REPOSITORY_FACTS_FILENAME),
            render_topic_file(
                MemoryTopic::RepositoryFacts,
                &[GroundedFactRecord {
                    fact: "Tests live under vtcode-core/tests".to_string(),
                    source: encode_topic_source(
                        MemoryTopic::RepositoryFacts,
                        "tool:unified_search",
                    ),
                }],
            ),
        )
        .expect("legacy facts");

        std::fs::create_dir_all(target_dir.join(ROLLOUT_SUMMARIES_DIRNAME)).expect("target dir");
        std::fs::write(
            target_dir.join(PREFERENCES_FILENAME),
            render_topic_file(MemoryTopic::Preferences, &[]),
        )
        .expect("target prefs");
        std::fs::write(
            target_dir.join(REPOSITORY_FACTS_FILENAME),
            render_topic_file(MemoryTopic::RepositoryFacts, &[]),
        )
        .expect("target facts");
        std::fs::write(
            target_dir.join(MEMORY_FILENAME),
            render_memory_index(&[], &[], &[], 0),
        )
        .expect("target memory");
        std::fs::write(
            target_dir.join(MEMORY_SUMMARY_FILENAME),
            render_memory_summary(&[], &[], &[]),
        )
        .expect("target summary");

        migrate_legacy_memory_dir(&legacy_dir, &target_dir).expect("migrate");

        assert!(!legacy_dir.exists());
        let migrated = std::fs::read_to_string(target_dir.join(REPOSITORY_FACTS_FILENAME))
            .expect("target facts");
        assert!(migrated.contains("Tests live under vtcode-core/tests"));
    }
}