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
//! Drift detection and per-mem change synthesis.
//!
//! `reload_if_stale` probes each candidate mount's `current_head()`
//! cursor on every operation (no throttle), reloads mems whose
//! on-disk state has advanced past the engine's cached head, and
//! surfaces `MemReloaded` warnings for handlers that need to
//! re-derive conclusions from a now-reloaded snapshot. `changes_since`
//! produces
//! the per-entity diff between a stored cursor and the backend's
//! current state — folder mounts synthesise from the changelog, the
//! git-branch hook walks the tree with rename detection, archive
//! mounts return empty.
use crate::backend::BackendError;
use crate::workspace::MountStorage;
use super::mutation::lookup_title_and_type;
use super::{Engine, EngineError};
/// What [`Engine::fast_forward_ref`] did with one local ref.
enum FastForward {
/// The remote-tracking ref does not exist.
NotOnRemote,
/// Local and remote already point at the same commit.
InSync,
/// The local ref moved (or was created, `previous` empty).
Moved { previous: String, new: String },
/// The local ref already contains the remote's commit and more
/// (unpushed local work); it was left alone.
LocalAhead,
/// Local and remote each have commits the other lacks; not moved.
Diverged,
}
impl Engine {
/// Reload-before-operation: before any read or write executes,
/// check the mem ref; if it advanced past the engine's cached
/// `last_known_head`, reload the affected mem(s) and return one
/// [`WarningHint::MemReloaded`] per reload so the caller can
/// surface the drift to the agent (the response *itself* already
/// carries fresh content — the warning explains why state
/// shifted).
///
/// The ref check runs on **every** call — there is no throttle
/// window. A per-operation `current_head()` read is microseconds,
/// effectively free at LLM latencies, and a throttle that let an
/// operation execute against an already-moved ref would reintroduce
/// the exact silent-staleness this guards against. This is the
/// correctness floor: no operation acts on a projection that is
/// behind git truth.
///
/// `mem = Some(name)` scopes the probe to one mount; `None`
/// scans every mount. Read handlers that target a known mem
/// (`memstead_entity` derives the mem from the id;
/// `memstead_changes_since` takes it as a param) and every mutation
/// (which knows its target mem) pass a name; tools that scan
/// multi-mem (`memstead_search` without a mem filter,
/// `memstead_overview`, `memstead_health`) pass `None`.
///
/// Behaviour matrix per mount:
/// - cached `Some(old)` + on-disk `Some(new)`, `old != new` →
/// reload the mem, emit `MemReloaded`, refresh the cached
/// head to `new`.
/// - cached `None` + on-disk `Some(new)` → reload the mem and
/// emit `MemReloaded`: a head appeared where none was seen (a
/// branch that arrived, a folder ledger written by another
/// process), so the view is behind it.
/// - cached / on-disk match, or on-disk `None` (a backend without a
/// head) → no-op.
/// - `current_head` errors, or the mem's last reload failed or was
/// incomplete → reload the mem whatever the head says; until a
/// reload succeeds the mem takes no write.
///
/// Reload errors are warn-logged and the affected mem is
/// skipped — the caller's response is still served from the (now
/// stale) in-memory snapshot rather than failing the entire
/// request. The next operation retries.
///
/// Cache invalidation rides on `reload_one_mem` — community
/// and search-index memos drop when any mem reloads.
pub fn reload_if_stale(&mut self, mem: Option<&str>) -> Vec<crate::ops::WarningHint> {
let mut warnings = self.roster_warnings();
warnings.extend(self.reload_if_stale_content_only(mem));
warnings
}
/// The membership half of [`Self::reload_if_stale`]: the roster is
/// probed before content, because a mem that left must not be loaded
/// or served and a mem that arrived must be there for the operation
/// that follows (roster.rs). Also run on its own by a verb that
/// locks every writable mount, before it computes that lock set.
pub(in crate::engine) fn roster_warnings(&mut self) -> Vec<crate::ops::WarningHint> {
let mut warnings = Vec::new();
match self.reconcile_roster() {
Ok(Some(change)) if !change.is_empty() => {
warnings.push(crate::ops::WarningHint::MemRosterChanged {
added: change.added,
removed: change.removed,
quarantined: change.quarantined,
failures: change
.failures
.iter()
.map(|f| format!("{}: {}", f.item, f.error))
.collect(),
});
}
Ok(_) => {}
Err(e) => {
warnings.push(crate::ops::WarningHint::MemRosterChanged {
added: Vec::new(),
removed: Vec::new(),
quarantined: Vec::new(),
failures: vec![e.to_string()],
});
}
}
warnings
}
/// The content half of [`Self::reload_if_stale`] alone — the branch-tip
/// probe without the roster probe. Exposed for the cost comparison the
/// roster probe is held to; every operation goes through the full form.
pub fn reload_if_stale_content_only(
&mut self,
mem: Option<&str>,
) -> Vec<crate::ops::WarningHint> {
let mut warnings = Vec::new();
// Phase 0 — the lazy-mount first-read trigger. Every operation
// funnels through this check, so a deferred mem the operation's
// scope touches loads here, before the staleness probes — a
// scoped operation loads exactly its mem, a workspace-scoped one
// loads every deferred mem so no answer is computed over a
// partial store. Operations scoped to eager mems never load a
// lazy sibling as a side effect.
self.ensure_mems_loaded(mem);
// Phase 1 — pick candidate mem names that match the filter.
// Cloned so the immutable borrow doesn't survive into the
// mutation phase.
let candidates: Vec<String> = self
.mounts
.iter()
.filter(|m| mem.is_none_or(|v| m.mount.mem == v))
.map(|m| m.mount.mem.clone())
.collect();
if candidates.is_empty() {
return warnings;
}
// Before anything reads a backend: drop what a failed mutation
// left staged on it when its discard failed. While that cannot
// be done the mem's view takes no write, and no reload reads
// the backend (it would read the staged bytes as content).
for name in &candidates {
if let Err(e) = self.discard_strays(name)
&& let Some(state) = self.mounts.iter_mut().find(|m| &m.mount.mem == name)
{
state.reload_failure = Some(crate::engine::ViewFailure {
cause: crate::engine::StaleCause::DiscardFailed,
detail: e.to_string(),
});
}
}
// Phase 2 — probe every candidate's current head via the
// backend. A probe error surfaces no warning; it marks the
// mem's view as unsure, which a reload below settles.
let mut probe_failures: Vec<(String, String)> = Vec::new();
let probes: Vec<(String, Option<String>, Option<String>, bool)> = candidates
.iter()
.filter_map(|name| {
let m = self.mounts.iter().find(|m| &m.mount.mem == name)?;
// A probe that fails says nothing about drift, and
// "nothing" must not read as "none": a write that
// followed would be computed from a view a sibling may
// have moved past. The mem is marked like one whose
// reload failed, and reloaded below regardless of what
// the head says.
let new_head = match m.backend.current_head() {
Ok(head) => head,
Err(e) => {
probe_failures.push((name.clone(), e.to_string()));
None
}
};
let cached = m.last_known_head.clone();
let unsure = m.reload_failure.is_some()
|| probe_failures.last().is_some_and(|(n, _)| n == name);
Some((name.clone(), cached, new_head, unsure))
})
.collect();
for (name, error) in probe_failures {
if let Some(state) = self.mounts.iter_mut().find(|m| m.mount.mem == name) {
state.reload_failure = Some(crate::engine::ViewFailure::drift(format!(
"the drift probe failed: {error}"
)));
}
}
// Phase 3 — act on each probe. The drift case is the only
// one that calls `reload_one_mem`; every other arm just
// (for first-observation) captures the baseline head silently.
for (name, cached, new_head, view_incomplete) in probes {
match (cached, new_head.clone()) {
(Some(old), Some(new)) if old != new => {
match self.reload_one_mem(&name) {
Ok(report) => {
let new = self.head_after_reload(&name, new);
warnings.push(crate::ops::WarningHint::MemReloaded {
mem: name.clone(),
old_head: old.clone(),
new_head: new.clone(),
entities_loaded: report.added.len() + report.changed.len(),
});
if let Some(state) =
self.mounts.iter_mut().find(|m| m.mount.mem == name)
{
state.last_known_head = Some(new.clone());
}
// Build the structured notice now — the
// backend's current head equals `new` and no
// follow-on write in this operation has
// committed yet, so the `old → new` delta
// describes only the sibling's change. Stashed
// for the response layer to drain.
let notice = self.mem_changed_notice(&name, &old, &new);
self.pending_mem_changed.push(notice);
// Emit the same change on the mem-change
// event channel: subscribers (SSE forwarders
// foremost) previously saw only this engine's
// own writes — a sibling process's commit,
// detected here as drift, is every bit as
// much a change. `n_commits: 1` per the
// watcher precedent (events batch by
// detection, not by commit archaeology).
self.emit_mem_changed(&crate::engine::events::MemChangedEvent {
mem: name.clone(),
head: new.clone(),
previous: old.clone(),
n_commits: 1,
});
}
Err(e) => {
self.note_reload_failure(&name, &e);
tracing::warn!(
mem = %name,
error = %e,
"drift-detected reload_one_mem failed; serving \
stale snapshot — will retry on the next operation"
);
}
}
}
// A head that appears where none was cached is a change
// too: the branch was born, fetched or pushed into place
// since the engine last looked (a mount whose branch was
// missing at boot, an unborn mem that took its first
// commit). Adopting the head silently left the store at
// the empty load and the boot-time `MOUNT_UNBACKED`
// probe standing over entities the branch now holds.
(None, Some(new)) => match self.reload_one_mem(&name) {
Ok(report) => {
let new = self.head_after_reload(&name, new);
warnings.push(crate::ops::WarningHint::MemReloaded {
mem: name.clone(),
old_head: String::new(),
new_head: new.clone(),
entities_loaded: report.added.len() + report.changed.len(),
});
if let Some(state) = self.mounts.iter_mut().find(|m| m.mount.mem == name) {
state.last_known_head = Some(new.clone());
}
let changes: Vec<crate::ops::ChangeEnvelope> = report
.added
.iter()
.map(|id| crate::ops::ChangeEnvelope::Added {
id: id.clone(),
title: None,
entity_type: None,
})
.collect();
let notice = crate::ops::MemChangedNotice::from_delta(
name.clone(),
String::new(),
new.clone(),
changes,
);
self.pending_mem_changed.push(notice);
self.emit_mem_changed(&crate::engine::events::MemChangedEvent {
mem: name.clone(),
head: new.clone(),
previous: String::new(),
n_commits: 1,
});
}
Err(e) => {
self.note_reload_failure(&name, &e);
tracing::warn!(
mem = %name,
error = %e,
"reload of a mem whose branch appeared failed; serving the \
empty snapshot — will retry on the next operation"
);
}
},
// A head that was there and is gone: the mem's storage
// was moved or removed under this engine (a mem rename
// by another process moves the branch away). The view
// is of storage that no longer exists under this name,
// and a write would recreate it beside the mem that
// moved. The view takes no write; the roster reconcile
// of a workspace engine unmounts the mem, and a reload
// settles an engine that has no roster.
(Some(old), None) if !view_incomplete => {
// Only storage that says it is gone: a backend with
// no head to report (an in-memory mem) is as
// present as ever.
if let Some(state) = self.mounts.iter_mut().find(|m| m.mount.mem == name)
&& matches!(state.backend.storage_present(), Ok(false))
{
state.reload_failure = Some(crate::engine::ViewFailure::drift(format!(
"the mem's storage is gone: its head was {old} and it has none now"
)));
}
}
// No drift, and the view in place is known to be
// incomplete or behind (its last load could not read
// everything): try again, so the mem takes writes again
// once storage delivers.
_ if view_incomplete => {
if let Err(e) = self.reload_one_mem(&name) {
self.note_reload_failure(&name, &e);
}
}
_ => {}
}
}
// A commit that a load completed is reported by an operation,
// whatever became of that load after it. It waits while its
// mem's view is still behind (the operation at hand will be
// refused or serve the stale view), and it keeps a standing copy
// among the load warnings.
let (ready, waiting): (Vec<_>, Vec<_>) = std::mem::take(&mut self.completed_commits)
.into_iter()
.partition(|w| {
!self.mounts.iter().any(|m| {
m.reload_failure.is_some() && w.source_mem() == Some(m.mount.mem.as_str())
})
});
self.completed_commits = waiting;
for warning in ready {
let text = warning.to_string();
if !self.load_warnings.iter().any(|w| w.to_string() == text) {
self.load_warnings.push(warning.clone());
}
warnings.push(warning);
}
warnings
}
/// Remember that the drift reload of `mem` failed: its view is
/// behind storage until a reload succeeds, and no write may land on
/// it meanwhile ([`Self::commit_staged`]).
/// After this engine moved a mem's branch (a pull, a reset): serve the
/// tree the branch now names. The head cursor moves only with a
/// reload that went through; a failed one marks the view stale, so
/// the next operation reloads again and no write lands from the old
/// view in the meantime.
fn adopt_moved_head(
&mut self,
mount_idx: usize,
mem: &str,
new_head: &str,
) -> Result<(), EngineError> {
match self.reload_one_mem(mem) {
Ok(_) => {
if let Some(state) = self.mounts.get_mut(mount_idx) {
state.last_known_head = Some(new_head.to_string());
}
Ok(())
}
Err(e) => {
self.note_reload_failure(mem, &e);
Err(e)
}
}
}
pub(in crate::engine) fn note_reload_failure(&mut self, mem: &str, error: &EngineError) {
if let Some(state) = self.mounts.iter_mut().find(|m| m.mount.mem == mem) {
state.reload_failure = Some(crate::engine::ViewFailure::drift(error.to_string()));
}
}
/// The head to record after a reload of `mem`. A load can move the
/// head itself: it completes a commit that was cut off, and the
/// cursor probed before the reload named the unfinished commit.
/// Recording that stale cursor would make the next operation see
/// drift again and reload a second time.
fn head_after_reload(&self, mem: &str, probed: String) -> String {
self.mounts
.iter()
.find(|m| m.mount.mem == mem)
.and_then(|m| m.backend.current_head().ok().flatten())
.unwrap_or(probed)
}
/// Mark `mount_idx`'s on-disk head as advanced by *this* engine's
/// own write so the next `reload_if_stale` doesn't surface
/// `MEM_RELOADED` for the commit we just produced. Mutation
/// paths call this immediately after `backend.commit` returns —
/// the cached `last_known_head` jumps straight to the new SHA
/// without going through a reload. Because every mutation runs
/// `reload_if_stale` for its target mem *before* committing,
/// the cached `last_known_head` is current at commit time, so
/// this advance is over a verified parent — it can never jump
/// the cache past an unobserved sibling commit. Cross-session and
/// out-of-band advances (sibling engine, manual `git pull`) that
/// land before the next operation still mismatch the cached value
/// and fire the warning as before.
///
/// Empty SHA is a no-op (no commit landed — e.g. duplicate-add
/// relate). A folder backend's head is its change-ledger
/// watermark, recorded here like a branch tip; an archive tracks
/// no head and leaves `last_known_head` at `None`.
pub(crate) fn record_self_write(&mut self, mount_idx: usize, write_id: &str) {
if write_id.is_empty() {
return;
}
// Capture the pre-write head + mem name so the
// `MemChangedEvent` we emit reflects the transition the
// current commit produced. We do this before mutating
// `last_known_head` because that field is the previous SHA
// from the event's point of view.
let (mem, previous) = match self.mounts.get(mount_idx) {
Some(state) => (
state.mount.mem.clone(),
state.last_known_head.clone().unwrap_or_default(),
),
None => return,
};
// The recorded head must equal what the backend's next
// `current_head()` probe will report, or every self-write
// would look like sibling drift on the following operation.
// For git-branch backends the probe returns exactly the commit
// SHA just produced; the folder backend's drift cursor is the
// changelog's last-line timestamp (a different dialect from
// its synthetic commit id), so probe once and prefer the
// backend's answer. Probe errors fall back to the commit id —
// drift detection stays best-effort, never blocking the write.
let recorded = self
.mounts
.get(mount_idx)
.and_then(|state| state.backend.current_head().ok().flatten())
.unwrap_or_else(|| write_id.to_string());
if let Some(state) = self.mounts.get_mut(mount_idx) {
state.last_known_head = Some(recorded.clone());
}
// Skip emit when no SHA actually advanced — folder backends
// (and archive backends) carry `last_known_head: None` and
// pass `write_id = ""` in some paths; the early-return at
// the top already catches the explicit empty case, but
// `previous == write_id` covers idempotent re-writes that
// pass through the same write path (e.g. a relate that
// re-applies the same edge). Skipping keeps the event stream
// a stream of *changes* rather than a stream of *writes*.
if previous == recorded {
return;
}
let event = crate::engine::events::MemChangedEvent {
mem,
// The corrected head, not the raw commit id: consumers feed
// event heads into `changes_since`, whose folder dialect is
// the changelog-timestamp cursor `recorded` carries.
head: recorded,
previous,
n_commits: 1,
};
self.emit_mem_changed(&event);
}
/// Build a [`crate::ops::MemChangedNotice`] describing the
/// per-entity delta a reload applied to `mem` (from `from_head`
/// to `to_head`). Derived from [`Self::changes_since`] so it
/// carries rename detection on git-branch mounts; on any backend
/// error (e.g. an unresolvable cursor) it falls back to an empty
/// delta — the heads alone still tell the agent the mem moved.
///
/// Callers pair this with [`Self::reload_if_stale`]: a returned
/// [`crate::ops::WarningHint::MemReloaded`] carries the
/// `old_head` / `new_head` to pass here. The delta matches the
/// transition the reload applied (`changes_since` walks the same
/// `from_head → current` range).
pub fn mem_changed_notice(
&self,
mem: &str,
from_head: &str,
to_head: &str,
) -> crate::ops::MemChangedNotice {
let changes = self
.changes_since(mem, from_head, None)
.map(|r| r.changes)
.unwrap_or_default();
crate::ops::MemChangedNotice::from_delta(
mem.to_string(),
from_head.to_string(),
to_head.to_string(),
changes,
)
}
/// Per-entity events for `mem` between `since` and the backend's
/// current state.
///
/// 1. Resolves the mount (returns [`EngineError::UnknownMem`]
/// on unknown mem).
/// 2. Validates `rename_similarity` against
/// `[RENAME_SIMILARITY_MIN, RENAME_SIMILARITY_MAX]`. Out-of-range
/// values refuse with [`EngineError::InvalidInput`] carrying
/// `details.allowed_range` and `details.requested`. `None` falls
/// back to [`crate::ops::RENAME_SIMILARITY_DEFAULT`].
/// 3. Dispatches on the mount's `MountStorage`:
/// - Folder mounts synthesize from the JSONL changelog via
/// [`crate::ops::folder_changes_since`].
/// - Git-branch mounts call the registered
/// [`GitBranchOps::changes_since`] hook (real tree-diff with
/// rename detection); missing hook = git-branch ops not wired
/// and the report comes back empty.
/// - Archive mounts return an empty report.
/// 4. Enriches each envelope's `title` / `entity_type` from the
/// in-memory store (best-effort — `Removed` envelopes always
/// leave both `None`; missing-from-store entities also leave
/// them `None`).
/// 5. Returns [`crate::ops::ChangesReport`] with `mem`,
/// `since` (echoed), `head` (backend-resolved current
/// cursor), enriched `changes`, and any clamping warnings.
pub fn changes_since(
&self,
mem: &str,
since: &str,
rename_similarity: Option<f32>,
) -> Result<crate::ops::ChangesReport, EngineError> {
let m = self.find_mount(mem)?;
// Reject out-of-range `rename_similarity` early so CLI and MCP
// share one refusal surface.
// The prior clamp+warn shape silently accepted nonsense values
// (e.g. 1.5 ≡ 1.0); typed refusal gives the agent a recoverable
// signal.
if let Some(v) = rename_similarity
&& !(crate::ops::RENAME_SIMILARITY_MIN..=crate::ops::RENAME_SIMILARITY_MAX).contains(&v)
{
return Err(EngineError::RenameSimilarityOutOfRange {
requested: v,
allowed_min: crate::ops::RENAME_SIMILARITY_MIN,
allowed_max: crate::ops::RENAME_SIMILARITY_MAX,
});
}
let clamped = rename_similarity.unwrap_or(crate::ops::RENAME_SIMILARITY_DEFAULT);
// The folder replay pairs a rename row with the id that vanished
// for it only over a loaded store: a deferred mount would read
// every id as vanished.
let store_lookup = |id: &crate::EntityId| -> Option<String> {
let e = self.store.get(id)?;
if e.stub {
return None;
}
Some(
e.metadata
.get("created_date")
.map(|v| v.to_frontmatter_string())
.unwrap_or_default(),
)
};
let store_ref: Option<crate::ops::StoreLookup<'_>> = if m.deferred {
None
} else {
Some(&store_lookup)
};
let backend_changes = match &m.mount.storage {
MountStorage::Folder { path } => {
match crate::ops::folder_changes_since(path, mem, since, store_ref) {
Ok(c) => c,
// Lift the backend's typed bad-`since` marker, parallel
// to the git arm's COMMIT_NOT_FOUND lift below: the
// folder cursor is a timestamp, and anything else —
// a mutation's `write_id` above all — refuses instead
// of silently replaying the whole history.
Err(BackendError::Other(msg)) if msg.starts_with("INVALID_TS_CURSOR:") => {
let since = msg
.strip_prefix("INVALID_TS_CURSOR:")
.unwrap_or_default()
.to_string();
return Err(EngineError::InvalidTimestampCursor {
mem: mem.to_string(),
since,
});
}
Err(e) => return Err(EngineError::Backend(e)),
}
}
MountStorage::GitBranch { gitdir, branch } => match self.git_branch_ops.as_ref() {
Some(hook) => match (hook.changes_since)(gitdir, branch, mem, since, clamped) {
Ok(c) => c,
// Lift the backend's typed bad-`since` marker to a typed
// engine error carrying the untruncated SHA, parallel
// to the UNKNOWN_REMOTE / LOCAL_DIVERGENCE prefixes.
Err(BackendError::Other(msg)) if msg.starts_with("COMMIT_NOT_FOUND:") => {
let since = msg
.strip_prefix("COMMIT_NOT_FOUND:")
.unwrap_or_default()
.to_string();
return Err(EngineError::InvalidChangesCursor {
mem: mem.to_string(),
since,
});
}
Err(e) => return Err(EngineError::Backend(e)),
},
None => crate::ops::BackendChanges::empty_at(since),
},
// Archive is sealed; the in-memory backend keeps a
// provenance log but no cursor-addressable change history,
// so both yield no backend-derived changes here (the live
// playground stream rides the engine's event broadcast, not
// this path).
MountStorage::Archive { .. } | MountStorage::InMemory => {
crate::ops::BackendChanges::empty_at(since)
}
};
// Enrich each id-only envelope from the engine's store.
// `Removed` always leaves title / entity_type None — the
// entity is gone by definition; the post-reload store does
// not have it. Other variants populate when the lookup
// succeeds; missing ids stay None.
let enriched: Vec<crate::ops::ChangeEnvelope> = backend_changes
.changes
.into_iter()
.map(|env| match env {
crate::ops::ChangeEnvelope::Added { id, .. } => {
let (title, entity_type) = lookup_title_and_type(&self.store, &id);
crate::ops::ChangeEnvelope::Added {
id,
title,
entity_type,
}
}
crate::ops::ChangeEnvelope::Updated { id, .. } => {
let (title, entity_type) = lookup_title_and_type(&self.store, &id);
crate::ops::ChangeEnvelope::Updated {
id,
title,
entity_type,
}
}
crate::ops::ChangeEnvelope::Removed { id, .. } => {
crate::ops::ChangeEnvelope::Removed {
id,
title: None,
entity_type: None,
}
}
crate::ops::ChangeEnvelope::Renamed { from_id, to_id, .. } => {
let (title, entity_type) = lookup_title_and_type(&self.store, &to_id);
crate::ops::ChangeEnvelope::Renamed {
from_id,
to_id,
title,
entity_type,
}
}
})
.collect();
// Out-of-range `rename_similarity` is now a hard refusal (see
// early-return above); the response carries no clamping warning.
let warnings: Vec<crate::ops::WarningHint> = Vec::new();
// The backend populates
// notes + memstead_ref on every git-branch call (folder + archive
// backends leave them empty / None). Surface them
// unconditionally; the MCP `include_notes` parameter becomes
// a renderer-side filter rather than a separate engine call.
let notes = if backend_changes.notes.is_empty() && backend_changes.memstead_ref.is_none() {
None
} else {
Some(backend_changes.notes)
};
Ok(crate::ops::ChangesReport {
mem: mem.to_string(),
since: backend_changes.since,
head: backend_changes.head,
changes: enriched,
warnings,
notes,
memstead_ref: backend_changes.memstead_ref,
})
}
/// Fetch updates from `remote` into the workspace's mem-repo.
/// Advances remote-tracking refs only; the local branch pointer
/// is not moved.
///
/// `refspecs` is forwarded verbatim to `git fetch`. An empty list
/// uses the remote's configured defaults.
///
/// Refusal codes: `UNKNOWN_MEM`, `UNKNOWN_REMOTE`,
/// `INVALID_INPUT` (folder / archive mounts).
///
/// V1 atomicity: schema-validation quarantine for
/// fetched commits is not yet wired. The remote-tracking refs
/// advance unconditionally on a successful fetch; downstream
/// schema validation runs on read via the engine's existing
/// reload pipeline.
pub fn fetch(
&self,
mem: &str,
remote: &str,
refspecs: &[String],
) -> Result<crate::ops::FetchOutcome, EngineError> {
// A fetch moves remote-tracking refs only. A refspec whose
// destination is a local branch would move a mem's branch or the
// schema ref with no fast-forward test and no schema gate; the
// routes that move local branches are `pull` and `pull --all`.
// The destination is admitted by allowlist (`refs/remotes/`, in
// the exact spelling), never by denying `refs/heads/`: on a
// case-insensitive filesystem `refs/HEADS/x` is the same file.
for spec in refspecs {
if spec.starts_with('-') {
return Err(EngineError::InvalidInput(format!(
"refspec `{spec}` starts with '-'; a refspec is never a git option"
)));
}
let spec_body = spec.trim_start_matches('+');
if spec_body.starts_with('^') {
continue;
}
if let Some((_, dst)) = spec_body.split_once(':')
&& !dst.is_empty()
&& !dst.starts_with("refs/remotes/")
{
return Err(EngineError::InvalidInput(format!(
"refspec `{spec}` writes outside the remote-tracking refs (`{dst}`); a fetch \
only updates `refs/remotes/<remote>/…` — move local branches with \
`memstead pull <mem>` or `memstead pull --all`"
)));
}
}
let m = self.find_mount(mem)?;
match &m.mount.storage {
MountStorage::Folder { .. } | MountStorage::Archive { .. } | MountStorage::InMemory => {
Err(EngineError::NotGitBacked {
mem: Some(mem.to_string()),
operation: "memstead_fetch".to_string(),
})
}
MountStorage::GitBranch { gitdir, .. } => match self.git_branch_ops.as_ref() {
Some(hook) => {
let mut outcome =
(hook.fetch)(gitdir, remote, refspecs).map_err(|e| match e {
other if EngineError::is_remote_marker(&other) => {
EngineError::from_transport(other)
}
other => EngineError::Backend(other),
})?;
// The mem's check-ledger rows travel with it: the
// remote's transport ref, unioned into the local
// ledger (engine::checks_transport).
let merged = self.import_checks(hook, gitdir, remote, &[mem])?;
outcome.checks_imported = merged.appended;
outcome.checks_refused = merged.refused;
Ok(outcome)
}
None => Err(EngineError::Backend(BackendError::Other(
"git-branch fetch hook not installed (git-branch ops not wired)".to_string(),
))),
},
}
}
/// Pull updates from `remote` into the named mem's branch.
/// Fetches into the remote-tracking ref, runs a pre-merge schema
/// validation pass against the prospective state, then
/// fast-forwards the local branch. Refuses with
/// `LOCAL_DIVERGENCE` for diverged local branches and with
/// `SCHEMA_VIOLATION_IN_FETCH` when the prospective state fails
/// schema validation — in both refusal cases the local branch
/// pointer is untouched (the underlying fetch has updated
/// `refs/remotes/*` but the engine has not promoted the new
/// state).
pub fn pull(
&mut self,
mem: &str,
remote: &str,
) -> Result<crate::ops::PullOutcome, EngineError> {
// A ref move waits for a write in progress in any mem: a guard
// elsewhere may have read a reference the move takes away. The
// subject itself may be unreadable (a pull is how it is repaired).
let (_write_lock, _) = self.lock_workspace_for_mem_operation(mem)?;
let mount_idx = self
.mounts
.iter()
.position(|m| m.mount.mem == mem)
.ok_or_else(|| self.unknown_mem_error(mem))?;
let (gitdir, branch) = match &self.mounts[mount_idx].mount.storage {
MountStorage::Folder { .. } | MountStorage::Archive { .. } | MountStorage::InMemory => {
return Err(EngineError::NotGitBacked {
mem: Some(mem.to_string()),
operation: "memstead_pull".to_string(),
});
}
MountStorage::GitBranch { gitdir, branch } => (gitdir.clone(), branch.clone()),
};
// Run the fetch step alone first so we can validate the
// prospective state against the schema before letting the
// pull's fast-forward land. Errors map to the typed surface
// just like a standalone `memstead_fetch` call.
let hook = self.git_branch_ops.ok_or_else(|| {
EngineError::Backend(BackendError::Other(
"git-branch pull hook not installed (git-branch ops not wired)".to_string(),
))
})?;
(hook.fetch)(&gitdir, remote, &[]).map_err(|e| match e {
other if EngineError::is_remote_marker(&other) => EngineError::from_transport(other),
other => EngineError::Backend(other),
})?;
// Pre-merge schema validation. The remote-tracking ref now
// points at the fetched tip; we walk it, parse every `.md`
// blob against the mem's pinned schema, and refuse the
// pull if any parse fails. The local branch pointer is still
// unchanged at this point — the refusal is fully atomic.
// The remote-tracking ref follows the mount's declared
// branch, never the mem name — the two differ on namespaced
// mounts.
let remote_ref = format!(
"refs/remotes/{remote}/{}",
crate::workspace::branch_short_name(&branch)
);
self.validate_ref_against_schema(&hook, &gitdir, mem, &remote_ref)?;
// Run the underlying pull (re-runs the fetch via git CLI, but
// that's a no-op cache-wise and keeps the fast-forward logic
// co-located with the rest of the transport implementation).
let mut outcome = (hook.pull)(&gitdir, remote, &branch, mem).map_err(|e| match e {
other if EngineError::is_remote_marker(&other) => EngineError::from_transport(other),
BackendError::Other(msg) if msg.starts_with("LOCAL_DIVERGENCE:") => {
let payload = msg.trim_start_matches("LOCAL_DIVERGENCE:");
let mut parts = payload.splitn(2, ':');
let v = parts.next().unwrap_or(mem).to_string();
let remote_ref = parts.next().unwrap_or("refs/remotes/?/?").to_string();
EngineError::LocalDivergence { mem: v, remote_ref }
}
other => EngineError::Backend(other),
})?;
// The mem's check-ledger rows travel with it (engine::checks_transport).
let merged = self.import_checks(&hook, &gitdir, remote, &[mem])?;
outcome.checks_imported = merged.appended;
outcome.checks_refused = merged.refused;
// Rewind cached head, reload the store so it serves the pulled
// state before this call returns (as `pull_all` does; a
// long-lived engine used to serve the old content until its
// next stale probe), then emit the change event.
if outcome.previous_sha != outcome.new_sha {
if let Err(e) = self.adopt_moved_head(mount_idx, mem, &outcome.new_sha) {
outcome.notices.push(format!(
"mem `{mem}` was pulled but did not reload in this process: {e}"
));
}
let event = crate::engine::events::MemChangedEvent {
mem: mem.to_string(),
head: outcome.new_sha.clone(),
previous: outcome.previous_sha.clone(),
n_commits: 1,
};
self.emit_mem_changed(&event);
}
Ok(outcome)
}
/// Push the named mem's branch to `remote`. Runs a pre-push
/// schema validation pass against the local branch tree; refuses
/// with `LOCAL_INVALID_STATE` when the local state fails schema
/// validation (the remote is not contacted in that case). Refuses
/// with `NON_FAST_FORWARD` when the push is not a fast-forward
/// and `force: false`; with `force: true` runs a
/// `--force-with-lease` push instead.
pub fn push(
&self,
mem: &str,
remote: &str,
force: bool,
) -> Result<crate::ops::PushOutcome, EngineError> {
let m = self.find_mount(mem)?;
let (gitdir, branch) = match &m.mount.storage {
MountStorage::Folder { .. } | MountStorage::Archive { .. } | MountStorage::InMemory => {
return Err(EngineError::NotGitBacked {
mem: Some(mem.to_string()),
operation: "memstead_push".to_string(),
});
}
MountStorage::GitBranch { gitdir, branch } => (gitdir.clone(), branch.clone()),
};
let hook = self.git_branch_ops.ok_or_else(|| {
EngineError::Backend(BackendError::Other(
"git-branch push hook not installed (git-branch ops not wired)".to_string(),
))
})?;
// Pre-push schema validation: walk the local branch tree (the
// mount's declared branch, never a ref derived from the mem
// name), run the mem's pinned schema over every `.md` blob.
// Any parse failure refuses the push with
// `LOCAL_INVALID_STATE` — the remote is not contacted. A gate
// that cannot run (the ref unresolvable, the tree unreadable)
// refuses too: a validation that did not happen must never
// read as a pass.
let local_ref = crate::workspace::branch_full_ref(&branch);
match self.validate_ref_against_schema(&hook, &gitdir, mem, &local_ref) {
Ok(()) => {}
Err(EngineError::SchemaViolationInFetch { violations, .. }) => {
return Err(EngineError::LocalInvalidState {
mem: mem.to_string(),
remote: remote.to_string(),
detail: format!(
"{} violation(s) in local branch: {}",
violations.len(),
violations.join("; "),
),
});
}
Err(EngineError::UnknownRef(raw)) => {
// Names the declared branch the gate looked for, so
// the reader sees what was resolved, not an invented
// ref.
return Err(EngineError::UnknownRef(raw));
}
Err(other) => {
return Err(EngineError::Backend(BackendError::Other(format!(
"pre-push schema validation could not run for mem '{mem}' \
(declared branch `{local_ref}`): {other}",
))));
}
}
let mut outcome =
(hook.push)(&gitdir, remote, &branch, mem, force).map_err(|e| match e {
other if EngineError::is_remote_marker(&other) => {
EngineError::from_transport(other)
}
BackendError::Other(msg) if msg.starts_with("NON_FAST_FORWARD:") => {
let payload = msg.trim_start_matches("NON_FAST_FORWARD:");
let mut parts = payload.splitn(2, ':');
let v = parts.next().unwrap_or(mem).to_string();
let r = parts.next().unwrap_or(remote).to_string();
EngineError::NonFastForward { mem: v, remote: r }
}
BackendError::Other(msg) if msg.starts_with("UNKNOWN_REF:") => {
EngineError::UnknownRef(
msg.trim_start_matches("UNKNOWN_REF:").trim().to_string(),
)
}
other => EngineError::Backend(other),
})?;
// The mem's check-ledger rows follow its branch: published on
// the transport ref and pushed beside it (engine::checks_transport).
// The branch is on the remote by now, so a failure here names
// that, and a rerun publishes the rows alone.
let (published, refused) = self
.publish_checks(&hook, &gitdir, remote, &[mem])
.map_err(|e| {
EngineError::Mem(format!(
"the branch of mem '{mem}' was pushed; its check-ledger rows were not \
({}); run the push again to publish them",
e.prose_render()
))
})?;
outcome.checks_published = published;
outcome.checks_refused = refused;
Ok(outcome)
}
/// `memstead status --remote`: every mounted git-branch mem and the
/// schemas ref compared against `remote` by one read-only
/// `ls-remote` per gitdir, classified in sync / local-ahead / behind
/// / forked / unfetched (the remote head is not in the local object
/// store, so behind or forked, which a fetch tells) / missing locally,
/// plus the remote's branches nothing mounts (a notice, whether or
/// not a local ref of that name exists) and the mounted branches the
/// remote lacks (a notice). Moves no ref and never refuses: no git-branch mount, no
/// hook (git-branch ops not wired), no remote configured or one that cannot be
/// reached each become a notice and the outcome stands as not stale,
/// so a network blip never blocks a session. The mount table the
/// classification reads is this engine's own, so a remote branch with
/// no mount is a leftover of a retired or re-homed mem, never
/// staleness; the reconcile itself stays `fetch` and `pull`.
pub fn remote_status(&self, remote: &str) -> crate::ops::RemoteStatusOutcome {
use crate::ops::{RemoteRefState, RemoteRefStatus, RemoteStatusOutcome};
let mut outcome = RemoteStatusOutcome {
remote: remote.to_string(),
..Default::default()
};
let mut gitdirs: Vec<std::path::PathBuf> = Vec::new();
for m in &self.mounts {
if let MountStorage::GitBranch { gitdir, .. } = &m.mount.storage
&& !gitdirs.contains(gitdir)
{
gitdirs.push(gitdir.clone());
}
}
if gitdirs.is_empty() {
outcome.notices.push(
"no git-branch mem is mounted, so there is no remote to compare against"
.to_string(),
);
return outcome;
}
let Some(hook) = self.git_branch_ops.as_ref() else {
outcome.notices.push(
"git-branch hooks not installed (git-branch ops not wired): the remote was not compared"
.to_string(),
);
return outcome;
};
let memstead_ref = crate::workspace::branch_full_ref(crate::MEMSTEAD_REF_BRANCH);
let checks_ref = crate::workspace::branch_full_ref(crate::MEMSTEAD_CHECKS_REF_BRANCH);
for gitdir in &gitdirs {
let remote_refs: std::collections::BTreeMap<String, String> =
match (hook.ls_remote)(gitdir, remote) {
Ok(v) => v.into_iter().collect(),
Err(e) if EngineError::is_remote_marker(&e) => {
outcome.notices.push(format!(
"{} (from {}): the comparison did not run (fail open)",
EngineError::from_transport(e),
gitdir.display()
));
continue;
}
Err(e) => {
outcome.notices.push(format!(
"remote `{remote}` could not be read from {}: {e} (fail open)",
gitdir.display()
));
continue;
}
};
// The branches this workspace mounts from this gitdir, by ref.
let mut mounted: std::collections::BTreeMap<String, String> =
std::collections::BTreeMap::new();
for m in &self.mounts {
if let MountStorage::GitBranch { gitdir: g, branch } = &m.mount.storage
&& g == gitdir
{
mounted.insert(
crate::workspace::branch_full_ref(branch),
m.mount.mem.clone(),
);
}
}
let local = |ref_name: &str| -> Option<String> {
(hook.resolve_ref)(gitdir, ref_name).ok().flatten()
};
// The ancestry verdict for a tracked ref whose heads differ.
// A remote head this clone has never fetched is not in the
// local object store, so neither direction can be tested:
// that is `Unfetched`, never a guessed `Forked`.
let compare = |local_sha: &str, remote_sha: &str| -> RemoteRefState {
match (hook.is_ancestor)(gitdir, remote_sha, local_sha) {
Ok(true) => RemoteRefState::LocalAhead,
Ok(false) => match (hook.is_ancestor)(gitdir, local_sha, remote_sha) {
Ok(true) => RemoteRefState::Behind,
Ok(false) => RemoteRefState::Forked,
Err(_) => RemoteRefState::Unfetched,
},
Err(_) => RemoteRefState::Unfetched,
}
};
for (ref_name, remote_sha) in &remote_refs {
// The check-ledger transport ref is derived from the
// workspace ledger before every publish and unioned on
// every fetch: it has no ahead or behind to report.
if *ref_name == checks_ref {
continue;
}
let schemas_ref = *ref_name == memstead_ref;
let mem = mounted.get(ref_name).cloned();
let tracked = schemas_ref || mem.is_some();
let local_sha = local(ref_name);
// Mount first: a branch nothing mounts is not graph state,
// whatever a local ref of that name says, so it can never
// be staleness.
let state = match (&local_sha, tracked) {
(_, false) => RemoteRefState::UnmountedRemote,
(None, true) => RemoteRefState::MissingLocal,
(Some(l), true) if l == remote_sha => RemoteRefState::InSync,
(Some(l), true) => compare(l, remote_sha),
};
outcome.refs.push(RemoteRefStatus {
ref_name: ref_name.clone(),
mem,
schemas_ref,
state,
remote_sha: Some(remote_sha.clone()),
local_sha,
});
}
// Tracked refs the remote lacks: every mounted branch, and the
// schemas ref when this clone carries one. Never pushed, a
// notice.
let mut tracked_only: Vec<(String, Option<String>, bool)> = mounted
.iter()
.map(|(r, m)| (r.clone(), Some(m.clone()), false))
.collect();
if local(&memstead_ref).is_some() {
tracked_only.push((memstead_ref.clone(), None, true));
}
for (ref_name, mem, schemas_ref) in tracked_only {
if remote_refs.contains_key(&ref_name) {
continue;
}
outcome.refs.push(RemoteRefStatus {
local_sha: local(&ref_name),
ref_name,
mem,
schemas_ref,
state: RemoteRefState::NotOnRemote,
remote_sha: None,
});
}
}
outcome.refs.sort_by(|a, b| a.ref_name.cmp(&b.ref_name));
for r in &outcome.refs {
*outcome
.counts
.entry(r.state.as_wire().to_string())
.or_default() += 1;
}
outcome.stale = outcome.refs.iter().any(|r| r.state.is_stale());
outcome
}
/// Push every mounted git-branch mem's declared branch, plus the
/// `__MEMSTEAD` ref of every mem-repo those mounts share, to
/// `remote` — fast-forward only, there is no force variant. One
/// `ls-remote` per mem-repo decides which refs lag; a ref whose
/// local and remote SHA agree is reported `in_sync` and never
/// sent. Each lagging mem branch goes through [`Self::push`]
/// (the pre-push schema gate included); `__MEMSTEAD` goes through
/// the same transport seam with no schema gate, it IS the
/// schemas. A refusal on one ref lands in `refused` with its
/// typed code and the run continues with the next ref — the
/// caller decides the exit status from the outcome. Folder,
/// archive and in-memory mounts have no branch and are skipped.
/// Only a remote that cannot be listed at all (`UNKNOWN_REMOTE`)
/// fails the run as a whole.
pub fn push_all(&self, remote: &str) -> Result<crate::ops::PushAllOutcome, EngineError> {
use crate::ops::{PushAllOutcome, PushedRef, RefusedRef};
let hook = self.git_branch_ops.ok_or_else(|| {
EngineError::Backend(BackendError::Other(
"git-branch push hook not installed (git-branch ops not wired)".to_string(),
))
})?;
// Mem-repos in mount order, each once; a workspace may spread
// its mounts over more than one gitdir.
let mut gitdirs: Vec<std::path::PathBuf> = Vec::new();
for m in &self.mounts {
if let MountStorage::GitBranch { gitdir, .. } = &m.mount.storage
&& !gitdirs.contains(gitdir)
{
gitdirs.push(gitdir.clone());
}
}
let mut outcome = PushAllOutcome {
remote: remote.to_string(),
..Default::default()
};
for gitdir in &gitdirs {
let remote_refs: std::collections::HashMap<String, String> =
(hook.ls_remote)(gitdir, remote)
.map_err(|e| match e {
other if EngineError::is_remote_marker(&other) => {
EngineError::from_transport(other)
}
other => EngineError::Backend(other),
})?
.into_iter()
.collect();
// `__MEMSTEAD` first: schemas and mem configs before the
// content that depends on them, so a clone that pulls
// mid-run never sees a mem its schema ref lacks.
let memstead_ref = crate::workspace::branch_full_ref(crate::MEMSTEAD_REF_BRANCH);
let mut targets: Vec<(String, Option<String>, String)> = Vec::new();
match (hook.resolve_ref)(gitdir, &memstead_ref) {
Ok(Some(_)) => targets.push((
memstead_ref.clone(),
None,
crate::MEMSTEAD_REF_BRANCH.to_string(),
)),
Ok(None) => {}
Err(e) => return Err(EngineError::Backend(e)),
}
for m in &self.mounts {
if let MountStorage::GitBranch { gitdir: g, branch } = &m.mount.storage
&& g == gitdir
{
targets.push((
crate::workspace::branch_full_ref(branch),
Some(m.mount.mem.clone()),
branch.clone(),
));
}
}
for (ref_name, mem, branch) in targets {
let local_sha = match (hook.resolve_ref)(gitdir, &ref_name) {
Ok(Some(sha)) => sha,
Ok(None) => {
outcome.refused.push(RefusedRef {
ref_name: ref_name.clone(),
mem: mem.clone(),
code: "UNKNOWN_REF".to_string(),
message: format!(
"{ref_name} does not exist locally{}",
mem.as_deref()
.map(|m| format!(" (mem `{m}`'s declared branch)"))
.unwrap_or_default()
),
});
continue;
}
Err(e) => return Err(EngineError::Backend(e)),
};
let previous_sha = remote_refs.get(&ref_name).cloned().unwrap_or_default();
if previous_sha == local_sha {
outcome.in_sync.push(ref_name);
continue;
}
let result = match &mem {
Some(m) => self.push(m, remote, false).map(|o| o.new_sha),
None => (hook.push)(gitdir, remote, &branch, crate::MEMSTEAD_REF_BRANCH, false)
.map(|o| o.new_sha)
.map_err(|e| match e {
BackendError::Other(msg) if msg.starts_with("NON_FAST_FORWARD:") => {
EngineError::NonFastForward {
mem: crate::MEMSTEAD_REF_BRANCH.to_string(),
remote: remote.to_string(),
}
}
other if EngineError::is_remote_marker(&other) => {
EngineError::from_transport(other)
}
other => EngineError::Backend(other),
}),
};
match result {
Ok(new_sha) => outcome.pushed.push(PushedRef {
ref_name,
mem,
previous_sha,
new_sha,
}),
Err(e) => {
// The single-mem refusal names `force`, which
// `--all` does not offer; say what applies here.
let message = match &e {
EngineError::NonFastForward { .. } => format!(
"remote `{remote}` carries commits on {ref_name} this clone lacks; \
fetch and pull {}, then push again",
mem.as_deref()
.map(|m| format!("mem `{m}`"))
.unwrap_or_else(|| "the schema ref".to_string()),
),
other => other.to_string(),
};
outcome.refused.push(RefusedRef {
ref_name,
mem,
code: e.code().to_string(),
message,
})
}
}
}
// The check-ledger rows of every mem mounted from this
// gitdir ride the transport ref, published once per gitdir
// after the branches (engine::checks_transport).
let mems: Vec<String> = self
.mounts
.iter()
.filter_map(|m| match &m.mount.storage {
MountStorage::GitBranch { gitdir: g, .. } if g == gitdir => {
Some(m.mount.mem.clone())
}
_ => None,
})
.collect();
let mem_refs: Vec<&str> = mems.iter().map(String::as_str).collect();
let checks_ref = crate::workspace::branch_full_ref(crate::MEMSTEAD_CHECKS_REF_BRANCH);
let previous_sha = remote_refs.get(&checks_ref).cloned().unwrap_or_default();
match self.publish_checks(&hook, gitdir, remote, &mem_refs) {
Ok((Some(new_sha), refused)) => {
outcome.checks_refused.extend(refused);
outcome.pushed.push(PushedRef {
ref_name: checks_ref,
mem: None,
previous_sha,
new_sha,
})
}
Ok((None, refused)) => {
outcome.checks_refused.extend(refused);
if !previous_sha.is_empty() {
outcome.in_sync.push(checks_ref);
}
}
Err(e) => outcome.refused.push(RefusedRef {
ref_name: checks_ref,
mem: None,
code: e.code().to_string(),
message: e.prose_render(),
}),
}
}
Ok(outcome)
}
/// Bring every mem-repo the workspace mounts from to `remote`'s
/// state, fast-forward only — the inverse of [`Self::push_all`].
///
/// Order, per the dependency between the refs: one fetch per
/// mem-repo; the `__MEMSTEAD` ref first (schemas and mem configs);
/// then the schema catalogue is re-read, every mounted mem's pin is
/// re-resolved from its (possibly new) config, and every mem
/// quarantined `SCHEMA_NOT_FOUND` is re-attached; then each mounted
/// mem's declared branch, validated against the schema it now
/// resolves to exactly as [`Self::pull`] validates; last the check
/// rows of the mounted mems. A ref absent locally is created; a ref
/// whose local side has commits the remote lacks is never moved
/// (`LOCAL_DIVERGENCE`), and the run continues with the next ref.
/// A mem quarantined for any other reason is never pulled and is
/// reported with its reason. Only a remote that cannot be fetched at
/// all (`UNKNOWN_REMOTE`) fails the run as a whole.
pub fn pull_all(&mut self, remote: &str) -> Result<crate::ops::PullAllOutcome, EngineError> {
use crate::ops::{PullAllOutcome, PulledRef, QuarantinedAfterPull, RefusedRef};
// Every ref move waits for a write in progress; each mem is a
// subject here, so an unreadable one does not refuse the pull
// that repairs it.
let subjects: Vec<String> = self
.mounts
.iter()
.map(|m| m.mount.mem.clone())
.chain(self.quarantined.iter().map(|q| q.mount.mem.clone()))
.collect();
let subject_refs: Vec<&str> = subjects.iter().map(String::as_str).collect();
let (_write_lock, _) = self.lock_workspace_for_mems_operation(&subject_refs)?;
let hook = self.git_branch_ops.ok_or_else(|| {
EngineError::Backend(BackendError::Other(
"git-branch pull hook not installed (git-branch ops not wired)".to_string(),
))
})?;
let map_fetch_err = |e: BackendError| match e {
other if EngineError::is_remote_marker(&other) => EngineError::from_transport(other),
other => EngineError::Backend(other),
};
// Mem-repos of mounted AND quarantined git-branch mems, each
// once: a mem quarantined because its schema lives only on the
// remote is exactly what this run repairs.
let gitdirs = self.workspace_gitdirs();
let mut outcome = PullAllOutcome {
remote: remote.to_string(),
..Default::default()
};
// --- Leg 1: fetch, then the schema-and-config ref. ---
// A mem-repo that cannot be fetched is refused by name and its
// refs are skipped; the other mem-repos still move. Only when no
// mem-repo could be fetched because the remote is unknown or
// unreachable does the run fail as a whole.
let mut failed: Vec<std::path::PathBuf> = Vec::new();
let mut first_unknown_remote: Option<EngineError> = None;
for gitdir in &gitdirs {
if let Err(e) = (hook.fetch)(gitdir, remote, &[]).map_err(map_fetch_err) {
outcome.refused.push(RefusedRef {
ref_name: gitdir.display().to_string(),
mem: None,
code: e.code().to_string(),
message: format!(
"the mem-repo at {} could not be fetched from `{remote}`; its refs \
were not touched: {e}",
gitdir.display()
),
});
if matches!(e, EngineError::UnknownRemote(_)) && first_unknown_remote.is_none() {
first_unknown_remote = Some(e);
}
failed.push(gitdir.clone());
continue;
}
let local_ref = crate::workspace::branch_full_ref(crate::MEMSTEAD_REF_BRANCH);
let remote_ref = format!("refs/remotes/{remote}/{}", crate::MEMSTEAD_REF_BRANCH);
// A local schema ref that is nothing but a bootstrap seed
// carries no state, so adopting the backup's history in its
// place loses nothing, whichever engine version seeded either.
match Self::fast_forward_ref(&hook, gitdir, &local_ref, &remote_ref, true)? {
FastForward::NotOnRemote => outcome.notices.push(format!(
"remote `{remote}` carries no schema-and-config ref for {}; \
the local one was left as it is",
gitdir.display()
)),
FastForward::InSync => outcome.in_sync.push(local_ref),
FastForward::Moved { previous, new } => outcome.pulled.push(PulledRef {
ref_name: local_ref,
mem: None,
previous_sha: previous,
new_sha: new,
}),
FastForward::LocalAhead => outcome.local_ahead.push(local_ref),
// Both clones moved the ref (each created a mem, say).
// The ref holds files, one per mem and schema, so the two
// histories merge path by path when no file changed on
// both sides; a file both changed is a decision the merge
// does not make, and nothing moves.
FastForward::Diverged => {
match self.merge_config_ref(&hook, gitdir, &local_ref, &remote_ref, remote)? {
Ok(pulled) => outcome.pulled.push(pulled),
Err(Some(paths)) => outcome.refused.push(RefusedRef {
ref_name: local_ref,
mem: None,
code: "LOCAL_DIVERGENCE".to_string(),
message: format!(
"the local schema-and-config ref and remote `{remote}`'s both \
changed {}; it was not moved. Settle those files on one clone \
and push them (`memstead push --all`), then pull here",
paths
.iter()
.map(|p| format!("`{p}`"))
.collect::<Vec<_>>()
.join(", ")
),
}),
Err(None) => outcome.refused.push(RefusedRef {
ref_name: local_ref,
mem: None,
code: "LOCAL_DIVERGENCE".to_string(),
message: format!(
"the local schema-and-config ref and remote `{remote}`'s share \
no history, so there is nothing to merge from; it was not \
moved. Push from this clone (`memstead push --all`) or \
reconcile on the other clone first"
),
}),
}
}
}
}
if failed.len() == gitdirs.len()
&& let Some(e) = first_unknown_remote
{
return Err(e);
}
let usable: Vec<std::path::PathBuf> = gitdirs
.iter()
.filter(|g| !failed.contains(g))
.cloned()
.collect();
// --- Leg 2: schemas, pins and quarantines re-resolved. ---
let mut refresh = crate::ops::FullRefreshReport::default();
self.refresh_schema_sources(&mut refresh);
let mut unresolved: std::collections::HashMap<String, EngineError> =
std::collections::HashMap::new();
let mounted_git: Vec<String> = self
.mounts
.iter()
.filter(|m| matches!(m.mount.storage, MountStorage::GitBranch { .. }))
.map(|m| m.mount.mem.clone())
.collect();
for mem in &mounted_git {
if let Err(e) = self.rebind_schema_from_config(mem) {
unresolved.insert(mem.clone(), e);
}
}
let schema_quarantined: Vec<String> = self
.quarantined
.iter()
.filter(|q| {
q.reason_code == "SCHEMA_NOT_FOUND"
&& matches!(q.mount.storage, MountStorage::GitBranch { .. })
})
.map(|q| q.mount.mem.clone())
.collect();
for mem in schema_quarantined {
if self.reload_one_mem(&mem).is_ok() && self.quarantine_reason(&mem).is_none() {
outcome.returned_to_service.push(mem);
}
}
// Mems on the remote that nothing here mounts: named with the
// command that mounts them, never mounted by this run.
let known: std::collections::HashSet<String> = self
.mounts
.iter()
.map(|m| &m.mount.storage)
.chain(self.quarantined.iter().map(|q| &q.mount.storage))
.filter_map(|s| match s {
MountStorage::GitBranch { branch, .. } => {
Some(crate::workspace::branch_full_ref(branch))
}
_ => None,
})
.collect();
let schema_ref = crate::workspace::branch_full_ref(crate::MEMSTEAD_REF_BRANCH);
for gitdir in &usable {
let Ok(remote_refs) = (hook.ls_remote)(gitdir, remote) else {
continue;
};
for (ref_name, _) in remote_refs {
let Some(short) = ref_name.strip_prefix("refs/heads/") else {
continue;
};
if known.contains(&ref_name)
|| short.starts_with(crate::MEMSTEAD_REF_BRANCH)
|| short == "main"
{
continue;
}
let Ok(Some(bytes)) = (hook.read_config_at_ref)(gitdir, &schema_ref, short) else {
continue;
};
let schema = serde_json::from_slice::<serde_json::Value>(&bytes)
.ok()
.and_then(|v| memstead_schema::config::parse_mem_config(&v).ok())
.and_then(|c| c.schema)
.map(|p| p.as_display());
outcome
.unmounted_on_remote
.push(crate::ops::UnmountedRemoteMem {
branch: short.to_string(),
schema,
});
}
}
// --- Leg 3: every mounted mem's declared branch. ---
let targets: Vec<(String, std::path::PathBuf, String)> = self
.mounts
.iter()
.filter_map(|m| match &m.mount.storage {
MountStorage::GitBranch { gitdir, branch } => {
Some((m.mount.mem.clone(), gitdir.clone(), branch.clone()))
}
_ => None,
})
.collect();
for (mem, gitdir, branch) in targets {
if failed.contains(&gitdir) {
continue;
}
let local_ref = crate::workspace::branch_full_ref(&branch);
if let Some(e) = unresolved.remove(&mem) {
outcome.refused.push(RefusedRef {
ref_name: local_ref,
mem: Some(mem.clone()),
code: e.code().to_string(),
message: e.to_string(),
});
continue;
}
let remote_ref = format!(
"refs/remotes/{remote}/{}",
crate::workspace::branch_short_name(&branch)
);
let Some(remote_sha) =
(hook.resolve_ref)(&gitdir, &remote_ref).map_err(EngineError::Backend)?
else {
outcome.notices.push(format!(
"remote `{remote}` does not carry {local_ref} (mem `{mem}`); \
the local branch was left as it is"
));
continue;
};
let local_sha =
(hook.resolve_ref)(&gitdir, &local_ref).map_err(EngineError::Backend)?;
if local_sha.as_deref() == Some(remote_sha.as_str()) {
outcome.in_sync.push(local_ref);
continue;
}
if let Some(l) = &local_sha
&& (hook.is_ancestor)(&gitdir, &remote_sha, l).map_err(EngineError::Backend)?
{
outcome.local_ahead.push(local_ref);
continue;
}
// The same whole-tree gate `pull` runs, against the schema
// the mem resolves to now that the schema ref has arrived.
if let Err(e) = self.validate_ref_against_schema(&hook, &gitdir, &mem, &remote_ref) {
outcome.refused.push(RefusedRef {
ref_name: local_ref,
mem: Some(mem.clone()),
code: e.code().to_string(),
message: e.to_string(),
});
continue;
}
match Self::fast_forward_ref(&hook, &gitdir, &local_ref, &remote_ref, false)? {
FastForward::Moved { previous, new } => {
// The store serves the pulled state before the run
// returns; a reload failure is reported, the ref
// move stands (the next operation reloads again).
if let Err(e) = self.reload_one_mem(&mem) {
outcome.notices.push(format!(
"mem `{mem}` was pulled but did not reload in this process: {e}"
));
}
let event = crate::engine::events::MemChangedEvent {
mem: mem.clone(),
head: new.clone(),
previous: previous.clone(),
n_commits: 1,
};
self.emit_mem_changed(&event);
outcome.pulled.push(PulledRef {
ref_name: local_ref,
mem: Some(mem.clone()),
previous_sha: previous,
new_sha: new,
});
}
FastForward::InSync => outcome.in_sync.push(local_ref),
FastForward::LocalAhead => outcome.local_ahead.push(local_ref),
FastForward::NotOnRemote => {}
FastForward::Diverged => outcome.refused.push(RefusedRef {
ref_name: local_ref.clone(),
mem: Some(mem.clone()),
code: "LOCAL_DIVERGENCE".to_string(),
message: EngineError::LocalDivergence {
mem: mem.clone(),
remote_ref,
}
.to_string(),
}),
}
}
// --- Leg 4: the mounted mems' check rows, once per mem-repo. ---
for gitdir in &usable {
let mems: Vec<String> = self
.mounts
.iter()
.filter_map(|m| match &m.mount.storage {
MountStorage::GitBranch { gitdir: g, .. } if g == gitdir => {
Some(m.mount.mem.clone())
}
_ => None,
})
.collect();
if mems.is_empty() {
continue;
}
let mem_refs: Vec<&str> = mems.iter().map(String::as_str).collect();
let merged = self.import_checks(&hook, gitdir, remote, &mem_refs)?;
outcome.checks_imported += merged.appended;
outcome.checks_refused.extend(merged.refused);
}
outcome.quarantined = self
.quarantined
.iter()
.map(|q| QuarantinedAfterPull {
mem: q.mount.mem.clone(),
code: q.reason_code.clone(),
message: q.reason_message.clone(),
})
.collect();
Ok(outcome)
}
/// The mem-repos this workspace keeps git-branch mems in, each once:
/// those of the mounted mems, then those of the quarantined ones (a
/// mem quarantined because its schema lives only on the remote is
/// still in its mem-repo), and, when no mount names one, the
/// workspace's own `mem-repo/` as `memstead mem-repo init` creates
/// it, so a workspace with no mem yet can still be wired to a remote
/// and restored from it.
fn workspace_gitdirs(&self) -> Vec<std::path::PathBuf> {
let mut gitdirs: Vec<std::path::PathBuf> = Vec::new();
let storages = self
.mounts
.iter()
.map(|m| &m.mount.storage)
.chain(self.quarantined.iter().map(|q| &q.mount.storage));
for storage in storages {
if let MountStorage::GitBranch { gitdir, .. } = storage
&& !gitdirs.contains(gitdir)
{
gitdirs.push(gitdir.clone());
}
}
if gitdirs.is_empty()
&& let Some(root) = self.workspace_root.as_ref()
{
let default = root.join("mem-repo").join(".git");
if default.is_dir() {
gitdirs.push(default);
}
}
gitdirs
}
/// Merge the remote's schema-and-config ref into the local one when
/// their histories diverged and no file changed on both sides: a
/// commit with both parents, the ref moved onto it compare-and-set
/// against the local tip the merge was computed on. `Err` carries
/// the files both sides changed; then nothing is written or moved.
fn merge_config_ref(
&self,
hook: &crate::engine::GitBranchOps,
gitdir: &std::path::Path,
local_ref: &str,
remote_ref: &str,
remote: &str,
) -> Result<Result<crate::ops::PulledRef, Option<Vec<String>>>, EngineError> {
let local = (hook.resolve_ref)(gitdir, local_ref)
.map_err(EngineError::Backend)?
.ok_or_else(|| {
EngineError::Backend(BackendError::Other(format!("{local_ref} vanished")))
})?;
let theirs = (hook.resolve_ref)(gitdir, remote_ref)
.map_err(EngineError::Backend)?
.ok_or_else(|| {
EngineError::Backend(BackendError::Other(format!("{remote_ref} vanished")))
})?;
let ctx = self.commit_context(Some("pull_all"), crate::vcs::Actor::Cli, None, None);
let message = crate::vcs::format_commit_message(
&format!("memstead: merge schema-and-config ref from {remote}"),
&ctx,
);
match (hook.merge_disjoint)(gitdir, &local, &theirs, &message)
.map_err(EngineError::Backend)?
{
crate::engine::DisjointMerge::Overlap { paths } => Ok(Err(Some(paths))),
crate::engine::DisjointMerge::Unrelated => Ok(Err(None)),
crate::engine::DisjointMerge::Merged { commit } => {
(hook.update_ref)(
gitdir,
local_ref,
&commit,
crate::engine::RefPrevious::At(&local),
)
.map_err(EngineError::Backend)?;
Ok(Ok(crate::ops::PulledRef {
ref_name: local_ref.to_string(),
mem: None,
previous_sha: local,
new_sha: commit,
}))
}
}
}
/// Fast-forward `local_ref` to what `remote_ref` points at, the
/// ancestry tested first. A local ref that does not exist is
/// created (a fast-forward from nothing).
fn fast_forward_ref(
hook: &crate::engine::GitBranchOps,
gitdir: &std::path::Path,
local_ref: &str,
remote_ref: &str,
replace_empty_seed: bool,
) -> Result<FastForward, EngineError> {
let Some(remote_sha) =
(hook.resolve_ref)(gitdir, remote_ref).map_err(EngineError::Backend)?
else {
return Ok(FastForward::NotOnRemote);
};
// The move is pinned to the local tip the decision was made on, so
// a commit that lands in between fails the move instead of being
// dropped from the branch. A lost race decides again on the new
// tip, which then usually reads as local-ahead or diverged.
let mut attempt = 0;
loop {
let local_sha = (hook.resolve_ref)(gitdir, local_ref).map_err(EngineError::Backend)?;
if let Some(l) = &local_sha {
if *l == remote_sha {
return Ok(FastForward::InSync);
}
let fast_forward =
(hook.is_ancestor)(gitdir, l, &remote_sha).map_err(EngineError::Backend)?;
let local_ahead = !fast_forward
&& (hook.is_ancestor)(gitdir, &remote_sha, l).map_err(EngineError::Backend)?;
if local_ahead {
return Ok(FastForward::LocalAhead);
}
let replaceable_seed = !fast_forward
&& replace_empty_seed
&& (hook.is_empty_root)(gitdir, l).map_err(EngineError::Backend)?;
if !fast_forward && !replaceable_seed {
return Ok(FastForward::Diverged);
}
}
let previous = match &local_sha {
Some(l) => crate::engine::RefPrevious::At(l),
None => crate::engine::RefPrevious::Absent,
};
match (hook.update_ref)(gitdir, local_ref, &remote_sha, previous) {
Ok(()) => {
return Ok(FastForward::Moved {
previous: local_sha.unwrap_or_default(),
new: remote_sha,
});
}
Err(e) => {
let now =
(hook.resolve_ref)(gitdir, local_ref).map_err(EngineError::Backend)?;
attempt += 1;
if now == local_sha || attempt == 3 {
return Err(EngineError::Backend(e));
}
}
}
}
}
/// Re-read a mounted mem's config and re-resolve its schema pin
/// against the current catalogue, the boot resolver's order. Used
/// after the schema-and-config ref moved: a pin another clone
/// switched must govern what this engine validates next. A pin that
/// no longer resolves leaves the mem's current schema in place and
/// returns the typed refusal.
fn rebind_schema_from_config(&mut self, mem: &str) -> Result<(), EngineError> {
let Some(idx) = self.mounts.iter().position(|m| m.mount.mem == mem) else {
return Ok(());
};
let mem_config = self.mounts[idx]
.backend
.read_mem_config()
.ok()
.flatten()
.and_then(|bytes| {
let value: serde_json::Value = serde_json::from_slice(&bytes).ok()?;
memstead_schema::config::parse_mem_config(&value).ok()
});
let Some(pin) = self.mounts[idx]
.mount
.migration_target
.clone()
.or_else(|| mem_config.as_ref().and_then(|c| c.schema.clone()))
.or_else(|| self.mounts[idx].mount.schema.clone())
else {
return Ok(());
};
let catalogue: Vec<std::sync::Arc<memstead_schema::Schema>> = self
.workspace_schemas
.iter()
.cloned()
.chain(self.builtin_schemas.iter().cloned())
.collect();
let schema = crate::engine::SchemaResolver::new(&catalogue)
.resolve(&pin)
.map_err(|sources| {
EngineError::SchemaNotFound {
mem: mem.to_string(),
pin: pin.as_display(),
sources,
install_hint: None,
}
.with_schema_install_probe(self.workspace_root())
})?;
let unchanged = self
.schemas
.get(mem)
.is_some_and(|current| current.id() == schema.id());
if mem_config.is_some() {
self.mounts[idx].mem_config = mem_config;
}
if !unchanged {
self.schemas_insert(mem.to_string(), schema);
}
Ok(())
}
/// Configure (or re-point) a named remote on the workspace's
/// mem-repo, so `fetch` / `pull` / `push` have somewhere to go.
/// Upsert semantics — safe to re-run with a new URL. The mem-repo
/// is shared by every git-branch mount, so the op is
/// workspace-level: any git-branch mount locates it; refuses
/// `INVALID_INPUT` when the workspace has none.
pub fn remote_add(
&self,
name: &str,
url: &str,
) -> Result<crate::ops::RemoteAddOutcome, EngineError> {
// Both values become git subprocess arguments — refuse shapes
// that would parse as flags.
if name.is_empty() || name.starts_with('-') || url.is_empty() || url.starts_with('-') {
return Err(EngineError::InvalidInput(format!(
"remote name and url must be non-empty and must not start with '-' \
(got name '{name}', url '{url}')",
)));
}
let gitdir = self.workspace_gitdirs().into_iter().next().ok_or_else(|| {
EngineError::InvalidInput(
"no mem-repo in this workspace — `remote-add` requires a mem-repo workspace"
.to_string(),
)
})?;
let hook = self.git_branch_ops.ok_or_else(|| {
EngineError::Backend(BackendError::Other(
"git-branch remote_add hook not installed (git-branch ops not wired)".to_string(),
))
})?;
(hook.remote_add)(&gitdir, name, url).map_err(EngineError::Backend)
}
/// Pre-merge schema validation pass: walks every `.md` blob at
/// `ref_name` and runs `parse_entries` with the mem's pinned
/// schema. Returns `Ok(())` when the tree is schema-clean;
/// returns `EngineError::SchemaViolationInFetch` with the list of
/// per-entity violation messages otherwise. The validation is
/// strict on parse-time errors — any `(path, error)` pair from
/// `parse_entries` triggers a refusal.
///
/// `ref_name` is the prospective state (a `refs/remotes/*` ref
/// for pull, `refs/heads/*` for push). The engine layer maps the
/// returned error into the surface code it needs
/// (`SCHEMA_VIOLATION_IN_FETCH` for pull, `LOCAL_INVALID_STATE`
/// for push).
fn validate_ref_against_schema(
&self,
hook: &crate::engine::GitBranchOps,
gitdir: &std::path::Path,
mem: &str,
ref_name: &str,
) -> Result<(), EngineError> {
// The REF first, then the schema. A branch that does not exist is the
// clearer answer, and asking for the schema first turned "that branch
// is not there" into "the schema pin did not resolve", which is true
// of a quarantined mem and tells the reader nothing about why their
// push failed (04/05).
let blobs = Self::read_ref_blobs(hook, gitdir, ref_name)?;
let schema = self
.schemas
.get(mem)
.ok_or_else(|| EngineError::SchemaNotFound {
mem: mem.to_string(),
pin: "<missing engine-side resolution>".to_string(),
// Internal invariant breach (an already-resolved schema
// absent from the per-mem map), not a source-resolution
// failure — no per-source diagnostics apply.
sources: Vec::new(),
install_hint: None,
})?
.clone();
Self::validate_blobs_against_schema(mem, ref_name, blobs, schema.as_ref())
}
/// The same whole-tree validation `pull` runs before it moves a
/// pointer, for a mem that is not mounted yet: the caller resolved
/// the schema itself (a fork validates the fetched source tree
/// against the source's pin before the mount exists). Refuses with
/// `SCHEMA_VIOLATION_IN_FETCH`, the pull path's code.
pub(crate) fn validate_ref_with_schema(
hook: &crate::engine::GitBranchOps,
gitdir: &std::path::Path,
mem: &str,
ref_name: &str,
schema: &memstead_schema::Schema,
) -> Result<(), EngineError> {
let blobs = Self::read_ref_blobs(hook, gitdir, ref_name)?;
Self::validate_blobs_against_schema(mem, ref_name, blobs, schema)
}
/// Every `.md` blob at `ref_name`; an absent ref is `UNKNOWN_REF`.
fn read_ref_blobs(
hook: &crate::engine::GitBranchOps,
gitdir: &std::path::Path,
ref_name: &str,
) -> Result<Vec<(String, String)>, EngineError> {
(hook.read_tree)(gitdir, ref_name).map_err(|e| match e {
BackendError::Other(msg) if msg.starts_with("UNKNOWN_REF:") => {
EngineError::UnknownRef(msg.trim_start_matches("UNKNOWN_REF:").trim().to_string())
}
other => EngineError::Backend(other),
})
}
/// The permissive parse plus the strict per-entity pass over the
/// blobs of one ref, against one schema.
fn validate_blobs_against_schema(
mem: &str,
ref_name: &str,
blobs: Vec<(String, String)>,
schema: &memstead_schema::Schema,
) -> Result<(), EngineError> {
let mut source_entries: Vec<crate::entity::source::SourceEntry> = Vec::new();
for (rel_path, content) in blobs {
source_entries.push(crate::entity::source::SourceEntry {
relative_path: rel_path.clone(),
source_path: std::path::PathBuf::from(rel_path),
content,
});
}
// First pass: permissive parse via the engine's loader so we
// can build Entity values for the strict validator. The
// loader silently absorbs frontmatter / title / section
// drift; the strict pass below is what catches it.
let load_result =
crate::entity::loader::parse_entries(source_entries.clone(), Vec::new(), mem, schema);
let mut violations: Vec<String> = load_result
.errors
.iter()
.map(|(path, msg)| format!("{}: {msg}", path.display()))
.collect();
// Strict per-entity validator: enforces "looks like a mem
// entity" invariants (frontmatter shape, title presence,
// required sections, unknown sections, relationship syntax,
// wiki-link shape) that the permissive loader doesn't refuse.
// Re-runs against the same source bytes so unparseable
// frontmatter surfaces here even when the loader's tolerant
// path produces an Entity stub.
let entities_by_path: std::collections::HashMap<String, &crate::entity::Entity> =
load_result
.entities
.iter()
.map(|p| (p.entity.file_path.clone(), &p.entity))
.collect();
for source in &source_entries {
let Some(entity) = entities_by_path.get(&source.relative_path) else {
continue;
};
let type_def = match schema.get_type(&entity.entity_type) {
Some(t) => t,
None => {
violations.push(format!(
"{}: unknown entity_type '{}' in schema",
source.relative_path, entity.entity_type,
));
continue;
}
};
if let Err(e) = crate::validator::strict::validate_strict(
&source.content,
entity,
type_def.as_ref(),
&source.relative_path,
) {
violations.push(format!("{}: {e}", source.relative_path));
}
}
if violations.is_empty() {
Ok(())
} else {
Err(EngineError::SchemaViolationInFetch {
mem: mem.to_string(),
ref_name: ref_name.to_string(),
violations,
})
}
}
/// Reset a mem's branch pointer to `target_sha`. The only
/// engine surface that moves a branch pointer over existing
/// commits — every other mutation appends. Refuses if any commit
/// that would be discarded by the reset is already reachable from
/// a `refs/remotes/*` ref (the engine's definition of "pushed").
///
/// `target_sha` accepts anything `gix::rev_parse_single` admits:
/// a SHA, an abbreviated SHA, a branch name, a tag. The branch
/// itself (the mount's declared branch) must exist.
///
/// Refusal codes:
/// - [`EngineError::UnknownMem`] (`UNKNOWN_MEM`)
/// - [`EngineError::UnknownRef`] (`UNKNOWN_REF`) — branch or
/// target ref does not resolve.
/// - [`EngineError::PushedCommitsProtected`]
/// (`PUSHED_COMMITS_PROTECTED`) — at least one discarded commit
/// is pushed. The error carries the offending SHAs verbatim.
/// - [`EngineError::InvalidInput`] (`INVALID_INPUT`) — mem is
/// folder / archive-backed (history rewriting only makes sense
/// for git-branch mounts).
///
/// Emits a [`crate::engine::events::MemChangedEvent`] on
/// success when the SHA actually changed; the reset's effect is
/// observable through the same change-event surface every commit
/// flows through. Engine's cached `last_known_head` for the
/// affected mount is rewound to the new SHA so the next drift
/// probe doesn't flag the reset as a sibling-writer surprise.
pub fn branch_reset(
&mut self,
mem: &str,
target_sha: &str,
expected_head: Option<&str>,
) -> Result<crate::ops::BranchResetOutcome, EngineError> {
// A branch move waits for a write in progress in any mem (a
// delete elsewhere may have read a reference the move removes);
// the subject may be unreadable. Under a proposal merge's own
// lock this is a nested acquisition and takes nothing more.
let (_write_lock, _) = self.lock_workspace_for_mem_operation(mem)?;
let mount_idx = self
.mounts
.iter()
.position(|m| m.mount.mem == mem)
.ok_or_else(|| self.unknown_mem_error(mem))?;
// History rewriting is a write — read-only and archive mounts
// refuse before any dispatch (parity with the mutation surface).
if self.mounts[mount_idx].mount.capability != crate::workspace::MountCapability::Write {
return Err(EngineError::ReadOnlyMount(mem.to_string()));
}
let outcome = match &self.mounts[mount_idx].mount.storage {
MountStorage::Folder { .. } | MountStorage::Archive { .. } | MountStorage::InMemory => {
return Err(EngineError::NotGitBacked {
mem: Some(mem.to_string()),
operation: "memstead_branch_reset".to_string(),
});
}
MountStorage::GitBranch { gitdir, branch } => match self.git_branch_ops.as_ref() {
Some(hook) => (hook.branch_reset)(gitdir, branch, target_sha, expected_head)
.map_err(|e| match e {
BackendError::Other(msg) if msg.starts_with("UNKNOWN_REF:") => {
let raw = msg.trim_start_matches("UNKNOWN_REF:").trim().to_string();
EngineError::UnknownRef(raw)
}
BackendError::Other(msg) if msg.starts_with("EXPECTED_HEAD_MISMATCH:") => {
let current = msg
.trim_start_matches("EXPECTED_HEAD_MISMATCH:")
.trim()
.to_string();
EngineError::BranchResetHeadMoved {
mem: mem.to_string(),
expected: expected_head.unwrap_or_default().to_string(),
current,
}
}
BackendError::Other(msg)
if msg.starts_with("PUSHED_COMMITS_PROTECTED:") =>
{
let payload =
msg.trim_start_matches("PUSHED_COMMITS_PROTECTED:").trim();
let pushed_shas = payload
.split(',')
.map(|s| s.trim().to_string())
.filter(|s| !s.is_empty())
.collect();
EngineError::PushedCommitsProtected {
mem: mem.to_string(),
target_sha: target_sha.to_string(),
pushed_shas,
}
}
other => EngineError::Backend(other),
})?,
None => {
return Err(EngineError::Backend(BackendError::Other(
"git-branch branch_reset hook not installed (git-branch ops not wired)"
.to_string(),
)));
}
},
};
// Rewind the engine's cached HEAD so subsequent drift probes
// don't surface MEM_RELOADED for the reset we just made.
// Then emit a change event so subscribers see the transition
// (skipping the no-op case where previous == new).
if outcome.previous_sha != outcome.new_sha {
// The store serves the tree the branch was reset to; a reload
// that fails leaves the view marked stale, so no write lands
// from the discarded commits' contents.
let _ = self.adopt_moved_head(mount_idx, mem, &outcome.new_sha);
let event = crate::engine::events::MemChangedEvent {
mem: mem.to_string(),
head: outcome.new_sha.clone(),
previous: outcome.previous_sha.clone(),
// n_commits stays at 1 for reset events. The wire
// shape is the same `MemChangedEvent` consumers
// already key on; semantics: "the head moved by this
// operation". Replay-aware consumers branch on the
// commit-vs-reset distinction by inspecting the
// produced commit (a reset's new head is an existing
// commit, not a freshly minted one).
n_commits: 1,
};
self.emit_mem_changed(&event);
}
Ok(outcome)
}
/// Cross-mem references that a reset of `mem` to `target_sha` would
/// strand: incoming edges from entities in *other* mems whose target
/// exists at the current head but would not exist at the target
/// commit — entities created after the target, or renamed to their
/// current id after it (the reset re-materialises the old id, so
/// references to the new id dangle either way).
///
/// A read — computes against the live store and the commit history,
/// moves nothing. The human surface calls this fresh at
/// confirmation-dialog time and warns before `branch_reset`. Sorted
/// (from_id, to_id, rel_type) for stable rendering.
///
/// Refusals mirror `changes_since`: `UnknownMem`, `InvalidCursor`
/// for an unresolvable `target_sha`, `InvalidInput` for
/// non-git-backed mounts.
pub fn branch_reset_stranded_refs(
&self,
mem: &str,
target_sha: &str,
) -> Result<Vec<crate::ops::StrandedCrossMemRef>, EngineError> {
use crate::ops::ChangeEnvelope;
let report = self.changes_since(mem, target_sha, None)?;
let mut discarded: std::collections::HashSet<String> = std::collections::HashSet::new();
for change in &report.changes {
match change {
ChangeEnvelope::Added { id, .. } => {
discarded.insert(id.to_string());
}
ChangeEnvelope::Renamed { to_id, .. } => {
discarded.insert(to_id.to_string());
}
ChangeEnvelope::Updated { .. } | ChangeEnvelope::Removed { .. } => {}
}
}
if discarded.is_empty() {
return Ok(Vec::new());
}
let mut stranded: Vec<crate::ops::StrandedCrossMemRef> = self
.store
.all_entities()
.filter(|e| e.mem != mem)
.flat_map(|e| {
e.relationships
.iter()
.filter(|r| discarded.contains(&r.target.to_string()))
.map(|r| crate::ops::StrandedCrossMemRef {
from_id: e.id.to_string(),
from_mem: e.mem.clone(),
to_id: r.target.to_string(),
rel_type: r.rel_type.clone(),
})
.collect::<Vec<_>>()
})
.collect();
stranded.sort_by(|a, b| {
(&a.from_id, &a.to_id, &a.rel_type).cmp(&(&b.from_id, &b.to_id, &b.rel_type))
});
Ok(stranded)
}
/// Two-ref structural diff. Produces a per-entity [`crate::ops::Diff`]
/// comparing the trees at `ref_a` and `ref_b` for the named
/// mem's storage. Folder and archive backends carry no git
/// refs and refuse via [`EngineError::InvalidInput`]; the
/// git-branch backend routes through [`GitBranchOps::diff`] when
/// the git-branch ops are wired.
///
/// `mem` selects the storage context (the gitdir, for
/// git-branch mounts). `ref_a` / `ref_b` are arbitrary refs the
/// underlying git layer accepts — branch names, commit SHAs, tag
/// names — so cross-mem diffs work via fully-qualified refs
/// (the other mount's declared branch) without a separate API. A
/// bare `HEAD` token re-anchors onto this mem's declared branch.
///
/// Refusal codes:
/// - [`EngineError::UnknownMem`] (`UNKNOWN_MEM`) — no mount
/// for `mem`.
/// - [`EngineError::UnknownRef`] (`UNKNOWN_REF`) — either ref
/// does not resolve. Surfaces verbatim from the git layer's
/// `rev_parse` refusal.
/// - [`EngineError::RenameSimilarityOutOfRange`] (`INVALID_INPUT`)
/// — `config.rename_similarity` outside `[0.1, 1.0]`.
/// - [`EngineError::InvalidInput`] (`INVALID_INPUT`) — mem is
/// folder or archive-backed (no refs to diff).
pub fn diff(
&self,
mem: &str,
ref_a: &str,
ref_b: &str,
config: Option<crate::ops::DiffConfig>,
) -> Result<crate::ops::Diff, EngineError> {
let m = self.find_mount(mem)?;
let config = config.unwrap_or_default();
if config.rename_similarity < crate::ops::RENAME_SIMILARITY_MIN
|| config.rename_similarity > crate::ops::RENAME_SIMILARITY_MAX
{
return Err(EngineError::RenameSimilarityOutOfRange {
requested: config.rename_similarity,
allowed_min: crate::ops::RENAME_SIMILARITY_MIN,
allowed_max: crate::ops::RENAME_SIMILARITY_MAX,
});
}
match &m.mount.storage {
MountStorage::Folder { .. } | MountStorage::Archive { .. } | MountStorage::InMemory => {
Err(EngineError::NotGitBacked {
mem: Some(mem.to_string()),
operation: "memstead_diff".to_string(),
})
}
MountStorage::GitBranch { gitdir, branch } => match self.git_branch_ops.as_ref() {
Some(hook) => {
(hook.diff)(gitdir, branch, mem, ref_a, ref_b, &config).map_err(|e| match e {
// Map the standard backend-side "ref not found" shape into the
// typed engine-level refusal. The git-branch dispatcher uses
// `BackendError::Other` with a leading marker so the engine can
// recover the typed code without re-parsing the message.
BackendError::Other(msg) if msg.starts_with("UNKNOWN_REF:") => {
let raw = msg.trim_start_matches("UNKNOWN_REF:").trim().to_string();
EngineError::UnknownRef(raw)
}
other => EngineError::Backend(other),
})
}
None => Err(EngineError::Backend(BackendError::Other(
"git-branch diff hook not installed (git-branch ops not wired)".to_string(),
))),
},
}
}
}
/// Anything that hands out an [`Engine`]: the engine itself, a mutable
/// borrow, a boxed engine, or a mutex guard. What [`OperationScope`]
/// wraps.
pub trait EngineHandle {
fn engine(&self) -> &Engine;
fn engine_mut(&mut self) -> &mut Engine;
}
impl EngineHandle for Engine {
fn engine(&self) -> &Engine {
self
}
fn engine_mut(&mut self) -> &mut Engine {
self
}
}
impl EngineHandle for &mut Engine {
fn engine(&self) -> &Engine {
self
}
fn engine_mut(&mut self) -> &mut Engine {
self
}
}
impl EngineHandle for Box<Engine> {
fn engine(&self) -> &Engine {
self
}
fn engine_mut(&mut self) -> &mut Engine {
self
}
}
impl EngineHandle for std::sync::MutexGuard<'_, Engine> {
fn engine(&self) -> &Engine {
self
}
fn engine_mut(&mut self) -> &mut Engine {
self
}
}
/// The scope of one operation against the engine, and the only way
/// the reload-before-operation notices reach a response.
///
/// [`Engine::reload_if_stale`] runs before every operation and, when
/// it reloaded a mem a sibling had advanced, records a
/// [`crate::ops::MemChangedNotice`] describing the delta. Until
/// 2026-09-11 those notices accumulated on the engine and every
/// response builder had to remember to drain them, or the next
/// operation's response carried a notice that was not its own (the
/// hazard the old drain's doc comment named, guarded by convention at
/// some fifty call sites). Now the notices belong to a scope: opening
/// one ([`OperationScope::begin`]) discards whatever an unscoped
/// caller left behind, [`OperationScope::finish`] hands the notices
/// out as a value together with the engine handle, and dropping a
/// scope without finishing discards them. No operation can inherit
/// another operation's notice, and there is no method on the engine
/// that hands accumulated notices out on demand.
///
/// The scope derefs to the engine, so a handler uses it exactly as it
/// used the engine handle before.
#[must_use = "an operation scope hands its notices out through `finish`; dropping it discards them"]
pub struct OperationScope<G: EngineHandle> {
inner: Option<G>,
}
impl<G: EngineHandle> OperationScope<G> {
/// Open the scope: whatever notices an unscoped caller left on the
/// engine are discarded first, so this operation starts clean.
pub fn begin(mut handle: G) -> Self {
handle.engine_mut().pending_mem_changed.clear();
Self {
inner: Some(handle),
}
}
/// Close the scope: the engine handle comes back together with the
/// notices this operation's reloads recorded, in order.
pub fn finish(mut self) -> (G, Vec<crate::ops::MemChangedNotice>) {
let mut handle = self
.inner
.take()
.expect("an operation scope is finished at most once");
let notices = std::mem::take(&mut handle.engine_mut().pending_mem_changed);
(handle, notices)
}
}
impl<G: EngineHandle> std::ops::Deref for OperationScope<G> {
type Target = Engine;
fn deref(&self) -> &Engine {
self.inner
.as_ref()
.expect("an operation scope holds its engine until finished")
.engine()
}
}
impl<G: EngineHandle> std::ops::DerefMut for OperationScope<G> {
fn deref_mut(&mut self) -> &mut Engine {
self.inner
.as_mut()
.expect("an operation scope holds its engine until finished")
.engine_mut()
}
}
impl<G: EngineHandle> Drop for OperationScope<G> {
fn drop(&mut self) {
if let Some(handle) = self.inner.as_mut() {
handle.engine_mut().pending_mem_changed.clear();
}
}
}
#[cfg(test)]
mod remote_status_source_scan;
#[cfg(test)]
mod tests;