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
//! Git-backed write tools (GWS.12).
//!
//! Mirrors the mutating surface of [`crate::FileTools`] + [`crate::BatchTools`]
//! but routes every change through the git substrate's
//! [`turbovault_git::VaultRepo::commit_changeset`]. Reads still go through the
//! shared [`VaultManager`] — working tree == HEAD, so working-tree reads agree
//! with the git tip.
//!
//! Selected per vault by [`turbovault_core::config::WriteBackend::Git`]. Lives
//! beside `FileTools` only until the cutover (GWS.15), then this becomes the
//! sole write surface.
//!
//! **Discipline (do not violate):** `GitFileTools` reads from `VaultManager`
//! but must **never** call its mutators (`write_file`/`edit_file`/`delete_file`
//! /`move_file`). All mutations route through [`VaultRepo::commit_changeset`].
use crate::file_tools::{NoteInfo, WriteMode};
use futures::future::BoxFuture;
use std::path::PathBuf;
use std::sync::Arc;
use turbovault_batch::{BatchOperation, BatchResult, OperationRecord};
use turbovault_core::prelude::*;
use turbovault_git::{Changeset, CommitHook, CommitLocks, Oid, VaultRepo};
use turbovault_vault::{EditEngine, EditResult, VaultManager};
/// turbovault-lqr: result of an atomic `move_file_with_link_updates`. The
/// rename + every link-source rewrite landed as ONE commit. Reports which
/// sources were rewritten so the caller can surface the diff to the user.
#[derive(Debug, Clone, serde::Serialize)]
pub struct MoveWithLinksResult {
pub from: String,
pub to: String,
/// Vault-relative paths of source files whose inbound wikilinks were
/// rewritten in the same commit.
pub link_sources_updated: Vec<String>,
}
/// Callback invoked **before** returning a `ConcurrencyError` from
/// the internal `GitFileTools::apply_txn` path (GWS.14b). The MCP server installs one that
/// drains the per-vault reindex queue — so the agent's re-read (which the
/// error tells it to do) sees a coherent graph + search state, not the
/// pre-conflict snapshot.
///
/// Boxed-future shape rather than a plain `async fn` so the type can be
/// stored on the `GitFileTools` struct without each call site naming an
/// `impl Future`.
pub type CasCollisionFlush = Arc<dyn Fn() -> BoxFuture<'static, Result<()>> + Send + Sync>;
/// turbovault-a0l (PERF-1): a per-vault cached substrate handle. `VaultRepo`
/// wraps a `git2::Repository` which is `Send + !Sync` (libgit2 raw pointers),
/// so it lives behind a `std::sync::Mutex`; the `Arc` lets the MCP server cache
/// one handle per vault and hand a clone to each `GitFileTools`. Reusing it
/// elides the ~140µs `Repository::open` (config re-parse + odb/strmap setup)
/// that otherwise fired on every write. The `Mutex` serializes commit sections
/// exactly where `CommitLocks` already does, so net concurrency is unchanged,
/// and cross-process CAS stays safe (libgit2 re-reads refs under `lock_ref` —
/// guarded by `cas::tests::reused_handle_detects_external_ref_advance_no_lost_update`).
pub type CachedRepo = Arc<std::sync::Mutex<VaultRepo>>;
/// Write-side tools backed by the git substrate.
///
/// Holds the vault path + a shared `CommitLocks` registry rather than an
/// `Arc<VaultRepo>` — `VaultRepo` wraps a `git2::Repository` which is `!Sync`
/// (raw pointer), so it cannot live inside an `async fn` future that needs
/// to be `Send`. The substrate handle is opened fresh inside a
/// `spawn_blocking` task per call (open is ~µs); the shared `CommitLocks`
/// keeps cross-call commit-section serialization intact.
#[derive(Clone)]
pub struct GitFileTools {
pub manager: Arc<VaultManager>,
pub vault_path: PathBuf,
pub commit_locks: Arc<CommitLocks>,
/// Optional post-commit hook installed on every `VaultRepo` opened
/// inside `apply_txn`. Plumbed for GWS.14 lazy GSU: the MCP server
/// passes a closure that pushes the new commit onto a per-vault
/// `ReindexQueue`. `None` = no reindex wiring (acceptable for tests
/// that don't care about derived state).
pub commit_hook: Option<CommitHook>,
/// Optional flush callback fired BEFORE returning a `ConcurrencyError`
/// (GWS.14b). Drains the reindex queue so the agent's re-read sees
/// coherent derived state. `None` = skip flush; callers see the raw
/// concurrency error and the graph stays as stale as the last
/// flush-on-query did.
pub flush_on_collision: Option<CasCollisionFlush>,
/// turbovault-lri: when `false`, every mutation pre-checks each
/// touched path against the worktree's `.gitignore` matcher and
/// refuses the changeset if any path would be ignored. Default
/// `true` preserves pre-lri "always-write" behavior. Wired from
/// `VaultGitConfig::include_ignored` by the MCP server.
pub include_ignored: bool,
/// turbovault-a0l (PERF-1): optional cached per-vault `VaultRepo` handle.
/// When `Some`, `apply_txn` reuses it instead of opening a fresh repo per
/// call (saving the ~140µs `Repository::open`). The MCP server installs one
/// shared across all in-process writes to the vault. Bare `Self::new*`
/// leaves it `None`, falling back to per-call open (tests / migrations that
/// don't run the server-side cache).
pub cached_repo: Option<CachedRepo>,
}
impl GitFileTools {
/// Construct without a reindex hook (graph + search stay stale until
/// another path triggers their rebuild). Tests use this; the MCP
/// server uses [`Self::new_with_hook`].
pub fn new(
manager: Arc<VaultManager>,
vault_path: PathBuf,
commit_locks: Arc<CommitLocks>,
) -> Self {
Self {
manager,
vault_path,
commit_locks,
commit_hook: None,
flush_on_collision: None,
include_ignored: true,
cached_repo: None,
}
}
/// Construct with a reindex hook fired post-commit. The MCP server
/// installs one that pushes onto a per-vault [`crate::ReindexQueue`].
pub fn new_with_hook(
manager: Arc<VaultManager>,
vault_path: PathBuf,
commit_locks: Arc<CommitLocks>,
commit_hook: CommitHook,
) -> Self {
Self {
manager,
vault_path,
commit_locks,
commit_hook: Some(commit_hook),
flush_on_collision: None,
include_ignored: true,
cached_repo: None,
}
}
/// Construct with both a reindex hook AND a CAS-collision flush callback
/// (GWS.14b). The flush callback runs BEFORE the `ConcurrencyError` is
/// returned to the caller, so the agent's re-read sees coherent derived
/// state.
pub fn new_with_hook_and_flush(
manager: Arc<VaultManager>,
vault_path: PathBuf,
commit_locks: Arc<CommitLocks>,
commit_hook: CommitHook,
flush_on_collision: CasCollisionFlush,
) -> Self {
Self {
manager,
vault_path,
commit_locks,
commit_hook: Some(commit_hook),
flush_on_collision: Some(flush_on_collision),
include_ignored: true,
cached_repo: None,
}
}
/// turbovault-lri: builder-style override for `include_ignored`.
/// `false` makes every subsequent mutation pre-check each touched
/// path against the worktree's `.gitignore` matcher and refuse the
/// changeset if any path would be ignored. Default `true`.
pub fn with_include_ignored(mut self, include_ignored: bool) -> Self {
self.include_ignored = include_ignored;
self
}
/// turbovault-a0l (PERF-1): install a cached per-vault `VaultRepo` handle so
/// writes reuse it instead of opening a fresh repo per call. The handle must
/// already carry the shared `CommitLocks` + reindex `CommitHook` (the MCP
/// server opens it that way via `get_or_init_git_repo`). When set, `apply_txn`
/// ignores `commit_locks`/`commit_hook` on `self` — the cached handle owns
/// both.
pub fn with_cached_repo(mut self, cached_repo: CachedRepo) -> Self {
self.cached_repo = Some(cached_repo);
self
}
// -------- Reads (forwarded to VaultManager / fs) --------
/// Read a file from the vault (working tree == HEAD, so this is the
/// committed bytes).
pub async fn read_file(&self, path: &str) -> Result<String> {
self.manager.read_file(&PathBuf::from(path)).await
}
/// Lightweight metadata for multiple files — same shape as
/// [`crate::FileTools::get_notes_info`].
pub async fn get_notes_info(&self, paths: &[String]) -> Result<Vec<NoteInfo>> {
let files = crate::FileTools::new(Arc::clone(&self.manager));
files.get_notes_info(paths).await
}
// -------- Writes (route through VaultRepo) --------
/// Write a file — overwrite by default, append/prepend for the other
/// modes (mirrors [`crate::FileTools::write_file_with_mode`]).
///
/// `expected_hash`, when present, must be a **git blob oid hex string**
/// (40 hex chars). The substrate's version token is the blob oid (not a
/// SHA-256 content hash). A non-Oid string is rejected loudly rather than
/// silently dropping CAS protection.
pub async fn write_file_with_mode(
&self,
path: &str,
content: &str,
mode: WriteMode,
expected_hash: Option<&str>,
) -> Result<()> {
// v3b.1: delegate to the _with_message variant with the auto-derived
// subject rather than duplicating the body.
self.write_file_with_mode_and_message(
path,
content,
mode,
expected_hash,
&format!("write_file {}", path),
)
.await
}
/// turbovault-0bh: caller-supplied commit message variant of
/// [`Self::write_file_with_mode`]. Substrate auto-derives the message
/// otherwise (`write_file <path>`); this override lets the MCP layer
/// pass a richer message (caller's text + verb=tool_name per TV-008).
pub async fn write_file_with_mode_and_message(
&self,
path: &str,
content: &str,
mode: WriteMode,
expected_hash: Option<&str>,
message: &str,
) -> Result<()> {
let final_content = self.resolve_write_content(path, content, mode).await?;
let expected = parse_blob_oid(expected_hash)?;
let txn = build_upsert_txn(message.to_string(), path, &final_content, expected);
self.apply_txn(&txn).await
}
/// Overwrite shortcut — equivalent to `write_file_with_mode(.., Overwrite, None)`.
pub async fn write_file(&self, path: &str, content: &str) -> Result<()> {
self.write_file_with_mode(path, content, WriteMode::Overwrite, None)
.await
}
/// Strict create: write a NEW file with an `expect_absent` precondition.
/// If the path becomes occupied between the caller's check and the
/// substrate's CAS, `apply_txn` returns `ConcurrencyError` — the create
/// race the MCP layer's pre-check cannot close on its own.
///
/// This is the substrate-side guarantee for turbovault-947 / write-note
/// CAS-by-default: even with parallel subagents racing to create the
/// same absent path, exactly one commit lands; the loser sees a loud
/// ConcurrencyError and re-decides.
pub async fn create_file(&self, path: &str, content: &str) -> Result<()> {
self.create_file_with_message(path, content, &format!("create_file {}", path))
.await
}
/// turbovault-0bh: caller-supplied commit message variant of
/// [`Self::create_file`]. The `message` becomes the commit subject (and
/// body, when newline-separated). All other semantics are identical.
pub async fn create_file_with_message(
&self,
path: &str,
content: &str,
message: &str,
) -> Result<()> {
let txn = Changeset::new(message.to_string()).create(path, content.as_bytes().to_vec());
self.apply_txn(&txn).await
}
/// Edit a file via SEARCH/REPLACE blocks. Reads working-tree bytes,
/// applies the blocks in memory, and commits the result as one
/// changeset. `dry_run = true` returns the preview without committing.
pub async fn edit_file(
&self,
path: &str,
edits: &str,
expected_hash: Option<&str>,
dry_run: bool,
) -> Result<EditResult> {
// v3b.1: delegate to the _with_message variant with the auto-derived
// subject rather than duplicating the read/parse/apply/hash body.
self.edit_file_with_message(
path,
edits,
expected_hash,
dry_run,
&format!("edit_file {}", path),
)
.await
}
/// turbovault-0bh: caller-supplied commit message variant of
/// [`Self::edit_file`]. Behaviorally identical except the commit
/// subject is the caller's message instead of the auto-derived
/// `edit_file <path>`.
pub async fn edit_file_with_message(
&self,
path: &str,
edits: &str,
expected_hash: Option<&str>,
dry_run: bool,
message: &str,
) -> Result<EditResult> {
let expected = parse_blob_oid(expected_hash)?;
let current = self.read_file(path).await?;
let engine = EditEngine::new();
let blocks = engine.parse_blocks(edits)?;
let (mut result, new_content) = engine.apply_edits(¤t, &blocks, dry_run)?;
// 6sj: blob-OID hashes; same as edit_file.
result.old_hash = VaultRepo::blob_oid_of(current.as_bytes())
.map_err(|e| Error::config_error(format!("blob_oid_of(current): {}", e)))?
.to_string();
result.new_hash = VaultRepo::blob_oid_of(new_content.as_bytes())
.map_err(|e| Error::config_error(format!("blob_oid_of(new): {}", e)))?
.to_string();
if dry_run {
return Ok(result);
}
let txn = build_upsert_txn(message.to_string(), path, &new_content, expected);
self.apply_txn(&txn).await?;
Ok(result)
}
/// Delete a file. `expected_hash` (blob oid hex) enforces a CAS
/// precondition — pass `None` for a blind delete.
pub async fn delete_file(&self, path: &str) -> Result<()> {
self.delete_file_with_hash(path, None).await
}
/// Delete with optional blob-oid CAS.
pub async fn delete_file_with_hash(
&self,
path: &str,
expected_hash: Option<&str>,
) -> Result<()> {
// v3b.1: delegate to the _with_message variant with the auto-derived
// subject rather than duplicating the body.
self.delete_file_with_hash_and_message(
path,
expected_hash,
&format!("delete_file {}", path),
)
.await
}
/// turbovault-0bh: caller-supplied commit message variant of
/// [`Self::delete_file_with_hash`].
pub async fn delete_file_with_hash_and_message(
&self,
path: &str,
expected_hash: Option<&str>,
message: &str,
) -> Result<()> {
let expected = parse_blob_oid(expected_hash)?;
let mut txn = Changeset::new(message.to_string()).remove(path);
if let Some(oid) = expected {
txn = txn.expect_blob(path, oid);
}
self.apply_txn(&txn).await
}
/// Move a file — `remove(from) + upsert(to, bytes)` in one commit.
pub async fn move_file(&self, from: &str, to: &str) -> Result<()> {
self.move_file_with_hash(from, to, None).await
}
/// Move with optional blob-oid CAS on the source path.
pub async fn move_file_with_hash(
&self,
from: &str,
to: &str,
expected_hash: Option<&str>,
) -> Result<()> {
self.move_file_with_hash_and_message(
from,
to,
expected_hash,
&format!("move_file {} -> {}", from, to),
)
.await
}
/// turbovault-0bh: caller-supplied commit message variant of
/// [`Self::move_file_with_hash`].
pub async fn move_file_with_hash_and_message(
&self,
from: &str,
to: &str,
expected_hash: Option<&str>,
message: &str,
) -> Result<()> {
let expected_from = parse_blob_oid(expected_hash)?;
let content = self.read_file(from).await?;
let mut txn = Changeset::new(message.to_string())
.remove(from)
.upsert(to, content.into_bytes());
if let Some(oid) = expected_from {
txn = txn.expect_blob(from, oid);
}
// Destination is always required to be absent — refuses to clobber.
txn = txn.expect_absent(to);
self.apply_txn(&txn).await
}
/// turbovault-oz6: atomic delete + inbound-wikilink wrap-as-stale.
/// Removes `path` AND rewrites every backlinking source's wikilinks
/// targeting it as `~~[[old]]~~` strikethrough (signaling a dead
/// reference) — all in **one substrate changeset**.
///
/// Each source carries an `expect_blob` precondition; a concurrent
/// edit to ANY source aborts the whole delete with
/// `ConcurrencyError`. `expected_hash` (optional, blob OID hex)
/// guards the target page itself.
///
/// Returns the list of source paths whose content was rewritten so
/// the caller can surface what changed.
pub async fn delete_file_with_link_rewrite_to_stale(
&self,
path: &str,
expected_hash: Option<&str>,
message: &str,
) -> Result<MoveWithLinksResult> {
let expected_target = parse_blob_oid(expected_hash)?;
let txn = Changeset::new(message.to_string());
let (txn, link_sources_updated) = self
.fold_delete_with_stale_links(txn, path, expected_target)
.await?;
self.apply_txn(&txn).await?;
Ok(MoveWithLinksResult {
from: path.to_string(),
to: String::new(), // No destination for a delete.
link_sources_updated,
})
}
/// turbovault-0g4.7: fold a delete + inbound-wikilink stale-wrap onto an
/// existing changeset. Resolves backlinks via the link graph, wraps each
/// linker's references to `path` as `~~[[old]]~~` strikethrough, and chains
/// `remove(path)` (+ optional `expect_blob(path)`) + each source's
/// `upsert`/`expect_blob`. Returns the augmented changeset and the list of
/// rewritten source paths. Shared by the single-op
/// [`Self::delete_file_with_link_rewrite_to_stale`] and the batch `DeleteNote`
/// arm so both produce identical commits. Same link-graph coherence caveat
/// as [`Self::fold_move_with_links`].
async fn fold_delete_with_stale_links(
&self,
txn: Changeset,
path: &str,
expected_target: Option<Oid>,
) -> Result<(Changeset, Vec<String>)> {
use crate::wikilink_rewriter::wrap_wikilinks_as_stale;
let backlink_paths = {
let lg = self.manager.link_graph();
let graph = lg.read().await;
graph
.backlinks(&self.manager.vault_path().join(path))
.map_err(|e| Error::config_error(format!("backlink lookup: {}", e)))?
.into_iter()
.map(|(p, _links)| p)
.collect::<Vec<_>>()
};
let mut link_updates: Vec<(String, String, Oid)> = Vec::new();
for full_src in &backlink_paths {
let rel = full_src
.strip_prefix(self.manager.vault_path())
.map(|p| p.to_path_buf())
.unwrap_or_else(|_| full_src.clone());
let rel_str = rel
.to_str()
.ok_or_else(|| Error::config_error(format!("non-utf8 source path: {:?}", rel)))?
.to_string();
let src_content = self.read_file(&rel_str).await?;
let rewritten = wrap_wikilinks_as_stale(&src_content, path);
if rewritten == src_content {
continue;
}
let src_oid = VaultRepo::blob_oid_of(src_content.as_bytes())
.map_err(|e| Error::config_error(format!("blob_oid_of: {}", e)))?;
link_updates.push((rel_str, rewritten, src_oid));
}
let mut txn = txn.remove(path);
if let Some(oid) = expected_target {
txn = txn.expect_blob(path, oid);
}
for (rel_path, rewritten, oid) in &link_updates {
txn = txn
.upsert(rel_path.clone(), rewritten.clone().into_bytes())
.expect_blob(rel_path.clone(), *oid);
}
let updated = link_updates.into_iter().map(|(p, _, _)| p).collect();
Ok((txn, updated))
}
/// turbovault-oz6: return the list of vault-relative source paths
/// that have inbound wikilinks targeting `path`. Used by the MCP
/// layer's "refuse-if-backlinks" pre-check (option A) before
/// committing to a delete.
pub async fn list_inbound_backlinks(&self, path: &str) -> Result<Vec<String>> {
let backlink_paths = {
let lg = self.manager.link_graph();
let graph = lg.read().await;
graph
.backlinks(&self.manager.vault_path().join(path))
.map_err(|e| Error::config_error(format!("backlink lookup: {}", e)))?
.into_iter()
.map(|(p, _)| p)
.collect::<Vec<_>>()
};
let mut out = Vec::new();
for full_src in backlink_paths {
let rel = full_src
.strip_prefix(self.manager.vault_path())
.map(|p| p.to_path_buf())
.unwrap_or_else(|_| full_src.clone());
if let Some(s) = rel.to_str() {
out.push(s.to_string());
}
}
Ok(out)
}
/// turbovault-lqr: atomic move + inbound-wikilink rewrite. Renames
/// `from` -> `to` AND rewrites every backlinking source's
/// `[[from-basename]]` / `[[from-path]]` (plus alias / section /
/// block-anchor / embed forms) to point at the new target, all in
/// **one substrate changeset**.
///
/// Per-source CAS: each rewritten source carries an `expect_blob`
/// precondition. If ANY source's blob OID changed between the
/// read-modify and the substrate apply, the WHOLE changeset
/// aborts (architecture §6.3 reconsideration domino). The
/// destination always carries `expect_absent` (no clobber).
///
/// `expected_hash` (optional, blob OID hex) protects the SOURCE
/// against a concurrent edit between the caller's read and this
/// call.
///
/// Returns the list of source paths whose content was rewritten so
/// the caller can surface what changed.
pub async fn move_file_with_link_updates(
&self,
from: &str,
to: &str,
expected_hash: Option<&str>,
message: &str,
) -> Result<MoveWithLinksResult> {
let expected_from = parse_blob_oid(expected_hash)?;
let txn = Changeset::new(message.to_string());
let (txn, link_sources_updated) = self
.fold_move_with_links(txn, from, to, expected_from)
.await?;
self.apply_txn(&txn).await?;
Ok(MoveWithLinksResult {
from: from.to_string(),
to: to.to_string(),
link_sources_updated,
})
}
/// turbovault-0g4.6: fold an atomic move + inbound-wikilink rewrite onto an
/// existing changeset. Resolves backlinks via the in-memory link graph,
/// rewrites each source (OFM-aware), and chains `remove(from)` +
/// `upsert(to)` + `expect_absent(to)` (+ optional `expect_blob(from)`) +
/// each source's `upsert`/`expect_blob`. Returns the augmented changeset
/// and the list of rewritten source paths.
///
/// Shared by the single-op [`Self::move_file_with_link_updates`] and the
/// batch `MoveNote` arm so both produce identical commits. Resolves against
/// the link graph, so the caller must ensure it is coherent: the MCP layer
/// drains the reindex queue before a backlink-aware move; unit tests call
/// `manager.initialize()`.
async fn fold_move_with_links(
&self,
txn: Changeset,
from: &str,
to: &str,
expected_from: Option<Oid>,
) -> Result<(Changeset, Vec<String>)> {
use crate::wikilink_rewriter::rewrite_wikilinks;
let content = self.read_file(from).await?;
// Source paths are vault-relative PathBuf.
let backlink_paths = {
let lg = self.manager.link_graph();
let graph = lg.read().await;
graph
.backlinks(&self.manager.vault_path().join(from))
.map_err(|e| Error::config_error(format!("backlink lookup: {}", e)))?
.into_iter()
.map(|(p, _links)| p)
.collect::<Vec<_>>()
};
// Read each source, rewrite, capture blob OID for the precondition.
// Skip sources whose rewritten content equals the original (no actual
// link change — e.g. the `[[from]]` literal sits in a code fence).
let mut link_updates: Vec<(String, String, Oid)> = Vec::new();
for full_src in &backlink_paths {
let rel = full_src
.strip_prefix(self.manager.vault_path())
.map(|p| p.to_path_buf())
.unwrap_or_else(|_| full_src.clone());
let rel_str = rel
.to_str()
.ok_or_else(|| Error::config_error(format!("non-utf8 source path: {:?}", rel)))?
.to_string();
let src_content = self.read_file(&rel_str).await?;
let rewritten = rewrite_wikilinks(&src_content, from, to);
if rewritten == src_content {
continue;
}
let src_oid = VaultRepo::blob_oid_of(src_content.as_bytes())
.map_err(|e| Error::config_error(format!("blob_oid_of: {}", e)))?;
link_updates.push((rel_str, rewritten, src_oid));
}
// Source rename + each link source's rewrite, with preconditions.
let mut txn = txn.remove(from).upsert(to, content.into_bytes());
if let Some(oid) = expected_from {
txn = txn.expect_blob(from, oid);
}
txn = txn.expect_absent(to);
for (rel_path, rewritten, oid) in &link_updates {
txn = txn
.upsert(rel_path.clone(), rewritten.clone().into_bytes())
.expect_blob(rel_path.clone(), *oid);
}
let updated = link_updates.into_iter().map(|(p, _, _)| p).collect();
Ok((txn, updated))
}
/// Copy a file — read source, commit target (no source change). One
/// commit. Same expect-absent guard on the destination as `move_file`.
pub async fn copy_file(&self, from: &str, to: &str) -> Result<()> {
let content = self.read_file(from).await?;
let txn = Changeset::new(format!("copy_file {} -> {}", from, to))
.upsert(to, content.into_bytes())
.expect_absent(to);
self.apply_txn(&txn).await
}
// -------- Batch (the atomicity win) --------
/// Translate every [`BatchOperation`] to a single [`Changeset`] and
/// commit as **one atomic commit** — either every op lands or none do.
/// This is the spec-promised behavior the legacy [`crate::BatchTools`] never
/// actually delivered (the legacy path stopped at `failed_at` and left
/// partial state on disk).
pub async fn batch_execute(&self, operations: Vec<BatchOperation>) -> Result<BatchResult> {
self.batch_execute_inner(operations, None).await
}
/// turbovault-0bh: caller-supplied commit message variant of
/// [`Self::batch_execute`]. Overrides the auto-derived
/// `batch_execute (N ops)` subject with the caller's message.
pub async fn batch_execute_with_message(
&self,
operations: Vec<BatchOperation>,
message: &str,
) -> Result<BatchResult> {
self.batch_execute_inner(operations, Some(message)).await
}
// -------- internals --------
async fn translate_op(&self, txn: Changeset, op: &BatchOperation) -> Result<Changeset> {
// Per-op preconditions (turbovault-c0e). Every variant that touches
// an existing target accepts `expected_hash` (git blob OID hex on
// git backend); `CreateNote` carries an implicit `expect_absent`
// unless `force == Some(true)`. A mismatch on any single op aborts
// the whole batch (architecture §6.3 reconsideration domino).
Ok(match op {
BatchOperation::CreateNote {
path,
content,
force,
} => {
if force.unwrap_or(false) {
// Caller-acknowledged blind create/overwrite — drops
// expect_absent. Equivalent to a WriteNote with no
// expected_hash but kept under CreateNote semantics
// for the intent the caller declared.
txn.upsert(path, content.as_bytes())
} else {
// Strict create — `txn.create` carries `expect_absent`.
txn.create(path, content.as_bytes())
}
}
BatchOperation::WriteNote {
path,
content,
expected_hash,
} => upsert_expecting(
txn,
path,
content.as_bytes().to_vec(),
expected_hash.as_deref(),
)?,
BatchOperation::DeleteNote {
path,
expected_hash,
on_backlinks,
} => {
self.fold_delete_note(txn, path, expected_hash.as_deref(), on_backlinks.as_deref())
.await?
}
BatchOperation::MoveNote {
from,
to,
expected_hash,
update_backlinks,
} => {
self.fold_move_note(txn, from, to, expected_hash.as_deref(), *update_backlinks)
.await?
}
BatchOperation::UpdateLinks {
file,
old_target,
new_target,
expected_hash,
} => {
let current = self.read_file(file).await?;
let updated = current.replace(old_target, new_target);
upsert_expecting(txn, file, updated.into_bytes(), expected_hash.as_deref())?
}
BatchOperation::EditNote {
path,
edits,
expected_hash,
} => {
self.fold_edit_note(txn, path, edits, expected_hash.as_deref())
.await?
}
BatchOperation::UpdateFrontmatter {
path,
frontmatter,
merge,
expected_hash,
} => {
self.fold_update_frontmatter(
txn,
path,
frontmatter,
*merge,
expected_hash.as_deref(),
)
.await?
}
BatchOperation::ManageTags {
path,
operation,
tags,
expected_hash,
} => {
self.fold_manage_tags(txn, path, operation, tags, expected_hash.as_deref())
.await?
}
BatchOperation::CreateFromTemplate {
template_id,
path,
fields,
force,
} => {
self.fold_create_from_template(txn, template_id, path, fields, *force)
.await?
}
})
}
/// v3b.2: DeleteNote arm (turbovault-0g4.7) — backlink-aware delete:
/// refuse (default) / rewrite-stale-callout / force. Extracted from
/// translate_op to keep that dispatcher flat.
async fn fold_delete_note(
&self,
txn: Changeset,
path: &str,
expected_hash: Option<&str>,
on_backlinks: Option<&str>,
) -> Result<Changeset> {
let expected = parse_blob_oid(expected_hash)?;
Ok(match on_backlinks.unwrap_or("refuse") {
// Bare delete — leave inbound links dangling (pre-0g4.7 behavior).
"force" => remove_expecting(txn, path, expected),
// Atomically strikethrough every linker in the same commit.
"rewrite-stale-callout" => {
self.fold_delete_with_stale_links(txn, path, expected)
.await?
.0
}
"refuse" => {
let backlinks = self.list_inbound_backlinks(path).await?;
if !backlinks.is_empty() {
return Err(Error::config_error(format!(
"DeleteNote refused (turbovault-0g4.7): '{}' has {} inbound backlink(s) [{}]. Pass on_backlinks=\"rewrite-stale-callout\" to strikethrough every linker in the same commit, or \"force\" to delete and leave them broken.",
path,
backlinks.len(),
backlinks.join(", ")
)));
}
remove_expecting(txn, path, expected)
}
other => {
return Err(Error::config_error(format!(
"DeleteNote: unknown on_backlinks mode '{}' (expected refuse|rewrite-stale-callout|force)",
other
)));
}
})
}
/// v3b.2: MoveNote arm (turbovault-0g4.6) — default rewrites inbound
/// wikilinks in the same commit; update_backlinks=false is rename-only.
async fn fold_move_note(
&self,
txn: Changeset,
from: &str,
to: &str,
expected_hash: Option<&str>,
update_backlinks: Option<bool>,
) -> Result<Changeset> {
let expected_from = parse_blob_oid(expected_hash)?;
if update_backlinks.unwrap_or(true) {
Ok(self
.fold_move_with_links(txn, from, to, expected_from)
.await?
.0)
} else {
// Rename-only: no backlink rewrite, inbound links dangle. The
// destination always carries expect_absent (refuses to clobber).
let content = self.read_file(from).await?;
let mut t = txn.remove(from).upsert(to, content.into_bytes());
if let Some(oid) = expected_from {
t = t.expect_blob(from, oid);
}
Ok(t.expect_absent(to))
}
}
/// v3b.2: EditNote arm (turbovault-0g4.1) — SEARCH/REPLACE blocks folded
/// into the batch commit (the same EditEngine path edit_file uses, minus
/// the dry-run/hash reporting a batch doesn't need).
async fn fold_edit_note(
&self,
txn: Changeset,
path: &str,
edits: &str,
expected_hash: Option<&str>,
) -> Result<Changeset> {
let current = self.read_file(path).await?;
let engine = EditEngine::new();
let blocks = engine.parse_blocks(edits)?;
let (_result, new_content) = engine.apply_edits(¤t, &blocks, false)?;
upsert_expecting(txn, path, new_content.into_bytes(), expected_hash)
}
/// v3b.2: UpdateFrontmatter arm (turbovault-0g4.2) — reuse the pure
/// compute_update_frontmatter helper (read + merge in memory), fold the
/// resulting content into the batch commit.
async fn fold_update_frontmatter(
&self,
txn: Changeset,
path: &str,
frontmatter: &std::collections::HashMap<String, serde_json::Value>,
merge: Option<bool>,
expected_hash: Option<&str>,
) -> Result<Changeset> {
let mt = crate::MetadataTools::new(Arc::clone(&self.manager));
let fm_map: serde_json::Map<String, serde_json::Value> =
frontmatter.clone().into_iter().collect();
let (new_content, _info) = mt
.compute_update_frontmatter(path, fm_map, merge.unwrap_or(true))
.await?;
upsert_expecting(txn, path, new_content.into_bytes(), expected_hash)
}
/// v3b.2: ManageTags arm (turbovault-0g4.3) — reuse compute_manage_tags;
/// "list" is read-only (returns None) and rejected inside a batch.
async fn fold_manage_tags(
&self,
txn: Changeset,
path: &str,
operation: &str,
tags: &[String],
expected_hash: Option<&str>,
) -> Result<Changeset> {
let mt = crate::MetadataTools::new(Arc::clone(&self.manager));
let (maybe, _info) = mt.compute_manage_tags(path, operation, Some(tags)).await?;
let new_content = maybe.ok_or_else(|| {
Error::config_error(format!(
"ManageTags operation '{}' produces no write; only 'add'/'remove' are valid in a batch ('list' is read-only)",
operation
))
})?;
upsert_expecting(txn, path, new_content.into_bytes(), expected_hash)
}
/// v3b.2: CreateFromTemplate arm (turbovault-0g4.4) — render via
/// TemplateEngine, then strict-create (default, expect_absent) or
/// force-upsert (overwrite).
async fn fold_create_from_template(
&self,
txn: Changeset,
template_id: &str,
path: &str,
fields: &std::collections::HashMap<String, String>,
force: Option<bool>,
) -> Result<Changeset> {
let engine = crate::TemplateEngine::new(Arc::clone(&self.manager));
let (content, _info) = engine
.compute_from_template(template_id, path, fields.clone())
.await?;
Ok(if force.unwrap_or(false) {
txn.upsert(path, content.into_bytes())
} else {
txn.create(path, content.into_bytes())
})
}
/// turbovault-0bh internal: full batch implementation accepting an
/// optional caller-supplied commit message. `None` falls back to the
/// auto-derived `batch_execute (N ops)` subject (existing behavior).
async fn batch_execute_inner(
&self,
operations: Vec<BatchOperation>,
message: Option<&str>,
) -> Result<BatchResult> {
let started = std::time::Instant::now();
let transaction_id = uuid::Uuid::new_v4().to_string();
let total = operations.len();
if operations.is_empty() {
return Ok(BatchResult {
success: false,
executed: 0,
total: 0,
failed_at: None,
changes: vec![],
errors: vec!["Batch cannot be empty".to_string()],
records: vec![],
transaction_id,
duration_ms: started.elapsed().as_millis() as u64,
});
}
let commit_msg = message
.map(String::from)
.unwrap_or_else(|| format!("batch_execute ({} ops)", total));
let mut txn = Changeset::new(commit_msg);
let mut changes = Vec::with_capacity(total);
let mut records = Vec::with_capacity(total);
// turbovault-0g4.5: intra-batch same-path conflict policy. The git
// path skips the legacy `validate()`/`conflicts_with()` O(n²) check;
// the substrate DOES reject a changeset with duplicate change paths
// (`commit_changeset` → "duplicate change for path …"), but only at
// apply time and with a message that names neither the offending op
// index nor that the cause is a *batch* overlap. Detect the collision
// here instead — as each op folds into the shared changeset, any path
// it newly writes that an earlier op already wrote aborts the batch with
// a clear, op-indexed error. Reject-overlap (not coalesce): a path may
// be mutated by at most one op per batch.
let mut seen_paths: std::collections::HashSet<String> = std::collections::HashSet::new();
for (idx, op) in operations.iter().enumerate() {
let operation_desc = format!("{:?}", op);
let affected = op.affected_files();
// Paths already folded into `txn` before this op runs; anything
// appended past this index is what THIS op contributes.
let before = txn.touched_paths().len();
match self.translate_op(txn, op).await {
Ok(next) => {
txn = next;
if let Some(dup) = txn
.touched_paths()
.into_iter()
.skip(before)
.find(|p| !seen_paths.insert(p.clone()))
{
let err_msg = format!(
"intra-batch path collision (turbovault-0g4.5): operation {} writes '{}', which an earlier operation in this batch already writes. A path may be mutated by at most one operation per batch — split the conflicting writes across separate batches.",
idx, dup
);
records.push(OperationRecord {
operation_index: idx,
operation: operation_desc,
success: false,
error: Some(err_msg.clone()),
affected_files: affected,
});
return Ok(BatchResult {
success: false,
executed: idx,
total,
failed_at: Some(idx),
changes,
errors: vec![err_msg],
records,
transaction_id,
duration_ms: started.elapsed().as_millis() as u64,
});
}
changes.push(describe_op(op));
records.push(OperationRecord {
operation_index: idx,
operation: operation_desc,
success: true,
error: None,
affected_files: affected,
});
}
Err(e) => {
let err_msg = e.to_string();
records.push(OperationRecord {
operation_index: idx,
operation: operation_desc,
success: false,
error: Some(err_msg.clone()),
affected_files: affected,
});
return Ok(BatchResult {
success: false,
executed: idx,
total,
failed_at: Some(idx),
changes,
errors: vec![err_msg],
records,
transaction_id,
duration_ms: started.elapsed().as_millis() as u64,
});
}
}
}
match self.apply_txn(&txn).await {
Ok(()) => Ok(BatchResult {
success: true,
executed: total,
total,
failed_at: None,
changes,
errors: vec![],
records,
transaction_id,
duration_ms: started.elapsed().as_millis() as u64,
}),
Err(e) => {
let err_msg = e.to_string();
// turbovault-jk6 (TV-013): the per-op records were built
// `success: true` during the translate loop, but an apply-phase
// abort (a stale CAS precondition rolls the whole batch back)
// commits NOTHING (`executed: 0`). Re-mark every op not-applied
// so a caller iterating `records[]` cannot conclude any op
// committed. Point the error at the op whose path the failure
// names; the rest are rolled back.
for rec in records.iter_mut() {
rec.success = false;
rec.error = Some(
if rec
.affected_files
.iter()
.any(|f| err_msg.contains(f.as_str()))
{
err_msg.clone()
} else {
format!("rolled back (batch aborted): {err_msg}")
},
);
}
Ok(BatchResult {
success: false,
executed: 0,
total,
failed_at: None,
changes: vec![],
errors: vec![err_msg],
records,
transaction_id,
duration_ms: started.elapsed().as_millis() as u64,
})
}
}
}
/// Compute the bytes to write given mode + path.
async fn resolve_write_content(
&self,
path: &str,
content: &str,
mode: WriteMode,
) -> Result<String> {
Ok(match mode {
WriteMode::Overwrite => content.to_string(),
WriteMode::Append => {
let existing = self.read_file(path).await.unwrap_or_default();
if existing.is_empty() {
content.to_string()
} else {
format!("{}\n{}", existing, content)
}
}
WriteMode::Prepend => {
let existing = self.read_file(path).await.unwrap_or_default();
if existing.is_empty() {
content.to_string()
} else if existing.starts_with("---\n") || existing.starts_with("---\r\n") {
if let Some(end_idx) = find_frontmatter_end(&existing) {
let (fm, body) = existing.split_at(end_idx);
format!("{}\n{}\n{}", fm.trim_end(), content, body.trim_start())
} else {
format!("{}\n{}", content, existing)
}
} else {
format!("{}\n{}", content, existing)
}
}
})
}
async fn apply_txn(&self, txn: &Changeset) -> Result<()> {
// `VaultRepo` is `Send` but `!Sync`; the substrate work is blocking
// libgit2. Move it to the blocking pool. The `Arc<CommitLocks>` is
// shared across calls so cross-call commit-section serialization
// survives even though we open a fresh `VaultRepo` per call. The
// optional commit hook is cloned in and installed on each per-call
// open so the substrate fires it after a successful materialize.
let txn = txn.clone();
let include_ignored = self.include_ignored;
let result = match &self.cached_repo {
// turbovault-a0l (PERF-1): reuse the cached per-vault handle — no
// per-op `Repository::open`. Lock it on the blocking thread (the
// Mutex makes the `!Sync` `VaultRepo` workable and serializes the
// commit section, matching the CommitLocks boundary writes already
// pass through). Cross-process CAS stays safe (libgit2 re-reads refs
// under `lock_ref`).
Some(cached) => {
let cached = Arc::clone(cached);
tokio::task::spawn_blocking(move || -> Result<()> {
let repo = cached
.lock()
.unwrap_or_else(|poisoned| poisoned.into_inner());
run_txn(&repo, &txn, include_ignored)
})
.await
.map_err(|e| Error::config_error(format!("git changeset task failed: {}", e)))?
}
// Fallback: open a fresh `VaultRepo` per call (the pre-PERF-1 path).
// Used by bare `Self::new*` — tests / migrations without the
// server-side cache. The `Arc<CommitLocks>` is shared across calls
// so cross-call commit-section serialization survives; the optional
// hook is installed on each per-call open.
None => {
let path = self.vault_path.clone();
let locks = Arc::clone(&self.commit_locks);
let hook = self.commit_hook.clone();
tokio::task::spawn_blocking(move || -> Result<()> {
let repo = match hook {
Some(h) => VaultRepo::open_with_locks_and_hook(&path, locks, h),
None => VaultRepo::open_with_locks(&path, locks),
}
.map_err(git_err_to_core)?;
run_txn(&repo, &txn, include_ignored)
})
.await
.map_err(|e| Error::config_error(format!("git changeset task failed: {}", e)))?
}
};
// GWS.14b: on the reconsideration-domino abort, drain the reindex
// queue BEFORE returning the error so the agent's re-read sees a
// coherent graph/search state. In-process bursts where the conflict
// is against THIS process's own earlier commit benefit directly;
// cross-process conflicts (§8.4) still need a separate listener.
if let Err(ref e) = result
&& matches!(e, Error::ConcurrencyError { .. })
&& let Some(flush) = &self.flush_on_collision
&& let Err(flush_err) = flush().await
{
log::warn!(
"GWS.14b CAS-collision flush failed (returning original error): {}",
flush_err
);
}
result
}
}
/// Run one changeset against an already-open `repo`: the turbovault-lri
/// gitignore gate (when `include_ignored == false`), then `commit_changeset`.
/// Shared by `apply_txn`'s cached-handle and per-call-open paths so the policy
/// + commit logic stays in one place.
fn run_txn(repo: &VaultRepo, txn: &Changeset, include_ignored: bool) -> Result<()> {
if !include_ignored {
for changed in txn.touched_paths() {
if repo.is_path_ignored(&changed).map_err(git_err_to_core)? {
return Err(Error::config_error(format!(
"path '{}' is gitignored and include_ignored=false (turbovault-lri); enable include_ignored or add an exclusion in .gitignore",
changed
)));
}
}
}
repo.commit_changeset(txn)
.map(|_| ())
.map_err(git_err_to_core)
}
fn build_upsert_txn(
message: String,
path: &str,
content: &str,
expected: Option<Oid>,
) -> Changeset {
let mut txn = Changeset::new(message).upsert(path, content.as_bytes().to_vec());
if let Some(oid) = expected {
txn = txn.expect_blob(path, oid);
}
txn
}
/// v3b.2: fold `upsert(path, bytes)` plus an optional `expect_blob` CAS
/// precondition (parsed from a blob-OID hex string) into `txn`. The shared tail
/// of every content-replacing batch op (WriteNote / UpdateLinks / EditNote /
/// UpdateFrontmatter / ManageTags).
fn upsert_expecting(
txn: Changeset,
path: &str,
bytes: Vec<u8>,
expected_hash: Option<&str>,
) -> Result<Changeset> {
let mut t = txn.upsert(path, bytes);
if let Some(oid) = parse_blob_oid(expected_hash)? {
t = t.expect_blob(path, oid);
}
Ok(t)
}
/// v3b.2: fold `remove(path)` plus an already-parsed optional `expect_blob`
/// precondition into `txn` — the shared tail of the bare-delete branches.
fn remove_expecting(txn: Changeset, path: &str, expected: Option<Oid>) -> Changeset {
let mut t = txn.remove(path);
if let Some(oid) = expected {
t = t.expect_blob(path, oid);
}
t
}
fn parse_blob_oid(s: Option<&str>) -> Result<Option<Oid>> {
match s {
None => Ok(None),
Some(hex) => Oid::from_str(hex).map(Some).map_err(|_| {
// `ConcurrencyError` (not `ConfigError`) so callers can switch on
// ONE error type for both backends. Cross-restart edge case
// (server flipped `write_backend` between the client's read and
// write) lands here for SHA-256→git, and as a hash-mismatch
// `ConcurrencyError` for git→SHA-256 — same shape, same fix
// (re-read + retry).
Error::ConcurrencyError {
reason: format!(
"expected_hash for git backend must be a 40-char git blob oid hex (got {:?}). Re-read the file and retry with the fresh token.",
hex
),
}
}),
}
}
fn describe_op(op: &BatchOperation) -> String {
match op {
BatchOperation::CreateNote { path, .. } => format!("created {}", path),
BatchOperation::WriteNote { path, .. } => format!("wrote {}", path),
BatchOperation::DeleteNote { path, .. } => format!("deleted {}", path),
BatchOperation::MoveNote { from, to, .. } => format!("moved {} -> {}", from, to),
BatchOperation::UpdateLinks { file, .. } => format!("updated links in {}", file),
BatchOperation::EditNote { path, .. } => format!("edited {}", path),
BatchOperation::UpdateFrontmatter { path, .. } => {
format!("updated frontmatter in {}", path)
}
BatchOperation::ManageTags {
path, operation, ..
} => format!("{} tags in {}", operation, path),
BatchOperation::CreateFromTemplate {
template_id, path, ..
} => format!("created {} from template {}", path, template_id),
}
}
/// Translate a substrate error into the core error space used by the tool
/// layer. Precondition failures (the OCC CAS abort) become `ConcurrencyError`
/// so callers and tests can switch on the same shape they get from the
/// legacy path.
fn git_err_to_core(e: turbovault_git::Error) -> Error {
match e {
turbovault_git::Error::PreconditionFailed {
path,
expected,
found,
} => Error::ConcurrencyError {
reason: format!(
"precondition failed for {}: expected {:?}, found {:?}",
path, expected, found
),
},
other => Error::config_error(format!("git substrate error: {}", other)),
}
}
// -------- frontmatter helper (mirrors file_tools, deliberately not re-exported) --------
fn find_frontmatter_end(content: &str) -> Option<usize> {
let start = if content.starts_with("---\r\n") {
5
} else if content.starts_with("---\n") {
4
} else {
return None;
};
let bytes = content.as_bytes();
let check_closing = |pos: usize| -> Option<usize> {
if !bytes[pos..].starts_with(b"---") {
return None;
}
let after = pos + 3;
if after >= bytes.len() {
return Some(after);
}
match bytes[after] {
b'\n' => Some(after + 1),
b'\r' if after + 1 < bytes.len() && bytes[after + 1] == b'\n' => Some(after + 2),
_ => None,
}
};
if let Some(end) = check_closing(start) {
return Some(end);
}
let mut i = start;
while i < bytes.len() {
let nl = bytes[i..]
.iter()
.position(|&b| b == b'\n' || b == b'\r')
.map(|p| i + p)?;
let line_start = if bytes[nl] == b'\r' && nl + 1 < bytes.len() && bytes[nl + 1] == b'\n' {
nl + 2
} else {
nl + 1
};
if line_start >= bytes.len() {
break;
}
if let Some(end) = check_closing(line_start) {
return Some(end);
}
i = line_start;
}
None
}
#[cfg(test)]
mod tests {
use super::*;
use std::path::Path as StdPath;
use tempfile::TempDir;
use turbovault_core::config::{ServerConfig, VaultConfig};
use turbovault_vault::VaultManager;
fn init_repo(dir: &StdPath) {
let mut opts = git2::RepositoryInitOptions::new();
opts.initial_head("main");
git2::Repository::init_opts(dir, &opts).unwrap();
}
fn test_server_config(vault_dir: &StdPath) -> ServerConfig {
let mut cfg = ServerConfig::new();
cfg.vaults
.push(VaultConfig::builder("t", vault_dir).build().unwrap());
cfg
}
async fn setup() -> (TempDir, GitFileTools) {
let tmp = TempDir::new().unwrap();
init_repo(tmp.path());
let manager = Arc::new(VaultManager::new(test_server_config(tmp.path())).unwrap());
let locks = Arc::new(CommitLocks::new());
let tools = GitFileTools::new(manager, tmp.path().to_path_buf(), locks);
(tmp, tools)
}
/// turbovault-a0l: like `setup`, but installs a server-style CACHED
/// `VaultRepo` handle (the PERF-1 path) so writes reuse it instead of
/// opening a fresh repo per call.
async fn setup_cached() -> (TempDir, GitFileTools) {
let tmp = TempDir::new().unwrap();
init_repo(tmp.path());
let manager = Arc::new(VaultManager::new(test_server_config(tmp.path())).unwrap());
let locks = Arc::new(CommitLocks::new());
let repo = VaultRepo::open_with_locks(tmp.path(), Arc::clone(&locks)).unwrap();
let cached: CachedRepo = Arc::new(std::sync::Mutex::new(repo));
let tools =
GitFileTools::new(manager, tmp.path().to_path_buf(), locks).with_cached_repo(cached);
(tmp, tools)
}
fn head_oid(tools: &GitFileTools) -> Option<git2::Oid> {
VaultRepo::open(&tools.vault_path).unwrap().head_oid()
}
fn head_commit_message(tools: &GitFileTools) -> String {
let repo = git2::Repository::open(&tools.vault_path).unwrap();
let oid = head_oid(tools).unwrap();
repo.find_commit(oid)
.unwrap()
.message()
.unwrap()
.to_string()
}
#[tokio::test]
async fn write_file_creates_commit_and_materializes() {
let (tmp, tools) = setup().await;
tools.write_file("a.md", "alpha").await.unwrap();
assert_eq!(
std::fs::read_to_string(tmp.path().join("a.md")).unwrap(),
"alpha"
);
assert!(head_oid(&tools).is_some(), "commit landed on HEAD");
}
#[tokio::test]
async fn write_file_overwrites_existing() {
let (_tmp, tools) = setup().await;
tools.write_file("a.md", "v1").await.unwrap();
tools.write_file("a.md", "v2").await.unwrap();
assert_eq!(tools.read_file("a.md").await.unwrap(), "v2");
}
/// turbovault-a0l (PERF-1): the cached-handle path writes, reuses the
/// handle across calls (the cached repo sees its own prior commits, so the
/// parent chain advances correctly), and materializes — same observable
/// behavior as the per-call-open path.
#[tokio::test]
async fn cached_repo_path_writes_reuses_and_reads_back() {
let (tmp, tools) = setup_cached().await;
tools.write_file("a.md", "v1").await.unwrap();
tools.write_file("a.md", "v2").await.unwrap();
assert_eq!(tools.read_file("a.md").await.unwrap(), "v2");
assert_eq!(
std::fs::read_to_string(tmp.path().join("a.md")).unwrap(),
"v2"
);
assert!(
head_oid(&tools).is_some(),
"commit landed via the cached handle"
);
// A second distinct file through the same handle also lands.
tools.write_file("b.md", "B").await.unwrap();
assert_eq!(tools.read_file("b.md").await.unwrap(), "B");
}
/// turbovault-a0l (PERF-1): the cached path must still enforce the blob-oid
/// CAS precondition — caching the handle changes nothing about correctness.
#[tokio::test]
async fn cached_repo_path_still_enforces_cas() {
let (_tmp, tools) = setup_cached().await;
tools.write_file("a.md", "v1").await.unwrap();
let bogus = VaultRepo::blob_oid_of(b"NOPE").unwrap();
let err = tools
.write_file_with_mode("a.md", "v2", WriteMode::Overwrite, Some(&bogus.to_string()))
.await
.unwrap_err();
assert!(
matches!(err, Error::ConcurrencyError { .. }),
"got: {err:?}"
);
assert_eq!(
tools.read_file("a.md").await.unwrap(),
"v1",
"stale CAS did not apply"
);
}
/// turbovault-jk6 (TV-013): on an apply-phase abort (a stale CAS
/// precondition on one op rolls the whole batch back, `executed: 0`),
/// the per-op `records[]` must NOT report `success: true` — nothing
/// committed. The failing op carries the error; the rest are rolled back.
#[tokio::test]
async fn batch_abort_marks_records_not_applied() {
let (tmp, tools) = setup().await;
// Seed an existing file so a stale `expected_hash` forces a CAS abort.
tools.write_file("s1.md", "v1").await.unwrap();
let stale = VaultRepo::blob_oid_of(b"STALE").unwrap().to_string();
let ops = vec![
BatchOperation::CreateNote {
path: "ghost.md".to_string(),
content: "x".to_string(),
force: None,
},
BatchOperation::WriteNote {
path: "s1.md".to_string(),
content: "v2".to_string(),
expected_hash: Some(stale),
},
];
let res = tools.batch_execute(ops).await.unwrap();
// Top-level: aborted, nothing executed.
assert!(!res.success, "batch must report failure");
assert_eq!(res.executed, 0, "nothing committed");
assert!(res.changes.is_empty());
assert!(!res.errors.is_empty(), "top-level error populated");
// Per-op records reflect the abort — the TV-013 bug was success:true here.
assert_eq!(res.records.len(), 2);
assert!(
res.records.iter().all(|r| !r.success),
"no op may claim success on an aborted batch: {:?}",
res.records
);
let s1 = res
.records
.iter()
.find(|r| r.affected_files.iter().any(|f| f == "s1.md"))
.expect("s1 op record present");
assert!(
s1.error.as_deref().is_some_and(|e| !e.is_empty()),
"failing op carries an error: {s1:?}"
);
// Disk: atomicity intact — ghost not created, s1 unchanged.
assert!(!tmp.path().join("ghost.md").exists(), "ghost not created");
assert_eq!(tools.read_file("s1.md").await.unwrap(), "v1");
}
/// turbovault-0g4.5: two ops in one batch writing the SAME path are
/// rejected with a clear, op-indexed collision error (not the substrate's
/// cryptic apply-time "duplicate change for path" abort), and NOTHING
/// commits.
#[tokio::test]
async fn batch_same_path_collision_is_loud_and_atomic() {
let (tmp, tools) = setup().await;
let ops = vec![
BatchOperation::WriteNote {
path: "dup.md".to_string(),
content: "first".to_string(),
expected_hash: None,
},
BatchOperation::WriteNote {
path: "dup.md".to_string(),
content: "second".to_string(),
expected_hash: None,
},
];
let res = tools.batch_execute(ops).await.unwrap();
assert!(!res.success, "same-path collision must fail the batch");
assert_eq!(res.failed_at, Some(1), "the second op is the collision");
assert!(
res.errors
.iter()
.any(|e| e.contains("dup.md") && e.to_lowercase().contains("collision")),
"error names the colliding path: {:?}",
res.errors
);
assert!(
!tmp.path().join("dup.md").exists(),
"atomic: nothing committed on collision"
);
}
/// turbovault-0g4.5: a MoveNote's two endpoints colliding with a sibling
/// write is caught (the `to` path is already written by an earlier op).
#[tokio::test]
async fn batch_move_dest_collision_with_prior_write_is_caught() {
let (tmp, tools) = setup().await;
tools.write_file("src.md", "body").await.unwrap();
let ops = vec![
BatchOperation::WriteNote {
path: "dest.md".to_string(),
content: "occupant".to_string(),
expected_hash: None,
},
BatchOperation::MoveNote {
from: "src.md".to_string(),
to: "dest.md".to_string(),
expected_hash: None,
update_backlinks: None,
},
];
let res = tools.batch_execute(ops).await.unwrap();
assert!(!res.success);
assert_eq!(res.failed_at, Some(1));
assert!(res.errors.iter().any(|e| e.contains("dest.md")));
// src untouched, dest never created.
assert_eq!(tools.read_file("src.md").await.unwrap(), "body");
assert!(!tmp.path().join("dest.md").exists());
}
/// turbovault-0g4.5: a disjoint multi-op batch still succeeds — the guard
/// only fires on genuine same-path overlap.
#[tokio::test]
async fn batch_disjoint_paths_still_succeed() {
let (tmp, tools) = setup().await;
let ops = vec![
BatchOperation::WriteNote {
path: "a.md".to_string(),
content: "A".to_string(),
expected_hash: None,
},
BatchOperation::WriteNote {
path: "b.md".to_string(),
content: "B".to_string(),
expected_hash: None,
},
];
let res = tools.batch_execute(ops).await.unwrap();
assert!(res.success);
assert_eq!(res.executed, 2);
assert_eq!(
std::fs::read_to_string(tmp.path().join("a.md")).unwrap(),
"A"
);
assert_eq!(
std::fs::read_to_string(tmp.path().join("b.md")).unwrap(),
"B"
);
}
/// turbovault-0g4.1: EditNote folds SEARCH/REPLACE blocks into the batch
/// commit; multiple blocks edit multiple locations in the one file, and a
/// sibling op rides the same atomic commit.
#[tokio::test]
async fn batch_edit_note_multi_block_in_one_commit() {
let (_tmp, tools) = setup().await;
tools
.write_file("doc.md", "alpha\nbeta\ngamma\n")
.await
.unwrap();
let before = head_oid(&tools);
let edits = "<<<<<<< SEARCH\nalpha\n=======\nALPHA\n>>>>>>> REPLACE\n\
<<<<<<< SEARCH\ngamma\n=======\nGAMMA\n>>>>>>> REPLACE";
let ops = vec![
BatchOperation::EditNote {
path: "doc.md".to_string(),
edits: edits.to_string(),
expected_hash: None,
},
BatchOperation::WriteNote {
path: "sibling.md".to_string(),
content: "S".to_string(),
expected_hash: None,
},
];
let res = tools.batch_execute(ops).await.unwrap();
assert!(res.success, "edit batch failed: {:?}", res.errors);
assert_eq!(res.executed, 2);
assert_eq!(
tools.read_file("doc.md").await.unwrap(),
"ALPHA\nbeta\nGAMMA\n"
);
assert_eq!(tools.read_file("sibling.md").await.unwrap(), "S");
assert_ne!(head_oid(&tools), before, "one new commit for the batch");
}
/// turbovault-0g4.1: a stale `expected_hash` on an EditNote aborts the
/// whole batch atomically — the file is untouched.
#[tokio::test]
async fn batch_edit_note_stale_hash_aborts() {
let (_tmp, tools) = setup().await;
tools.write_file("doc.md", "x\n").await.unwrap();
let stale = VaultRepo::blob_oid_of(b"STALE").unwrap().to_string();
let ops = vec![BatchOperation::EditNote {
path: "doc.md".to_string(),
edits: "<<<<<<< SEARCH\nx\n=======\ny\n>>>>>>> REPLACE".to_string(),
expected_hash: Some(stale),
}];
let res = tools.batch_execute(ops).await.unwrap();
assert!(!res.success);
assert_eq!(tools.read_file("doc.md").await.unwrap(), "x\n", "unchanged");
}
/// turbovault-0g4.2: UpdateFrontmatter merges keys into an existing note's
/// frontmatter as part of the batch commit (existing keys + body preserved).
#[tokio::test]
async fn batch_update_frontmatter_merges_in_one_commit() {
let (_tmp, tools) = setup().await;
tools
.write_file("n.md", "---\ntitle: T\n---\nbody\n")
.await
.unwrap();
let mut fm = std::collections::HashMap::new();
fm.insert("status".to_string(), serde_json::json!("active"));
let ops = vec![BatchOperation::UpdateFrontmatter {
path: "n.md".to_string(),
frontmatter: fm,
merge: Some(true),
expected_hash: None,
}];
let res = tools.batch_execute(ops).await.unwrap();
assert!(res.success, "frontmatter batch failed: {:?}", res.errors);
let content = tools.read_file("n.md").await.unwrap();
assert!(
content.contains("title: T"),
"existing key preserved: {content}"
);
assert!(
content.contains("status: active"),
"new key merged: {content}"
);
assert!(content.contains("body"), "body preserved: {content}");
}
/// turbovault-0g4.3: ManageTags "add" folds new frontmatter tags into the
/// batch commit.
#[tokio::test]
async fn batch_manage_tags_add_in_one_commit() {
let (_tmp, tools) = setup().await;
tools
.write_file("t.md", "---\ntitle: T\n---\nbody\n")
.await
.unwrap();
let ops = vec![BatchOperation::ManageTags {
path: "t.md".to_string(),
operation: "add".to_string(),
tags: vec!["work".to_string(), "urgent".to_string()],
expected_hash: None,
}];
let res = tools.batch_execute(ops).await.unwrap();
assert!(res.success, "manage_tags batch failed: {:?}", res.errors);
let content = tools.read_file("t.md").await.unwrap();
assert!(content.contains("work"), "tag added: {content}");
assert!(content.contains("urgent"), "tag added: {content}");
}
/// turbovault-0g4.3: a "list" ManageTags op in a batch is rejected — it is
/// read-only, so there is no write to fold into the commit.
#[tokio::test]
async fn batch_manage_tags_list_is_rejected() {
let (_tmp, tools) = setup().await;
tools
.write_file("t.md", "---\ntags: [a]\n---\n")
.await
.unwrap();
let ops = vec![BatchOperation::ManageTags {
path: "t.md".to_string(),
operation: "list".to_string(),
tags: vec![],
expected_hash: None,
}];
let res = tools.batch_execute(ops).await.unwrap();
assert!(!res.success, "list must be rejected inside a batch");
}
/// turbovault-0g4.4: CreateFromTemplate renders a built-in template and
/// creates the note as part of the batch commit (fields substituted,
/// template frontmatter present).
#[tokio::test]
async fn batch_create_from_template_in_one_commit() {
let (_tmp, tools) = setup().await;
let mut fields = std::collections::HashMap::new();
fields.insert("title".to_string(), "Auth".to_string());
fields.insert("summary".to_string(), "How auth works".to_string());
let ops = vec![BatchOperation::CreateFromTemplate {
template_id: "doc".to_string(),
path: "notes/auth.md".to_string(),
fields,
force: None,
}];
let res = tools.batch_execute(ops).await.unwrap();
assert!(res.success, "template batch failed: {:?}", res.errors);
let content = tools.read_file("notes/auth.md").await.unwrap();
assert!(content.contains("# Auth"), "title substituted: {content}");
assert!(
content.contains("How auth works"),
"summary substituted: {content}"
);
assert!(
content.contains("type: documentation"),
"template frontmatter present: {content}"
);
}
/// turbovault-0g4.4: default (force=None) is a strict create — a colliding
/// path aborts the whole batch (expect_absent), leaving the occupant intact.
#[tokio::test]
async fn batch_create_from_template_strict_create_aborts_on_collision() {
let (_tmp, tools) = setup().await;
tools.write_file("dup.md", "occupied").await.unwrap();
let mut fields = std::collections::HashMap::new();
fields.insert("title".to_string(), "X".to_string());
fields.insert("summary".to_string(), "Y".to_string());
let ops = vec![BatchOperation::CreateFromTemplate {
template_id: "doc".to_string(),
path: "dup.md".to_string(),
fields,
force: None,
}];
let res = tools.batch_execute(ops).await.unwrap();
assert!(!res.success, "strict create must abort on an existing path");
assert_eq!(
tools.read_file("dup.md").await.unwrap(),
"occupied",
"occupant unchanged"
);
}
/// turbovault-0g4.6: a batch MoveNote rewrites inbound wikilinks atomically
/// by default (parity with the standalone move_note) — the rename and the
/// backlink source land in ONE commit.
#[tokio::test]
async fn batch_move_note_rewrites_backlinks_by_default() {
let (tmp, tools) = setup().await;
tools.write_file("old.md", "# Old\n").await.unwrap();
tools
.write_file("linker.md", "see [[old]] here\n")
.await
.unwrap();
// Populate the link graph so backlinks resolve (the MCP layer drains
// the reindex queue; the unit test initializes directly).
tools.manager.initialize().await.unwrap();
let before = head_oid(&tools);
let ops = vec![BatchOperation::MoveNote {
from: "old.md".to_string(),
to: "new.md".to_string(),
expected_hash: None,
update_backlinks: None, // default → rewrite
}];
let res = tools.batch_execute(ops).await.unwrap();
assert!(res.success, "move batch failed: {:?}", res.errors);
assert!(!tmp.path().join("old.md").exists());
assert_eq!(
std::fs::read_to_string(tmp.path().join("new.md")).unwrap(),
"# Old\n"
);
assert_eq!(
std::fs::read_to_string(tmp.path().join("linker.md")).unwrap(),
"see [[new]] here\n",
"inbound wikilink rewritten in the same commit"
);
assert_ne!(head_oid(&tools), before, "one new commit");
}
/// turbovault-0g4.6: update_backlinks=false keeps the pre-0g4.6 rename-only
/// behavior — inbound links are left dangling.
#[tokio::test]
async fn batch_move_note_rename_only_when_backlinks_disabled() {
let (tmp, tools) = setup().await;
tools.write_file("old.md", "# Old\n").await.unwrap();
tools
.write_file("linker.md", "see [[old]] here\n")
.await
.unwrap();
tools.manager.initialize().await.unwrap();
let ops = vec![BatchOperation::MoveNote {
from: "old.md".to_string(),
to: "new.md".to_string(),
expected_hash: None,
update_backlinks: Some(false),
}];
let res = tools.batch_execute(ops).await.unwrap();
assert!(res.success, "rename-only batch failed: {:?}", res.errors);
assert!(tmp.path().join("new.md").exists());
assert_eq!(
std::fs::read_to_string(tmp.path().join("linker.md")).unwrap(),
"see [[old]] here\n",
"rename-only leaves the inbound link dangling"
);
}
/// turbovault-0g4.7: a batch DeleteNote of a backlinked note is REFUSED by
/// default, aborting the batch — prevents silently shipping broken links.
#[tokio::test]
async fn batch_delete_note_refuses_backlinked_by_default() {
let (tmp, tools) = setup().await;
tools.write_file("doomed.md", "# Doomed\n").await.unwrap();
tools
.write_file("linker.md", "see [[doomed]]\n")
.await
.unwrap();
tools.manager.initialize().await.unwrap();
let ops = vec![BatchOperation::DeleteNote {
path: "doomed.md".to_string(),
expected_hash: None,
on_backlinks: None, // default → refuse
}];
let res = tools.batch_execute(ops).await.unwrap();
assert!(!res.success, "refuse must abort the batch");
assert!(
res.errors
.iter()
.any(|e| e.contains("linker.md") && e.to_lowercase().contains("backlink")),
"error names the linker: {:?}",
res.errors
);
assert!(tmp.path().join("doomed.md").exists(), "nothing deleted");
}
/// turbovault-0g4.7: on_backlinks="rewrite-stale-callout" strikethroughs
/// every linker in the SAME commit as the delete.
#[tokio::test]
async fn batch_delete_note_rewrite_stale_wraps_linkers() {
let (tmp, tools) = setup().await;
tools.write_file("doomed.md", "# Doomed\n").await.unwrap();
tools
.write_file("linker.md", "see [[doomed]] here\n")
.await
.unwrap();
tools.manager.initialize().await.unwrap();
let ops = vec![BatchOperation::DeleteNote {
path: "doomed.md".to_string(),
expected_hash: None,
on_backlinks: Some("rewrite-stale-callout".to_string()),
}];
let res = tools.batch_execute(ops).await.unwrap();
assert!(res.success, "stale-wrap batch failed: {:?}", res.errors);
assert!(!tmp.path().join("doomed.md").exists());
assert_eq!(
std::fs::read_to_string(tmp.path().join("linker.md")).unwrap(),
"see ~~[[doomed]]~~ here\n",
"linker strikethrough-wrapped in the delete commit"
);
}
/// turbovault-0g4.7: on_backlinks="force" deletes and leaves linkers broken
/// (the pre-0g4.7 bare-delete behavior).
#[tokio::test]
async fn batch_delete_note_force_leaves_linkers_broken() {
let (tmp, tools) = setup().await;
tools.write_file("doomed.md", "# Doomed\n").await.unwrap();
tools
.write_file("linker.md", "see [[doomed]] here\n")
.await
.unwrap();
tools.manager.initialize().await.unwrap();
let ops = vec![BatchOperation::DeleteNote {
path: "doomed.md".to_string(),
expected_hash: None,
on_backlinks: Some("force".to_string()),
}];
let res = tools.batch_execute(ops).await.unwrap();
assert!(res.success, "force batch failed: {:?}", res.errors);
assert!(!tmp.path().join("doomed.md").exists());
assert_eq!(
std::fs::read_to_string(tmp.path().join("linker.md")).unwrap(),
"see [[doomed]] here\n",
"force leaves the inbound link dangling"
);
}
#[tokio::test]
async fn write_file_with_stale_blob_oid_aborts_concurrency_error() {
let (_tmp, tools) = setup().await;
tools.write_file("a.md", "v1").await.unwrap();
// Use a deliberately wrong blob oid.
let bogus = VaultRepo::blob_oid_of(b"NOPE").unwrap();
let err = tools
.write_file_with_mode("a.md", "v2", WriteMode::Overwrite, Some(&bogus.to_string()))
.await
.unwrap_err();
assert!(
matches!(err, Error::ConcurrencyError { .. }),
"got: {err:?}"
);
assert_eq!(tools.read_file("a.md").await.unwrap(), "v1");
}
#[tokio::test]
async fn write_file_with_garbage_hash_is_loud_concurrency_error() {
// A malformed hash from the caller (e.g. cross-restart edge case
// where the legacy SHA-256 hex still lives in the client) lands as
// ConcurrencyError, NOT ConfigError — same shape callers handle for
// any other stale-token failure, single switch arm fixes both
// backends.
let (_tmp, tools) = setup().await;
let err = tools
.write_file_with_mode("a.md", "v1", WriteMode::Overwrite, Some("not-a-hash"))
.await
.unwrap_err();
assert!(
matches!(err, Error::ConcurrencyError { .. }),
"got: {err:?}"
);
}
#[tokio::test]
async fn delete_file_removes_and_commits() {
let (tmp, tools) = setup().await;
tools.write_file("a.md", "x").await.unwrap();
tools.delete_file("a.md").await.unwrap();
assert!(!tmp.path().join("a.md").exists());
}
#[tokio::test]
async fn move_file_atomic_remove_plus_add_one_commit() {
let (tmp, tools) = setup().await;
tools.write_file("old.md", "body").await.unwrap();
let before = head_oid(&tools);
tools.move_file("old.md", "new.md").await.unwrap();
assert!(!tmp.path().join("old.md").exists());
assert_eq!(
std::fs::read_to_string(tmp.path().join("new.md")).unwrap(),
"body"
);
assert_ne!(head_oid(&tools), before, "new commit");
}
#[tokio::test]
async fn move_file_refuses_to_clobber_existing_destination() {
let (_tmp, tools) = setup().await;
tools.write_file("a.md", "A").await.unwrap();
tools.write_file("b.md", "B").await.unwrap();
let err = tools.move_file("a.md", "b.md").await.unwrap_err();
assert!(
matches!(err, Error::ConcurrencyError { .. }),
"got: {err:?}"
);
// Both files still present, untouched.
assert_eq!(tools.read_file("a.md").await.unwrap(), "A");
assert_eq!(tools.read_file("b.md").await.unwrap(), "B");
}
#[tokio::test]
async fn copy_file_writes_destination_only() {
let (_tmp, tools) = setup().await;
tools.write_file("a.md", "alpha").await.unwrap();
tools.copy_file("a.md", "b.md").await.unwrap();
assert_eq!(tools.read_file("a.md").await.unwrap(), "alpha");
assert_eq!(tools.read_file("b.md").await.unwrap(), "alpha");
}
#[tokio::test]
async fn edit_file_search_replace_commits() {
let (_tmp, tools) = setup().await;
tools.write_file("a.md", "hello world\n").await.unwrap();
let edits = "<<<<<<< SEARCH\nhello world\n=======\nhi world\n>>>>>>> REPLACE\n";
tools.edit_file("a.md", edits, None, false).await.unwrap();
assert_eq!(tools.read_file("a.md").await.unwrap(), "hi world\n");
}
#[tokio::test]
async fn edit_file_dry_run_does_not_commit() {
let (_tmp, tools) = setup().await;
tools.write_file("a.md", "hello\n").await.unwrap();
let head_before = head_oid(&tools);
let edits = "<<<<<<< SEARCH\nhello\n=======\nbye\n>>>>>>> REPLACE\n";
let _ = tools.edit_file("a.md", edits, None, true).await.unwrap();
assert_eq!(head_oid(&tools), head_before, "no commit on dry_run");
assert_eq!(tools.read_file("a.md").await.unwrap(), "hello\n");
}
/// turbovault-6sj / TV-011: edit_file's returned `old_hash`/`new_hash`
/// must be 40-char git blob OIDs on the git backend (NOT 64-char SHA-256).
/// Without this, callers cannot use them as `expected_hash` on a follow-up
/// call — the CAS round-trip breaks.
#[tokio::test]
async fn edit_file_returns_blob_oid_hashes_not_sha256() {
let (_tmp, tools) = setup().await;
tools.write_file("a.md", "hello\n").await.unwrap();
let edits = "<<<<<<< SEARCH\nhello\n=======\nbye\n>>>>>>> REPLACE\n";
let result = tools.edit_file("a.md", edits, None, false).await.unwrap();
assert_eq!(
result.old_hash.len(),
40,
"old_hash must be 40-char blob OID hex, got {:?}",
result.old_hash
);
assert_eq!(
result.new_hash.len(),
40,
"new_hash must be 40-char blob OID hex, got {:?}",
result.new_hash
);
// Sanity: each hash equals the blob OID of the actual content.
let expected_old = VaultRepo::blob_oid_of(b"hello\n").unwrap().to_string();
let expected_new = VaultRepo::blob_oid_of(b"bye\n").unwrap().to_string();
assert_eq!(result.old_hash, expected_old);
assert_eq!(result.new_hash, expected_new);
}
/// turbovault-6sj: the `new_hash` an edit returns must round-trip as
/// `expected_hash` on the next call. This is the CAS contract the legacy
/// path delivered; the git backend must do the same.
#[tokio::test]
async fn edit_file_new_hash_round_trips_as_expected_hash() {
let (_tmp, tools) = setup().await;
tools.write_file("a.md", "v1\n").await.unwrap();
let edits1 = "<<<<<<< SEARCH\nv1\n=======\nv2\n>>>>>>> REPLACE\n";
let r1 = tools.edit_file("a.md", edits1, None, false).await.unwrap();
// Use r1.new_hash as the next expected_hash — must succeed because
// no concurrent change has touched the file.
let edits2 = "<<<<<<< SEARCH\nv2\n=======\nv3\n>>>>>>> REPLACE\n";
let r2 = tools
.edit_file("a.md", edits2, Some(&r1.new_hash), false)
.await
.unwrap();
assert_eq!(
r2.old_hash, r1.new_hash,
"old_hash chains to prior new_hash"
);
assert_eq!(tools.read_file("a.md").await.unwrap(), "v3\n");
}
/// turbovault-6sj: dry-run hashes must match what an actual apply would
/// produce, so callers can use a preview's `new_hash` to plan the next
/// `expected_hash`.
#[tokio::test]
async fn edit_file_dry_run_hashes_match_real_apply() {
let (_tmp, tools) = setup().await;
tools.write_file("a.md", "hello\n").await.unwrap();
let edits = "<<<<<<< SEARCH\nhello\n=======\nbye\n>>>>>>> REPLACE\n";
let dry = tools.edit_file("a.md", edits, None, true).await.unwrap();
let live = tools.edit_file("a.md", edits, None, false).await.unwrap();
assert_eq!(dry.old_hash, live.old_hash);
assert_eq!(dry.new_hash, live.new_hash);
}
/// turbovault-947: create_file on an absent path lands one commit.
#[tokio::test]
async fn create_file_writes_absent_path() {
let (tmp, tools) = setup().await;
let head_before = head_oid(&tools);
tools.create_file("new.md", "fresh\n").await.unwrap();
assert_eq!(tools.read_file("new.md").await.unwrap(), "fresh\n");
let head_after = head_oid(&tools).unwrap();
assert_ne!(Some(head_after), head_before, "create advanced HEAD");
// Existence side-effect lands in the working tree.
assert!(tmp.path().join("new.md").exists());
}
/// turbovault-c0e: `WriteNote.expected_hash` carries an `expect_blob`
/// precondition. A stale hash aborts the WHOLE batch (atomicity §6.3),
/// not just that op — zero files land, HEAD unchanged. The substrate
/// folds the apply-time ConcurrencyError into the returned `BatchResult`
/// (matching the existing batch-failure shape) rather than surfacing
/// it as `Err`.
#[tokio::test]
async fn batch_write_note_with_stale_expected_hash_aborts_atomically() {
let (tmp, tools) = setup().await;
tools.write_file("a.md", "v1\n").await.unwrap();
let bogus = VaultRepo::blob_oid_of(b"NEVER_HERE").unwrap().to_string();
let head_before = head_oid(&tools).unwrap();
let ops = vec![
BatchOperation::CreateNote {
path: "fresh.md".into(),
content: "ok".into(),
force: None,
},
BatchOperation::WriteNote {
path: "a.md".into(),
content: "v2\n".into(),
expected_hash: Some(bogus),
},
];
let res = tools.batch_execute(ops).await.unwrap();
assert!(!res.success, "batch reports failure");
assert_eq!(res.executed, 0, "no op committed on abort");
let any_concurrency = res.errors.iter().any(|e| e.contains("precondition failed"));
assert!(
any_concurrency,
"expected precondition-failed error in result: {:?}",
res.errors
);
// Atomic abort: fresh.md was NOT created; a.md is unchanged.
assert!(!tmp.path().join("fresh.md").exists());
assert_eq!(tools.read_file("a.md").await.unwrap(), "v1\n");
assert_eq!(head_oid(&tools), Some(head_before), "no commit on abort");
}
/// turbovault-c0e: matching `expected_hash` succeeds — the whole batch
/// lands as one commit.
#[tokio::test]
async fn batch_write_note_with_matching_expected_hash_lands() {
let (_tmp, tools) = setup().await;
tools.write_file("a.md", "v1\n").await.unwrap();
let current = VaultRepo::blob_oid_of(b"v1\n").unwrap().to_string();
let head_before = head_oid(&tools);
let ops = vec![BatchOperation::WriteNote {
path: "a.md".into(),
content: "v2\n".into(),
expected_hash: Some(current),
}];
let res = tools.batch_execute(ops).await.unwrap();
assert!(res.success);
assert_eq!(tools.read_file("a.md").await.unwrap(), "v2\n");
assert_ne!(head_oid(&tools), head_before, "commit advanced HEAD");
}
/// turbovault-c0e: `CreateNote { force: true }` drops `expect_absent`,
/// behaving as a blind upsert. Existing content is replaced; the batch
/// lands.
#[tokio::test]
async fn batch_create_note_force_true_is_blind_upsert() {
let (_tmp, tools) = setup().await;
tools.write_file("dup.md", "v1\n").await.unwrap();
let ops = vec![BatchOperation::CreateNote {
path: "dup.md".into(),
content: "v2\n".into(),
force: Some(true),
}];
let res = tools.batch_execute(ops).await.unwrap();
assert!(res.success);
assert_eq!(tools.read_file("dup.md").await.unwrap(), "v2\n");
}
/// turbovault-947: create_file on an existing path fails its `expect_absent`
/// precondition. ZERO commits land; the working tree is unchanged. This is
/// the substrate guarantee for the concurrent-create race the MCP layer
/// pre-check cannot close on its own.
#[tokio::test]
async fn create_file_aborts_on_existing_path() {
let (tmp, tools) = setup().await;
tools.write_file("dup.md", "v1\n").await.unwrap();
let head_before = head_oid(&tools).unwrap();
let err = tools.create_file("dup.md", "v2\n").await.unwrap_err();
assert!(
matches!(err, Error::ConcurrencyError { .. }),
"expected ConcurrencyError, got: {err:?}"
);
assert_eq!(
tools.read_file("dup.md").await.unwrap(),
"v1\n",
"original content untouched on aborted create"
);
assert_eq!(head_oid(&tools), Some(head_before), "no commit on abort");
// Working tree file count unchanged: only `dup.md` exists.
assert!(tmp.path().join("dup.md").exists());
}
#[tokio::test]
async fn batch_execute_one_atomic_commit_all_op_types() {
let (tmp, tools) = setup().await;
// Seed for delete + move + update-links.
tools.write_file("seed_del.md", "gone").await.unwrap();
tools.write_file("seed_mv.md", "moveme").await.unwrap();
tools
.write_file("links.md", "see [[old-target]]")
.await
.unwrap();
let head_before = head_oid(&tools);
let ops = vec![
BatchOperation::CreateNote {
path: "new1.md".into(),
content: "C1".into(),
force: None,
},
BatchOperation::WriteNote {
path: "new2.md".into(),
content: "W2".into(),
expected_hash: None,
},
BatchOperation::DeleteNote {
path: "seed_del.md".into(),
expected_hash: None,
on_backlinks: None,
},
BatchOperation::MoveNote {
from: "seed_mv.md".into(),
to: "moved.md".into(),
expected_hash: None,
update_backlinks: None,
},
BatchOperation::UpdateLinks {
file: "links.md".into(),
old_target: "old-target".into(),
new_target: "new-target".into(),
expected_hash: None,
},
];
let res = tools.batch_execute(ops).await.unwrap();
assert!(res.success, "batch should succeed: {:?}", res.errors);
assert_eq!(res.executed, 5);
// HEAD advanced by exactly one commit (the batch landed as one txn).
let head_after = head_oid(&tools).unwrap();
assert_ne!(Some(head_after), head_before);
let repo = git2::Repository::open(tmp.path()).unwrap();
let commit = repo.find_commit(head_after).unwrap();
assert_eq!(commit.parent_count(), 1, "exactly one new commit");
// Filesystem state matches.
assert_eq!(
std::fs::read_to_string(tmp.path().join("new1.md")).unwrap(),
"C1"
);
assert_eq!(
std::fs::read_to_string(tmp.path().join("new2.md")).unwrap(),
"W2"
);
assert!(!tmp.path().join("seed_del.md").exists());
assert!(!tmp.path().join("seed_mv.md").exists());
assert_eq!(
std::fs::read_to_string(tmp.path().join("moved.md")).unwrap(),
"moveme"
);
assert_eq!(
std::fs::read_to_string(tmp.path().join("links.md")).unwrap(),
"see [[new-target]]"
);
}
#[tokio::test]
async fn batch_execute_failure_leaves_no_partial_state() {
// CreateNote on a path that already exists -> precondition abort.
// Atomicity contract: zero files from the batch should land.
let (tmp, tools) = setup().await;
tools.write_file("exists.md", "already").await.unwrap();
let head_before = head_oid(&tools);
let ops = vec![
BatchOperation::WriteNote {
path: "untouched1.md".into(),
content: "X".into(),
expected_hash: None,
},
BatchOperation::CreateNote {
path: "exists.md".into(),
content: "boom".into(),
force: None,
},
BatchOperation::WriteNote {
path: "untouched2.md".into(),
content: "Y".into(),
expected_hash: None,
},
];
let res = tools.batch_execute(ops).await.unwrap();
assert!(!res.success);
// Neither untouched file was written; the existing file is unchanged.
assert!(!tmp.path().join("untouched1.md").exists());
assert!(!tmp.path().join("untouched2.md").exists());
assert_eq!(tools.read_file("exists.md").await.unwrap(), "already");
assert_eq!(head_oid(&tools), head_before, "no commit on abort");
}
#[tokio::test]
async fn batch_execute_empty_is_a_loud_failure() {
let (_tmp, tools) = setup().await;
let res = tools.batch_execute(vec![]).await.unwrap();
assert!(!res.success);
assert_eq!(res.total, 0);
}
// -------- GWS.14b: CAS-collision flush --------
#[tokio::test]
async fn cas_collision_flush_fires_before_concurrency_error_returns() {
// Wire a sentinel flush callback that flips an Arc<AtomicBool> so we
// can prove flush ran BEFORE the error reached the caller.
let tmp = TempDir::new().unwrap();
init_repo(tmp.path());
let manager = Arc::new(VaultManager::new(test_server_config(tmp.path())).unwrap());
let locks = Arc::new(CommitLocks::new());
let commit_hook: CommitHook = Arc::new(|_p, _c| {});
let flushed = Arc::new(std::sync::atomic::AtomicBool::new(false));
let flushed_clone = Arc::clone(&flushed);
let flush: CasCollisionFlush = Arc::new(move || {
let f = Arc::clone(&flushed_clone);
Box::pin(async move {
f.store(true, std::sync::atomic::Ordering::SeqCst);
Ok(())
})
});
let tools = GitFileTools::new_with_hook_and_flush(
manager,
tmp.path().to_path_buf(),
locks,
commit_hook,
flush,
);
// Trigger a guaranteed precondition failure: write v1, then update
// with a stale expected blob.
tools.write_file("a.md", "v1").await.unwrap();
let stale_oid = VaultRepo::blob_oid_of(b"WAS_NEVER_HERE").unwrap();
let err = tools
.write_file_with_mode(
"a.md",
"v2",
WriteMode::Overwrite,
Some(&stale_oid.to_string()),
)
.await
.unwrap_err();
assert!(
matches!(err, Error::ConcurrencyError { .. }),
"got: {err:?}"
);
assert!(
flushed.load(std::sync::atomic::Ordering::SeqCst),
"flush callback must fire before the ConcurrencyError surfaces to the caller"
);
}
/// turbovault-9zr: the full batch path. `batch_execute` must fire the
/// commit hook (enqueue exactly one commit), and draining that commit must
/// produce the one -> two link edge in the graph.
#[tokio::test]
async fn batch_execute_enqueues_and_reindexes_intra_commit_edge() {
let tmp = TempDir::new().unwrap();
init_repo(tmp.path());
let manager = Arc::new(VaultManager::new(test_server_config(tmp.path())).unwrap());
let locks = Arc::new(CommitLocks::new());
let queue = Arc::new(crate::ReindexQueue::new());
let q = Arc::clone(&queue);
let commit_hook: CommitHook = Arc::new(move |_p, c| q.push(c));
let flush: CasCollisionFlush = Arc::new(|| Box::pin(async { Ok(()) }));
let tools = GitFileTools::new_with_hook_and_flush(
Arc::clone(&manager),
tmp.path().to_path_buf(),
locks,
commit_hook,
flush,
);
tools
.batch_execute(vec![
BatchOperation::CreateNote {
path: "one.md".to_string(),
content: "# One\n\nlinks [[two]]\n".to_string(),
force: None,
},
BatchOperation::CreateNote {
path: "two.md".to_string(),
content: "# Two\n".to_string(),
force: None,
},
])
.await
.unwrap();
assert_eq!(
queue.pending_count(),
1,
"batch_execute should enqueue exactly one commit"
);
let repo = VaultRepo::open(tmp.path()).unwrap();
queue.drain_through(&repo, &manager).await.unwrap();
assert_eq!(
manager.link_graph().read().await.edge_count(),
1,
"drained batch commit should produce the one -> two edge"
);
}
#[tokio::test]
async fn cas_collision_flush_skipped_on_successful_write() {
let tmp = TempDir::new().unwrap();
init_repo(tmp.path());
let manager = Arc::new(VaultManager::new(test_server_config(tmp.path())).unwrap());
let locks = Arc::new(CommitLocks::new());
let commit_hook: CommitHook = Arc::new(|_p, _c| {});
let flush_calls = Arc::new(std::sync::atomic::AtomicUsize::new(0));
let flush_calls_clone = Arc::clone(&flush_calls);
let flush: CasCollisionFlush = Arc::new(move || {
let c = Arc::clone(&flush_calls_clone);
Box::pin(async move {
c.fetch_add(1, std::sync::atomic::Ordering::SeqCst);
Ok(())
})
});
let tools = GitFileTools::new_with_hook_and_flush(
manager,
tmp.path().to_path_buf(),
locks,
commit_hook,
flush,
);
tools.write_file("a.md", "alpha").await.unwrap();
tools.write_file("b.md", "beta").await.unwrap();
assert_eq!(
flush_calls.load(std::sync::atomic::Ordering::SeqCst),
0,
"flush only fires on ConcurrencyError, never on successful writes"
);
}
#[tokio::test]
async fn cas_collision_flush_error_does_not_mask_original_concurrency_error() {
// Even when the flush callback itself errors, the caller still sees
// the original ConcurrencyError — flush failures are logged + dropped
// (correctness contract).
let tmp = TempDir::new().unwrap();
init_repo(tmp.path());
let manager = Arc::new(VaultManager::new(test_server_config(tmp.path())).unwrap());
let locks = Arc::new(CommitLocks::new());
let commit_hook: CommitHook = Arc::new(|_p, _c| {});
let flush: CasCollisionFlush =
Arc::new(|| Box::pin(async { Err(Error::config_error("simulated flush failure")) }));
let tools = GitFileTools::new_with_hook_and_flush(
manager,
tmp.path().to_path_buf(),
locks,
commit_hook,
flush,
);
tools.write_file("a.md", "v1").await.unwrap();
let stale_oid = VaultRepo::blob_oid_of(b"WAS_NEVER_HERE").unwrap();
let err = tools
.write_file_with_mode(
"a.md",
"v2",
WriteMode::Overwrite,
Some(&stale_oid.to_string()),
)
.await
.unwrap_err();
// Caller sees the original ConcurrencyError, NOT the flush's
// ConfigError. Flush failures are best-effort.
assert!(
matches!(err, Error::ConcurrencyError { .. }),
"got: {err:?}"
);
}
// -------- turbovault-0bh: caller-supplied commit messages --------
#[tokio::test]
async fn write_file_with_mode_and_message_uses_caller_subject() {
let (_tmp, tools) = setup().await;
tools
.write_file_with_mode_and_message(
"a.md",
"alpha",
WriteMode::Overwrite,
None,
"add concept page for Alpha",
)
.await
.unwrap();
let msg = head_commit_message(&tools);
assert!(msg.contains("add concept page for Alpha"), "got: {msg:?}");
}
#[tokio::test]
async fn create_file_with_message_uses_caller_subject() {
let (_tmp, tools) = setup().await;
tools
.create_file_with_message("new.md", "fresh", "create stub page")
.await
.unwrap();
let msg = head_commit_message(&tools);
assert!(msg.contains("create stub page"), "got: {msg:?}");
}
#[tokio::test]
async fn edit_file_with_message_uses_caller_subject() {
let (_tmp, tools) = setup().await;
tools.write_file("a.md", "hello\n").await.unwrap();
let edits = "<<<<<<< SEARCH\nhello\n=======\nbye\n>>>>>>> REPLACE\n";
let _ = tools
.edit_file_with_message("a.md", edits, None, false, "fix greeting")
.await
.unwrap();
let msg = head_commit_message(&tools);
assert!(msg.contains("fix greeting"), "got: {msg:?}");
}
#[tokio::test]
async fn delete_file_with_hash_and_message_uses_caller_subject() {
let (_tmp, tools) = setup().await;
tools.write_file("a.md", "v").await.unwrap();
tools
.delete_file_with_hash_and_message("a.md", None, "remove superseded page")
.await
.unwrap();
let msg = head_commit_message(&tools);
assert!(msg.contains("remove superseded page"), "got: {msg:?}");
}
#[tokio::test]
async fn move_file_with_hash_and_message_uses_caller_subject() {
let (_tmp, tools) = setup().await;
tools.write_file("a.md", "v").await.unwrap();
tools
.move_file_with_hash_and_message("a.md", "b.md", None, "rename to canonical slug")
.await
.unwrap();
let msg = head_commit_message(&tools);
assert!(msg.contains("rename to canonical slug"), "got: {msg:?}");
}
#[tokio::test]
async fn batch_execute_with_message_uses_caller_subject() {
let (_tmp, tools) = setup().await;
let ops = vec![
BatchOperation::CreateNote {
path: "x.md".into(),
content: "x".into(),
force: None,
},
BatchOperation::CreateNote {
path: "y.md".into(),
content: "y".into(),
force: None,
},
];
tools
.batch_execute_with_message(ops, "ingest source S: 2 concept pages")
.await
.unwrap();
let msg = head_commit_message(&tools);
assert!(
msg.contains("ingest source S: 2 concept pages"),
"got: {msg:?}"
);
}
/// Auto-derived fallback still says `batch_execute (N ops)` when no
/// message is supplied (legacy behavior preserved).
#[tokio::test]
async fn batch_execute_auto_derive_unchanged() {
let (_tmp, tools) = setup().await;
let ops = vec![BatchOperation::CreateNote {
path: "x.md".into(),
content: "x".into(),
force: None,
}];
tools.batch_execute(ops).await.unwrap();
let msg = head_commit_message(&tools);
assert!(msg.contains("batch_execute (1 ops)"), "got: {msg:?}");
}
// -------- turbovault-lqr: atomic move + wikilink rewrite --------
/// turbovault-lqr: move with one backlinking source. The rename AND
/// the link rewrite land as ONE commit. HEAD advances by exactly one
/// commit touching both paths.
#[tokio::test]
async fn move_with_link_updates_atomic_one_commit() {
let (tmp, tools) = setup().await;
tools.write_file("old.md", "# Old\n").await.unwrap();
tools
.write_file("linker.md", "I link to [[old]] here.\n")
.await
.unwrap();
// Initialize link graph from the seeded files so backlinks resolve.
tools.manager.initialize().await.unwrap();
let head_before = head_oid(&tools).unwrap();
let result = tools
.move_file_with_link_updates("old.md", "new.md", None, "rename old -> new")
.await
.unwrap();
assert_eq!(result.link_sources_updated, vec!["linker.md".to_string()]);
// Working tree state.
assert!(!tmp.path().join("old.md").exists());
assert_eq!(
std::fs::read_to_string(tmp.path().join("new.md")).unwrap(),
"# Old\n"
);
assert_eq!(
std::fs::read_to_string(tmp.path().join("linker.md")).unwrap(),
"I link to [[new]] here.\n"
);
// Exactly one new commit touched both files.
let head_after = head_oid(&tools).unwrap();
assert_ne!(head_after, head_before);
let repo = git2::Repository::open(&tools.vault_path).unwrap();
let commit = repo.find_commit(head_after).unwrap();
assert_eq!(commit.parent_count(), 1, "single parent");
}
/// turbovault-lqr: move with multiple backlinking sources. All link
/// rewrites + the rename land in one commit.
#[tokio::test]
async fn move_with_link_updates_handles_multiple_sources() {
let (tmp, tools) = setup().await;
tools.write_file("old.md", "# Old\n").await.unwrap();
tools
.write_file("a.md", "see [[old|the page]]\n")
.await
.unwrap();
tools
.write_file("b.md", "embed: ![[old]]\nsection: [[old#Header]]\n")
.await
.unwrap();
// turbovault-34p: a source where "old" is a SUBSTRING of unrelated words
// (golden, oldie) AND that also links to a page we must NOT touch
// ([[keeper]]). A substring/too-greedy rewrite would corrupt these; only
// the [[old]] wikilink may change.
tools
.write_file("c.md", "golden oldie [[old]] keep [[keeper]]\n")
.await
.unwrap();
tools.manager.initialize().await.unwrap();
let result = tools
.move_file_with_link_updates("old.md", "new.md", None, "rename")
.await
.unwrap();
let mut updated = result.link_sources_updated.clone();
updated.sort();
assert_eq!(
updated,
vec!["a.md".to_string(), "b.md".to_string(), "c.md".to_string()]
);
assert_eq!(
std::fs::read_to_string(tmp.path().join("a.md")).unwrap(),
"see [[new|the page]]\n"
);
assert_eq!(
std::fs::read_to_string(tmp.path().join("b.md")).unwrap(),
"embed: ![[new]]\nsection: [[new#Header]]\n"
);
// Only the [[old]] wikilink changed: "golden"/"oldie" + [[keeper]] intact.
assert_eq!(
std::fs::read_to_string(tmp.path().join("c.md")).unwrap(),
"golden oldie [[new]] keep [[keeper]]\n"
);
}
/// turbovault-uag: git-backend Prepend into a note WITH frontmatter inserts
/// AFTER the `---` block (never above it); Append goes to the end. The legacy
/// `test_file_tools` suite covered only the legacy path; the git-backend
/// resolve_write_content + find_frontmatter_end path was uncovered.
#[tokio::test]
async fn git_prepend_after_frontmatter_and_append_at_end() {
let (tmp, tools) = setup().await;
tools
.write_file("n.md", "---\ntitle: T\n---\n\nbody line\n")
.await
.unwrap();
// Prepend lands below the closing `---`, above the body.
tools
.write_file_with_mode("n.md", "PRE", WriteMode::Prepend, None)
.await
.unwrap();
assert_eq!(
tools.read_file("n.md").await.unwrap(),
"---\ntitle: T\n---\nPRE\nbody line\n",
"prepend must not push above the frontmatter"
);
// Append lands at the very end.
tools
.write_file_with_mode("n.md", "POST", WriteMode::Append, None)
.await
.unwrap();
let after = tools.read_file("n.md").await.unwrap();
assert_eq!(after, "---\ntitle: T\n---\nPRE\nbody line\n\nPOST");
// Working tree == HEAD.
assert_eq!(
std::fs::read_to_string(tmp.path().join("n.md")).unwrap(),
after
);
}
/// Advance the branch ref + change `file`'s blob via a bare git2 commit,
/// then materialize that commit as the external writer would.
fn external_commit_change(repo_path: &StdPath, file: &str, content: &str) {
let commit = {
let repo = git2::Repository::open(repo_path).unwrap();
let head = repo.head().unwrap();
let branch = head.shorthand().unwrap().to_string();
let parent = head.peel_to_commit().unwrap();
let mut tb = repo.treebuilder(Some(&parent.tree().unwrap())).unwrap();
let blob = repo.blob(content.as_bytes()).unwrap();
tb.insert(file, blob, 0o100644).unwrap();
let tree = repo.find_tree(tb.write().unwrap()).unwrap();
let sig = git2::Signature::now("Ext", "ext@x").unwrap();
repo.commit(
Some(&format!("refs/heads/{branch}")),
&sig,
&sig,
"external",
&tree,
&[&parent],
)
.unwrap()
};
VaultRepo::open(repo_path)
.unwrap()
.materialize(commit, &[file.to_string()])
.unwrap();
}
/// turbovault-xw4: the CACHED `VaultRepo` handle (PERF-1) must still detect
/// a SEPARATE-PROCESS ref advance and reject a stale-precondition write — no
/// lost update. Prior coverage proved this for a raw handle (cas.rs) but not
/// at the cached GitFileTools seam, which is the exact safety question PERF-1
/// raised.
#[tokio::test]
async fn cached_handle_detects_external_ref_advance() {
let (tmp, tools) = setup_cached().await;
tools.write_file("a.md", "v1").await.unwrap();
let v1 = VaultRepo::blob_oid_of(b"v1").unwrap().to_string();
// Another process advances the ref + rewrites a.md's blob.
external_commit_change(tmp.path(), "a.md", "EXTERNAL");
// The cached handle must re-read the ref under lock and REJECT the write
// carrying the now-stale precondition.
let err = tools
.write_file_with_mode("a.md", "v2", WriteMode::Overwrite, Some(&v1))
.await
.unwrap_err();
assert!(
matches!(err, Error::ConcurrencyError { .. }),
"stale precondition must surface ConcurrencyError, got: {err:?}"
);
// The external commit is still HEAD — our stale write did not clobber it.
let repo = git2::Repository::open(tmp.path()).unwrap();
let head = repo.head().unwrap().peel_to_commit().unwrap();
assert_eq!(
head.message().unwrap(),
"external",
"external commit survived; no lost update"
);
}
/// turbovault-oz6: atomic delete + wrap-as-stale across multiple
/// linkers. One commit; target gone; sources strikethrough-wrapped.
#[tokio::test]
async fn delete_with_link_rewrite_to_stale_wraps_all_linkers() {
let (tmp, tools) = setup().await;
tools.write_file("doomed.md", "# Doomed").await.unwrap();
tools
.write_file("a.md", "see [[doomed]] for details\n")
.await
.unwrap();
tools
.write_file("b.md", "another ref ![[doomed#Sec]]\n")
.await
.unwrap();
tools.manager.initialize().await.unwrap();
let head_before = head_oid(&tools).unwrap();
let result = tools
.delete_file_with_link_rewrite_to_stale("doomed.md", None, "kill doomed")
.await
.unwrap();
let mut updated = result.link_sources_updated.clone();
updated.sort();
assert_eq!(updated, vec!["a.md".to_string(), "b.md".to_string()]);
// Target gone.
assert!(!tmp.path().join("doomed.md").exists());
// Sources wrapped.
assert_eq!(
std::fs::read_to_string(tmp.path().join("a.md")).unwrap(),
"see ~~[[doomed]]~~ for details\n"
);
assert_eq!(
std::fs::read_to_string(tmp.path().join("b.md")).unwrap(),
"another ref ~~![[doomed#Sec]]~~\n"
);
// Single commit.
let head_after = head_oid(&tools).unwrap();
assert_ne!(head_after, head_before);
let repo = git2::Repository::open(&tools.vault_path).unwrap();
let commit = repo.find_commit(head_after).unwrap();
assert_eq!(commit.parent_count(), 1);
}
/// turbovault-oz6: list_inbound_backlinks returns the linkers the
/// MCP layer uses to decide whether to refuse, rewrite-stale, or
/// force-delete.
#[tokio::test]
async fn list_inbound_backlinks_returns_linkers() {
let (_tmp, tools) = setup().await;
tools.write_file("doomed.md", "# Doomed").await.unwrap();
tools
.write_file("linker.md", "see [[doomed]]")
.await
.unwrap();
tools
.write_file("unrelated.md", "no links here")
.await
.unwrap();
tools.manager.initialize().await.unwrap();
let mut bls = tools.list_inbound_backlinks("doomed.md").await.unwrap();
bls.sort();
assert_eq!(bls, vec!["linker.md".to_string()]);
}
/// turbovault-lqr: a source modified between the read and the apply
/// fails its expect_blob precondition, aborting the entire move —
/// zero files change.
#[tokio::test]
async fn move_with_link_updates_aborts_on_stale_source() {
let (tmp, tools) = setup().await;
tools.write_file("old.md", "# Old\n").await.unwrap();
tools
.write_file("linker.md", "see [[old]]\n")
.await
.unwrap();
tools.manager.initialize().await.unwrap();
// Simulate stale read: an external commit mutates linker.md
// between the link-graph lookup and the substrate apply. We
// approximate that by using a stale expected_hash on the
// source — substrate aborts identically.
// Compute a bogus oid to feed as expected_hash.
let bogus_oid = VaultRepo::blob_oid_of(b"NEVER_HERE_LQR")
.unwrap()
.to_string();
let head_before = head_oid(&tools).unwrap();
let res = tools
.move_file_with_link_updates("old.md", "new.md", Some(&bogus_oid), "should abort")
.await;
let err = res.unwrap_err();
assert!(
matches!(err, Error::ConcurrencyError { .. }),
"expected ConcurrencyError, got: {err:?}"
);
// Working tree unchanged.
assert!(tmp.path().join("old.md").exists());
assert!(!tmp.path().join("new.md").exists());
assert_eq!(
std::fs::read_to_string(tmp.path().join("linker.md")).unwrap(),
"see [[old]]\n"
);
assert_eq!(head_oid(&tools), Some(head_before), "no commit on abort");
}
}