1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135
3136
3137
3138
3139
3140
3141
3142
3143
3144
3145
3146
3147
3148
3149
3150
3151
3152
3153
3154
3155
3156
3157
3158
3159
3160
3161
3162
3163
3164
3165
3166
3167
3168
3169
3170
3171
3172
3173
3174
3175
3176
3177
3178
3179
3180
3181
3182
3183
3184
3185
3186
3187
3188
3189
3190
3191
3192
3193
3194
3195
3196
3197
3198
3199
3200
3201
3202
3203
3204
3205
3206
3207
3208
3209
3210
3211
3212
3213
3214
3215
3216
3217
3218
3219
3220
3221
3222
3223
3224
3225
3226
3227
3228
3229
3230
3231
3232
3233
3234
3235
3236
3237
3238
3239
3240
3241
3242
3243
3244
3245
3246
3247
3248
3249
3250
3251
3252
3253
3254
3255
3256
3257
3258
3259
3260
3261
3262
3263
3264
3265
3266
3267
3268
3269
3270
3271
3272
3273
3274
3275
3276
3277
3278
3279
3280
3281
3282
3283
3284
3285
3286
3287
3288
3289
3290
3291
3292
3293
3294
3295
3296
3297
3298
3299
3300
3301
3302
3303
3304
3305
3306
3307
3308
3309
3310
3311
3312
3313
3314
3315
3316
3317
3318
3319
3320
3321
3322
3323
3324
3325
3326
3327
3328
3329
3330
3331
3332
3333
3334
3335
3336
3337
3338
3339
3340
3341
3342
3343
3344
3345
3346
3347
3348
3349
3350
3351
3352
3353
3354
3355
3356
3357
3358
3359
3360
3361
3362
3363
3364
3365
3366
3367
3368
3369
3370
3371
3372
3373
3374
3375
3376
3377
3378
3379
3380
3381
3382
3383
3384
3385
3386
3387
3388
3389
3390
3391
3392
3393
3394
3395
3396
3397
3398
3399
3400
3401
3402
3403
3404
3405
3406
3407
3408
3409
3410
3411
3412
3413
3414
3415
3416
3417
3418
3419
3420
3421
3422
3423
3424
3425
3426
3427
3428
3429
3430
3431
3432
3433
3434
3435
3436
3437
3438
3439
3440
3441
3442
3443
3444
3445
3446
3447
3448
3449
3450
3451
3452
3453
3454
3455
3456
3457
3458
3459
3460
3461
3462
3463
3464
3465
3466
3467
3468
3469
3470
3471
3472
3473
3474
3475
3476
3477
3478
3479
3480
3481
3482
3483
3484
3485
3486
3487
3488
3489
3490
3491
3492
3493
3494
3495
3496
3497
3498
3499
3500
3501
3502
3503
3504
3505
3506
3507
3508
3509
3510
3511
3512
3513
3514
3515
3516
3517
3518
3519
3520
3521
3522
3523
3524
3525
3526
3527
3528
3529
3530
3531
3532
3533
3534
3535
3536
3537
3538
3539
3540
3541
3542
3543
3544
3545
3546
3547
3548
3549
3550
3551
3552
3553
3554
3555
3556
3557
3558
3559
3560
3561
3562
3563
3564
3565
3566
3567
3568
3569
3570
3571
3572
3573
3574
3575
3576
3577
3578
3579
3580
3581
3582
3583
3584
3585
3586
3587
3588
3589
3590
3591
3592
3593
3594
3595
3596
3597
3598
3599
3600
3601
3602
3603
3604
3605
3606
3607
3608
3609
3610
3611
3612
3613
3614
3615
3616
3617
3618
3619
3620
3621
3622
3623
3624
3625
3626
3627
3628
3629
3630
3631
3632
3633
3634
3635
3636
3637
3638
3639
3640
3641
3642
3643
3644
3645
3646
3647
3648
3649
3650
3651
3652
3653
3654
3655
3656
3657
3658
3659
3660
3661
3662
3663
3664
3665
3666
3667
3668
3669
3670
3671
3672
3673
3674
3675
3676
3677
3678
3679
3680
3681
3682
3683
3684
3685
3686
//! Engine read paths — accessors and queries.
//!
//! Read-only methods on `Engine`: store / schema / mount accessors,
//! per-mem path helpers (`gitdir_for` / `worktree_for`), aggregated
//! views (`communities`, `orphans`, `stubs`, `most_connected`,
//! `missing_required_outgoing`), per-mem summaries (`health`,
//! `status`, `context`), search (`list`, `search`,
//! `search_indexes`), and the bytes-level read wrappers
//! (`list_entities`, `read_entity`, `read_provenance`). Capability and
//! cross-mem link gating live here too — they're consulted by
//! handlers before any mutation reaches the backend.
use std::cell::OnceCell;
use std::collections::HashMap;
use std::path::{Path, PathBuf};
use std::sync::Arc;
use memstead_schema::Schema;
use crate::engine_fallback_type;
use crate::entity::{Entity, EntityId};
use crate::graph::{LouvainOutput, community::detect_communities};
use crate::mem::MemRouterSnapshot;
use crate::ops::{ContextResult, Direction, NeighborInfo, SearchResult, SearchScope, WarningHint};
use crate::provenance::Provenance;
#[cfg(not(target_arch = "wasm32"))]
use crate::search_index::{MemIndex, build_all};
use crate::store::Store;
use crate::workspace::{MountCapability, MountStorage, WorkspaceSettings};
use super::{BackendFactory, Engine, EngineError, MountedBackend};
impl Engine {
/// In-memory store populated at construction time from every
/// mount's backend. Read-only at this point in the rebuild —
/// mutation paths land in a later session.
pub fn store(&self) -> &Store {
&self.store
}
/// Per-mem schema, keyed by mount's mem name. Each entry is the
/// schema resolved from that mount's pin at boot, so the map holds
/// genuinely heterogeneous schemas in a multi-schema workspace.
pub fn schemas(&self) -> &HashMap<String, Arc<Schema>> {
&self.schemas
}
/// Workspace-authored schemas loaded from
/// `WorkspaceSettings.schemas_dir` at construction. Distinct from
/// [`Self::schemas`] (per-mem, only schemas pinned by a mount):
/// this slice carries every workspace-loaded schema regardless of
/// whether a mem pins it. Used by `memstead_overview` to enumerate
/// schemas referenced by `mem_create_rules.schemas[]` but not
/// pinned by any mem — agents see what could be pinned without
/// looking up the workspace.toml directly.
pub fn workspace_schemas(&self) -> &[Arc<Schema>] {
&self.workspace_schemas
}
/// Embedded built-in schemas loaded once at boot. Handlers
/// resolving a schema pin by `<name>@<version>` (MCP's `memstead_schema`,
/// `memstead_overview` rendering) walk mem-pinned, workspace, and
/// built-in catalogues in order — built-ins are the catch-all when
/// no mem or workspace dir pins the schema. Workspace schemas
/// shadow built-ins on `(name, version)` collision; resolve from
/// `workspace_schemas()` first.
pub fn builtin_schemas(&self) -> &[Arc<Schema>] {
&self.builtin_schemas
}
/// Classify a schema's trust origin — the single authority every read
/// surface consults before serving a schema's instruction-prose.
///
/// A schema is [`OriginClass::FirstParty`] iff it is an engine built-in
/// **or** pinned by a writable mount in this workspace. Built-ins are
/// compiled into the binary — unforgeable. A non-built-in schema earns
/// first-party status only once the operator *adopts* it by writably
/// mounting a mem that pins it: writing into a mem is the act that
/// legitimately needs a schema's authoring prose (`system_message`,
/// `write_rules`, …), and the mount's writable posture is set by the
/// consumer's own config — a publisher cannot forge it.
///
/// Everything else is [`OriginClass::ThirdParty`]: a schema present in
/// the catalogue but pinned only by read-only mounts (a registry-
/// installed read-mem or an adopted foreign folder/clone), or one the
/// engine cannot vouch for at all. Its prose is served structural-only
/// so a stranger's free-text never reaches a consuming agent as
/// instructions. This classifies by the mount graph — never by scanning
/// the schema's content, which a publisher controls — and `ThirdParty`
/// is the safe default for any ambiguous origin.
///
/// Note a read-only mount pinning a *built-in* schema (e.g. a registry
/// mem on `default@1.0.0`) resolves to the consumer's own clean copy
/// and stays first-party — the de-framing targets only foreign,
/// non-built-in schemas that no writable mem has adopted.
pub fn schema_origin(&self, schema: &Arc<Schema>) -> crate::render::OriginClass {
use crate::render::OriginClass;
let (name, version) = schema.id();
// Built-in schemas are compiled in — first-party, unforgeable.
let is_builtin = self.builtin_schemas.iter().any(|s| {
let id = s.id();
id.0 == name && id.1 == version
});
if is_builtin {
return OriginClass::FirstParty;
}
// Adoption signal: some writable mount pins this exact schema, so
// the operator authors against it here.
let canon = format!("{name}@{version}");
let pinned_by_writable = self.mounts().iter().any(|m| {
m.schema.as_ref().map(|s| s.to_string()).as_deref() == Some(canon.as_str())
&& self.mem_router().is_writable(&m.mem)
});
if pinned_by_writable {
OriginClass::FirstParty
} else {
OriginClass::ThirdParty
}
}
/// Classify a mem's *data* trust origin — the authority every read
/// surface consults before serving an entity's content (bodies,
/// snippets, titles). A writable mount is [`OriginClass::FirstParty`]:
/// its content is authored in this workspace. Anything else — a
/// read-only mount (a registry-installed read-mem or an adopted
/// foreign folder/clone) or an unknown mem — is
/// [`OriginClass::ThirdParty`], so the consuming agent/host treats the
/// content as quoted, untrusted data.
///
/// This reads the deployment's declaration when one exists (see
/// [`Self::declare_mem_origin`]), else the mount's already-decided
/// writable/read-only posture (fixed at adopt/mount time) — it never
/// scans content, and both levers are consumer-side config, so a
/// publisher cannot forge first-party. Distinct from
/// [`Self::schema_origin`], which governs a schema's
/// instruction-prose: the data channel and the instruction channel
/// are separate vectors with separate authorities.
pub fn mem_origin_class(&self, mem: &str) -> crate::render::OriginClass {
if let Some(declared) = self.declared_origins.get(mem) {
return *declared;
}
if self.mem_router().is_writable(mem) {
crate::render::OriginClass::FirstParty
} else {
crate::render::OriginClass::ThirdParty
}
}
/// Declare a mem's data-trust origin as a deployment fact — the
/// embedding process (a curated hosted read tier, an app that vouches
/// for a bundled mem) overrides the writability inference for one mem.
/// Composition-layer-only by design: not persisted, not reachable over
/// MCP, never derived from mem content — the operator running the
/// process is the only authority that can set it, so a served mem the
/// deployment does *not* vouch for keeps reporting third-party on
/// every surface. (Deliberately absent from UniFFI/CLI: those surfaces
/// operate a workspace, not a deployment; the CLI counterpart would be
/// a workspace-config knob no use case demands yet.)
pub fn declare_mem_origin(
&mut self,
mem: impl Into<String>,
origin: crate::render::OriginClass,
) {
self.declared_origins.insert(mem.into(), origin);
}
/// Per-file errors collected during load. Non-fatal: the engine
/// continues with whatever did parse. Empty when every backend's
/// content parses cleanly.
pub fn load_errors(&self) -> &[(PathBuf, String)] {
&self.load_errors
}
/// Workspace-level operator policy (mem create/delete rules,
/// cross-mem links). Defaults to empty; populated via
/// [`Engine::set_settings`] after construction. Surfaced for MCP
/// handlers (`memstead_health { include_config: true }`,
/// `memstead_overview`'s lifecycle-namespaces section) and other
/// consumers that need to read workspace policy.
pub fn settings(&self) -> &WorkspaceSettings {
&self.settings
}
/// The pipeline configs — the v2 single-record binding store — loaded
/// from the workspace at boot: the read-only queryable surface the
/// loader exposes. Empty for engines not booted from a workspace root,
/// or for a workspace that declares no pipelines. The ingest skill,
/// future MCP tools, and the macOS app consume this structured form
/// rather than re-reading the JSON folders.
pub fn pipeline_configs(&self) -> &crate::pipeline_store::BindingConfigs {
&self.pipeline_configs
}
/// The pipeline configs serialized as a JSON string — the read
/// counterpart of the `add_projection_json` edit entry point.
/// Serialization-boundary callers (UniFFI, where serde does not live)
/// get the store in one call and deserialize on their side.
///
/// Shape: `{ "bindings": [{ mem, name, config }] }` — the v2
/// single-record store (`config` carries the whole binding: inline
/// `sources`, `operations`, everything). The `mediums` / `facets` /
/// `ingests` keys are **gone** with their record kinds. This reads the
/// live binding store fresh (like the brief path) rather than the
/// in-memory snapshot, so an edit shows back immediately. A missing
/// root or a legacy/unreadable store yields the fallback empty object.
pub fn pipeline_configs_json(&self) -> String {
let empty = || "{\"bindings\":[]}".to_string();
let Some(root) = self.workspace_root() else {
return empty();
};
match crate::pipeline_store::load_pipeline_configs(root) {
Ok(configs) => serde_json::to_string(&configs).unwrap_or_else(|_| empty()),
Err(_) => empty(),
}
}
/// Overwrite the in-memory pipeline configs. The workspace-root boot
/// paths call this after [`crate::pipeline_store::load_pipeline_configs`];
/// exposed so the full boot helper (a separate crate) can populate the
/// same surface.
pub fn set_pipeline_configs(&mut self, configs: crate::pipeline_store::BindingConfigs) {
self.pipeline_configs = configs;
}
/// Build a [`WarningHint::NoteMissing`] when the workspace has
/// `[mutations].require_notes = true` and the caller omitted (or
/// passed a blank/whitespace-only) `note`; `None` otherwise.
///
/// This is the single enforcement point for the `require_notes`
/// provenance nudge. Every mutation that accepts a `note` calls it
/// on its commit-landing path and pushes the result onto the
/// outcome's `warnings`, so both the CLI and the MCP transports
/// inherit identical behaviour from the engine response rather than
/// each re-deriving the policy at its own boundary (the drift that
/// left the policy decorative on the CLI). `tool` becomes the
/// warning's `details.tool` — callers pass the engine-level verb
/// (`create_entity`, `update_entity`, `relate_entity`,
/// `delete_entity`, `rename_entity`, `create_mem`,
/// `delete_mem`), matching the commit `Tool:` provenance trailer.
/// The mutation still commits — the policy nudges, it never blocks.
pub fn note_missing_warning(&self, tool: &str, note: Option<&str>) -> Option<WarningHint> {
if !self.settings.mutations.require_notes.unwrap_or(false) {
return None;
}
let has_note = note.map(|n| !n.trim().is_empty()).unwrap_or(false);
if has_note {
return None;
}
Some(WarningHint::NoteMissing {
tool: tool.to_string(),
})
}
/// Backend factory currently installed on this engine. Returned by
/// value because [`BackendFactory`] is a function pointer (`Copy`).
/// Used by [`crate::mem_management::create_mem`] to materialise
/// the backend for a freshly-registered mount; consumers that need
/// to instantiate a backend ad-hoc can call this directly.
pub fn backend_factory(&self) -> BackendFactory {
self.backend_factory
}
/// Git-branch ops bundle currently installed on this engine.
/// `None` on lean-flavor engines that don't see mem-repo
/// mounts. Returned by value because [`super::GitBranchOps`] is
/// `Copy`. `create_mem` reaches for
/// the bundle to drive `prune_residue` against an unmounted
/// gitdir when the `ForceOverwrite` recovery action is selected.
pub fn git_branch_ops(&self) -> Option<super::GitBranchOps> {
self.git_branch_ops
}
/// Convenience: look up a parsed entity by id. Returns `None` for
/// unknown ids, including stub entries created for unresolved
/// inline-link targets — callers that want to distinguish real
/// from stub branch on `Entity::stub`.
pub fn get_entity(&self, id: &EntityId) -> Option<&Entity> {
self.store.get(id)
}
/// The stored provenance anchors for `id`, read from its mem's
/// anchors sidecar. Empty for an entity with none, an unknown mem, or
/// a backend that does not persist anchors (a pre-anchor archive / any
/// sealed read-only mount). Additive read surface (E3a): the
/// resolution *model* lives in [`crate::anchor`]
/// ([`crate::anchor::resolve_anchor`] / [`crate::anchor::compose_entity_anchors`]);
/// the live per-anchor *state* (which requires observing the source
/// artifacts through the medium/preparation pipeline) is E3b's concern.
pub fn entity_anchors(&self, id: &EntityId) -> Vec<crate::anchor::Anchor> {
let Some(mount) = self.mounts.iter().find(|m| m.mount.mem == id.mem()) else {
return Vec::new();
};
let Ok(Some(bytes)) = mount.backend.read_anchors_sidecar() else {
return Vec::new();
};
match crate::anchor::AnchorSidecar::from_bytes(&bytes) {
Ok(sc) => sc.get(id.as_ref()).to_vec(),
Err(_) => Vec::new(),
}
}
/// The stored anchors for `id`, each paired with its **live** resolution
/// state when the engine could observe the source artifact this pass.
///
/// Additive over [`Self::entity_anchors`]: the durable data is unchanged;
/// `state` is the [`crate::anchor::resolve_anchor`] outcome against an
/// observation the engine produces here. It is produced **only** for a
/// `path`-namespace, single-medium mem (codebase / filesystem) whose
/// medium root resolves from the workspace — the engine observes
/// working-tree existence at the current HEAD:
///
/// - artifact absent ⇒ [`AnchorState::Orphaned`](crate::anchor::AnchorState::Orphaned);
/// - artifact present, non-hash class (`authored` / `informed-by`) ⇒
/// [`Resolves`](crate::anchor::AnchorState::Resolves);
/// - artifact present, hash-bearing class (`anchored` / `derived`) ⇒ the
/// prepared-content hash comparison decides:
/// [`Resolves`](crate::anchor::AnchorState::Resolves) on a match,
/// [`Drifted`](crate::anchor::AnchorState::Drifted) on a stable-medium
/// mismatch, [`Recheck`](crate::anchor::AnchorState::Recheck) on an
/// unstable medium or when a hash is unavailable on either side (a
/// hash-less anchor, a `tree` grain, an unreadable artifact).
///
/// `state` is `None` (unobserved — never a fabricated state) when the mem
/// has no single path-medium, no workspace root, or the grain/namespace is
/// not a filesystem path. Non-`path` mediums / commit-pinned reads stay
/// deferred (E3b's remaining leg).
pub fn entity_anchors_resolved(&self, id: &EntityId) -> Vec<ResolvedAnchor> {
let anchors = self.entity_anchors(id);
anchors
.into_iter()
.map(|anchor| {
let observed = self.observe_anchor(&anchor);
let (state, observed_hash) = match observed {
Some((state, hash)) => (Some(state), hash),
None => (None, None),
};
ResolvedAnchor {
anchor,
state,
observed_hash,
}
})
.collect()
}
/// Per-anchor observation — THE one resolution mechanism, shared by
/// binding-backed verify (`mem_anchors_resolved`, which the ingest
/// render/report/prune/findings paths consume), the per-entity read
/// (`entity_anchors_resolved`), and the standalone
/// `verify_mem_anchors` operation. Each anchor resolves against its
/// own declared reference: path-shaped grains (`span`/`file`/`tree`)
/// observe against the **workspace root** — anchor artifact ids are
/// workspace-relative (pointer-prefixed), so no binding roster is
/// consulted and a hand-authored mem's anchors resolve identically
/// to a binding-backed mem's. `url`/`entity` grains have no
/// filesystem observation and return `None` (the report vocabulary's
/// `unresolvable`), as does a workspace-root-less engine. This
/// replaces the retired `single_path_medium_root` gate, whose
/// single-source assumption nulled every anchor of a mem with zero
/// or several bindings — the honest per-anchor answer supersedes the
/// all-or-nothing mem-level one.
fn observe_anchor(
&self,
anchor: &crate::anchor::Anchor,
) -> Option<(crate::anchor::AnchorState, Option<String>)> {
let root = self.workspace_root.as_deref()?;
observe_path_anchor(root, anchor)
}
/// Reverse anchor lookup: every `(entity_id, anchor)` across all mems
/// whose anchor references `artifact_path`. This is the query the
/// rebuilt check-realization hook consumes — given the file an agent
/// just edited, which entities anchored to it. A `span`/`file`/`tree`
/// anchor references the path when its base path (locator suffix
/// `@commit` / `#span` stripped) equals the path, or — for a `tree`
/// grain — when the path lies under the tree. Path-shaped grains only;
/// `url` / `entity` anchors are matched by exact base equality.
pub fn anchors_referencing_artifact(
&self,
artifact_path: &str,
) -> Vec<(EntityId, crate::anchor::Anchor)> {
let mut out = Vec::new();
for mount in &self.mounts {
let Ok(Some(bytes)) = mount.backend.read_anchors_sidecar() else {
continue;
};
let Ok(sc) = crate::anchor::AnchorSidecar::from_bytes(&bytes) else {
continue;
};
for (eid, anchors) in &sc.entities {
for a in anchors {
if anchor_references_path(a, artifact_path) {
out.push((EntityId(eid.clone()), a.clone()));
}
}
}
}
out
}
/// Every `(entity_id, resolved anchor)` in `mem`, read from its anchors
/// sidecar once and each paired with its **live** resolution state (the
/// same observation [`Self::entity_anchors_resolved`] produces per entity,
/// computed here mem-wide in a single sidecar read). Empty for an unknown
/// mem, a backend that persists no anchors, or a mem with none.
///
/// Additive read surface: the durable data is unchanged; `state` is the
/// [`crate::anchor::resolve_anchor`] outcome against an observation the
/// engine produces for a single `path`-namespace medium, or `None` when
/// unobserved (never fabricated). The verify pipeline consumes it to
/// adjudicate a mem's anchors against the source; audit/health can reuse it.
pub fn mem_anchors_resolved(&self, mem: &str) -> Vec<(EntityId, ResolvedAnchor)> {
let Some(mount) = self.mounts.iter().find(|m| m.mount.mem == mem) else {
return Vec::new();
};
let Ok(Some(bytes)) = mount.backend.read_anchors_sidecar() else {
return Vec::new();
};
let Ok(sc) = crate::anchor::AnchorSidecar::from_bytes(&bytes) else {
return Vec::new();
};
let mut out = Vec::new();
for (eid, anchors) in &sc.entities {
for anchor in anchors {
let observed = self.observe_anchor(anchor);
let (state, observed_hash) = match observed {
Some((state, hash)) => (Some(state), hash),
None => (None, None),
};
out.push((
EntityId(eid.clone()),
ResolvedAnchor {
anchor: anchor.clone(),
state,
observed_hash,
},
));
}
}
out
}
/// Standalone anchor verification — "do my sources still say what I
/// recorded?" for one mem, regardless of how it was built. Walks the
/// mem's anchor sidecar through the shared per-anchor mechanism
/// ([`Self::observe_anchor`] via [`Self::mem_anchors_resolved`]) and
/// classifies every anchor into the report vocabulary: `resolved`
/// (source present, hash matches or non-hash class), `drifted`
/// (present, hash differs, stability `stable`), `recheck` (hash
/// differs under `unstable`, or a hash is missing on either side),
/// `unresolvable` (source absent, or a grain/medium the mechanism
/// does not reach — never fabricated into drift). Read-only on mem
/// content: pure sidecar read + filesystem observation, no commit on
/// any backend. A mem with no anchors returns an empty report.
pub fn verify_mem_anchors(&self, mem: &str) -> Result<MemAnchorVerification, EngineError> {
if !self.mem_router.is_visible(mem) {
return Err(self.unknown_mem_error(mem));
}
let mut report = MemAnchorVerification {
mem: mem.to_string(),
..Default::default()
};
for (eid, resolved) in self.mem_anchors_resolved(mem) {
let state = match resolved.state {
Some(crate::anchor::AnchorState::Resolves) => {
report.resolved += 1;
"resolved"
}
Some(crate::anchor::AnchorState::Drifted) => {
report.drifted += 1;
"drifted"
}
Some(crate::anchor::AnchorState::Recheck) => {
report.recheck += 1;
"recheck"
}
Some(crate::anchor::AnchorState::Orphaned) | None => {
report.unresolvable += 1;
"unresolvable"
}
};
report.anchors.push(VerifiedAnchor {
entity_id: eid.to_string(),
artifact: resolved.anchor.artifact.clone(),
grain: resolved.anchor.grain.as_wire().to_string(),
class: resolved.anchor.class.as_wire().to_string(),
state: state.to_string(),
observed_hash: resolved.observed_hash,
});
}
Ok(report)
}
/// Mem names the engine knows about, in declaration order.
/// Cheap; useful for callers that need to enumerate before
/// dispatching by mem.
pub fn mem_names(&self) -> Vec<&str> {
self.mounts.iter().map(|m| m.mount.mem.as_str()).collect()
}
/// Derivation-staleness report for one mem (agent-trust plan 12):
/// every EXPLICIT edge whose rel-type the mem's schema declares
/// `derivation: true`, compared against its recorded baseline.
/// Baseline differs from the target's current hash → `stale`;
/// no baseline recorded (edge predates the declaration, or was
/// load-derived) → `unbaselined`, distinctly — never fabricated
/// as fresh or stale. Fresh edges are not reported. A mem whose
/// schema declares no derivation rel-types returns the empty
/// report; an unreadable sidecar reads as empty (every edge
/// unbaselined) rather than an error.
pub fn derivation_report(
&self,
mem: &str,
) -> Result<Vec<crate::ops::health::DerivationFinding>, EngineError> {
if !self.mem_router.is_visible(mem) {
return Err(self.unknown_mem_error(mem));
}
let Some(schema) = self.schemas.get(mem) else {
return Ok(Vec::new());
};
let declared: std::collections::HashSet<&str> = schema
.manifest
.relationships
.definitions
.iter()
.filter(|d| d.derivation)
.map(|d| d.name.as_str())
.collect();
if declared.is_empty() {
return Ok(Vec::new());
}
let sidecar = self
.mounts
.iter()
.find(|m| m.mount.mem == mem)
.and_then(|m| {
m.backend
.read_entity(Path::new(crate::derivation::DERIVATION_SIDECAR_PATH))
.ok()
.flatten()
})
.and_then(|bytes| crate::derivation::DerivationSidecar::from_bytes(&bytes).ok())
.unwrap_or_default();
let mut out = Vec::new();
let mut sources: Vec<&crate::entity::Entity> = self
.store
.all_entities()
.filter(|e| !e.stub && e.id.mem() == mem)
.collect();
sources.sort_by(|a, b| a.id.as_ref().cmp(b.id.as_ref()));
for entity in sources {
for edge in self.store.outgoing(&entity.id) {
if !declared.contains(edge.rel_type.as_str())
|| edge.source != crate::store::EdgeSource::Explicit
{
continue;
}
let current = self
.store
.get(&edge.target)
.map(|t| t.content_hash.clone())
.unwrap_or_default();
match sidecar.get(entity.id.as_ref(), &edge.rel_type, edge.target.as_ref()) {
None => out.push(crate::ops::health::DerivationFinding {
source: entity.id.clone(),
rel_type: edge.rel_type.clone(),
target: edge.target.clone(),
state: "unbaselined".to_string(),
baseline: None,
current,
}),
Some(baseline) if baseline != current => {
out.push(crate::ops::health::DerivationFinding {
source: entity.id.clone(),
rel_type: edge.rel_type.clone(),
target: edge.target.clone(),
state: "stale".to_string(),
baseline: Some(baseline.to_string()),
current,
})
}
Some(_) => {}
}
}
}
Ok(out)
}
/// Public-shape mount record for `mem`, or `None` for an unknown
/// mem.
///
/// Surfaces the operator-facing
/// [`crate::workspace::Mount`] (mem name, schema pin, storage
/// reference, capability, lifecycle, cross_linkable) so MCP / CLI
/// handlers can branch on backend-specific shapes via
/// [`crate::workspace::MountStorage`] when they need accessors
/// that don't make sense on every backend (e.g. gitdir / branch
/// for `memstead_health { include_config: true }`'s git-class
/// payload). Backends that want the equivalent of full's
/// `engine.gitdir_for(mem)` match
/// `engine.mount(mem).map(|m| &m.storage)` against
/// `MountStorage::GitBranch { gitdir, branch }` and walk
/// directly — keeps the engine surface backend-neutral.
///
/// Counterpart to [`Self::mem_names`] which lists every mount.
pub fn mount(&self, mem: &str) -> Option<&crate::workspace::Mount> {
self.mounts
.iter()
.find(|m| m.mount.mem == mem)
.map(|m| &m.mount)
}
/// Orphan count attributed to each mem's pinned schema, over the
/// given `orphan_ids` (the caller pre-filters them by any mem scope).
/// Lets a health surface show that ingest-mem isolates (orphans by
/// design) and code-mem debt land in different schema buckets rather
/// than one blended, misleading total. Mems with no settled pin
/// bucket under the empty string.
pub fn orphans_by_schema(
&self,
orphan_ids: &[EntityId],
) -> std::collections::BTreeMap<String, usize> {
let mut by_schema = std::collections::BTreeMap::new();
for id in orphan_ids {
let schema = self
.store()
.get(id)
.and_then(|e| self.mount(&e.mem))
.and_then(|m| m.schema.as_ref().map(|s| s.as_display()))
.unwrap_or_default();
*by_schema.entry(schema).or_insert(0) += 1;
}
by_schema
}
/// Community count attributed to each schema across `mems`: a cluster
/// counts toward every schema whose mems it touches, so these figures
/// can sum above the global community count — the same "touches"
/// semantic as the mem-scoped count. Per-schema dedup keeps a cluster
/// touching two mems of one schema from being counted twice.
pub fn communities_by_schema(
&self,
mems: &[String],
) -> std::collections::BTreeMap<String, usize> {
let louvain = self.communities();
let mut buckets: std::collections::BTreeMap<String, std::collections::BTreeSet<String>> =
std::collections::BTreeMap::new();
for name in mems {
let schema = self
.mount(name)
.and_then(|m| m.schema.as_ref().map(|s| s.as_display()))
.unwrap_or_default();
let clusters = crate::graph::community::clusters_in_mem(self.store(), louvain, name);
buckets.entry(schema).or_default().extend(clusters);
}
buckets
.into_iter()
.map(|(schema, set)| (schema, set.len()))
.collect()
}
/// All mounts the engine knows about, in declaration order.
/// Counterpart to [`Self::mem_names`] when the caller needs
/// the full mount shape (e.g. to enumerate by storage variant).
pub fn mounts(&self) -> Vec<&crate::workspace::Mount> {
self.mounts.iter().map(|m| &m.mount).collect()
}
/// Names of mems whose mount declares
/// [`crate::workspace::MountCapability::Write`], in declaration
/// order. Convenience over `mounts().iter().filter(...).map(...)`
/// for handlers that gate by writable status (`memstead_health`,
/// `memstead_overview`'s mem roster, the lifecycle tools'
/// candidate list). Read-only mounts (archive backends) are
/// excluded.
pub fn writable_mem_names(&self) -> Vec<&str> {
self.mounts
.iter()
.filter(|m| m.mount.capability == MountCapability::Write)
.map(|m| m.mount.mem.as_str())
.collect()
}
/// The default writable mem — the target a mutation lands in when
/// it omits `mem`. `None` when no writable mem is mounted.
///
/// Defined as the **first writable mount in declaration order**, i.e.
/// the seed / earliest-created writable mem. This is a *stable*
/// designation, not a function of the current name set: new mems
/// register via `register_writable_mem`, which pushes onto the end
/// of the mount list (and `mounts.json` preserves that order across
/// reboots), so creating an additional mem never moves the default
/// — even one whose name sorts ahead alphabetically. Deleting the
/// current default promotes the next-earliest writable mem; that is
/// the only thing that shifts it. Both the MCP `resolve_mem` and the
/// CLI's omitted-`--mem` path resolve through here so the two
/// surfaces always agree (the
/// pre-fix MCP path read `writable_mems().iter().next()` off an
/// unordered `HashSet`, which silently retargeted writes when a second
/// mem appeared).
pub fn default_writable_mem(&self) -> Option<&str> {
self.mounts
.iter()
.find(|m| m.mount.capability == MountCapability::Write)
.map(|m| m.mount.mem.as_str())
}
/// On-disk folder path for a folder-backed mount, or `None` for
/// any other backend (git-branch, archive) or unknown mem.
/// Convenience over `engine.mount(mem).map(|m| &m.storage)` +
/// matching on `MountStorage::Folder { path }`. Used by
/// handlers that need a filesystem path for a folder mem
/// (e.g. `memstead_health { include_config: true }`'s
/// `mems[].vcs.worktree` field for folder mounts).
pub fn folder_path_for_mem(&self, mem: &str) -> Option<&Path> {
match self.mount(mem).map(|m| &m.storage) {
Some(crate::workspace::MountStorage::Folder { path }) => Some(path.as_path()),
_ => None,
}
}
/// Runtime snapshot of writable / visible mems. Handlers that
/// need the writable roster (`memstead_health`'s `writable_mems` /
/// `read_mems`), per-mem origin tag (`include_config:
/// true`'s `mems[].origin`), or visibility check
/// (`memstead_overview`'s mem list, the lifecycle tools' collision
/// guard) consume the router here. Returned by reference — the
/// `Arc` is held on the engine; callers that need a clonable
/// handle can `Arc::clone` the engine's field directly when that
/// surface arrives.
pub fn mem_router(&self) -> &MemRouterSnapshot {
&self.mem_router
}
/// Resolve the gitdir for a writable mem. Used by `memstead_health
/// { include_config: true }` to surface per-mem `vcs.gitdir`
/// so outer-repo bookkeeping clients can `git -C <gitdir>` per
/// mem without hardcoding the layout.
///
/// - `EngineError::UnknownMem` when the name does not resolve.
/// - `EngineError::Mem` when the mount's storage is not
/// git-branch-backed (folder, archive — they have no gitdir).
pub fn gitdir_for(&self, mem_name: &str) -> Result<PathBuf, EngineError> {
let m = self
.mount(mem_name)
.ok_or_else(|| self.unknown_mem_error(mem_name))?;
match &m.storage {
MountStorage::GitBranch { gitdir, .. } => Ok(gitdir.clone()),
MountStorage::Folder { .. } | MountStorage::Archive { .. } | MountStorage::InMemory => {
Err(EngineError::Mem(format!(
"mem '{mem_name}' has no resolved gitdir"
)))
}
}
}
/// Resolve the worktree for a writable mem. Used by
/// `memstead_health { include_config: true }` to surface per-mem
/// `vcs.worktree`.
///
/// - `EngineError::UnknownMem` when the name does not resolve.
/// - `EngineError::Mem` when the mount's backend has no
/// worktree concept (git-branch with no working tree, archive).
///
/// Folder mounts surface their on-disk path. Git-branch mounts
/// follow the `dir: Some(...)` composition pattern: when the
/// workspace root contains a folder named after the mem with a
/// `.memstead/config.json` marker, that folder is the worktree
/// (disk-shape composition). Otherwise — pure mem-repo-backed
/// — return Err.
pub fn worktree_for(&self, mem_name: &str) -> Result<PathBuf, EngineError> {
let m = self
.mount(mem_name)
.ok_or_else(|| self.unknown_mem_error(mem_name))?;
match &m.storage {
MountStorage::Folder { path } => Ok(path.clone()),
MountStorage::GitBranch { .. } => {
if let Some(root) = self.workspace_root.as_deref() {
let candidate = root.join(mem_name);
if candidate
.join(crate::mem::MEM_META_DIR)
.join("config.json")
.is_file()
{
return Ok(candidate.canonicalize().unwrap_or(candidate));
}
}
Err(EngineError::Mem(format!(
"mem '{mem_name}' has no working tree (mem-repo-backed)"
)))
}
MountStorage::Archive { .. } => Err(EngineError::Mem(format!(
"mem '{mem_name}' is archive-backed and has no worktree"
))),
MountStorage::InMemory => Err(EngineError::Mem(format!(
"mem '{mem_name}' is in-memory and has no worktree"
))),
}
}
/// Per-mem `.memstead/config.json` payload, when available. Used
/// by `memstead_health { include_config: true }` to surface the
/// opaque `write_guidance` map and the catch-all `extra` fields
/// per mem.
///
/// Folder-backed mounts return `Some(&MemConfig)` when
/// `<path>/.memstead/config.json` parsed cleanly at construction.
/// Git-branch and archive backends return `None` until the
/// read-from-storage-backend path lifts (the V1 unified engine
/// loads configs only from folder layouts; the file lives
/// inside the gitdir / archive for the other backends and
/// needs a backend-level read primitive).
///
/// Unknown mem names return `None` (no error variant — the
/// accessor is intentionally lenient because memstead_health emits
/// an empty detail block per missing config rather than
/// aborting the call).
pub fn mem_config_for(&self, mem: &str) -> Option<&memstead_schema::config::MemConfig> {
self.mounts
.iter()
.find(|m| m.mount.mem == mem)
.and_then(|m| m.mem_config.as_ref())
}
/// The authoring-provenance payload an installed mem carries, read
/// from the archive's `.memstead/provenance.json` at construction.
/// `None` when the mem carries none (a pre-provenance archive, a
/// runtime-created mem, or a backend that does not surface one) —
/// the read path reports provenance as absent. Unknown mem names
/// return `None`.
pub fn archive_provenance_for(&self, mem: &str) -> Option<&memstead_schema::ArchiveProvenance> {
self.mounts
.iter()
.find(|m| m.mount.mem == mem)
.and_then(|m| m.archive_provenance.as_ref())
}
/// Iterate `(mem_name, &MemConfig)` for every mount whose
/// mem-config payload loaded at construction. Used by callers
/// that walk every writable mount's config (`memstead health`'s
/// per-mem dump, the workspace-dump CLI). The yielded `&str` is
/// the authoritative mem leaf from the mount record.
///
/// Folder-backed mounts yield when their `.memstead/config.json`
/// parsed cleanly. Git-branch and archive backends are silent in
/// V1 (the same deferred-read-from-storage gap that
/// [`Self::mem_config_for`] documents).
pub fn mem_configs_named(
&self,
) -> impl Iterator<Item = (&str, &memstead_schema::config::MemConfig)> {
self.mounts
.iter()
.filter_map(|m| m.mem_config.as_ref().map(|c| (m.mount.mem.as_str(), c)))
}
/// Resolved `Arc<Schema>` for a writable mem by name. `None`
/// when the name is not a registered mount.
///
/// Cheap — `Arc::clone` over the per-mem schema map. Resolved
/// schemas are stored in `HashMap<String, Arc<Schema>>` so the
/// lookup is a single hash hit + clone.
pub fn schema_for(&self, mem: &str) -> Option<std::sync::Arc<memstead_schema::Schema>> {
self.schemas.get(mem).cloned()
}
/// Cached current branch-tip cursor (typically a 40-char hex
/// SHA for git-branch backends; `None` for fresh mems or
/// backends that don't track a head — folder / archive).
///
/// The value is the per-mount `last_known_head`, seeded at
/// construction by `backend.current_head()` and refreshed by
/// [`Self::reload_if_stale`] / mutation paths after a
/// successful commit.
///
/// - `EngineError::UnknownMem` when the name does not resolve.
pub fn mem_head_sha(&self, mem_name: &str) -> Result<Option<String>, EngineError> {
let m = self
.mounts
.iter()
.find(|m| m.mount.mem == mem_name)
.ok_or_else(|| self.unknown_mem_error(mem_name))?;
Ok(m.last_known_head.clone())
}
/// Whether a sibling writer has advanced this mem's backend past
/// the engine's cached `last_known_head` — a read-only drift probe
/// that does **not** reload (unlike [`Self::reload_if_stale`]). One
/// `backend.current_head()` read compared against the cached cursor;
/// the comparison clears once the engine re-reads (a `reload` /
/// `reload_if_stale` refreshes `last_known_head` to the live tip).
///
/// Only git-branch backends track a head, so folder / archive /
/// in-memory mounts always report `false`. A backend that errors on
/// the probe (transient refdb hiccup) reports `false` rather than
/// surfacing the error — drift is advisory, and the next real
/// operation's reload path is the authoritative sync.
///
/// - `EngineError::UnknownMem` when the name does not resolve.
pub fn mem_drifted(&self, mem_name: &str) -> Result<bool, EngineError> {
let m = self
.mounts
.iter()
.find(|m| m.mount.mem == mem_name)
.ok_or_else(|| self.unknown_mem_error(mem_name))?;
let live = m.backend.current_head().ok().flatten();
Ok(live != m.last_known_head)
}
/// Workspace root the engine booted from, when one is known.
/// `None` for engines built directly from a mount list (tests,
/// ad-hoc consumers). Set by [`Self::from_workspace_root`] and
/// the full counterpart.
pub fn workspace_root(&self) -> Option<&Path> {
self.workspace_root.as_deref()
}
/// Typed warnings surfaced during mem load — drift findings
/// the loader pipeline collects per entity. Empty for V1; the
/// accessor surfaces them so handlers can merge into health
/// summaries uniformly.
pub fn load_warnings(&self) -> &[WarningHint] {
&self.load_warnings
}
/// The quarantine roster: mems that failed their mem-level boot
/// step and serve nothing until repaired + reloaded. Empty on a
/// fully healthy workspace. Surfaced on overview and health.
pub fn quarantined_mems(&self) -> &[crate::engine::QuarantinedMem] {
&self.quarantined
}
/// The quarantine entry for `mem`, when it is quarantined.
pub fn quarantine_reason(&self, mem: &str) -> Option<&crate::engine::QuarantinedMem> {
self.quarantined.iter().find(|q| q.mount.mem == mem)
}
/// The typed error for a mem name that did not resolve to a
/// serving mount: `MEM_QUARANTINED` (carrying the underlying boot
/// failure and its repair command) when the mem is on the
/// quarantine roster, `UNKNOWN_MEM` otherwise. Every lookup site
/// that fails to find a mem routes here so a quarantined mem is
/// never misreported as unknown — honest absence, with the reason.
pub fn unknown_mem_error(&self, mem: &str) -> EngineError {
match self.quarantine_reason(mem) {
Some(q) => EngineError::MemQuarantined {
mem: mem.to_string(),
reason_code: q.reason_code.clone(),
reason_message: q.reason_message.clone(),
},
None => EngineError::UnknownMem(mem.to_string()),
}
}
/// The workspace-level boot diagnosis a diagnostic-shell engine
/// carries (`None` on ordinarily booted engines).
pub fn boot_diagnosis(&self) -> Option<(&str, &str)> {
self.boot_diagnosis
.as_ref()
.map(|(c, m)| (c.as_str(), m.as_str()))
}
/// Build a mem-less diagnostic-shell engine for a workspace whose
/// boot failed at the WORKSPACE level (nothing loadable — e.g. an
/// unparseable store). It serves no mems and no entities; its one
/// job is answering overview/health with the typed boot diagnosis
/// so a session can always ask WHY the graph is gone — the MCP
/// server serves this instead of exiting into `-32000 Connection
/// closed` (degrade, never disappear).
pub fn diagnostic_shell(reason_code: String, reason_message: String) -> Engine {
let mut engine =
Engine::from_mounts(Vec::new()).expect("an empty mount list always constructs");
engine.boot_diagnosis = Some((reason_code, reason_message));
engine
}
/// Append boot-path quarantine entries recorded outside
/// `from_mounts_inner` (backend-instantiation failures happen
/// before the mount list reaches the engine constructor). Boot
/// paths only — quarantine is a boot judgment, never a runtime
/// mutation.
pub fn extend_quarantine(&mut self, entries: Vec<crate::engine::QuarantinedMem>) {
self.quarantined.extend(entries);
}
// ---------------------------------------------------------------
// Read-side delegates onto the kernel ops/graph functions.
//
// The mem-router engine exposed each of these directly so the
// MCP layer could call them without reaching into the store. The
// unified engine mirrors that surface so the MCP migration is a
// straight rename rather than a re-architecture.
//
// Multi-mem cache strategy: per-mem community detection and
// per-mem search indexes are unnecessary at this layer — the
// engine-wide store already carries every mount's edges; Louvain
// and tantivy run once across the union. `mem_schemas` for
// health/search is the engine's existing `schemas` field as-is.
// ---------------------------------------------------------------
/// Lazy community-detection cache. First call runs Louvain
/// against the current store using one pinned schema for
/// `community.{resolution, seed}` and the per-rel weights.
/// Subsequent calls return the cached result. Mutations invalidate
/// the cache via [`Self::invalidate_communities`].
///
/// One detection run per engine. The partition is workspace-global,
/// so it needs a single source for the Louvain parameters; that
/// source is the schema of the lexicographically-first mem name —
/// a stable key, so the partition is deterministic across processes
/// even when mounts pin heterogeneous schemas. For a single-schema
/// workspace every mem's schema is identical, so the choice of
/// key is immaterial there.
pub fn communities(&self) -> &LouvainOutput {
self.community_memo.get_or_init(|| {
// Select the parameter schema by a stable key (smallest
// mem name) rather than unordered-map iteration, so the
// partition does not vary between processes. Fall back to
// the builtin default for the empty-mounts case (caller
// still gets a valid empty Louvain result against an empty
// store).
let schema = self
.schemas
.iter()
.min_by(|a, b| a.0.cmp(b.0))
.map(|(_, s)| s.clone())
.unwrap_or_else(Schema::builtin_default);
let manifest = &schema.manifest;
let resolution = manifest.community.resolution;
let seed = manifest.community.seed;
let schema_for_weights = schema.clone();
detect_communities(&self.store, resolution, seed, move |rel_type| {
schema_for_weights
.manifest
.relationships
.definitions
.iter()
.find(|d| d.name == rel_type)
.map(|d| d.default_weight as f64)
.unwrap_or(1.0)
})
})
}
/// Drop the cached community detection result.
pub fn invalidate_communities(&mut self) {
self.community_memo = OnceCell::new();
}
/// Real entities with no incoming or outgoing edges — leaf-declared
/// types exempt (their edge-less entities are terminal by
/// construction; see [`Self::leaf_population`]).
pub fn orphans(&self) -> Vec<EntityId> {
crate::graph::query::find_orphans_with_schemas(&self.store, &self.schemas)
}
/// Count of real entities per leaf-declared type, keyed
/// `<schema_ref>:<type>` — the visible population the orphan
/// exemption covers.
pub fn leaf_population(&self) -> std::collections::BTreeMap<String, usize> {
crate::graph::query::leaf_population(&self.store, &self.schemas)
}
/// Stub entities with their referencer ids.
pub fn stubs(&self) -> Vec<(EntityId, Vec<EntityId>)> {
crate::graph::query::find_stubs(&self.store)
}
/// Top `limit` entities by total degree.
pub fn most_connected(&self, limit: usize) -> Vec<crate::graph::query::Connectivity> {
crate::graph::query::most_connected(&self.store, limit)
}
/// Entities whose type's `required_outgoing` blocks are not yet
/// satisfied. `mem_filter = None` scans every mem; `Some(v)`
/// scans only that mem.
pub fn missing_required_outgoing(
&self,
mem_filter: Option<&str>,
) -> Vec<crate::ops::health::MissingRequiredOutgoingReport> {
crate::ops::health::collect_missing_required_outgoing(
&self.store,
mem_filter,
&self.schemas,
)
}
/// Standing violations of declared `constraints` (the health
/// `constraints` include) — every non-stub entity whose type
/// declares constraints its current state violates, in
/// deterministic `(mem, id)` order.
pub fn constraint_findings(
&self,
mem_filter: Option<&str>,
) -> Vec<crate::ops::health::ConstraintFindingReport> {
crate::ops::health::collect_constraint_findings(&self.store, mem_filter, &self.schemas)
}
/// Defective section-format declarations the loaded schemas carry
/// (lenient boot recorded them; install would have refused).
pub fn schema_format_defects(&self) -> Vec<crate::ops::health::SchemaFormatDefect> {
crate::ops::health::collect_schema_format_defects(&self.schemas)
}
/// Conformance-axis integrity findings for one mem — which
/// entities a write would refuse under the effective schema, and
/// why. `target_schema = None` lints against the mem's current
/// pin; `Some(ref)` lints against that schema instead (resolved
/// among mem-pinned, workspace, and built-in schemas).
pub fn conformance_findings(
&self,
mem: &str,
target_schema: Option<&memstead_schema::SchemaRef>,
) -> Result<Vec<crate::ops::integrity::IntegrityFinding>, EngineError> {
let pinned = self
.schemas
.get(mem)
.ok_or_else(|| self.unknown_mem_error(mem))?;
let effective: Arc<Schema> = match target_schema {
None => pinned.clone(),
Some(target) => self.resolve_schema_by_ref(target).ok_or_else(|| {
let consulted: Vec<_> = self
.workspace_schemas
.iter()
.chain(self.builtin_schemas.iter())
.cloned()
.collect();
EngineError::SchemaNotFound {
mem: mem.to_string(),
pin: target.as_display(),
sources: crate::engine::error::SchemaSourceDiagnostic::for_failed_pin(
&target.name,
&target.version,
&consulted,
),
install_hint: None,
}
.with_schema_install_probe(self.workspace_root())
})?,
};
Ok(crate::ops::integrity::conformance_findings(
&self.store,
mem,
&effective,
&self.schemas,
))
}
/// Resolve an exact `name@version` ref against every schema this
/// engine can see: mem-pinned, workspace-authored, built-in.
/// `None` when no loaded schema matches.
pub(crate) fn resolve_schema_by_ref(
&self,
target: &memstead_schema::SchemaRef,
) -> Option<Arc<Schema>> {
self.schemas
.values()
.chain(self.workspace_schemas.iter())
.chain(self.builtin_schemas.iter())
.find(|s| {
let (name, version) = s.id();
name == target.name && version == target.version
})
.cloned()
}
/// The mem's `Mount.schema` expectation assertion, when set.
/// `None` for unknown mems *and* for mems whose mount carries no
/// assertion (the authoritative pin then lives in the backend
/// config; the resolved active schema, not this, is the effective pin).
pub fn schema_pin(&self, mem: &str) -> Option<memstead_schema::SchemaRef> {
self.mounts
.iter()
.find(|m| m.mount.mem == mem)
.and_then(|m| m.mount.schema.clone())
}
/// The mem's in-flight migration target, when dual-pin state is
/// active. `None` for settled or unknown mems.
pub fn migration_target(&self, mem: &str) -> Option<memstead_schema::SchemaRef> {
self.mounts
.iter()
.find(|m| m.mount.mem == mem)
.and_then(|m| m.mount.migration_target.clone())
}
/// Consistency-axis integrity findings for one mem — the
/// pre-existing graph-coherence categories (dangling links, stubs)
/// projected into the `{ id, axis, code, detail }` finding shape.
pub fn consistency_findings(
&self,
mem: &str,
) -> Result<Vec<crate::ops::integrity::IntegrityFinding>, EngineError> {
if !self.schemas.contains_key(mem) {
return Err(self.unknown_mem_error(mem));
}
Ok(crate::ops::integrity::consistency_findings(
&self.store,
mem,
))
}
/// Engine-wide health summary across every mount.
pub fn health(&self) -> crate::ops::HealthSummary {
let fallback = engine_fallback_type();
let mut summary =
crate::ops::health::compute_health(&self.store, fallback.as_ref(), &self.schemas);
// Merge in load-time drift warnings so every caller of
// Engine::health — MCP handler, Swift FFI, direct CLI —
// sees the SuspiciousNestedPrefix / DuplicateSectionHeading
// findings without reaching into private engine state. The
// MCP handler further appends request-scoped warnings on
// top. Mirrors full's merge.
if !self.load_warnings.is_empty() {
let mut merged = self.load_warnings.clone();
merged.append(&mut summary.warnings);
summary.warnings = merged;
}
// Quarantine roster — a boot-honesty fact, present whenever
// non-empty, never behind an include gate. Empty (and omitted
// from the wire) on a healthy workspace.
summary.quarantined = self
.quarantined
.iter()
.map(|q| crate::ops::QuarantinedMemReport {
mem: q.mount.mem.clone(),
reason_code: q.reason_code.clone(),
reason_message: q.reason_message.clone(),
})
.collect();
summary.boot_diagnosis = self
.boot_diagnosis
.as_ref()
.map(|(code, message)| serde_json::json!({ "code": code, "message": message }));
// Surface OUTER_REPO_NOT_IGNORING_MEM_REPO when the
// workspace is embedded inside a git repository whose
// .gitignore does not list `mem-repo/`. Skipped when
// workspace_root is unset (engine built ad-hoc from a mount
// list).
if let Some(root) = self.workspace_root.as_deref()
&& let Some(outer) = crate::workspace_root::find_enclosing_git_repo(root)
&& !crate::workspace_root::outer_repo_ignores_mem_repo(&outer, root)
{
summary
.warnings
.push(WarningHint::OuterRepoNotIgnoringMemRepo {
outer_repo_root: outer.display().to_string(),
workspace_root: root.display().to_string(),
});
}
// Authoring-drift axis: for every pinned schema whose sealed
// copy carries an install-provenance stamp, report a MISSING
// authoring package (stamped path gone) or a DIVERGED one
// (present but no longer parsed-equivalent to the seal).
// Unstamped schemas — sealed pre-stamp, built-ins, archive
// installs — produce no finding. Read-only on both copies.
summary.warnings.extend(self.authoring_drift_findings());
summary
}
/// Compute the authoring-drift findings for every stamped pinned
/// schema. See the call site in [`Self::health`] for the axis
/// contract; returns an empty list when no workspace root is set
/// (ad-hoc mount-list engines have no authoring tree to check).
fn authoring_drift_findings(&self) -> Vec<WarningHint> {
let Some(root) = self.workspace_root.as_deref() else {
return Vec::new();
};
// Group pinning mems by (name, version) — BTreeMap for a
// deterministic finding order.
let mut pins: std::collections::BTreeMap<(String, String), Vec<String>> =
std::collections::BTreeMap::new();
for (mem, schema) in &self.schemas {
let (name, version) = schema.id();
pins.entry((name.to_string(), version.to_string()))
.or_default()
.push(mem.clone());
}
let mut out = Vec::new();
for ((name, version), mut mems) in pins {
mems.sort();
let Some(stamped_path) = self.read_install_provenance(root, &name, &version) else {
continue;
};
let schema_ref = format!("{name}@{version}");
let authoring = std::path::Path::new(&stamped_path);
if !authoring.is_dir() {
out.push(WarningHint::SchemaAuthoringSourceMissing {
schema_ref,
stamped_path,
mems,
});
continue;
}
let sealed = self
.schemas
.get(&mems[0])
.expect("mems collected from self.schemas keys")
.clone();
match memstead_schema::load_schema_from_dir(authoring) {
Err(e) => out.push(WarningHint::SchemaAuthoringSourceDiverged {
schema_ref,
stamped_path,
mems,
detail: format!("the authoring package no longer loads: {e}"),
}),
Ok(authored) => {
if schema_parsed_fingerprint(&authored) != schema_parsed_fingerprint(&sealed) {
out.push(WarningHint::SchemaAuthoringSourceDiverged {
schema_ref,
stamped_path,
mems,
detail: "the parsed authoring package differs from the sealed copy \
the engine runs on"
.to_string(),
});
}
}
}
}
out
}
/// Read the install-provenance stamp for a sealed schema package,
/// checking the folder location first
/// (`.memstead/schemas/<name>@<version>/`) and falling back to the
/// `__MEMSTEAD:schemas/` ref via the git-branch ops bundle when
/// wired. `None` when no stamp exists anywhere — the normal state
/// for pre-stamp seals, built-ins, and archive installs.
fn read_install_provenance(&self, root: &Path, name: &str, version: &str) -> Option<String> {
let folder_stamp = root
.join(".memstead")
.join("schemas")
.join(format!("{name}@{version}"))
.join(memstead_schema::INSTALL_PROVENANCE_FILE);
let bytes = if folder_stamp.is_file() {
std::fs::read(&folder_stamp).ok()
} else {
let ops = self.git_branch_ops()?;
let gitdir = self
.mounts
.iter()
.find_map(|m| match &m.mount.storage {
crate::workspace::MountStorage::GitBranch { gitdir, .. } => {
Some(gitdir.clone())
}
_ => None,
})
.or_else(|| {
let g = root.join("mem-repo").join(".git");
g.is_dir().then_some(g)
})?;
(ops.read_schema_file)(
&gitdir,
name,
version,
memstead_schema::INSTALL_PROVENANCE_FILE,
)
.ok()
.flatten()
}?;
let v: serde_json::Value = serde_json::from_slice(&bytes).ok()?;
v.get("authoring_path")?.as_str().map(String::from)
}
/// Engine-wide [`crate::ops::Status`] across every mount — the graph
/// counts behind `memstead status` (renamed from `stats` with the
/// command, D11; fields unchanged).
pub fn status(&self) -> crate::ops::Status {
let mut types_in_use: Vec<String> = self
.store
.all_entities()
.filter(|e| !e.stub && !e.entity_type.is_empty())
.map(|e| e.entity_type.clone())
.collect();
types_in_use.sort();
types_in_use.dedup();
let mut edge_types: HashMap<String, usize> = HashMap::new();
for id in self.store.all_ids() {
for edge in self.store.outgoing(id) {
*edge_types.entry(edge.rel_type.clone()).or_insert(0) += 1;
}
}
crate::ops::Status {
entity_count: self.store.all_entities().filter(|e| !e.stub).count(),
edge_count: self.store.edge_count(),
edge_types,
community_count: self.communities().count,
mem_count: self.mounts.len(),
types_in_use,
}
}
/// Build a [`ContextResult`] for `id`: the community cluster id
/// (or `None` when the entity is a stub or not present), plus the
/// outgoing + incoming neighbour lists.
pub fn context(&self, id: &EntityId) -> Option<ContextResult> {
let entity = self.store.get(id)?;
let community = self
.communities()
.entity_cluster_map
.get(id.as_ref())
.cloned();
let mut neighbors = Vec::new();
for edge in self.store.outgoing(id) {
if let Some(target) = self.store.get(&edge.target) {
neighbors.push(NeighborInfo {
id: target.id.clone(),
title: target.title.clone(),
relationship: edge.rel_type.clone(),
direction: Direction::Outgoing,
});
}
}
for edge in self.store.incoming(id) {
if let Some(source) = self.store.get(&edge.from) {
neighbors.push(NeighborInfo {
id: source.id.clone(),
title: source.title.clone(),
relationship: edge.rel_type.clone(),
direction: Direction::Incoming,
});
}
}
Some(ContextResult {
entity_id: entity.id.clone(),
community,
neighbors,
})
}
/// Lazily-built per-mem search index map. The map carries one
/// entry per writable mem. Build cost scales with entity count;
/// expect hundreds-of-ms for thousand-entity workspaces. Not
/// available on `wasm32` targets — search lives behind the bridge
/// (see [`Self::search`] for the typed refuse).
#[cfg(not(target_arch = "wasm32"))]
pub fn search_indexes(&self) -> &HashMap<String, MemIndex> {
self.search_indexes_memo
.get_or_init(|| build_all(&self.store, &self.schemas))
}
/// Drop the cached per-mem search index map. No-op on `wasm32`
/// where no index exists; the method stays present so mutation
/// hooks can call it unconditionally.
pub fn invalidate_search_indexes(&mut self) {
#[cfg(not(target_arch = "wasm32"))]
{
self.search_indexes_memo = OnceCell::new();
}
}
/// Filter the in-memory store by metadata only (no text match).
#[cfg(not(target_arch = "wasm32"))]
pub fn list(&self, scope: &SearchScope) -> crate::ops::ListResult {
let fallback = engine_fallback_type();
crate::ops::search::list(&self.store, scope, fallback.as_ref(), &self.schemas)
}
/// Run a search against the lazily-built index map. Returns
/// [`EngineError::SearchUnavailable`] on `wasm32` targets — browser
/// consumers route search to the bridge; the local
/// engine never builds a tantivy index in WASM. Native targets get
/// the same shape as before, wrapped in `Ok`.
pub fn search(&self, scope: &SearchScope) -> Result<SearchResult, EngineError> {
// A mem filter naming a quarantined mem refuses typed — an
// empty result with a missing-index warning would misstate the
// reason (the mem is quarantined, not index-less).
if let Some(mem) = scope.mem.as_deref()
&& self.quarantine_reason(mem).is_some()
{
return Err(self.unknown_mem_error(mem));
}
#[cfg(target_arch = "wasm32")]
{
let _ = scope;
return Err(EngineError::SearchUnavailable);
}
#[cfg(not(target_arch = "wasm32"))]
{
let fallback = engine_fallback_type();
Ok(crate::ops::search::search(
&self.store,
scope,
fallback.as_ref(),
self.search_indexes(),
&self.schemas,
))
}
}
/// All mem-relative entity paths under `mem`. Delegates to
/// the backend's `list_entities`. Order is backend-defined.
pub fn list_entities(&self, mem: &str) -> Result<Vec<PathBuf>, EngineError> {
let m = self.find_mount(mem)?;
m.backend.list_entities().map_err(EngineError::Backend)
}
/// Raw bytes for a single entity (`Ok(None)` if absent).
pub fn read_entity(&self, mem: &str, rel_path: &Path) -> Result<Option<Vec<u8>>, EngineError> {
let m = self.find_mount(mem)?;
m.backend
.read_entity(rel_path)
.map_err(EngineError::Backend)
}
/// Provenance entries for `mem` since `cursor`. Cursor shape is
/// backend-specific (RFC-3339 timestamp for folder, commit SHA for
/// git-branch); `None` means "from the beginning".
pub fn read_provenance(
&self,
mem: &str,
cursor: Option<&str>,
) -> Result<Vec<Provenance>, EngineError> {
let m = self.find_mount(mem)?;
m.backend
.read_provenance(cursor)
.map_err(EngineError::Backend)
}
/// Capability declared on the mount for `mem`. Surfaced for
/// callers that need to gate before dispatching a write — the
/// engine itself does not yet enforce capability (mutation paths
/// land in a later session).
pub fn capability(&self, mem: &str) -> Result<crate::workspace::MountCapability, EngineError> {
let m = self.find_mount(mem)?;
Ok(m.mount.capability)
}
/// Returns `true` when `from`'s source mem is mounted with
/// [`crate::workspace::MountCapability::ReadOnly`]. Returns
/// `false` for Write-Mems and for mems whose mount is absent
/// from the router (no mount → no ReadOnly assertion can be
/// made; the absence is treated as not-ReadOnly so consumers
/// don't trip on transient lookup misses).
///
/// Plan body §"Single edge source in the store" specifies this
/// helper as the derived-on-demand alternative to adding a new
/// field on [`crate::store::Edge`]. Strict-invariant validators
/// and surfaces that want to highlight cross-mount references
/// call this rather than pattern-matching on a per-edge marker.
/// The information is fully derivable from the current mount
/// roster, so no new state needs to live on the edge itself.
pub fn edge_is_from_readonly(&self, from: &EntityId) -> bool {
match self.capability(from.mem()) {
Ok(crate::workspace::MountCapability::ReadOnly) => true,
Ok(crate::workspace::MountCapability::Write) | Err(_) => false,
}
}
/// Whether a cross-mem edge from `from_mem` to `to_mem` is
/// permitted under the current [`crate::WorkspaceSettings`]
/// cross-mem link policy.
///
/// Resolution rules (matches full's `mem_router` semantics):
/// 1. Same-mem edge (`from_mem == to_mem`) → always
/// allowed; the policy gates *cross*-mem edges only.
/// 2. Explicit `cross_mem_links[from_mem]`:
/// - `"*"` (wildcard) → allowed regardless of target.
/// - `["a", ...]` (allowlist) → allowed iff `to_mem` is in
/// the list.
/// 3. Per-create-rule `default_cross_links` synthesis — if
/// rule (1) didn't grant permission and `from_mem` matches
/// a `[[mem_management.create]]` rule whose
/// `default_cross_links` is set, the synthesised value
/// contributes:
/// - `"*"` → allowed regardless of target.
/// - `["a", ...]` → allowed iff `to_mem` is in the list.
/// 4. Otherwise → denied (default-deny posture).
///
/// The synthesis layer compiles a [`crate::mem_management::CreateRuleSet`]
/// lazily on first call and caches it; [`Self::set_settings`]
/// invalidates the cache. Compilation failure (malformed glob
/// in a rule) logs a warning and the synthesis layer is silently
/// skipped — the resolver still returns `true` from explicit
/// policy alone, so a half-broken config doesn't lock out edges
/// the operator did intend to allow. Operators who want hard
/// validation pre-compile via
/// [`crate::mem_management::CreateRuleSet::new`] before
/// calling [`Self::set_settings`].
///
/// The MCP `memstead_relate` handler's cross-mem gate consumes
/// this method directly.
pub fn cross_mem_link_allowed(&self, from_mem: &str, to_mem: &str) -> bool {
use memstead_schema::workspace_config::CrossLinkValue;
if from_mem == to_mem {
return true;
}
// Step 1: explicit cross_mem_links policy.
if let Some(value) = self.settings.cross_mem_links.get(from_mem) {
match value {
CrossLinkValue::Wildcard => return true,
CrossLinkValue::List(targets) => {
if targets.iter().any(|t| t == to_mem) {
return true;
}
// Fall through to synthesis check — a List that
// doesn't include the target may still allow it
// via per-rule default_cross_links union.
}
}
}
// Step 2: per-create-rule default_cross_links synthesis.
let rule_set = self.create_rule_set_memo.get_or_init(|| {
crate::mem_management::CreateRuleSet::new(
self.settings.mem_create_rules.clone(),
)
.unwrap_or_else(|err| {
tracing::warn!(
error = %err,
"cross_mem_link_allowed: failed to compile mem_create_rules — synthesis disabled (resolver falls back to explicit-policy-only)"
);
crate::mem_management::CreateRuleSet::default()
})
});
// Compose the same `<mem_path>/<name>` candidate the create-rule
// composer matched against. The rule globs are keyed on the composed
// lifecycle path (e.g. `memstead/project`, compiled with
// `literal_separator`), not the bare leaf name — matching
// `from_mem` alone silently misses, so synthesis denied a link
// that `memstead_overview` rendered as rule-granted (the
// leaf-vs-composed-path divergence). Flat-layout mems (no
// hierarchical path) keep the bare leaf, matching their bare rule.
let candidate = match self.mount(from_mem).and_then(|m| m.mem_path()) {
Some(path) => format!("{path}/{from_mem}"),
None => from_mem.to_string(),
};
if let Some(matched) = rule_set.first_match(std::path::Path::new(&candidate))
&& let Some(synth) = matched.default_cross_links.as_ref()
{
return match synth {
CrossLinkValue::Wildcard => true,
CrossLinkValue::List(targets) => targets.iter().any(|t| t == to_mem),
};
}
false
}
pub(super) fn find_mount(&self, mem: &str) -> Result<&MountedBackend, EngineError> {
self.mounts
.iter()
.find(|m| m.mount.mem == mem)
.ok_or_else(|| self.unknown_mem_error(mem))
}
}
/// The base path of an anchor artifact ref — the locator suffixes a
/// medium may append (`@<commit>`, `#<span>`) stripped so the reverse
/// lookup compares paths, not versioned/located refs.
fn anchor_base_path(artifact: &str) -> &str {
let cut = artifact.find(['@', '#']).unwrap_or(artifact.len());
&artifact[..cut]
}
/// One mem's standalone anchor-verification report — the counts plus
/// the per-anchor rows, in sidecar order.
#[derive(Debug, Clone, Default, serde::Serialize)]
pub struct MemAnchorVerification {
pub mem: String,
/// Source present, hash matches (or a non-hash class whose source
/// exists).
pub resolved: usize,
/// Source present, hash differs, stability `stable` — real drift.
pub drifted: usize,
/// Hash differs under `unstable` stability, or a hash is missing on
/// either side — flagged for re-examination, never called drift.
pub recheck: usize,
/// Source absent, or a grain/medium the mechanism does not reach.
pub unresolvable: usize,
pub anchors: Vec<VerifiedAnchor>,
}
/// One anchor's verification row.
#[derive(Debug, Clone, serde::Serialize)]
pub struct VerifiedAnchor {
pub entity_id: String,
pub artifact: String,
pub grain: String,
pub class: String,
/// `resolved` | `drifted` | `recheck` | `unresolvable`.
pub state: String,
#[serde(skip_serializing_if = "Option::is_none")]
pub observed_hash: Option<String>,
}
/// Whether `anchor` references `path`. `tree`-grain anchors match `path`
/// itself and anything beneath the tree; every other grain matches by
/// exact base-path equality.
/// A stored anchor paired with its live resolution state, when observable.
/// See [`Engine::entity_anchors_resolved`] for how `state` is produced and
/// when it is `None` (unobserved, never fabricated).
#[derive(Debug, Clone, PartialEq, Eq, serde::Serialize)]
pub struct ResolvedAnchor {
/// The durable anchor record (flattened on the wire so the resolved shape
/// is the stored anchor plus a `state` field).
#[serde(flatten)]
pub anchor: crate::anchor::Anchor,
/// The live resolution state, or `None` when the engine could not observe
/// the source artifact this pass (non-path medium, ambiguous / absent
/// medium, no workspace root, or a non-filesystem grain).
#[serde(skip_serializing_if = "Option::is_none")]
pub state: Option<crate::anchor::AnchorState>,
/// The prepared-content hash the observation computed this pass —
/// present only for a hash-bearing (`anchored` / `derived`) `file` /
/// `span` anchor whose artifact resolved to a readable file. The verify
/// pass's backfill leg records it onto a hash-less anchor. Engine-internal
/// observation detail, deliberately not serialized: the wire shape stays
/// the stored anchor plus `state`.
#[serde(skip)]
pub observed_hash: Option<String>,
}
/// Observe a single path-namespace anchor against `root` (its medium's
/// filesystem root) and resolve its live state plus — for a present
/// hash-bearing (`anchored` / `derived`) `file` / `span` anchor — the
/// artifact's **prepared-content hash**
/// ([`crate::anchor::prepared_content_hash`]). `None` when the anchor's
/// grain does not reference a filesystem path.
///
/// The computed hash is what lets [`crate::anchor::resolve_anchor`]
/// adjudicate `drifted` vs `resolves` deterministically against the recorded
/// hash. A `span` anchor hashes its whole containing file (the span locator
/// selects within it; the file is the hashed unit); a `tree` grain has no
/// prepared form this cycle and observes no hash; a read failure likewise
/// observes no hash — those resolve `recheck`, never a fabricated `drifted`.
/// Non-hash classes (`authored` / `informed-by`) skip the read entirely, so
/// an anchor-less or hash-free mem pays no observation cost.
fn observe_path_anchor(
root: &Path,
anchor: &crate::anchor::Anchor,
) -> Option<(crate::anchor::AnchorState, Option<String>)> {
use crate::anchor::AnchorGrain;
match anchor.grain {
AnchorGrain::Span | AnchorGrain::File | AnchorGrain::Tree => {}
AnchorGrain::Url | AnchorGrain::Entity => return None,
}
let base = anchor_base_path(&anchor.artifact);
let path = root.join(base);
if !path.exists() {
return Some((
crate::anchor::resolve_anchor(anchor, &crate::anchor::ArtifactObservation::Absent),
None,
));
}
let current_hash = if anchor.class.is_hash_bearing()
&& matches!(anchor.grain, AnchorGrain::File | AnchorGrain::Span)
&& path.is_file()
{
std::fs::read(&path)
.ok()
.map(|bytes| crate::anchor::prepared_content_hash(&bytes))
} else {
None
};
let observation = crate::anchor::ArtifactObservation::Present {
current_hash: current_hash.clone(),
};
Some((
crate::anchor::resolve_anchor(anchor, &observation),
current_hash,
))
}
/// Deterministic fingerprint of a PARSED schema for the
/// authoring-drift equivalence check. Compares semantic content, never
/// raw bytes: YAML comments (the CLI-injected editor-header lines) and
/// whitespace vanish at parse time, and `Schema.types` — a `HashMap`
/// with nondeterministic iteration order — is rendered sorted by type
/// name so two loads of equivalent packages always fingerprint alike.
fn schema_parsed_fingerprint(schema: &memstead_schema::Schema) -> String {
let mut keys: Vec<&String> = schema.types.keys().collect();
keys.sort();
let types: Vec<String> = keys
.iter()
.map(|k| format!("{k}={:?}", schema.types[k.as_str()]))
.collect();
format!(
"{:?}|{}|{}",
schema.manifest,
schema.version,
types.join(";")
)
}
fn anchor_references_path(anchor: &crate::anchor::Anchor, path: &str) -> bool {
let base = anchor_base_path(&anchor.artifact);
if base == path {
return true;
}
if anchor.grain == crate::anchor::AnchorGrain::Tree {
let prefix = base.strip_suffix('/').unwrap_or(base);
return path.starts_with(&format!("{prefix}/"));
}
false
}
#[cfg(test)]
mod tests {
use std::path::Path;
use tempfile::TempDir;
use crate::backend::{BackendError, MemBackend};
use crate::engine::test_helpers::*;
use crate::engine::{Engine, EngineError, RelateEntityArgs};
use crate::entity::EntityId;
use crate::ops::{Direction, SearchScope, WarningHint};
use crate::provenance::Provenance;
use crate::storage::{ArchiveBackend, FilesystemMemWriter, MemWriter};
use crate::vcs::CommitContext;
use crate::workspace::{Mount, MountCapability, MountLifecycle, MountStorage};
/// `schema_origin` is the trust-classification authority: a built-in
/// (or workspace-authored) schema is first-party; a schema whose
/// `(name, version)` is in neither catalogue is third-party — the safe
/// default for an origin the engine cannot vouch for.
#[test]
fn schema_origin_classifies_builtin_first_party_and_unknown_third_party() {
use std::sync::Arc;
use crate::render::OriginClass;
let tmp = TempDir::new().unwrap();
let engine = Engine::from_mounts(vec![(
folder_mount("specs", tmp.path().to_path_buf()),
Box::new(FilesystemMemWriter::new(tmp.path().to_path_buf())) as Box<dyn MemBackend>,
)])
.unwrap();
// A built-in schema (the catalogue the engine resolved against).
let builtin = engine.builtin_schemas()[0].clone();
assert_eq!(
engine.schema_origin(&builtin),
OriginClass::FirstParty,
"a built-in schema is first-party"
);
// A schema whose version is in no catalogue — a stand-in for a
// schema that entered from outside the workspace. Same name, a
// version the engine never loaded.
let foreign = Arc::new(memstead_schema::Schema {
manifest: builtin.manifest.clone(),
version: semver::Version::new(99, 0, 0),
types: builtin.types.clone(),
});
assert_eq!(
engine.schema_origin(&foreign),
OriginClass::ThirdParty,
"a schema in neither catalogue classifies third-party (safe default)"
);
}
/// `mem_origin_class` classifies a writable mount first-party (its
/// content is authored in this workspace) and a read-only mount
/// third-party (registry-installed read-mem or adopted foreign
/// folder/clone — quoted, untrusted data). An unknown mem is
/// third-party (the safe default).
#[test]
fn mem_origin_class_writable_first_party_readonly_third_party() {
use crate::render::OriginClass;
let tmp = TempDir::new().unwrap();
// Writable folder mem.
let writable_dir = tmp.path().join("writable");
std::fs::create_dir_all(&writable_dir).unwrap();
let writer = FilesystemMemWriter::new(writable_dir.clone());
// Read-only archive mem.
let body = "---\ntype: spec\n---\n# Ext\n\n## Identity\n\nFrom an archive.\n";
let archive_path = build_archive(tmp.path(), "ext", &[("ext.md", body.as_bytes())]);
let engine = Engine::from_mounts(vec![
(
folder_mount("local", writable_dir),
Box::new(writer) as Box<dyn MemBackend>,
),
(
archive_mount("external", archive_path.clone()),
Box::new(ArchiveBackend::new(archive_path)) as Box<dyn MemBackend>,
),
])
.unwrap();
assert_eq!(
engine.mem_origin_class("local"),
OriginClass::FirstParty,
"a writable mount is first-party"
);
assert_eq!(
engine.mem_origin_class("external"),
OriginClass::ThirdParty,
"a read-only mount is third-party"
);
assert_eq!(
engine.mem_origin_class("no-such-mem"),
OriginClass::ThirdParty,
"an unknown mem is third-party (safe default)"
);
}
/// `declare_mem_origin` lets the embedding deployment vouch for one
/// read-only mount as first-party (the curated hosted read tier),
/// overriding the writability inference for that mem only — sibling
/// read-only mounts keep the safe third-party default.
#[test]
fn declared_origin_overrides_inference_per_mem() {
use crate::render::OriginClass;
let tmp = TempDir::new().unwrap();
let body = "---\ntype: spec\n---\n# Ext\n\n## Identity\n\nFrom an archive.\n";
let vouched_path = build_archive(tmp.path(), "vouched", &[("v.md", body.as_bytes())]);
let other_path = build_archive(tmp.path(), "other", &[("o.md", body.as_bytes())]);
let mut engine = Engine::from_mounts(vec![
(
archive_mount("vouched", vouched_path.clone()),
Box::new(ArchiveBackend::new(vouched_path)) as Box<dyn MemBackend>,
),
(
archive_mount("other", other_path.clone()),
Box::new(ArchiveBackend::new(other_path)) as Box<dyn MemBackend>,
),
])
.unwrap();
engine.declare_mem_origin("vouched", OriginClass::FirstParty);
assert_eq!(
engine.mem_origin_class("vouched"),
OriginClass::FirstParty,
"the deployment's declaration wins over the read-only inference"
);
assert_eq!(
engine.mem_origin_class("other"),
OriginClass::ThirdParty,
"an undeclared sibling mount keeps the safe default"
);
}
/// The adopt-gate: a non-built-in schema is first-party only once a
/// writable mount pins it (the operator authors against it here).
/// Pinned only by a read-only mount — a registry read-mem or an
/// adopted foreign folder/clone — it stays third-party, so
/// `memstead_schema` serves it structural-only.
#[test]
fn schema_origin_third_party_until_pinned_by_a_writable_mount() {
use memstead_schema::SchemaRef;
use crate::render::OriginClass;
let manifest = r#"name: trust-test
version: 0.1.0
description: adopt-gate test schema
when_to_use: tests
types:
- doc
relationships:
mode: strict
definitions:
- name: _default
description: fallback
default_weight: 1.0
community:
resolution: 1.0
seed: 42
"#;
let pin = SchemaRef::new("trust-test", semver::Version::new(0, 1, 0));
let mk_engine = |cap: MountCapability| -> Engine {
let tmp = TempDir::new().unwrap();
let schemas_dir = tmp.path().join("schemas");
std::fs::create_dir_all(&schemas_dir).unwrap();
write_schema_files_with_default_type(&schemas_dir, "trust-test", manifest, &["doc"]);
let mem_dir = tmp.path().join("mem");
std::fs::create_dir_all(&mem_dir).unwrap();
let mount = Mount {
mem: "v".to_string(),
schema: Some(pin.clone()),
storage: MountStorage::Folder {
path: mem_dir.clone(),
},
capability: cap,
lifecycle: MountLifecycle::Eager,
cross_linkable: true,
migration_target: None,
};
let backend = Box::new(FilesystemMemWriter::new(mem_dir)) as Box<dyn MemBackend>;
// Keep `tmp` alive for the engine's lifetime by leaking it —
// the test process is short-lived and the folder must outlast
// the closure.
std::mem::forget(tmp);
Engine::from_mounts_with_schemas_dir(vec![(mount, backend)], Some(&schemas_dir))
.unwrap()
};
// Read-only mount: the foreign schema is never adopted → third-party.
let ro = mk_engine(MountCapability::ReadOnly);
let schema = ro.schemas().get("v").expect("schema resolved").clone();
assert_eq!(
ro.schema_origin(&schema),
OriginClass::ThirdParty,
"a non-built-in schema pinned only by a read-only mount is third-party"
);
// Writable mount pinning the same schema: adopted → first-party.
let rw = mk_engine(MountCapability::Write);
let schema = rw.schemas().get("v").expect("schema resolved").clone();
assert_eq!(
rw.schema_origin(&schema),
OriginClass::FirstParty,
"a writable mount pinning the schema adopts it → first-party"
);
}
/// Consumer read path: an installed (archive-backed) mem that ships
/// a `.memstead/provenance.json` payload surfaces per-entity authoring
/// provenance through `archive_provenance_for`. A noted entity carries
/// its rationale; an entity authored without a note is absent from the
/// payload and reads as provenance-absent (no fabricated value); the
/// `history` disposition records that full history is not shipped.
#[test]
fn archive_provenance_surfaces_per_entity_and_reports_absence() {
use memstead_schema::History;
let tmp = TempDir::new().unwrap();
let config = br#"{"format":3,"name":"seed","version":"0.1.0","schema":"default@1.0.0"}"#;
let alpha = b"---\ntype: spec\n---\n# Alpha\n\n## Identity\n\na\n\n## Purpose\n\np\n";
let beta = b"---\ntype: spec\n---\n# Beta\n\n## Identity\n\nb\n\n## Purpose\n\np\n";
// alpha noted; beta deliberately absent from the payload.
let provenance = br#"{"format":1,"history":"summarised","entities":{"alpha":{"rationale":"why alpha exists","kind":"create","timestamp":"2026-06-24T00:00:00Z","actor":"agent"}}}"#;
let archive = build_archive(
tmp.path(),
"seed",
&[
(".memstead/config.json", config),
("alpha.md", alpha),
("beta.md", beta),
(".memstead/provenance.json", provenance),
],
);
let engine = Engine::from_mounts(vec![(
archive_mount("seed", archive.clone()),
Box::new(ArchiveBackend::new(archive)) as Box<dyn MemBackend>,
)])
.unwrap();
let prov = engine
.archive_provenance_for("seed")
.expect("provenance payload read from the archive");
assert_eq!(
prov.history,
History::Summarised,
"history-not-shipped is observable"
);
assert_eq!(
prov.entity("alpha").and_then(|r| r.rationale.as_deref()),
Some("why alpha exists"),
"noted entity surfaces its rationale"
);
assert!(
prov.entity("beta").is_none(),
"unnoted entity is absent (reported absent, not fabricated)"
);
}
/// A pre-provenance archive (no `.memstead/provenance.json`) reads as
/// provenance uniformly absent — the additive contract: a newer engine
/// installing an old archive reports no provenance, never an error.
#[test]
fn archive_without_provenance_reports_absent() {
let tmp = TempDir::new().unwrap();
let config = br#"{"format":3,"name":"seed","version":"0.1.0","schema":"default@1.0.0"}"#;
let alpha = b"---\ntype: spec\n---\n# Alpha\n\n## Identity\n\na\n\n## Purpose\n\np\n";
let archive = build_archive(
tmp.path(),
"seed",
&[(".memstead/config.json", config), ("alpha.md", alpha)],
);
let engine = Engine::from_mounts(vec![(
archive_mount("seed", archive.clone()),
Box::new(ArchiveBackend::new(archive)) as Box<dyn MemBackend>,
)])
.unwrap();
assert!(
engine.archive_provenance_for("seed").is_none(),
"an archive without a provenance payload reports provenance absent"
);
}
#[test]
fn folder_mount_routes_reads_to_filesystem_backend() {
let tmp = TempDir::new().unwrap();
let mem_dir = tmp.path().to_path_buf();
let writer = FilesystemMemWriter::new(mem_dir.clone());
// MemWriter and MemBackend share method names; the
// module-top `use` brings both into scope. Seed via fully-
// qualified MemWriter calls so dot-syntax stays unambiguous.
<FilesystemMemWriter as MemWriter>::write_entity(&writer, Path::new("a.md"), b"alpha")
.unwrap();
<FilesystemMemWriter as MemWriter>::commit(&writer, "seed", &CommitContext::internal())
.unwrap();
let engine = Engine::from_mounts(vec![(
folder_mount("specs", mem_dir),
Box::new(writer) as Box<dyn MemBackend>,
)])
.unwrap();
let mut paths: Vec<String> = engine
.list_entities("specs")
.unwrap()
.into_iter()
.map(|p| p.to_string_lossy().into_owned())
.collect();
paths.sort();
assert_eq!(paths, vec!["a.md".to_string()]);
assert_eq!(
engine.read_entity("specs", Path::new("a.md")).unwrap(),
Some(b"alpha".to_vec())
);
}
#[test]
fn heterogeneous_mounts_route_to_correct_backend() {
let tmp = TempDir::new().unwrap();
// Folder mem.
let folder_dir = tmp.path().join("folder-mem");
std::fs::create_dir_all(&folder_dir).unwrap();
let folder_writer = FilesystemMemWriter::new(folder_dir.clone());
<FilesystemMemWriter as MemWriter>::write_entity(
&folder_writer,
Path::new("local.md"),
b"local",
)
.unwrap();
<FilesystemMemWriter as MemWriter>::commit(
&folder_writer,
"seed",
&CommitContext::internal(),
)
.unwrap();
// Archive mem.
let archive_path = build_archive(
tmp.path(),
"external",
&[("ext.md", b"external"), ("dir/nested.md", b"nested")],
);
let engine = Engine::from_mounts(vec![
(
folder_mount("local", folder_dir),
Box::new(folder_writer) as Box<dyn MemBackend>,
),
(
archive_mount("external", archive_path.clone()),
Box::new(ArchiveBackend::new(archive_path)),
),
])
.unwrap();
// Routes correctly by mem name.
assert_eq!(engine.mem_names(), vec!["local", "external"]);
assert_eq!(
engine.read_entity("local", Path::new("local.md")).unwrap(),
Some(b"local".to_vec())
);
assert_eq!(
engine.read_entity("external", Path::new("ext.md")).unwrap(),
Some(b"external".to_vec())
);
assert_eq!(
engine
.read_entity("external", Path::new("dir/nested.md"))
.unwrap(),
Some(b"nested".to_vec())
);
// Cross-routing: reading a path from the wrong mem → None
// (the backend doesn't have it), not an error.
assert_eq!(
engine.read_entity("local", Path::new("ext.md")).unwrap(),
None
);
assert_eq!(
engine
.read_entity("external", Path::new("local.md"))
.unwrap(),
None
);
}
#[test]
fn edge_is_from_readonly_classifies_every_edge_by_source_mount_capability() {
// `engine.edge_is_from_readonly` is the derived-on-demand
// alternative to adding a per-edge marker: construct a mixed
// workspace (one Write-Mem + one ReadOnly archive with
// cross-mem wiki-links) and walk every edge in the store,
// asserting each edge's source-mount capability.
let tmp = TempDir::new().unwrap();
// Write folder mem `local` with a spec-shaped entity that
// declares an explicit cross-mem relation into the archive
// (under the alias model edges originate from `## Relationships`).
let folder_dir = tmp.path().join("local-mem");
std::fs::create_dir_all(&folder_dir).unwrap();
let folder_writer = FilesystemMemWriter::new(folder_dir.clone());
let local_md = b"---\ntype: spec\n---\n# Note\n\n## Identity\n\nsee [[external:archived]] for prior context.\n\n## Relationships\n\n- **REFERENCES**: [[external:archived]]\n";
<FilesystemMemWriter as MemWriter>::write_entity(
&folder_writer,
Path::new("note.md"),
local_md,
)
.unwrap();
<FilesystemMemWriter as MemWriter>::commit(
&folder_writer,
"seed",
&CommitContext::internal(),
)
.unwrap();
// ReadOnly archive mem `external` with a spec-shaped entity
// declaring an explicit cross-mem relation back to the local
// note.
let archive_md = b"---\ntype: spec\n---\n# Archived\n\n## Identity\n\nrefers back to [[local:note]] for the current revision.\n\n## Relationships\n\n- **REFERENCES**: [[local:note]]\n";
let archive_path = build_archive(tmp.path(), "external", &[("archived.md", archive_md)]);
let engine = Engine::from_mounts(vec![
(
folder_mount("local", folder_dir),
Box::new(folder_writer) as Box<dyn MemBackend>,
),
(
archive_mount("external", archive_path.clone()),
Box::new(ArchiveBackend::new(archive_path)),
),
])
.unwrap();
// Sanity: both entities are real, both mems are mounted.
let local_id = EntityId::new("local", "note");
let archived_id = EntityId::new("external", "archived");
assert!(engine.get_entity(&local_id).is_some());
assert!(engine.get_entity(&archived_id).is_some());
assert!(matches!(
engine.capability("local").unwrap(),
MountCapability::Write
));
assert!(matches!(
engine.capability("external").unwrap(),
MountCapability::ReadOnly
));
// Walk every edge in the store. For each (from, edge) pair,
// `edge_is_from_readonly(from)` must return true iff the
// source mount's capability is ReadOnly. The fixture's two
// wiki-links produce one edge from each mem — both halves
// exercise both branches of the helper.
let mut seen_write_edge = false;
let mut seen_readonly_edge = false;
for from in engine.store().all_ids().cloned().collect::<Vec<_>>() {
for _edge in engine.store().outgoing(&from) {
let is_ro = engine.edge_is_from_readonly(&from);
match engine.capability(from.mem()).unwrap() {
MountCapability::Write => {
assert!(
!is_ro,
"edge from write mem {} reported as ReadOnly",
from.mem()
);
seen_write_edge = true;
}
MountCapability::ReadOnly => {
assert!(
is_ro,
"edge from readonly mem {} reported as Write",
from.mem()
);
seen_readonly_edge = true;
}
}
}
}
assert!(
seen_write_edge,
"fixture must produce at least one edge from a write mem"
);
assert!(
seen_readonly_edge,
"fixture must produce at least one edge from a readonly mem"
);
// Helper also reports `false` for mems absent from the
// router — no mount → no ReadOnly assertion can be made.
let phantom = EntityId::new("missing-mem", "phantom");
assert!(
!engine.edge_is_from_readonly(&phantom),
"absent mount must not be reported as ReadOnly"
);
}
// ---- Engine::changes_since wrapper ------------------------------
#[test]
fn cross_mem_link_allowed_same_mem_always_true() {
// Self-edges (from == to) bypass the cross-mem policy
// entirely — the policy gates *cross*-mem edges only.
let tmp = TempDir::new().unwrap();
let engine = build_demo_engine(&tmp);
assert!(engine.cross_mem_link_allowed("specs", "specs"));
// Even when the mem doesn't exist (not enrolled in
// settings.cross_mem_links), same-mem returns true —
// the engine doesn't validate mem existence here, just the
// policy.
assert!(engine.cross_mem_link_allowed("anywhere", "anywhere"));
}
#[test]
fn cross_mem_link_allowed_absent_denies_by_default() {
// No entry in cross_mem_links for `from_mem` → denied.
// Default-deny is the V1 posture; operators opt in.
let tmp = TempDir::new().unwrap();
let engine = build_demo_engine(&tmp);
assert!(!engine.cross_mem_link_allowed("specs", "engine"));
assert!(!engine.cross_mem_link_allowed("missing", "anywhere"));
}
#[test]
fn cross_mem_link_allowed_wildcard_admits_any_target() {
use memstead_schema::workspace_config::CrossLinkValue;
let tmp = TempDir::new().unwrap();
let mut engine = build_demo_engine(&tmp);
let mut settings = crate::workspace::WorkspaceSettings::default();
settings
.cross_mem_links
.insert("specs".to_string(), CrossLinkValue::Wildcard);
engine.set_settings(settings);
assert!(engine.cross_mem_link_allowed("specs", "engine"));
assert!(engine.cross_mem_link_allowed("specs", "macos"));
assert!(engine.cross_mem_link_allowed("specs", "any-other"));
// Reverse direction is independent — no policy entry for
// engine→specs means denied.
assert!(!engine.cross_mem_link_allowed("engine", "specs"));
}
#[test]
fn cross_mem_link_allowed_allowlist_enforces_membership() {
use memstead_schema::workspace_config::CrossLinkValue;
let tmp = TempDir::new().unwrap();
let mut engine = build_demo_engine(&tmp);
let mut settings = crate::workspace::WorkspaceSettings::default();
settings.cross_mem_links.insert(
"specs".to_string(),
CrossLinkValue::List(vec!["engine".to_string(), "macos".to_string()]),
);
engine.set_settings(settings);
assert!(engine.cross_mem_link_allowed("specs", "engine"));
assert!(engine.cross_mem_link_allowed("specs", "macos"));
assert!(!engine.cross_mem_link_allowed("specs", "external"));
}
#[test]
fn cross_mem_link_allowed_synthesises_from_matching_create_rule_wildcard() {
// No explicit cross_mem_links entry, but a create rule
// matches `from_mem` and carries default_cross_links = "*".
// Synthesis grants permission to any target.
use memstead_schema::workspace_config::CrossLinkValue;
let tmp = TempDir::new().unwrap();
let mut engine = build_demo_engine(&tmp);
let mut settings = crate::workspace::WorkspaceSettings::default();
settings
.mem_create_rules
.push(crate::workspace::CreateRuleSetting {
pattern: "exec-*".to_string(),
schemas: vec!["default".to_string()],
default_cross_links: Some(CrossLinkValue::Wildcard),
});
engine.set_settings(settings);
// No explicit policy; synthesis grants permission for any
// target because the rule's value is Wildcard.
assert!(engine.cross_mem_link_allowed("exec-foo", "specs"));
assert!(engine.cross_mem_link_allowed("exec-foo", "engine"));
// Mem that doesn't match any rule → still denied.
assert!(!engine.cross_mem_link_allowed("orphan", "specs"));
}
/// #42: synthesis matches a hierarchical mem by composing the same
/// `<mem_path>/<name>` candidate the create-rule glob is keyed on,
/// not the bare leaf. Before the fix, `from_mem = "project"` could
/// never match a `memstead/*` rule (the leaf-vs-composed-path
/// divergence), so enforcement denied a link `memstead_overview`
/// rendered as rule-granted.
#[test]
fn cross_mem_link_allowed_synthesises_for_hierarchical_mem() {
use memstead_schema::workspace_config::CrossLinkValue;
let tmp = TempDir::new().unwrap();
let mem_dir = tmp.path().to_path_buf();
// Mount `project` with a hierarchical branch so its `mem_path()`
// is "memstead" and the composed candidate is "memstead/project".
// The Folder backend handles loading; only the Mount's storage
// feeds `mem_path()`.
let mount = Mount {
mem: "project".into(),
schema: Some(pin("default")),
storage: MountStorage::GitBranch {
gitdir: mem_dir.join(".git"),
branch: "memstead/project".into(),
},
capability: MountCapability::Write,
lifecycle: MountLifecycle::Eager,
cross_linkable: true,
migration_target: None,
};
let writer = FilesystemMemWriter::new(mem_dir.clone());
let mut engine =
Engine::from_mounts(vec![(mount, Box::new(writer) as Box<dyn MemBackend>)]).unwrap();
let mut settings = crate::workspace::WorkspaceSettings::default();
settings
.mem_create_rules
.push(crate::workspace::CreateRuleSetting {
pattern: "memstead/*".to_string(),
schemas: vec!["default".to_string()],
default_cross_links: Some(CrossLinkValue::List(vec!["engine".to_string()])),
});
engine.set_settings(settings);
assert!(
engine.cross_mem_link_allowed("project", "engine"),
"synthesis must match via the composed `memstead/project` candidate"
);
assert!(
!engine.cross_mem_link_allowed("project", "macos"),
"a target outside the rule's default_cross_links is still denied"
);
}
#[test]
fn cross_mem_link_allowed_synthesises_from_matching_create_rule_list() {
// Create rule's default_cross_links is a list — synthesis
// grants permission to listed targets only.
use memstead_schema::workspace_config::CrossLinkValue;
let tmp = TempDir::new().unwrap();
let mut engine = build_demo_engine(&tmp);
let mut settings = crate::workspace::WorkspaceSettings::default();
settings
.mem_create_rules
.push(crate::workspace::CreateRuleSetting {
pattern: "exec-*".to_string(),
schemas: vec!["default".to_string()],
default_cross_links: Some(CrossLinkValue::List(vec!["specs".to_string()])),
});
engine.set_settings(settings);
assert!(engine.cross_mem_link_allowed("exec-foo", "specs"));
// Target not in the synthesised list → denied.
assert!(!engine.cross_mem_link_allowed("exec-foo", "engine"));
}
#[test]
fn cross_mem_link_allowed_explicit_policy_wins_over_synthesis() {
// Explicit cross_mem_links wildcard fires first; the
// synthesis layer is never consulted (and would deny).
use memstead_schema::workspace_config::CrossLinkValue;
let tmp = TempDir::new().unwrap();
let mut engine = build_demo_engine(&tmp);
let mut settings = crate::workspace::WorkspaceSettings::default();
settings
.cross_mem_links
.insert("exec-foo".to_string(), CrossLinkValue::Wildcard);
// The synthesis layer would deny `exec-foo → engine` (no
// matching rule), but explicit policy returns true first.
engine.set_settings(settings);
assert!(engine.cross_mem_link_allowed("exec-foo", "engine"));
}
#[test]
fn cross_mem_link_allowed_synthesis_unions_into_explicit_list() {
// Explicit list = ["specs"]; create rule synthesises = ["macos"].
// Effective allowed targets: union ({specs, macos}).
use memstead_schema::workspace_config::CrossLinkValue;
let tmp = TempDir::new().unwrap();
let mut engine = build_demo_engine(&tmp);
let mut settings = crate::workspace::WorkspaceSettings::default();
settings.cross_mem_links.insert(
"exec-foo".to_string(),
CrossLinkValue::List(vec!["specs".to_string()]),
);
settings
.mem_create_rules
.push(crate::workspace::CreateRuleSetting {
pattern: "exec-*".to_string(),
schemas: vec!["default".to_string()],
default_cross_links: Some(CrossLinkValue::List(vec!["macos".to_string()])),
});
engine.set_settings(settings);
// Explicit allowlist contains specs → allowed.
assert!(engine.cross_mem_link_allowed("exec-foo", "specs"));
// Synthesis layer adds macos → allowed.
assert!(engine.cross_mem_link_allowed("exec-foo", "macos"));
// Neither layer allows engine → denied.
assert!(!engine.cross_mem_link_allowed("exec-foo", "engine"));
}
#[test]
fn cross_mem_link_allowed_set_settings_invalidates_compiled_rule_cache() {
// After set_settings, a fresh policy must be reflected on the
// next call — the lazy memo can't return stale rules.
use memstead_schema::workspace_config::CrossLinkValue;
let tmp = TempDir::new().unwrap();
let mut engine = build_demo_engine(&tmp);
// First settings: a rule allows exec-* → specs via synthesis.
let mut s1 = crate::workspace::WorkspaceSettings::default();
s1.mem_create_rules
.push(crate::workspace::CreateRuleSetting {
pattern: "exec-*".to_string(),
schemas: vec!["default".to_string()],
default_cross_links: Some(CrossLinkValue::List(vec!["specs".to_string()])),
});
engine.set_settings(s1);
assert!(engine.cross_mem_link_allowed("exec-foo", "specs"));
// Replace settings: the rule no longer carries
// default_cross_links. Cache must invalidate so the next
// call sees the new policy.
let mut s2 = crate::workspace::WorkspaceSettings::default();
s2.mem_create_rules
.push(crate::workspace::CreateRuleSetting {
pattern: "exec-*".to_string(),
schemas: vec!["default".to_string()],
default_cross_links: None,
});
engine.set_settings(s2);
assert!(!engine.cross_mem_link_allowed("exec-foo", "specs"));
}
#[test]
fn cross_mem_link_allowed_malformed_glob_falls_back_to_explicit_policy() {
// Malformed pattern in a create rule causes CreateRuleSet
// compilation to fail; the resolver logs and disables
// synthesis, but explicit cross_mem_links still works.
use memstead_schema::workspace_config::CrossLinkValue;
let tmp = TempDir::new().unwrap();
let mut engine = build_demo_engine(&tmp);
let mut settings = crate::workspace::WorkspaceSettings::default();
settings
.mem_create_rules
.push(crate::workspace::CreateRuleSetting {
pattern: "[unclosed".to_string(),
schemas: vec!["default".to_string()],
default_cross_links: Some(CrossLinkValue::Wildcard),
});
// Explicit policy still works.
settings
.cross_mem_links
.insert("specs".to_string(), CrossLinkValue::Wildcard);
engine.set_settings(settings);
// Explicit policy: specs → engine allowed.
assert!(engine.cross_mem_link_allowed("specs", "engine"));
// Synthesis disabled (compilation failed); rule's would-be
// wildcard doesn't apply.
assert!(!engine.cross_mem_link_allowed("orphan", "anything"));
}
#[test]
fn cross_mem_link_allowed_empty_list_denies_all_cross_mem_targets() {
// [cross_mem_links] specs = [] is the explicit
// "intentionally locked down" shape — same effect as
// default-deny but operator-acknowledged.
use memstead_schema::workspace_config::CrossLinkValue;
let tmp = TempDir::new().unwrap();
let mut engine = build_demo_engine(&tmp);
let mut settings = crate::workspace::WorkspaceSettings::default();
settings
.cross_mem_links
.insert("specs".to_string(), CrossLinkValue::List(Vec::new()));
engine.set_settings(settings);
// Same-mem still passes — policy only gates cross-mem.
assert!(engine.cross_mem_link_allowed("specs", "specs"));
// Cross-mem denied to every target.
assert!(!engine.cross_mem_link_allowed("specs", "engine"));
assert!(!engine.cross_mem_link_allowed("specs", "anything"));
}
#[test]
fn from_mounts_load_warnings_merge_into_health_summary() {
let tmp = TempDir::new().unwrap();
let mem_dir = tmp.path().to_path_buf();
let body = "---\ntype: spec\n---\n# Dup2\n\n## Identity\n\na.\n\n## Identity\n\nb.\n";
std::fs::write(mem_dir.join("dup2.md"), body).unwrap();
let writer = FilesystemMemWriter::new(mem_dir.clone());
let engine = Engine::from_mounts(vec![(
folder_mount("specs", mem_dir),
Box::new(writer) as Box<dyn MemBackend>,
)])
.unwrap();
let summary = engine.health();
assert!(
summary
.warnings
.iter()
.any(|w| matches!(w, WarningHint::DuplicateSectionHeading { .. })),
"health() must merge load_warnings into summary.warnings: {:?}",
summary.warnings,
);
}
#[test]
fn workspace_root_accessor_is_none_for_engine_built_from_mounts() {
let tmp = TempDir::new().unwrap();
let mem_dir = tmp.path().to_path_buf();
let writer = FilesystemMemWriter::new(mem_dir.clone());
// Newest default generation so the clean-boot assertion below
// isn't tripped by the SCHEMA_GENERATIONS_BEHIND hint.
let mut mount = folder_mount("specs", mem_dir);
mount.schema = Some("default@1.3.0".parse().unwrap());
let engine =
Engine::from_mounts(vec![(mount, Box::new(writer) as Box<dyn MemBackend>)]).unwrap();
assert!(
engine.workspace_root().is_none(),
"from_mounts has no workspace path",
);
assert!(engine.load_warnings().is_empty());
}
#[test]
fn health_omits_outer_repo_warning_when_workspace_root_unset() {
let tmp = TempDir::new().unwrap();
let mem_dir = tmp.path().to_path_buf();
let writer = FilesystemMemWriter::new(mem_dir.clone());
let engine = Engine::from_mounts(vec![(
folder_mount("specs", mem_dir),
Box::new(writer) as Box<dyn MemBackend>,
)])
.unwrap();
let health = engine.health();
assert!(
!health
.warnings
.iter()
.any(|w| matches!(w, WarningHint::OuterRepoNotIgnoringMemRepo { .. })),
"outer-repo check must skip when workspace_root is None",
);
}
#[test]
fn writable_mem_names_filters_by_capability() {
let tmp = TempDir::new().unwrap();
let mem_dir = tmp.path().to_path_buf();
let writer = FilesystemMemWriter::new(mem_dir.clone());
let archive_path = build_archive(tmp.path(), "ext", &[("a.md", b"a")]);
let engine = Engine::from_mounts(vec![
(
folder_mount("writable", mem_dir),
Box::new(writer) as Box<dyn MemBackend>,
),
(
archive_mount("sealed", archive_path.clone()),
Box::new(ArchiveBackend::new(archive_path)),
),
])
.unwrap();
// Only the writable mount surfaces; the archive (read-only)
// is filtered out.
let names = engine.writable_mem_names();
assert_eq!(names, vec!["writable"]);
}
/// The default writable mem is
/// the FIRST writable mount in declaration order — the stable seed,
/// not the alphabetically-first name. `test` is declared first;
/// `other` sorts ahead alphabetically but is declared second, so it
/// is NOT the default. This is the invariant that stops a second
/// mem from silently retargeting omitted-`mem` writes.
#[test]
fn default_writable_mem_is_declaration_first_not_alphabetical() {
let tmp = TempDir::new().unwrap();
let test_dir = tmp.path().join("test");
let other_dir = tmp.path().join("other");
std::fs::create_dir_all(&test_dir).unwrap();
std::fs::create_dir_all(&other_dir).unwrap();
let engine = Engine::from_mounts(vec![
(
folder_mount("test", test_dir.clone()),
Box::new(FilesystemMemWriter::new(test_dir)) as Box<dyn MemBackend>,
),
(
folder_mount("other", other_dir.clone()),
Box::new(FilesystemMemWriter::new(other_dir)) as Box<dyn MemBackend>,
),
])
.unwrap();
assert_eq!(
engine.default_writable_mem(),
Some("test"),
"default must be the declaration-first writable mem, not the alphabetically-first",
);
}
/// Reverse declaration order to prove the default tracks declaration
/// order rather than a fixed name: with `other` declared first it
/// becomes the default. Together with the test above this pins the
/// lean as mount order, not name sort.
#[test]
fn default_writable_mem_follows_declaration_order() {
let tmp = TempDir::new().unwrap();
let other_dir = tmp.path().join("other");
let test_dir = tmp.path().join("test");
std::fs::create_dir_all(&other_dir).unwrap();
std::fs::create_dir_all(&test_dir).unwrap();
let engine = Engine::from_mounts(vec![
(
folder_mount("other", other_dir.clone()),
Box::new(FilesystemMemWriter::new(other_dir)) as Box<dyn MemBackend>,
),
(
folder_mount("test", test_dir.clone()),
Box::new(FilesystemMemWriter::new(test_dir)) as Box<dyn MemBackend>,
),
])
.unwrap();
assert_eq!(engine.default_writable_mem(), Some("other"));
}
/// A read-only-only workspace has no default writable mem.
#[test]
fn default_writable_mem_none_without_writable_mount() {
let tmp = TempDir::new().unwrap();
let archive_path = build_archive(tmp.path(), "ext", &[("a.md", b"a")]);
let engine = Engine::from_mounts(vec![(
archive_mount("sealed", archive_path.clone()),
Box::new(ArchiveBackend::new(archive_path)) as Box<dyn MemBackend>,
)])
.unwrap();
assert_eq!(engine.default_writable_mem(), None);
}
#[test]
fn folder_path_for_mem_returns_path_for_folder_mounts_only() {
let tmp = TempDir::new().unwrap();
let mem_dir = tmp.path().join("specs");
std::fs::create_dir_all(&mem_dir).unwrap();
let writer = FilesystemMemWriter::new(mem_dir.clone());
let archive_path = build_archive(tmp.path(), "ext", &[("a.md", b"a")]);
let engine = Engine::from_mounts(vec![
(
folder_mount("specs", mem_dir.clone()),
Box::new(writer) as Box<dyn MemBackend>,
),
(
archive_mount("sealed", archive_path.clone()),
Box::new(ArchiveBackend::new(archive_path)),
),
])
.unwrap();
// Folder mount returns its path.
assert_eq!(engine.folder_path_for_mem("specs"), Some(mem_dir.as_path()),);
// Archive mount returns None — caller branches on storage type.
assert_eq!(engine.folder_path_for_mem("sealed"), None);
// Unknown mem returns None — same as Engine::mount.
assert_eq!(engine.folder_path_for_mem("missing"), None);
}
#[test]
fn mount_accessor_returns_public_mount_shape() {
// Build a heterogeneous engine and verify Engine::mount /
// Engine::mounts surface the operator-facing Mount records.
// Handlers branch on MountStorage variants through this
// accessor (replacing full's gitdir_for / worktree_for /
// mem_head_sha / mem_config_for direct-engine
// accessors).
let tmp = TempDir::new().unwrap();
let mem_dir = tmp.path().to_path_buf();
let writer = FilesystemMemWriter::new(mem_dir.clone());
let archive_path = build_archive(tmp.path(), "ext", &[("a.md", b"a")]);
let engine = Engine::from_mounts(vec![
(
folder_mount("writable", mem_dir.clone()),
Box::new(writer) as Box<dyn MemBackend>,
),
(
archive_mount("sealed", archive_path.clone()),
Box::new(ArchiveBackend::new(archive_path.clone())),
),
])
.unwrap();
// Known mems: each returns a Mount whose storage variant
// matches what the caller passed at construction.
let folder = engine.mount("writable").expect("known mem");
assert!(matches!(folder.storage, MountStorage::Folder { .. }));
assert_eq!(folder.capability, MountCapability::Write);
let archive = engine.mount("sealed").expect("known mem");
match &archive.storage {
MountStorage::Archive { path } => assert_eq!(path, &archive_path),
other => panic!("expected Archive storage, got {other:?}"),
}
assert_eq!(archive.capability, MountCapability::ReadOnly);
// Unknown mem — None, no panic, no error.
assert!(engine.mount("missing").is_none());
// Engine::mounts enumerates every mount in declaration order.
let mounts = engine.mounts();
assert_eq!(mounts.len(), 2);
assert_eq!(mounts[0].mem, "writable");
assert_eq!(mounts[1].mem, "sealed");
}
#[test]
fn mem_router_writable_set_matches_writable_mount_capability() {
// Build an engine with one writable folder mount and one
// read-only archive mount; the router's writable set must
// equal the writable mount's name only.
let tmp = TempDir::new().unwrap();
let mem_dir = tmp.path().join("specs");
std::fs::create_dir_all(&mem_dir).unwrap();
let writer = FilesystemMemWriter::new(mem_dir.clone());
let archive_path = build_archive(tmp.path(), "ext", &[("a.md", b"a")]);
let engine = Engine::from_mounts(vec![
(
folder_mount("specs", mem_dir.clone()),
Box::new(writer) as Box<dyn MemBackend>,
),
(
archive_mount("ext", archive_path.clone()),
Box::new(ArchiveBackend::new(archive_path)),
),
])
.unwrap();
let router = engine.mem_router();
assert!(router.is_writable("specs"));
assert!(!router.is_writable("ext"));
assert!(router.is_visible("specs"));
assert!(router.is_visible("ext"));
let writable: std::collections::HashSet<&String> = router.writable_mems().iter().collect();
assert_eq!(writable.len(), 1);
assert!(writable.contains(&"specs".to_string()));
}
#[test]
fn mem_router_origin_is_explicit_toml_for_workspace_mounts() {
// Every mount built via `from_mounts` lands as
// `MemOrigin::ExplicitToml` — the file-adapter origin.
// `RuntimeCreated` is reserved for `memstead_mem_create`
// runtime registrations once that handler migrates onto
// the unified engine.
let tmp = TempDir::new().unwrap();
let mem_dir = tmp.path().join("specs");
std::fs::create_dir_all(&mem_dir).unwrap();
let writer = FilesystemMemWriter::new(mem_dir.clone());
let engine = Engine::from_mounts(vec![(
folder_mount("specs", mem_dir),
Box::new(writer) as Box<dyn MemBackend>,
)])
.unwrap();
let origin = engine
.mem_router()
.origin_for_mem("specs")
.expect("known mem");
assert_eq!(origin.kind(), "explicit");
}
#[test]
fn mem_router_dir_for_writable_folder_mount_matches_storage_path() {
// Folder-backed writable mounts surface the storage path
// via `dir_for_mem`. Handlers consuming the router for
// per-mem path resolution rely on this.
let tmp = TempDir::new().unwrap();
let mem_dir = tmp.path().join("specs");
std::fs::create_dir_all(&mem_dir).unwrap();
let writer = FilesystemMemWriter::new(mem_dir.clone());
let engine = Engine::from_mounts(vec![(
folder_mount("specs", mem_dir.clone()),
Box::new(writer) as Box<dyn MemBackend>,
)])
.unwrap();
assert_eq!(
engine.mem_router().dir_for_mem("specs"),
Some(mem_dir.as_path()),
);
assert_eq!(engine.mem_router().dir_for_mem("unknown"), None);
}
#[test]
fn mem_router_archive_path_for_read_only_archive_mount() {
// Read-only archive mounts register via `add_read_only` so
// `archive_path_for_mem` resolves the archive's on-disk
// location.
let tmp = TempDir::new().unwrap();
let mem_dir = tmp.path().join("specs");
std::fs::create_dir_all(&mem_dir).unwrap();
let writer = FilesystemMemWriter::new(mem_dir.clone());
let archive_path = build_archive(tmp.path(), "ext", &[("a.md", b"a")]);
let engine = Engine::from_mounts(vec![
(
folder_mount("specs", mem_dir),
Box::new(writer) as Box<dyn MemBackend>,
),
(
archive_mount("ext", archive_path.clone()),
Box::new(ArchiveBackend::new(archive_path.clone())),
),
])
.unwrap();
let router = engine.mem_router();
assert_eq!(
router.archive_path_for_mem("ext"),
Some(archive_path.as_path()),
);
// Writable folder mount has no archive path.
assert_eq!(router.archive_path_for_mem("specs"), None);
}
#[test]
fn read_mem_config_via_backend_trait_folder_reads_bytes() {
// Direct trait call against FilesystemMemWriter. Verifies
// the backend-side primitive returns the raw bytes the
// engine then parses.
let tmp = TempDir::new().unwrap();
let mem_dir = tmp.path().to_path_buf();
std::fs::create_dir_all(mem_dir.join(".memstead")).unwrap();
let body = br#"{
"format": 1,
"schema": "default@1.0.0",
"writeGuidance": { "tone": "neutral" }
}"#;
std::fs::write(mem_dir.join(".memstead").join("config.json"), body).unwrap();
let writer = FilesystemMemWriter::new(mem_dir);
let result = MemBackend::read_mem_config(&writer).unwrap();
let bytes = result.expect("config bytes must surface");
let parsed: serde_json::Value = serde_json::from_slice(&bytes).unwrap();
assert_eq!(parsed["schema"], "default@1.0.0");
}
#[test]
fn read_mem_config_via_backend_trait_folder_missing_returns_none() {
let tmp = TempDir::new().unwrap();
let mem_dir = tmp.path().to_path_buf();
let writer = FilesystemMemWriter::new(mem_dir);
let result = MemBackend::read_mem_config(&writer).unwrap();
assert!(result.is_none());
}
#[test]
fn read_mem_config_via_backend_trait_archive_reads_bytes() {
// Build an archive containing .memstead/config.json and verify
// the ArchiveBackend impl returns its bytes.
let tmp = TempDir::new().unwrap();
let archive_path = tmp.path().join("seed.mem");
let body = br#"{
"format": 1,
"schema": "default@1.0.0",
"writeGuidance": { "tone": "archive" }
}"#;
{
let file = std::fs::File::create(&archive_path).unwrap();
let mut writer = zip::ZipWriter::new(file);
writer
.start_file(
".memstead/config.json",
zip::write::SimpleFileOptions::default(),
)
.unwrap();
use std::io::Write;
writer.write_all(body).unwrap();
writer.finish().unwrap();
}
let backend = ArchiveBackend::new(archive_path);
let result = MemBackend::read_mem_config(&backend).unwrap();
let bytes = result.expect("config bytes must surface");
let parsed: serde_json::Value = serde_json::from_slice(&bytes).unwrap();
assert_eq!(parsed["writeGuidance"]["tone"], "archive");
}
#[test]
fn mem_config_for_returns_none_when_no_config_file_present() {
// Folder backend without a `.memstead/config.json` file. The
// accessor must lenient — return None, not error.
let tmp = TempDir::new().unwrap();
let mem_dir = tmp.path().to_path_buf();
let writer = FilesystemMemWriter::new(mem_dir.clone());
let engine = Engine::from_mounts(vec![(
folder_mount("specs", mem_dir),
Box::new(writer) as Box<dyn MemBackend>,
)])
.unwrap();
assert!(engine.mem_config_for("specs").is_none());
}
#[test]
fn mem_config_for_returns_some_when_config_file_present() {
// Drop a valid `.memstead/config.json` into the mem dir,
// build the engine, and assert the accessor surfaces a
// MemConfig with the right shape (write_guidance entries
// round-trip).
let tmp = TempDir::new().unwrap();
let mem_dir = tmp.path().to_path_buf();
std::fs::create_dir_all(mem_dir.join(".memstead")).unwrap();
let config_body = r#"{
"format": 1,
"schema": "default@1.0.0",
"writeGuidance": {
"tone": "neutral",
"voice": "active"
}
}"#;
std::fs::write(mem_dir.join(".memstead").join("config.json"), config_body).unwrap();
let writer = FilesystemMemWriter::new(mem_dir.clone());
let engine = Engine::from_mounts(vec![(
folder_mount("specs", mem_dir),
Box::new(writer) as Box<dyn MemBackend>,
)])
.unwrap();
let cfg = engine
.mem_config_for("specs")
.expect("mem_config should load");
assert_eq!(cfg.write_guidance.len(), 2);
assert_eq!(
cfg.write_guidance.get("tone").and_then(|v| v.as_str()),
Some("neutral"),
);
assert_eq!(
cfg.write_guidance.get("voice").and_then(|v| v.as_str()),
Some("active"),
);
}
#[test]
fn mem_config_for_unknown_mem_returns_none() {
// Lenient accessor — unknown names get None, not Err.
let tmp = TempDir::new().unwrap();
let mem_dir = tmp.path().to_path_buf();
let writer = FilesystemMemWriter::new(mem_dir.clone());
let engine = Engine::from_mounts(vec![(
folder_mount("specs", mem_dir),
Box::new(writer) as Box<dyn MemBackend>,
)])
.unwrap();
assert!(engine.mem_config_for("missing").is_none());
}
#[test]
fn mem_config_for_archive_mount_returns_none() {
// Archive backends carry mem_config = None in V1 (the
// read-from-storage path is deferred to a follow-up).
let tmp = TempDir::new().unwrap();
let archive_path = build_archive(tmp.path(), "ext", &[("a.md", b"a")]);
let engine = Engine::from_mounts(vec![(
archive_mount("ext", archive_path.clone()),
Box::new(ArchiveBackend::new(archive_path)) as Box<dyn MemBackend>,
)])
.unwrap();
assert!(engine.mem_config_for("ext").is_none());
}
#[test]
fn mem_configs_named_iterates_only_mounts_with_config() {
// Two folder mounts; one has a config file, one doesn't.
// The iterator yields exactly the configured one — verifies
// the filter_map shape and that the name comes from the
// mount record (authoritative), not the config body.
let tmp = TempDir::new().unwrap();
let with_config = tmp.path().join("specs");
let without_config = tmp.path().join("memos");
std::fs::create_dir_all(with_config.join(".memstead")).unwrap();
std::fs::create_dir_all(&without_config).unwrap();
let config_body = r#"{
"format": 1,
"schema": "default@1.0.0",
"writeGuidance": { "tone": "neutral" }
}"#;
std::fs::write(
with_config.join(".memstead").join("config.json"),
config_body,
)
.unwrap();
let engine = Engine::from_mounts(vec![
(
folder_mount("specs", with_config.clone()),
Box::new(FilesystemMemWriter::new(with_config)) as Box<dyn MemBackend>,
),
(
folder_mount("memos", without_config.clone()),
Box::new(FilesystemMemWriter::new(without_config)) as Box<dyn MemBackend>,
),
])
.unwrap();
let yielded: Vec<(&str, usize)> = engine
.mem_configs_named()
.map(|(name, cfg)| (name, cfg.write_guidance.len()))
.collect();
assert_eq!(yielded, vec![("specs", 1)]);
}
#[test]
fn schema_for_returns_some_for_known_mem_and_none_for_unknown() {
// Every mount registers a schema (resolved from its pin at
// boot). Lookup by mem name surfaces the same Arc that
// mutations resolve internally; unknown names return None.
let tmp = TempDir::new().unwrap();
let mem_dir = tmp.path().to_path_buf();
let writer = FilesystemMemWriter::new(mem_dir.clone());
let engine = Engine::from_mounts(vec![(
folder_mount("specs", mem_dir),
Box::new(writer) as Box<dyn MemBackend>,
)])
.unwrap();
assert!(engine.schema_for("specs").is_some());
assert!(engine.schema_for("missing").is_none());
}
#[test]
fn gitdir_for_unknown_mem_returns_unknown_mem() {
let tmp = TempDir::new().unwrap();
let mem_dir = tmp.path().to_path_buf();
let writer = FilesystemMemWriter::new(mem_dir.clone());
let engine = Engine::from_mounts(vec![(
folder_mount("specs", mem_dir),
Box::new(writer) as Box<dyn MemBackend>,
)])
.unwrap();
let err = engine.gitdir_for("missing").unwrap_err();
assert!(matches!(err, EngineError::UnknownMem(v) if v == "missing"));
}
#[test]
fn gitdir_for_folder_mount_returns_no_gitdir_error() {
// Folder mounts do not have a gitdir — full's contract surfaces
// a mem-level error, not UnknownMem. Mirror that here.
let tmp = TempDir::new().unwrap();
let mem_dir = tmp.path().to_path_buf();
let writer = FilesystemMemWriter::new(mem_dir.clone());
let engine = Engine::from_mounts(vec![(
folder_mount("specs", mem_dir),
Box::new(writer) as Box<dyn MemBackend>,
)])
.unwrap();
let err = engine.gitdir_for("specs").unwrap_err();
match err {
EngineError::Mem(msg) => assert!(msg.contains("no resolved gitdir")),
other => panic!("expected EngineError::Mem, got {other:?}"),
}
}
#[test]
fn worktree_for_folder_mount_returns_storage_path() {
let tmp = TempDir::new().unwrap();
let mem_dir = tmp.path().to_path_buf();
let writer = FilesystemMemWriter::new(mem_dir.clone());
let engine = Engine::from_mounts(vec![(
folder_mount("specs", mem_dir.clone()),
Box::new(writer) as Box<dyn MemBackend>,
)])
.unwrap();
let worktree = engine.worktree_for("specs").unwrap();
assert_eq!(worktree, mem_dir);
}
#[test]
fn worktree_for_unknown_mem_returns_unknown_mem() {
let tmp = TempDir::new().unwrap();
let mem_dir = tmp.path().to_path_buf();
let writer = FilesystemMemWriter::new(mem_dir.clone());
let engine = Engine::from_mounts(vec![(
folder_mount("specs", mem_dir),
Box::new(writer) as Box<dyn MemBackend>,
)])
.unwrap();
let err = engine.worktree_for("missing").unwrap_err();
assert!(matches!(err, EngineError::UnknownMem(v) if v == "missing"));
}
#[test]
fn worktree_for_archive_mount_returns_archive_backed_error() {
let tmp = TempDir::new().unwrap();
let archive_path = build_archive(tmp.path(), "ext", &[("a.md", b"a")]);
let engine = Engine::from_mounts(vec![(
archive_mount("ext", archive_path.clone()),
Box::new(ArchiveBackend::new(archive_path)) as Box<dyn MemBackend>,
)])
.unwrap();
let err = engine.worktree_for("ext").unwrap_err();
match err {
EngineError::Mem(msg) => assert!(msg.contains("archive-backed")),
other => panic!("expected EngineError::Mem, got {other:?}"),
}
}
#[test]
fn mem_head_sha_for_folder_mount_is_none() {
// Folder backend doesn't track a head; current_head() returns
// Ok(None) at construction; mem_head_sha returns Ok(None).
let tmp = TempDir::new().unwrap();
let mem_dir = tmp.path().to_path_buf();
let writer = FilesystemMemWriter::new(mem_dir.clone());
let engine = Engine::from_mounts(vec![(
folder_mount("specs", mem_dir),
Box::new(writer) as Box<dyn MemBackend>,
)])
.unwrap();
let head = engine.mem_head_sha("specs").unwrap();
assert_eq!(head, None);
}
#[test]
fn mem_head_sha_unknown_mem_returns_unknown_mem() {
let tmp = TempDir::new().unwrap();
let mem_dir = tmp.path().to_path_buf();
let writer = FilesystemMemWriter::new(mem_dir.clone());
let engine = Engine::from_mounts(vec![(
folder_mount("specs", mem_dir),
Box::new(writer) as Box<dyn MemBackend>,
)])
.unwrap();
let err = engine.mem_head_sha("missing").unwrap_err();
assert!(matches!(err, EngineError::UnknownMem(v) if v == "missing"));
}
#[test]
fn capability_surfaces_per_mount() {
let tmp = TempDir::new().unwrap();
let mem_dir = tmp.path().to_path_buf();
let writer = FilesystemMemWriter::new(mem_dir.clone());
let archive_path = build_archive(tmp.path(), "ext", &[("a.md", b"a")]);
let engine = Engine::from_mounts(vec![
(
folder_mount("writable", mem_dir),
Box::new(writer) as Box<dyn MemBackend>,
),
(
archive_mount("read-only", archive_path.clone()),
Box::new(ArchiveBackend::new(archive_path)),
),
])
.unwrap();
assert_eq!(
engine.capability("writable").unwrap(),
MountCapability::Write
);
assert_eq!(
engine.capability("read-only").unwrap(),
MountCapability::ReadOnly
);
assert!(matches!(
engine.capability("missing"),
Err(EngineError::UnknownMem(_))
));
}
#[test]
fn read_provenance_routes_through_backend() {
let tmp = TempDir::new().unwrap();
let mem_dir = tmp.path().to_path_buf();
let writer = FilesystemMemWriter::new(mem_dir.clone());
// Append a provenance record via the backend trait directly,
// then read it back through the engine.
let backend_handle: &dyn MemBackend = &writer;
backend_handle
.append_provenance(&Provenance::new(
std::time::UNIX_EPOCH + std::time::Duration::from_secs(1_700_000_000),
crate::ProvenanceKind::Create,
Some("v:e".into()),
crate::vcs::Actor::Cli,
None,
Some("first".into()),
))
.unwrap();
let engine = Engine::from_mounts(vec![(
folder_mount("specs", mem_dir),
Box::new(writer) as Box<dyn MemBackend>,
)])
.unwrap();
let records = engine.read_provenance("specs", None).unwrap();
assert_eq!(records.len(), 1);
assert_eq!(records[0].kind, crate::ProvenanceKind::Create);
assert_eq!(records[0].entity.as_deref(), Some("v:e"));
assert_eq!(records[0].note.as_deref(), Some("first"));
}
#[test]
fn archive_mount_returns_sealed_indirectly_through_backend_layer() {
// The engine doesn't yet expose mutation methods, but an
// archive backend held on a Mount with ReadOnly capability is
// still a `&dyn MemBackend` whose write methods return
// Sealed. This test locks the trait routing — when the engine
// gains write methods in a later session, capability gating +
// backend Sealed errors must agree.
let tmp = TempDir::new().unwrap();
let archive_path = build_archive(tmp.path(), "ext", &[("a.md", b"a")]);
let backend = ArchiveBackend::new(archive_path);
match MemBackend::write_entity(&backend, Path::new("x.md"), b"x") {
Err(BackendError::Sealed) => {}
other => panic!("expected Sealed, got {other:?}"),
}
}
// ---- Read-side delegates ----------------------------------------
//
// These tests pin the surface that the MCP migration consumes
// (stats, health, context, communities, search, list, orphans,
// stubs, most_connected, missing_required_outgoing). They run
// against a folder-mount engine with a small fixture of created
// entities and one relate edge — enough to exercise both the
// graph-query path and the cache-invalidation hooks.
fn build_demo_engine(tmp: &TempDir) -> Engine {
let mem_dir = tmp.path().to_path_buf();
let writer = FilesystemMemWriter::new(mem_dir.clone());
let mut engine = Engine::from_mounts(vec![(
folder_mount("specs", mem_dir),
Box::new(writer) as Box<dyn MemBackend>,
)])
.unwrap();
let (actor, client) = cli_actor();
let source = engine
.create_entity(
empty_create_args("specs", "Source One"),
actor,
Some(&client),
None,
)
.unwrap();
let target = engine
.create_entity(
empty_create_args("specs", "Target Two"),
actor,
Some(&client),
None,
)
.unwrap();
engine
.create_entity(
empty_create_args("specs", "Lonely Three"),
actor,
Some(&client),
None,
)
.unwrap();
engine
.relate_entity(
RelateEntityArgs {
source: source.id.clone(),
expected_hash: Some(source.content_hash.clone()),
rel_type: "USES".to_string(),
target: target.id.clone(),
remove: false,
description: None,
dry_run: false,
},
actor,
Some(&client),
None,
)
.unwrap();
engine
}
#[test]
fn status_reports_per_engine_counts() {
let tmp = TempDir::new().unwrap();
let engine = build_demo_engine(&tmp);
let stats = engine.status();
assert_eq!(stats.entity_count, 3);
assert_eq!(stats.edge_count, 1);
assert_eq!(stats.mem_count, 1);
assert_eq!(stats.types_in_use, vec!["spec".to_string()]);
assert_eq!(stats.edge_types.get("USES"), Some(&1));
}
#[test]
fn orphans_lists_unconnected_real_entities() {
let tmp = TempDir::new().unwrap();
let engine = build_demo_engine(&tmp);
let orphans = engine.orphans();
assert_eq!(orphans.len(), 1);
assert_eq!(orphans[0].as_ref(), "specs--lonely-three");
}
/// #49: the orphan/community headlines can be attributed per pinned
/// schema. Single-mem here, so one bucket — but it proves the
/// attribution keys by `schema_of(mem)` and that the per-schema
/// counts sum to the raw total (which a health surface keeps verbatim).
#[test]
fn schema_breakdowns_attribute_to_mem_pin() {
let tmp = TempDir::new().unwrap();
let engine = build_demo_engine(&tmp);
let orphans = engine.orphans();
let orphans_by_schema = engine.orphans_by_schema(&orphans);
assert_eq!(
orphans_by_schema.values().sum::<usize>(),
orphans.len(),
"per-schema orphan counts must sum to the raw total"
);
assert_eq!(orphans_by_schema.len(), 1, "one mem ⇒ one schema bucket");
let (schema, count) = orphans_by_schema.iter().next().unwrap();
assert!(!schema.is_empty(), "specs mem is pinned: {schema:?}");
assert_eq!(*count, 1);
// communities_by_schema buckets the demo mem's clusters under the
// same pin; with one schema, its values sum to the global count.
let mems: Vec<String> = engine.mounts().iter().map(|m| m.mem.clone()).collect();
let communities_by_schema = engine.communities_by_schema(&mems);
assert_eq!(communities_by_schema.len(), 1);
assert_eq!(
communities_by_schema.values().sum::<usize>(),
engine.communities().count,
);
}
#[test]
fn stubs_lists_unresolved_link_targets() {
let tmp = TempDir::new().unwrap();
let mem_dir = tmp.path().to_path_buf();
let writer = FilesystemMemWriter::new(mem_dir.clone());
let mut engine = Engine::from_mounts(vec![(
folder_mount("specs", mem_dir),
Box::new(writer) as Box<dyn MemBackend>,
)])
.unwrap();
let (actor, client) = cli_actor();
let source = engine
.create_entity(
empty_create_args("specs", "Holder"),
actor,
Some(&client),
None,
)
.unwrap();
// Relate to a non-existent target — relate_entity creates a
// stub for the target so the edge can land.
engine
.relate_entity(
RelateEntityArgs {
source: source.id.clone(),
expected_hash: Some(source.content_hash.clone()),
rel_type: "USES".to_string(),
target: EntityId::new("specs", "ghost"),
remove: false,
description: None,
dry_run: false,
},
actor,
Some(&client),
None,
)
.unwrap();
let stubs = engine.stubs();
assert!(
stubs.iter().any(|(id, _)| id.as_ref() == "specs--ghost"),
"expected ghost stub: {stubs:?}"
);
}
#[test]
fn most_connected_orders_by_degree() {
let tmp = TempDir::new().unwrap();
let engine = build_demo_engine(&tmp);
let top = engine.most_connected(5);
assert_eq!(top.len(), 3);
// Source and Target each have one edge; Lonely has zero.
let zero_degree: Vec<_> = top
.iter()
.filter(|c| c.total == 0)
.map(|c| c.id.as_ref().to_string())
.collect();
assert_eq!(zero_degree, vec!["specs--lonely-three".to_string()]);
}
#[test]
fn health_returns_per_engine_summary() {
let tmp = TempDir::new().unwrap();
let engine = build_demo_engine(&tmp);
let health = engine.health();
// `memstead_create` refuses on missing required sections, so
// entities built through `empty_create_args` carry the
// helper-seeded `identity` + `purpose` bodies and no longer
// surface as missing-fields. Health remains the read-side
// tolerance surface for legacy on-disk drift — covered by
// the loader-tolerance tests that hand-craft pre-strict
// markdown files.
assert!(
health
.missing_fields
.iter()
.all(|r| r.id.as_ref() != "specs--source-one"),
"post-strict-create fixture must not surface as missing-fields; got {:?}",
health.missing_fields,
);
}
#[test]
fn context_carries_neighbors_and_community() {
let tmp = TempDir::new().unwrap();
let engine = build_demo_engine(&tmp);
let source_id = EntityId::new("specs", "source-one");
let ctx = engine.context(&source_id).unwrap();
assert_eq!(ctx.entity_id, source_id);
assert_eq!(ctx.neighbors.len(), 1);
assert_eq!(ctx.neighbors[0].relationship, "USES");
assert!(matches!(ctx.neighbors[0].direction, Direction::Outgoing));
}
#[test]
fn communities_caches_louvain_until_invalidated() {
let tmp = TempDir::new().unwrap();
let mut engine = build_demo_engine(&tmp);
// Population reflects the current store at first call.
let entities_before = engine.communities().entity_cluster_map.len();
// Cache hit — repeat call returns same data.
assert_eq!(
engine.communities().entity_cluster_map.len(),
entities_before
);
// Mutation invalidates the cache; next call re-runs against
// the post-mutation store and includes the new entity.
let (actor, client) = cli_actor();
engine
.create_entity(
empty_create_args("specs", "Disturber"),
actor,
Some(&client),
None,
)
.unwrap();
let entities_after = engine.communities().entity_cluster_map.len();
assert_eq!(
entities_after,
entities_before + 1,
"create_entity should have invalidated community cache and added the new entity"
);
}
#[test]
fn list_filters_by_metadata_only() {
let tmp = TempDir::new().unwrap();
let engine = build_demo_engine(&tmp);
let scope = SearchScope {
entity_type: Some("spec".to_string()),
..Default::default()
};
let result = engine.list(&scope);
// Three real spec entities created; stubs / non-spec types absent.
assert_eq!(result.hits.len(), 3);
}
#[test]
fn list_applies_schema_declared_filter_on_non_default_schema_mem() {
// A mem pinned to `planning` (non-default schema). The
// `decision` type declares `status` with `filterable: equality`.
// Pre-fix, filter dispatch consulted only the built-in default
// schema via `type_by_name`, missed `status`, silently bypassed
// the filter, and emitted the misleading "unknown filter key"
// warning. Post-fix, the filter is honored and no warning fires.
let tmp = TempDir::new().unwrap();
let mem_dir = tmp.path().to_path_buf();
let writer = FilesystemMemWriter::new(mem_dir.clone());
let mount = Mount {
mem: "planning".to_string(),
schema: Some(memstead_schema::SchemaRef::new(
"planning",
semver::Version::new(0, 1, 0),
)),
storage: MountStorage::Folder { path: mem_dir },
capability: MountCapability::Write,
lifecycle: MountLifecycle::Eager,
cross_linkable: true,
migration_target: None,
};
let mut engine =
Engine::from_mounts(vec![(mount, Box::new(writer) as Box<dyn MemBackend>)]).unwrap();
let (actor, client) = cli_actor();
// Two decisions with different status values; required fields
// (decision/context/consequences sections, decided_on, deciders)
// get placeholder defaults — the test only cares about the
// status field's filterability.
for (title, status) in &[("Skip Postgres", "accepted"), ("Use SQLite", "proposed")] {
let mut metadata = indexmap::IndexMap::new();
metadata.insert("status".to_string(), status.to_string());
metadata.insert("deciders".to_string(), "alice".to_string());
metadata.insert("decided_on".to_string(), "2026-05-19".to_string());
let args = crate::engine::CreateEntityArgs {
anchors: Vec::new(),
mem: "planning".to_string(),
title: title.to_string(),
entity_type: "decision".to_string(),
sections: indexmap::IndexMap::from_iter([
("decision".to_string(), "We chose this.".to_string()),
("context".to_string(), "Single-user dev.".to_string()),
("consequences".to_string(), "Lose multi-writer.".to_string()),
]),
metadata,
relations: Vec::new(),
dry_run: false,
};
engine
.create_entity(args, actor, Some(&client), None)
.unwrap();
}
// Filter on the schema-declared filterable field.
let scope = SearchScope {
entity_type: Some("decision".to_string()),
filters: std::collections::HashMap::from([(
"status".to_string(),
"accepted".to_string(),
)]),
..Default::default()
};
let result = engine.list(&scope);
assert_eq!(
result.hits.len(),
1,
"filter on schema-declared field must select only matching entities"
);
assert_eq!(result.hits[0].title, "Skip Postgres");
assert!(
result.warnings.is_empty(),
"no warning should fire when the filter is declared by the mem's pinned schema: {:?}",
result.warnings
);
}
#[test]
fn search_returns_results_against_built_index() {
let tmp = TempDir::new().unwrap();
let engine = build_demo_engine(&tmp);
let scope = SearchScope {
query: Some(crate::ops::Query {
any: vec!["source".to_string()],
..Default::default()
}),
..Default::default()
};
let result = engine.search(&scope).expect("native search returns Ok");
assert!(result.total >= 1, "expected ≥1 hit for source: {result:?}");
assert!(
result
.hits
.iter()
.any(|h| h.id.as_ref() == "specs--source-one"),
"expected source-one in hits: {result:?}"
);
}
// ---- Engine::from_workspace_root (lean boot path) --------------
}