memstead-cli 0.11.0

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

use assert_cmd::Command;
use memstead_base::binding::{Binding, BuildMode};
use memstead_base::pipeline::IngestTrigger;
use serde_json::Value;
use std::path::Path;
use tempfile::TempDir;

fn memstead() -> Command {
    Command::cargo_bin("memstead").expect("memstead binary must be built by cargo")
}

/// The binary's own path, for replaying a printed command through a shell.
fn memstead_bin() -> std::path::PathBuf {
    assert_cmd::cargo::cargo_bin("memstead")
}

/// Write `contents` to `<root>/.memstead/<rel>`, creating parent dirs.
fn write_store(root: &Path, rel: &str, contents: &str) {
    let path = root.join(".memstead").join(rel);
    std::fs::create_dir_all(path.parent().unwrap()).unwrap();
    std::fs::write(path, contents).unwrap();
}

/// A bare workspace: just the `.memstead/workspace.toml` marker.
fn bare_workspace() -> TempDir {
    let tmp = TempDir::new().unwrap();
    write_store(tmp.path(), "workspace.toml", "");
    tmp
}

/// A minimal gen-2 workspace: the workspace marker plus one codebase medium,
/// one source facet, one projection, and one flat ingest naming it. `mode` and
/// `deny` parameterise the ingest.
fn fixture(mode: &str, deny: &str) -> TempDir {
    let tmp = TempDir::new().unwrap();
    let root = tmp.path();
    write_store(root, "workspace.toml", "");
    write_store(
        root,
        "mediums/engine/src.json",
        r#"{"name":"src","type":"codebase","pointer":"../public"}"#,
    );
    write_store(
        root,
        "facets/engine/source-tree.json",
        r#"{"name":"source-tree","medium":"src","scope":[{"path":"../public/**/*.rs","mode":"allow"}]}"#,
    );
    write_store(
        root,
        "projections/engine/graph.json",
        r#"{"intent":"the engine graph","source_facets":["source-tree"],"reference_mems":["plugin"],"destination_mem":"engine","rules":{"routing":"r"}}"#,
    );
    write_store(
        root,
        "ingests/engine-graph.json",
        &format!(
            r#"{{"projection":"engine/graph","mode":"{mode}","trigger":"loop","batch_size":20,"deny_paths":[{deny}],"post_actions":{{"archive_source":true}}}}"#
        ),
    );
    tmp
}

fn read_binding(root: &Path) -> Binding {
    let bytes = std::fs::read(root.join(".memstead/projections/engine/graph.json")).unwrap();
    serde_json::from_slice(&bytes).expect("promoted projection file must parse as a v1 binding")
}

/// A discovery ingest migrates: the projection file is promoted to a v1
/// binding carrying the merged build operation, and the merged ingest is gone.
#[test]
fn migrate_promotes_projection_to_v2_binding() {
    let tmp = fixture("discovery", r#""dev","**/VISION.md""#);
    let root = tmp.path();

    let output = memstead()
        .current_dir(root)
        .args(["--json", "projection", "migrate"])
        .assert()
        .success()
        .get_output()
        .stdout
        .clone();
    let env: Value = serde_json::from_slice(&output).expect("--json migrate must emit JSON");
    assert_eq!(env["ok"], true);
    assert_eq!(env["migrated"], 1);
    assert_eq!(env["bindings"][0], "engine/graph");

    // The projection file now parses as a v2 binding with the merged build
    // op and the medium+facet folded inline under the facet's name verbatim.
    let b = read_binding(root);
    assert_eq!(b.version, 2);
    assert_eq!(b.destination_mem, "engine");
    assert_eq!(b.intent.as_deref(), Some("the engine graph"));
    assert_eq!(b.reference_mems, vec!["plugin".to_string()]);
    assert_eq!(b.sources.len(), 1);
    assert_eq!(b.sources[0].name, "source-tree");
    assert_eq!(b.sources[0].pointer, "../public");
    assert_eq!(b.sources[0].scope.len(), 1);
    assert_eq!(
        b.operations.build.as_ref().unwrap().mode,
        BuildMode::Discovery
    );
    assert_eq!(
        b.operations.build.as_ref().unwrap().trigger,
        IngestTrigger::Loop
    );
    assert_eq!(b.operations.build.as_ref().unwrap().batch_size, 20);
    assert_eq!(
        b.operations.build.as_ref().unwrap().post_actions,
        Some(serde_json::json!({ "archive_source": true }))
    );
    // Build-only: sync/verify are enabled later, never fabricated by migrate.
    assert!(b.operations.sync.is_none());
    assert!(b.operations.verify.is_none());
    // deny_paths moved up; the bare `dev` segment converted to the glob dialect.
    assert_eq!(
        b.deny_paths,
        vec!["dev/**".to_string(), "**/VISION.md".to_string()]
    );

    // Serde round-trip is lossless.
    let json = serde_json::to_string(&b).unwrap();
    let back: Binding = serde_json::from_str(&json).unwrap();
    assert_eq!(back, b);

    // The merged flat ingest was removed, along with the emptied
    // mediums/ and facets/ trees (their content folded inline).
    assert!(!root.join(".memstead/ingests/engine-graph.json").exists());
    assert!(!root.join(".memstead/mediums").exists());
    assert!(!root.join(".memstead/facets").exists());

    // A dialect-rewrite warning was reported.
    let warnings = env["warnings"].as_array().unwrap();
    assert!(
        warnings
            .iter()
            .any(|w| w["kind"] == "note" && w["message"].as_str().unwrap_or("").contains("dev/**")),
        "expected a deny-dialect note, got {warnings:?}"
    );
}

/// `--dry-run` reports the migration but writes nothing.
#[test]
fn migrate_dry_run_writes_nothing() {
    let tmp = fixture("discovery", "");
    let root = tmp.path();

    let output = memstead()
        .current_dir(root)
        .args(["--json", "projection", "migrate", "--dry-run"])
        .assert()
        .success()
        .get_output()
        .stdout
        .clone();
    let env: Value = serde_json::from_slice(&output).unwrap();
    assert_eq!(env["dry_run"], true);
    assert_eq!(env["migrated"], 1);

    // Disk untouched: the flat ingest survives and the projection file is still
    // the gen-2 shape (no `version` / `operations` keys).
    assert!(root.join(".memstead/ingests/engine-graph.json").exists());
    let raw =
        std::fs::read_to_string(root.join(".memstead/projections/engine/graph.json")).unwrap();
    assert!(
        !raw.contains("\"version\""),
        "gen-2 shape must be untouched"
    );
    assert!(!raw.contains("operations"), "gen-2 shape must be untouched");
}

/// A codebase binding validates clean — no capability warnings.
#[test]
fn migrate_legal_codebase_binding_validates_clean() {
    let tmp = fixture("discovery", "");
    let root = tmp.path();
    let output = memstead()
        .current_dir(root)
        .args(["--json", "projection", "migrate", "--dry-run"])
        .assert()
        .success()
        .get_output()
        .stdout
        .clone();
    let env: Value = serde_json::from_slice(&output).unwrap();
    let warnings = env["warnings"].as_array().unwrap();
    assert!(
        warnings.iter().all(|w| w["kind"] != "capability"),
        "a legal codebase binding must not surface a capability refusal: {warnings:?}"
    );
}

/// A facet declaring a preparation surfaces the D6 capability refusal as a
/// migrate warning (the format still carries it faithfully).
#[test]
fn migrate_surfaces_preparation_capability_warning() {
    let tmp = fixture("discovery", "");
    let root = tmp.path();
    // Overwrite the facet to declare a preparation the registry does not know.
    write_store(
        root,
        "facets/engine/source-tree.json",
        r#"{"name":"source-tree","medium":"src","scope":[{"path":"../public/**/*.rs","mode":"allow"}],"preparation":"pdf-to-markdown"}"#,
    );
    let output = memstead()
        .current_dir(root)
        .args(["--json", "projection", "migrate", "--dry-run"])
        .assert()
        .success()
        .get_output()
        .stdout
        .clone();
    let env: Value = serde_json::from_slice(&output).unwrap();
    let warnings = env["warnings"].as_array().unwrap();
    assert!(
        warnings.iter().any(|w| w["kind"] == "capability"
            && w["message"]
                .as_str()
                .unwrap_or("")
                .contains("pdf-to-markdown")),
        "expected a preparation capability warning, got {warnings:?}"
    );
}

/// `refinement` mode refuses with the typed `PROJECTION_MIGRATE_REFINEMENT`
/// code (exit 5) and writes nothing.
#[test]
fn migrate_refinement_mode_refuses_typed() {
    let tmp = fixture("refinement", "");
    let root = tmp.path();
    let output = memstead()
        .current_dir(root)
        .args(["--json", "projection", "migrate"])
        .assert()
        .failure()
        .get_output()
        .stdout
        .clone();
    let env: Value = serde_json::from_slice(&output).unwrap();
    assert_eq!(env["code"], "PROJECTION_MIGRATE_REFINEMENT");
    // All-or-nothing: the ingest survives untouched.
    assert!(root.join(".memstead/ingests/engine-graph.json").exists());
}

/// A dangling ingest→projection ref refuses with the typed
/// `PROJECTION_MIGRATE_DANGLING_REF` code (exit 5).
#[test]
fn migrate_dangling_ref_refuses_typed() {
    let tmp = fixture("discovery", "");
    let root = tmp.path();
    // Repoint the ingest at a projection that does not exist.
    write_store(
        root,
        "ingests/engine-graph.json",
        r#"{"projection":"engine/missing","mode":"discovery","trigger":"loop","batch_size":20,"deny_paths":[]}"#,
    );
    let output = memstead()
        .current_dir(root)
        .args(["--json", "projection", "migrate"])
        .assert()
        .failure()
        .get_output()
        .stdout
        .clone();
    let env: Value = serde_json::from_slice(&output).unwrap();
    assert_eq!(env["code"], "PROJECTION_MIGRATE_DANGLING_REF");
}

/// Running outside a workspace refuses with the shared, single-sourced
/// `WORKSPACE_NOT_INITIALISED` code — never a generic/internal leak.
#[test]
fn migrate_outside_workspace_is_typed() {
    let tmp = TempDir::new().unwrap();
    let output = memstead()
        .current_dir(tmp.path())
        .args(["--json", "projection", "migrate"])
        .assert()
        .failure()
        .get_output()
        .stdout
        .clone();
    let env: Value = serde_json::from_slice(&output).unwrap();
    assert_eq!(env["code"], "WORKSPACE_NOT_INITIALISED");
    assert_ne!(env["code"], "INTERNAL");
}

// ---------------------------------------------------------------------------
// projection init (D8)
// ---------------------------------------------------------------------------

/// Read the scaffolded binding file's raw bytes.
fn scaffold_bytes(root: &Path, mem: &str, stem: &str) -> Vec<u8> {
    std::fs::read(root.join(format!(".memstead/projections/{mem}/{stem}.json"))).unwrap()
}

/// A codebase source scaffolds ONE v2 record with the source inline, the
/// binding declares build+sync+verify (matrix-permitting), the on-disk
/// binding round-trips, and the `--json` output matches the pinned
/// byte-shape.
#[test]
fn init_codebase_scaffolds_all_three_with_full_operations() {
    let tmp = bare_workspace();
    let root = tmp.path();

    let output = memstead()
        .current_dir(root)
        .args([
            "--json",
            "projection",
            "init",
            "--mem",
            "engine",
            "--source",
            "../public",
            "--medium-type",
            "codebase",
            "--intent",
            "model the engine",
            "--name",
            "graph",
        ])
        .assert()
        .success()
        .get_output()
        .stdout
        .clone();
    let env: Value = serde_json::from_slice(&output).expect("--json init must emit JSON");

    // Pinned contract byte-shape: { binding, created, operations, warnings }.
    assert_eq!(env["binding"], "engine/graph");
    assert_eq!(
        env["created"],
        serde_json::json!([".memstead/projections/engine/graph.json"])
    );
    assert_eq!(
        env["operations"],
        serde_json::json!(["build", "sync", "verify"])
    );
    // `--source ../public` resolves outside this workspace root — init
    // warns with the works/degrades split and the common-parent recipe
    // (never the retired "anchors orphan" claim — post pointer-join,
    // out-of-root anchors resolve) and still succeeds.
    // Two warnings: the layout caveat, and — because this fixture's source
    // tree does not exist — the absent-source note. A declared pointer that
    // resolves to nothing is legal but never silent.
    let warnings = env["warnings"].as_array().expect("warnings array");
    assert_eq!(warnings.len(), 2, "got: {warnings:?}");
    assert!(
        warnings
            .iter()
            .any(|w| w.as_str().unwrap_or("").contains("which does not exist")),
        "the absent source must be named: {warnings:?}",
    );
    let w = warnings[0].as_str().unwrap();
    assert!(w.contains("outside the workspace root"), "got: {w}");
    assert!(
        w.contains("anchor resolution all work"),
        "warning must state what works: {w}"
    );
    assert!(
        w.contains("common parent directory"),
        "warning must carry the relocation recipe: {w}"
    );
    assert!(
        !w.contains("orphan"),
        "the retired anchors-orphan claim must not reappear: {w}"
    );
    // Exactly the four contract keys — no extras leaked.
    let keys: Vec<&str> = env
        .as_object()
        .unwrap()
        .keys()
        .map(String::as_str)
        .collect();
    assert_eq!(keys, vec!["binding", "created", "operations", "warnings"]);

    // Exactly one file exists on disk — no mediums/facets trees appear.
    assert!(
        root.join(".memstead/projections/engine/graph.json")
            .is_file()
    );
    assert!(!root.join(".memstead/mediums").exists());
    assert!(!root.join(".memstead/facets").exists());

    // The projection file parses as a v2 binding and round-trips losslessly.
    let bytes = scaffold_bytes(root, "engine", "graph");
    let b: Binding = serde_json::from_slice(&bytes).expect("scaffold must be a v2 binding");
    assert_eq!(b.version, 2);
    assert_eq!(b.destination_mem, "engine");
    assert_eq!(b.intent.as_deref(), Some("model the engine"));
    assert_eq!(b.sources.len(), 1);
    assert_eq!(b.sources[0].name, "graph");
    assert_eq!(
        b.operations.build.as_ref().unwrap().mode,
        BuildMode::Discovery
    );
    assert!(b.operations.sync.is_some());
    assert!(b.operations.verify.is_some());
    // F1 — a git-backed (codebase) source scaffolds a prune block with the
    // strongest supported guarantee: never-clobber (base leg retrievable).
    assert_eq!(
        b.prune.as_ref().unwrap().guarantee,
        memstead_base::binding::PruneGuarantee::NeverClobber
    );
    let round = serde_json::to_string(&b).unwrap();
    let back: Binding = serde_json::from_str(&round).unwrap();
    assert_eq!(back, b);
}

/// Complement to the out-of-root warning: an IN-root source scaffolds with
/// no warnings at all — the layout hint fires only where the shape is
/// affected, never as ambient noise.
#[test]
fn init_in_root_codebase_source_warns_nothing() {
    let tmp = bare_workspace();
    let root = tmp.path();
    std::fs::create_dir_all(root.join("src")).unwrap();

    let output = memstead()
        .current_dir(root)
        .args([
            "--json",
            "projection",
            "init",
            "--mem",
            "engine",
            "--source",
            "src",
            "--medium-type",
            "codebase",
            "--intent",
            "model the engine",
            "--name",
            "inroot",
        ])
        .assert()
        .success()
        .get_output()
        .stdout
        .clone();
    let env: Value = serde_json::from_slice(&output).expect("--json init must emit JSON");
    assert_eq!(
        env["warnings"],
        serde_json::json!([]),
        "in-root pointer must produce zero hint noise"
    );
}

/// Round-trip pin (Rust half): `projection init` still emits **exactly** the
/// committed golden binding the plugin's v1 schema test validates against
/// `binding.schema.json`. The JS half (in the v1 validator suite) proves the
/// golden validates against the schema; this proves init still produces that
/// golden. Together they keep the plugin's `memstead-plugin/v1` binding schema
/// and the engine's emitter from drifting apart: change the emitter's shape and
/// this fails until the golden (and thus the schema check) is revisited.
#[test]
fn init_output_matches_the_v1_schema_golden() {
    let tmp = bare_workspace();
    let root = tmp.path();

    // Args chosen to match the committed golden's content (mem, intent, name;
    // the source pointer lands only in the medium file, not the binding).
    memstead()
        .current_dir(root)
        .args([
            "projection",
            "init",
            "--mem",
            "docs",
            "--source",
            "../src",
            "--medium-type",
            "codebase",
            "--intent",
            "Keep the reference mem true to the source tree",
            "--name",
            "guide",
        ])
        .assert()
        .success();

    let emitted: Value = serde_json::from_slice(
        &std::fs::read(root.join(".memstead/projections/docs/guide.json")).unwrap(),
    )
    .unwrap();

    // The golden lives with the v1 format schemas under docs/ (repo-root-relative
    // to the cli crate: two levels up to `public/`, then the schemas tree).
    let golden_path = Path::new(env!("CARGO_MANIFEST_DIR"))
        .join("../../docs/schemas/memstead-plugin/v1/examples/binding.from-init.json");
    let golden: Value = serde_json::from_slice(&std::fs::read(&golden_path).unwrap_or_else(|e| {
        panic!(
            "golden fixture unreadable at {}: {e}",
            golden_path.display()
        )
    }))
    .unwrap();

    assert_eq!(
        emitted,
        golden,
        "`projection init` output drifted from the committed v1 binding golden \
         ({}). Update the golden AND re-check binding.schema.json — the two must \
         move together.",
        golden_path.display()
    );
}

/// A filesystem source likewise scaffolds build+sync+verify (the matrix marks
/// it path-shaped with a change signal).
#[test]
fn init_filesystem_scaffolds_full_operations() {
    let tmp = bare_workspace();
    let root = tmp.path();
    let output = memstead()
        .current_dir(root)
        .args([
            "--json",
            "projection",
            "init",
            "--mem",
            "docs",
            "--source",
            "../docs",
            "--medium-type",
            "filesystem",
            "--name",
            "manual",
        ])
        .assert()
        .success()
        .get_output()
        .stdout
        .clone();
    let env: Value = serde_json::from_slice(&output).unwrap();
    assert_eq!(env["binding"], "docs/manual");
    assert_eq!(
        env["operations"],
        serde_json::json!(["build", "sync", "verify"])
    );
    // `../docs` is outside the workspace root — the consequence-naming
    // warning fires here too (filesystem medium) — and the fixture's tree
    // does not exist, so the absent-source note joins it.
    let warnings = env["warnings"].as_array().expect("warnings array");
    assert_eq!(warnings.len(), 2, "got: {warnings:?}");
    assert!(
        warnings
            .iter()
            .any(|w| w.as_str().unwrap_or("").contains("which does not exist")),
        "the absent source must be named: {warnings:?}",
    );
    assert!(
        warnings[0]
            .as_str()
            .unwrap()
            .contains("outside the workspace root"),
        "got: {warnings:?}"
    );
}

/// A `web` source scaffolds build-only, with the deferral named in `warnings[]`
/// (operator decision 7). The binding on disk carries no sync/verify block.
#[test]
fn init_web_source_scaffolds_build_only_with_warning() {
    let tmp = bare_workspace();
    let root = tmp.path();
    let output = memstead()
        .current_dir(root)
        .args([
            "--json",
            "projection",
            "init",
            "--mem",
            "research",
            "--source",
            "https://example.com/docs",
            "--medium-type",
            "web",
        ])
        .assert()
        .success()
        .get_output()
        .stdout
        .clone();
    let env: Value = serde_json::from_slice(&output).unwrap();
    // Stem derived from the source's final path component.
    assert_eq!(env["binding"], "research/docs");
    assert_eq!(env["operations"], serde_json::json!(["build"]));
    let warnings = env["warnings"].as_array().unwrap();
    assert!(!warnings.is_empty(), "web must warn about the deferral");
    assert!(
        warnings
            .iter()
            .any(|w| w.as_str().unwrap_or("").contains("out of scope")
                && w.as_str().unwrap_or("").contains("operator decision 7")),
        "expected a deferral warning, got {warnings:?}"
    );

    // On disk: build-only binding.
    let bytes = std::fs::read(root.join(".memstead/projections/research/docs.json")).unwrap();
    let b: Binding = serde_json::from_slice(&bytes).unwrap();
    assert!(b.operations.sync.is_none());
    assert!(b.operations.verify.is_none());
}

/// Re-running `init` on an existing binding id refuses `PROJECTION_EXISTS`
/// (exit 5) and touches nothing — the record is byte-identical after the
/// refused second run.
#[test]
fn init_existing_binding_refuses_without_touching_disk() {
    let tmp = bare_workspace();
    let root = tmp.path();
    let args = [
        "projection",
        "init",
        "--mem",
        "engine",
        "--source",
        "../public",
        "--medium-type",
        "codebase",
        "--name",
        "graph",
    ];

    memstead().current_dir(root).args(args).assert().success();
    let before = scaffold_bytes(root, "engine", "graph");

    // Second run refuses.
    let output = memstead()
        .current_dir(root)
        .args(
            ["--json"]
                .iter()
                .chain(args.iter())
                .copied()
                .collect::<Vec<_>>(),
        )
        .assert()
        .failure()
        .get_output()
        .stdout
        .clone();
    let env: Value = serde_json::from_slice(&output).unwrap();
    assert_eq!(env["code"], "PROJECTION_EXISTS");
    assert_eq!(env["details"]["binding"], "engine/graph");

    // No partial writes: the record is byte-identical.
    let after = scaffold_bytes(root, "engine", "graph");
    assert_eq!(before, after, "refused init must not touch disk");
}

/// `init` outside a workspace refuses with the shared, single-sourced
/// `WORKSPACE_NOT_INITIALISED` code — never a generic/internal leak.
#[test]
fn init_outside_workspace_is_typed() {
    let tmp = TempDir::new().unwrap();
    let output = memstead()
        .current_dir(tmp.path())
        .args([
            "--json",
            "projection",
            "init",
            "--mem",
            "m",
            "--source",
            "../x",
            "--medium-type",
            "codebase",
        ])
        .assert()
        .failure()
        .get_output()
        .stdout
        .clone();
    let env: Value = serde_json::from_slice(&output).unwrap();
    assert_eq!(env["code"], "WORKSPACE_NOT_INITIALISED");
    assert_ne!(env["code"], "INTERNAL");
}

// ---------------------------------------------------------------------------
// projection enable (D6 — the remedy a refused mutating op cites)
// ---------------------------------------------------------------------------

/// A gen-2 fixture migrated to a build-only v1 `engine/graph` binding — the
/// substrate for `enable` tests (migrate produces no sync/verify block).
fn migrated_build_only_workspace() -> TempDir {
    let tmp = fixture("discovery", "");
    memstead()
        .current_dir(tmp.path())
        .args(["projection", "migrate"])
        .assert()
        .success();
    tmp
}

/// Enabling `sync` on a codebase binding that lacked it adds the block (with
/// sensible defaults) and round-trips; every other field is untouched, and
/// `verify` stays absent.
#[test]
fn enable_sync_adds_block_to_codebase_binding() {
    let tmp = migrated_build_only_workspace();
    let root = tmp.path();

    let before = read_binding(root);
    assert!(
        before.operations.sync.is_none(),
        "precondition: no sync block"
    );

    let output = memstead()
        .current_dir(root)
        .args(["--json", "projection", "enable", "sync", "engine/graph"])
        .assert()
        .success()
        .get_output()
        .stdout
        .clone();
    let env: Value = serde_json::from_slice(&output).expect("--json enable must emit JSON");
    assert_eq!(env["binding"], "engine/graph");
    assert_eq!(env["enabled"], "sync");
    assert_eq!(env["operations"], serde_json::json!(["build", "sync"]));

    let after = read_binding(root);
    // The sync block appeared, with the manual trigger and build's batch_size.
    let sync = after
        .operations
        .sync
        .as_ref()
        .expect("sync block was added");
    assert_eq!(sync.trigger, IngestTrigger::Manual);
    assert_eq!(
        sync.batch_size,
        before.operations.build.as_ref().unwrap().batch_size
    );
    // verify stays absent — enable adds only the named operation.
    assert!(after.operations.verify.is_none());
    // Every other field is the same declaration.
    assert_eq!(after.version, before.version);
    assert_eq!(after.intent, before.intent);
    assert_eq!(after.sources, before.sources);
    assert_eq!(after.reference_mems, before.reference_mems);
    assert_eq!(after.destination_mem, before.destination_mem);
    assert_eq!(after.deny_paths, before.deny_paths);
    assert_eq!(after.coverage_semantics, before.coverage_semantics);
    assert_eq!(after.rules, before.rules);
    assert_eq!(after.operations.build, before.operations.build);

    // Round-trips losslessly.
    let json = serde_json::to_string(&after).unwrap();
    let back: Binding = serde_json::from_str(&json).unwrap();
    assert_eq!(back, after);
}

/// Enabling `sync` on a `web`-medium binding refuses with the capability error
/// and leaves the binding file byte-identical (no partial write).
#[test]
fn enable_sync_on_web_refuses_and_leaves_file_identical() {
    let tmp = bare_workspace();
    let root = tmp.path();
    // Scaffold a build-only web binding (init strips sync/verify over web).
    memstead()
        .current_dir(root)
        .args([
            "projection",
            "init",
            "--mem",
            "research",
            "--source",
            "https://example.com/docs",
            "--medium-type",
            "web",
        ])
        .assert()
        .success();

    let path = root.join(".memstead/projections/research/docs.json");
    let before = std::fs::read(&path).unwrap();

    let output = memstead()
        .current_dir(root)
        .args(["--json", "projection", "enable", "sync", "research/docs"])
        .assert()
        .failure()
        .get_output()
        .stdout
        .clone();
    let env: Value = serde_json::from_slice(&output).unwrap();
    assert_eq!(env["code"], "PROJECTION_CAPABILITY_UNSUPPORTED");
    assert!(
        env["message"]
            .as_str()
            .unwrap_or("")
            .contains("out of scope"),
        "capability refusal must state the gap: {env}"
    );

    // The file is untouched by the refused enable.
    let after = std::fs::read(&path).unwrap();
    assert_eq!(before, after, "refused enable must not touch disk");
}

/// Enabling an already-present operation refuses `PROJECTION_OP_ALREADY_ENABLED`
/// and does not corrupt the binding. `build` is always present, so enabling it
/// always lands here.
#[test]
fn enable_already_present_op_refuses() {
    let tmp = migrated_build_only_workspace();
    let root = tmp.path();

    // `build` is always present on any binding.
    let path = root.join(".memstead/projections/engine/graph.json");
    let before = std::fs::read(&path).unwrap();
    let output = memstead()
        .current_dir(root)
        .args(["--json", "projection", "enable", "build", "engine/graph"])
        .assert()
        .failure()
        .get_output()
        .stdout
        .clone();
    let env: Value = serde_json::from_slice(&output).unwrap();
    assert_eq!(env["code"], "PROJECTION_OP_ALREADY_ENABLED");
    assert_eq!(env["details"]["operation"], "build");
    assert_eq!(std::fs::read(&path).unwrap(), before, "refusal is a no-op");

    // Enable sync once (succeeds), then again → already-enabled, still clean.
    memstead()
        .current_dir(root)
        .args(["projection", "enable", "sync", "engine/graph"])
        .assert()
        .success();
    let with_sync = std::fs::read(&path).unwrap();
    let output = memstead()
        .current_dir(root)
        .args(["--json", "projection", "enable", "sync", "engine/graph"])
        .assert()
        .failure()
        .get_output()
        .stdout
        .clone();
    let env: Value = serde_json::from_slice(&output).unwrap();
    assert_eq!(env["code"], "PROJECTION_OP_ALREADY_ENABLED");
    assert_eq!(
        std::fs::read(&path).unwrap(),
        with_sync,
        "re-enable is a no-op and does not corrupt the binding"
    );
    // Still a valid v1 binding with exactly one sync block.
    let b = read_binding(root);
    assert!(b.operations.sync.is_some());
    assert!(b.operations.verify.is_none());
}

/// Enabling an operation on a missing binding refuses `PROJECTION_NOT_FOUND`
/// (exit 3, NotFound) — never a generic/internal leak.
#[test]
fn enable_missing_binding_is_not_found() {
    let tmp = bare_workspace();
    let root = tmp.path();
    let output = memstead()
        .current_dir(root)
        .args(["--json", "projection", "enable", "sync", "engine/nope"])
        .assert()
        .failure()
        .get_output()
        .stdout
        .clone();
    let env: Value = serde_json::from_slice(&output).unwrap();
    assert_eq!(env["code"], "PROJECTION_NOT_FOUND");
    assert_eq!(env["details"]["binding"], "engine/nope");
}

/// A malformed binding id (no `/`) refuses `PROJECTION_INVALID_NAME` before any
/// disk access.
#[test]
fn enable_malformed_binding_id_refuses() {
    let tmp = bare_workspace();
    let root = tmp.path();
    let output = memstead()
        .current_dir(root)
        .args(["--json", "projection", "enable", "verify", "noslash"])
        .assert()
        .failure()
        .get_output()
        .stdout
        .clone();
    let env: Value = serde_json::from_slice(&output).unwrap();
    assert_eq!(env["code"], "PROJECTION_INVALID_NAME");
}

/// `enable` outside a workspace refuses with the shared, single-sourced
/// `WORKSPACE_NOT_INITIALISED` code — never a generic/internal leak.
#[test]
fn enable_outside_workspace_is_typed() {
    let tmp = TempDir::new().unwrap();
    let output = memstead()
        .current_dir(tmp.path())
        .args(["--json", "projection", "enable", "sync", "engine/graph"])
        .assert()
        .failure()
        .get_output()
        .stdout
        .clone();
    let env: Value = serde_json::from_slice(&output).unwrap();
    assert_eq!(env["code"], "WORKSPACE_NOT_INITIALISED");
    assert_ne!(env["code"], "INTERNAL");
}

// ---------------------------------------------------------------------------
// projection advance (D7)
// ---------------------------------------------------------------------------

/// Run `git` in `repo`, panicking on failure (deterministic committer identity).
fn git(repo: &Path, args: &[&str]) {
    let out = std::process::Command::new("git")
        .args(args)
        .current_dir(repo)
        .env("GIT_AUTHOR_NAME", "t")
        .env("GIT_AUTHOR_EMAIL", "t@example")
        .env("GIT_COMMITTER_NAME", "t")
        .env("GIT_COMMITTER_EMAIL", "t@example")
        .output()
        .unwrap();
    assert!(
        out.status.success(),
        "git {args:?}: {}",
        String::from_utf8_lossy(&out.stderr)
    );
}

fn git_head(repo: &Path) -> String {
    String::from_utf8(
        std::process::Command::new("git")
            .args(["rev-parse", "HEAD"])
            .current_dir(repo)
            .output()
            .unwrap()
            .stdout,
    )
    .unwrap()
    .trim()
    .to_string()
}

/// Build a bootable **filesystem** workspace (no `mem-repo/.git`) with one
/// writable folder mem `engine`, a v1 binding `engine/graph` over a git source
/// tree at `<root>/src`, and the source moved from a base commit to `head1`
/// (a.rs modified, b.rs deleted). The base commit's sha is pre-seeded into the
/// mem's `syncState` so `advance` sees a real changed slice. Written directly
/// into the mem config (not via `mem set-sync-state`) so the test is
/// flavour-independent — the lean CLI has no `mem` subcommand.
fn advance_workspace() -> TempDir {
    let tmp = TempDir::new().unwrap();
    let root = tmp.path();

    // Workspace adapter + engine folder mount.
    write_store(
        root,
        "workspace.toml",
        "format = \"memstead-git-branch-2\"\n\n[persistence_adapter]\nname = \"file-two-layer\"\n",
    );
    write_store(
        root,
        "state/mounts.json",
        r#"{"format":"memstead-mounts-3","mounts":[{"mem":"engine","schema":"default@1.0.0","storage":{"type":"folder","path":"engine-mem"},"capability":"write","lifecycle":"eager","cross_linkable":false}]}"#,
    );

    // v1 binding store: medium (git codebase at `src`), facet, binding.
    write_store(
        root,
        "projections/engine/graph.json",
        r#"{"version":2,"intent":"model the engine","sources":[{"name":"source-tree","type":"codebase","pointer":"src","change_detection":"git","scope":[{"path":"src/**/*.rs","mode":"allow"}]}],"reference_mems":[],"destination_mem":"engine","deny_paths":[],"coverage_semantics":"exhaustive","operations":{"build":{"mode":"discovery","trigger":"loop","batch_size":20},"sync":{"trigger":"manual","batch_size":20}}}"#,
    );

    // The git source tree: base (a.rs + b.rs), then head1 (modify a.rs, delete b.rs).
    let src = root.join("src");
    std::fs::create_dir_all(&src).unwrap();
    git(&src, &["init", "-q"]);
    std::fs::write(src.join("a.rs"), "one").unwrap();
    std::fs::write(src.join("b.rs"), "bee").unwrap();
    git(&src, &["add", "a.rs", "b.rs"]);
    git(&src, &["commit", "-qm", "base"]);
    let baseline = git_head(&src);
    std::fs::write(src.join("a.rs"), "one-longer").unwrap();
    std::fs::remove_file(src.join("b.rs")).unwrap();
    git(&src, &["add", "-A"]);
    git(&src, &["commit", "-qm", "head1"]);

    // The destination mem's config, with the sync baseline pre-seeded so the
    // changed slice (a.rs modified, b.rs deleted) is presented.
    let mem_meta = root.join("engine-mem").join(".memstead");
    std::fs::create_dir_all(&mem_meta).unwrap();
    std::fs::write(
        mem_meta.join("config.json"),
        format!(
            r#"{{"format":1,"schema":"default@1.0.0","syncState":{{"engine/graph/source-tree#synced":"{baseline}"}}}}"#
        ),
    )
    .unwrap();

    tmp
}

/// End-to-end through the CLI (three separate processes, proving on-disk
/// resumability): advance a partial disposition, refuse an unknown artifact
/// atomically, then complete — the `#synced` token advancing.
#[test]
fn advance_records_dispositions_completes_and_gates_unknown() {
    let tmp = advance_workspace();
    let root = tmp.path();

    // (1) Dispose a.rs → remainder = b.rs (deleted), not complete.
    let out = memstead()
        .current_dir(root)
        .args([
            "--json",
            "projection",
            "advance",
            "engine/graph",
            "--dispositions",
            r#"{"src/a.rs": "worked"}"#,
        ])
        .assert()
        .success()
        .get_output()
        .stdout
        .clone();
    let env: Value = serde_json::from_slice(&out).expect("advance --json must emit JSON");
    assert_eq!(env["binding"], "engine/graph");
    assert_eq!(env["completed"], false);
    assert_eq!(env["pending"], 1);
    assert_eq!(env["disposed"], 1);
    assert_eq!(env["remainder"]["deleted"], serde_json::json!(["src/b.rs"]));
    assert_eq!(env["remainder"]["modified"], serde_json::json!([]));

    // (2) An unknown artifact id refuses the whole call atomically.
    let store_path = root.join(".memstead/state/advance/engine/graph.json");
    let before = std::fs::read(&store_path).unwrap();
    let out = memstead()
        .current_dir(root)
        .args([
            "--json",
            "projection",
            "advance",
            "engine/graph",
            "--dispositions",
            r#"{"src/never.rs": "worked"}"#,
        ])
        .assert()
        .failure()
        .get_output()
        .stdout
        .clone();
    let env: Value = serde_json::from_slice(&out).unwrap();
    assert_eq!(env["code"], "PROJECTION_ADVANCE_UNKNOWN_ARTIFACT");
    let after = std::fs::read(&store_path).unwrap();
    assert_eq!(before, after, "refused advance must not touch the store");

    // (3) Dispose the rest → complete → the `#synced` token advances. The a.rs
    // disposition from step (1) persisted across processes (resumability).
    let out = memstead()
        .current_dir(root)
        .args([
            "--json",
            "projection",
            "advance",
            "engine/graph",
            "--dispositions",
            r#"{"src/b.rs": "worked"}"#,
        ])
        .assert()
        .success()
        .get_output()
        .stdout
        .clone();
    let env: Value = serde_json::from_slice(&out).unwrap();
    assert_eq!(env["completed"], true);
    assert_eq!(env["pending"], 0);
    assert_eq!(env["disposed"], 2, "a.rs (persisted) + b.rs (this call)");
    assert_eq!(
        env["tokens_written"],
        serde_json::json!(["engine/graph/source-tree#synced"])
    );
    // The durable store was dropped on completion.
    assert!(!store_path.exists());
}

/// A medium-relative artifact id (`a.rs` where the slice printed `src/a.rs`)
/// refuses with the corrected workspace-relative id in the message AND the
/// `corrected_artifacts` details map — and the dialect never widens: the
/// medium-relative form is refused, never accepted.
#[test]
fn advance_medium_relative_id_refuses_with_corrected_id() {
    let tmp = advance_workspace();
    let root = tmp.path();

    let out = memstead()
        .current_dir(root)
        .args([
            "--json",
            "projection",
            "advance",
            "engine/graph",
            "--dispositions",
            r#"{"a.rs": "worked"}"#,
        ])
        .assert()
        .failure()
        .get_output()
        .stdout
        .clone();
    let env: Value = serde_json::from_slice(&out).unwrap();
    assert_eq!(env["code"], "PROJECTION_ADVANCE_UNKNOWN_ARTIFACT");
    let message = env["message"].as_str().unwrap();
    assert!(
        message.contains("workspace-relative"),
        "message names the expected dialect: {message}"
    );
    assert!(
        message.contains("`a.rs` → `src/a.rs`"),
        "message carries the concrete corrected id: {message}"
    );
    assert_eq!(
        env["details"]["corrected_artifacts"]["a.rs"], "src/a.rs",
        "the remedy is machine-readable in details"
    );
    // Nothing was written — the refused medium-relative id was not accepted
    // in any form (the gate did not widen).
    assert!(
        !root
            .join(".memstead/state/advance/engine/graph.json")
            .exists()
    );
}

/// `advance` on a missing binding refuses with `PROJECTION_NOT_FOUND` (NotFound
/// exit) — before any engine boot.
#[test]
fn advance_missing_binding_is_typed() {
    let tmp = bare_workspace();
    let out = memstead()
        .current_dir(tmp.path())
        .args([
            "--json",
            "projection",
            "advance",
            "engine/nope",
            "--dispositions",
            "{}",
        ])
        .assert()
        .failure()
        .get_output()
        .stdout
        .clone();
    let env: Value = serde_json::from_slice(&out).unwrap();
    assert_eq!(env["code"], "PROJECTION_NOT_FOUND");
    assert_ne!(env["code"], "INTERNAL");
}

/// `advance` with a malformed `--dispositions` payload refuses with
/// `PROJECTION_INVALID_DISPOSITIONS` before touching configs or an engine.
#[test]
fn advance_invalid_dispositions_is_typed() {
    let tmp = bare_workspace();
    let out = memstead()
        .current_dir(tmp.path())
        .args([
            "--json",
            "projection",
            "advance",
            "engine/graph",
            "--dispositions",
            "not-json",
        ])
        .assert()
        .failure()
        .get_output()
        .stdout
        .clone();
    let env: Value = serde_json::from_slice(&out).unwrap();
    assert_eq!(env["code"], "PROJECTION_INVALID_DISPOSITIONS");
}

/// `projection exclude` records an authored exclusion for a **stable in-scope**
/// artifact (not in any changed slice), gates a non-member atomically, and
/// rejects a malformed payload — the direct write path for the exclusion ledger.
#[test]
fn exclude_records_authored_exclusion_and_gates_non_member() {
    let tmp = advance_workspace();
    let root = tmp.path();
    // S(D) for this binding = files on disk matching `src/**/*.rs` = {src/a.rs}
    // (b.rs was deleted at head1). a.rs is a stable member — declarable excluded.
    let out = memstead()
        .current_dir(root)
        .args([
            "--json",
            "projection",
            "exclude",
            "engine/graph",
            "--exclusions",
            r#"{"src/a.rs": "mined; warrants no entity"}"#,
        ])
        .assert()
        .success()
        .get_output()
        .stdout
        .clone();
    let env: Value = serde_json::from_slice(&out).expect("exclude --json must emit JSON");
    assert_eq!(env["binding"], "engine/graph");
    assert_eq!(env["added"], 1);
    assert_eq!(env["excluded"], 1);

    // The exclusion + rationale persisted to the durable ledger.
    let store: Value = serde_json::from_slice(
        &std::fs::read(root.join(".memstead/state/advance/engine/graph.json")).unwrap(),
    )
    .unwrap();
    assert_eq!(store["exclusions"]["src/a.rs"], "mined; warrants no entity");

    // An artifact outside S(D) refuses the whole call atomically.
    let before = std::fs::read(root.join(".memstead/state/advance/engine/graph.json")).unwrap();
    let out = memstead()
        .current_dir(root)
        .args([
            "--json",
            "projection",
            "exclude",
            "engine/graph",
            "--exclusions",
            r#"{"src/not-a-file.rs": "x"}"#,
        ])
        .assert()
        .failure()
        .get_output()
        .stdout
        .clone();
    let env: Value = serde_json::from_slice(&out).unwrap();
    assert_eq!(env["code"], "PROJECTION_EXCLUDE_NOT_SOURCE_MEMBER");
    let after = std::fs::read(root.join(".memstead/state/advance/engine/graph.json")).unwrap();
    assert_eq!(before, after, "refused call must not touch the ledger");

    // A malformed payload refuses with the typed parse code.
    let out = memstead()
        .current_dir(root)
        .args([
            "--json",
            "projection",
            "exclude",
            "engine/graph",
            "--exclusions",
            "not-json",
        ])
        .assert()
        .failure()
        .get_output()
        .stdout
        .clone();
    let env: Value = serde_json::from_slice(&out).unwrap();
    assert_eq!(env["code"], "PROJECTION_INVALID_EXCLUSIONS");
}

/// `advance` outside a workspace refuses with the shared, single-sourced
/// `WORKSPACE_NOT_INITIALISED` code — never a generic/internal leak.
#[test]
fn advance_outside_workspace_is_typed() {
    let tmp = TempDir::new().unwrap();
    let out = memstead()
        .current_dir(tmp.path())
        .args([
            "--json",
            "projection",
            "advance",
            "engine/graph",
            "--dispositions",
            "{}",
        ])
        .assert()
        .failure()
        .get_output()
        .stdout
        .clone();
    let env: Value = serde_json::from_slice(&out).unwrap();
    assert_eq!(env["code"], "WORKSPACE_NOT_INITIALISED");
    assert_ne!(env["code"], "INTERNAL");
}

// ── brief (D9) ───────────────────────────────────────────────────────────────

/// `projection brief <mem>/<stem>` renders a binding's discovery run-brief,
/// headed by the canonical binding id (D3/D9). Scaffold a binding with
/// `projection init`, then render it.
#[cfg(feature = "mem-repo")]
#[test]
fn brief_renders_for_scaffolded_binding() {
    let tmp = TempDir::new().unwrap();
    let ws = tmp.path().join("ws");
    memstead()
        .args(["mem-repo", "init", ws.to_str().unwrap(), "--no-gitignore"])
        .assert()
        .success();
    memstead()
        .current_dir(&ws)
        .args([
            "projection",
            "init",
            "--mem",
            "ws",
            "--source",
            "../src",
            "--medium-type",
            "codebase",
            "--name",
            "code",
        ])
        .assert()
        .success();

    let out = memstead()
        .current_dir(&ws)
        .args(["projection", "brief", "ws/code"])
        .assert()
        .success()
        .get_output()
        .stdout
        .clone();
    let brief = String::from_utf8(out).unwrap();
    assert!(
        brief.contains("ws/code"),
        "brief must name the canonical binding id; got:\n{brief}"
    );
    assert!(
        brief.contains("## Situation"),
        "a discovery brief carries the Situation block; got:\n{brief}"
    );
}

/// Backlog-sweep plan 09a criterion 2, re-expressed against the pointer
/// channel: the ACTIVE-BINDING pointer derives only from CONSUMING renders.
/// A peek-only brief (any named render — the `--consume` flag requires
/// `--all`, so named briefs are peeks by construction) leaves every cache
/// byte-identical and never points enforcement at the peeked binding; a
/// consuming `--all --consume` render publishes the picked binding's id.
#[cfg(feature = "mem-repo")]
#[test]
fn active_binding_pointer_derives_only_from_consuming_renders() {
    fn snapshot(dir: &Path) -> Vec<(String, Vec<u8>)> {
        let mut out = Vec::new();
        let mut stack = vec![dir.to_path_buf()];
        while let Some(d) = stack.pop() {
            let Ok(entries) = std::fs::read_dir(&d) else {
                continue;
            };
            for e in entries.flatten() {
                let p = e.path();
                if p.is_dir() {
                    stack.push(p);
                } else {
                    out.push((p.display().to_string(), std::fs::read(&p).unwrap()));
                }
            }
        }
        out.sort();
        out
    }

    let tmp = TempDir::new().unwrap();
    let ws = tmp.path().join("ws");
    memstead()
        .args(["mem-repo", "init", ws.to_str().unwrap(), "--no-gitignore"])
        .assert()
        .success();
    for name in ["alpha", "beta"] {
        memstead()
            .current_dir(&ws)
            .args([
                "projection",
                "init",
                "--mem",
                "ws",
                "--source",
                "../src",
                "--medium-type",
                "codebase",
                "--name",
                name,
            ])
            .assert()
            .success();
    }
    let cache_file = ws
        .join(".memstead.cache")
        .join("projection")
        .join("active-binding.json");

    // Peek binding beta: a pure read — the pointer is not created.
    memstead()
        .current_dir(&ws)
        .args(["projection", "brief", "ws/beta"])
        .assert()
        .success();
    assert!(
        !cache_file.exists(),
        "a peek-only render must not create the active-binding pointer"
    );

    // Repeated peeks are byte-idempotent on ALL caches.
    let before = snapshot(&ws.join(".memstead.cache"));
    memstead()
        .current_dir(&ws)
        .args(["projection", "brief", "ws/beta"])
        .assert()
        .success();
    assert_eq!(
        before,
        snapshot(&ws.join(".memstead.cache")),
        "repeated peeks must leave every cache byte-identical"
    );

    // A consuming rotation render publishes the PICKED binding's id.
    let out = memstead()
        .current_dir(&ws)
        .args(["--json", "projection", "brief", "--all", "--consume"])
        .assert()
        .success()
        .get_output()
        .stdout
        .clone();
    let payload: serde_json::Value = serde_json::from_slice(&out).unwrap();
    let brief = payload["brief"].as_str().expect("rotation renders a brief");
    let cache: serde_json::Value = serde_json::from_slice(
        &std::fs::read(&cache_file)
            .expect("a consuming render must publish the active-binding pointer"),
    )
    .unwrap();
    let guarded = cache["binding"].as_str().unwrap();
    let stem = guarded.split_once('/').map(|(_, s)| s).unwrap_or(guarded);
    assert!(
        brief.contains(stem),
        "enforcement must target the binding whose brief was consumed: pointer names \
         `{guarded}`, brief:\n{brief}"
    );
}

/// `projection check-path`: single and `--batch` stdin forms answer deny
/// verdicts against a named binding, naming the matched deny entry on a
/// block; the directory-prefix rule and `..`-escaping candidates produce the
/// verdicts the retired hook dialect produced.
#[cfg(feature = "mem-repo")]
#[test]
fn check_path_answers_single_and_batch() {
    let tmp = TempDir::new().unwrap();
    let ws = tmp.path().join("ws");
    memstead()
        .args(["mem-repo", "init", ws.to_str().unwrap(), "--no-gitignore"])
        .assert()
        .success();
    memstead()
        .current_dir(&ws)
        .args([
            "projection",
            "init",
            "--mem",
            "ws",
            "--source",
            "../src",
            "--medium-type",
            "codebase",
            "--name",
            "alpha",
        ])
        .assert()
        .success();
    // The author adds denies to the scaffolded record: a subtree and a
    // workspace-escaping entry (the dogfood cross-medium dialect).
    let record_path = ws
        .join(".memstead")
        .join("projections")
        .join("ws")
        .join("alpha.json");
    let mut record: Value = serde_json::from_slice(&std::fs::read(&record_path).unwrap()).unwrap();
    let denies = record["deny_paths"].as_array_mut().unwrap();
    denies.push(Value::String("dev/**".into()));
    denies.push(Value::String("../CLAUDE.md".into()));
    std::fs::write(&record_path, serde_json::to_vec(&record).unwrap()).unwrap();

    // Single form: a denied path names the matched entry.
    let out = memstead()
        .current_dir(&ws)
        .args([
            "--json",
            "projection",
            "check-path",
            "--binding",
            "ws/alpha",
            "dev/notes/a.md",
        ])
        .assert()
        .success()
        .get_output()
        .stdout
        .clone();
    let v: Value = serde_json::from_slice(&out).unwrap();
    assert_eq!(v["binding"], "ws/alpha");
    assert_eq!(v["results"][0]["denied"], true);
    assert_eq!(v["results"][0]["matched"], "dev/**");

    // Batch form: one process answers every candidate — the directory-
    // targeted read (`dev` itself), a `..`-escaping sibling candidate, a
    // recursing Glob pattern, and an allowed path.
    let batch = serde_json::json!({
        "cwd": ws.to_str().unwrap(),
        "paths": [
            "dev",
            tmp.path().join("CLAUDE.md").to_str().unwrap(),
            "dev/**/*.md",
            "src/lib.rs",
        ],
    });
    let out = memstead()
        .current_dir(&ws)
        .args([
            "--json",
            "projection",
            "check-path",
            "--binding",
            "ws/alpha",
            "--batch",
        ])
        .write_stdin(batch.to_string())
        .assert()
        .success()
        .get_output()
        .stdout
        .clone();
    let v: Value = serde_json::from_slice(&out).unwrap();
    let results = v["results"].as_array().unwrap();
    assert_eq!(results.len(), 4);
    assert_eq!(
        results[0]["denied"], true,
        "a read of the denied directory itself is blocked (prefix rule)"
    );
    assert_eq!(
        results[1]["denied"], true,
        "a `..`-escaping candidate matches a `../` deny entry"
    );
    assert_eq!(results[1]["matched"], "../CLAUDE.md");
    assert_eq!(
        results[2]["denied"], true,
        "a Glob pattern recursing the denied subtree is blocked"
    );
    assert_eq!(results[3]["denied"], false);
    assert_eq!(results[3]["matched"], Value::Null);
}

/// `projection check-path` refusals are typed, never "allowed" by omission:
/// an unknown binding, a quarantined binding, a missing active pointer, and
/// a malformed batch each refuse with their own code.
#[cfg(feature = "mem-repo")]
#[test]
fn check_path_refuses_typed() {
    let tmp = TempDir::new().unwrap();
    let ws = tmp.path().join("ws");
    memstead()
        .args(["mem-repo", "init", ws.to_str().unwrap(), "--no-gitignore"])
        .assert()
        .success();

    // Unknown binding → PROJECTION_NOT_FOUND (exit 3).
    memstead()
        .current_dir(&ws)
        .args([
            "projection",
            "check-path",
            "--binding",
            "ws/ghost",
            "dev/a.md",
        ])
        .assert()
        .failure()
        .code(3)
        .stderr(predicates::str::contains("PROJECTION_NOT_FOUND"));

    // No --binding and no active pointer → NO_ACTIVE_BINDING (exit 3).
    memstead()
        .current_dir(&ws)
        .args(["projection", "check-path", "dev/a.md"])
        .assert()
        .failure()
        .code(3)
        .stderr(predicates::str::contains("NO_ACTIVE_BINDING"));

    // A quarantined binding refuses with its typed reason, never answering
    // "allowed": a version-gate-failing record file lands in quarantine.
    write_store(
        &ws,
        "projections/ws/legacy.json",
        r#"{ "version": 1, "destination_mem": "ws" }"#,
    );
    memstead()
        .current_dir(&ws)
        .args([
            "projection",
            "check-path",
            "--binding",
            "ws/legacy",
            "dev/a.md",
        ])
        .assert()
        .failure()
        .stderr(predicates::str::contains("PROJECTION_QUARANTINED"));

    // A malformed batch refuses whole (INVALID_INPUT, exit 5) — never a
    // part-answer.
    memstead()
        .current_dir(&ws)
        .args([
            "projection",
            "init",
            "--mem",
            "ws",
            "--source",
            "../src",
            "--medium-type",
            "codebase",
            "--name",
            "alpha",
        ])
        .assert()
        .success();
    for bad in ["not json", r#"{"cwd": "/x"}"#, r#"{"paths": ["ok", 42]}"#] {
        memstead()
            .current_dir(&ws)
            .args([
                "projection",
                "check-path",
                "--binding",
                "ws/alpha",
                "--batch",
            ])
            .write_stdin(bad)
            .assert()
            .failure()
            .code(5)
            .stderr(predicates::str::contains("INVALID_INPUT"));
    }
}

/// With `--binding` omitted, `check-path` answers against the ACTIVE binding
/// — the one the last consuming render published — so enforcement follows
/// the loop with no list ever cached: after the pointer moves, the previous
/// binding's denies are no longer enforced (the stale-enforcement regression,
/// re-expressed at the new seam).
#[cfg(feature = "mem-repo")]
#[test]
fn check_path_follows_the_active_binding() {
    let tmp = TempDir::new().unwrap();
    let ws = tmp.path().join("ws");
    memstead()
        .args(["mem-repo", "init", ws.to_str().unwrap(), "--no-gitignore"])
        .assert()
        .success();
    for name in ["alpha", "beta"] {
        memstead()
            .current_dir(&ws)
            .args([
                "projection",
                "init",
                "--mem",
                "ws",
                "--source",
                "../src",
                "--medium-type",
                "codebase",
                "--name",
                name,
            ])
            .assert()
            .success();
    }
    // Alpha denies `secrets/**` on top of the scaffold defaults.
    let record_path = ws
        .join(".memstead")
        .join("projections")
        .join("ws")
        .join("alpha.json");
    let mut record: Value = serde_json::from_slice(&std::fs::read(&record_path).unwrap()).unwrap();
    record["deny_paths"]
        .as_array_mut()
        .unwrap()
        .push(Value::String("secrets/**".into()));
    std::fs::write(&record_path, serde_json::to_vec(&record).unwrap()).unwrap();

    let pointer = ws
        .join(".memstead.cache")
        .join("projection")
        .join("active-binding.json");
    std::fs::create_dir_all(pointer.parent().unwrap()).unwrap();

    let check = |expect_denied: bool| {
        let out = memstead()
            .current_dir(&ws)
            .args(["--json", "projection", "check-path", "secrets/key.txt"])
            .assert()
            .success()
            .get_output()
            .stdout
            .clone();
        let v: Value = serde_json::from_slice(&out).unwrap();
        assert_eq!(v["results"][0]["denied"], expect_denied);
    };

    std::fs::write(&pointer, r#"{"binding":"ws/alpha"}"#).unwrap();
    check(true);
    // The loop moves to beta: alpha's extra deny must not survive, because
    // nothing of alpha's list is cached anywhere — only the pointer moved.
    std::fs::write(&pointer, r#"{"binding":"ws/beta"}"#).unwrap();
    check(false);
}

/// `projection brief --all` on a workspace with NO bindings configured reports
/// a distinct `no_bindings` outcome (exit 0) — not the all-backing-off
/// `skipped` outcome, which would otherwise collapse into the same `None`. A
/// caller (the plugin's setup ramp, a status display) branches on this to
/// prompt first-time setup rather than retry a no-op pass.
#[cfg(feature = "mem-repo")]
#[test]
fn brief_all_empty_store_reports_no_bindings() {
    let tmp = TempDir::new().unwrap();
    let ws = tmp.path().join("ws");
    memstead()
        .args(["mem-repo", "init", ws.to_str().unwrap(), "--no-gitignore"])
        .assert()
        .success();

    // JSON: the distinct `{ "no_bindings": true }` envelope.
    let out = memstead()
        .current_dir(&ws)
        .args(["--json", "projection", "brief", "--all"])
        .assert()
        .success()
        .get_output()
        .stdout
        .clone();
    let env: Value = serde_json::from_slice(&out).unwrap();
    assert_eq!(env["no_bindings"], Value::Bool(true));
    assert!(
        env.get("skipped").is_none(),
        "empty store must NOT report the backing-off `skipped` outcome; got:\n{env}"
    );

    // Markdown: a distinct, human-readable no-bindings line (not "backing off").
    let out = memstead()
        .current_dir(&ws)
        .args(["projection", "brief", "--all"])
        .assert()
        .success()
        .get_output()
        .stdout
        .clone();
    let md = String::from_utf8(out).unwrap();
    assert!(
        md.contains("No bindings configured"),
        "empty store gets a distinct no-bindings message; got:\n{md}"
    );
    assert!(
        !md.contains("backing off"),
        "empty store must not use the backing-off message; got:\n{md}"
    );
}

/// `projection brief <binding> --verify` renders the verify brief (group C):
/// measurement + capped-adjudication instructions only, with the explicit
/// no-mutation refusal and NO repair block. Read-only on the mem.
#[cfg(feature = "mem-repo")]
#[test]
fn brief_verify_renders_measurement_only() {
    let tmp = TempDir::new().unwrap();
    let ws = tmp.path().join("ws");
    memstead()
        .args(["mem-repo", "init", ws.to_str().unwrap(), "--no-gitignore"])
        .assert()
        .success();
    memstead()
        .current_dir(&ws)
        .args([
            "projection",
            "init",
            "--mem",
            "ws",
            "--source",
            "../src",
            "--medium-type",
            "codebase",
            "--name",
            "code",
        ])
        .assert()
        .success();

    let out = memstead()
        .current_dir(&ws)
        .args(["projection", "brief", "ws/code", "--verify"])
        .assert()
        .success()
        .get_output()
        .stdout
        .clone();
    let brief = String::from_utf8(out).unwrap();
    assert!(brief.contains("## Verify — measure fidelity, do not mutate"));
    // Reworded 2026-08-20 with the engine-side assertion in
    // `ingest::brief::tests`: the brief used to claim verify writes
    // "**nothing**", which is false — a completed run records findings,
    // backfills anchor hashes and writes a `#verified` baseline. The refusal
    // being pinned is about ENTITY CONTENT, so the claim is narrowed to what
    // holds rather than dropped.
    assert!(
        brief.contains("Verify writes **no entity content**"),
        "C1 refusal present; got:\n{brief}"
    );
    // C1/C2 refusal: the verify brief carries NO repair block.
    assert!(
        !brief.contains("## How to repair"),
        "verify brief must not carry repair instructions; got:\n{brief}"
    );
    assert!(!brief.contains("## Open findings to repair"));
}

/// `projection brief <binding> --sync` renders the sync brief (group C): the
/// sole-maintenance-writer prompt with the absorbed reconcile conservatism. A
/// fresh mem (no anchors, never synced) triggers the adopt / first-sync framing.
#[cfg(feature = "mem-repo")]
#[test]
fn brief_sync_renders_sole_writer_with_conservatism() {
    let tmp = TempDir::new().unwrap();
    let ws = tmp.path().join("ws");
    memstead()
        .args(["mem-repo", "init", ws.to_str().unwrap(), "--no-gitignore"])
        .assert()
        .success();
    memstead()
        .current_dir(&ws)
        .args([
            "projection",
            "init",
            "--mem",
            "ws",
            "--source",
            "../src",
            "--medium-type",
            "codebase",
            "--name",
            "code",
        ])
        .assert()
        .success();

    let out = memstead()
        .current_dir(&ws)
        .args(["projection", "brief", "ws/code", "--sync"])
        .assert()
        .success()
        .get_output()
        .stdout
        .clone();
    let brief = String::from_utf8(out).unwrap();
    assert!(brief.contains("## Sync — repair the graph to match the source"));
    assert!(brief.contains("sole maintenance writer"));
    assert!(brief.contains("Sync commits nothing."));
    // Fresh mem → adopt / first-sync framing (E1 brief half).
    assert!(
        brief.contains("## First sync — adopting `ws`"),
        "fresh mem gets adopt framing; got:\n{brief}"
    );
    // Absorbed reconcile conservatism (C3).
    assert!(brief.contains("## How to repair — be conservative"));
    assert!(brief.contains("A dropped dependency FLAGS, it does not auto-remove."));
    assert!(brief.contains("`[commit <hash>]` log-style entries"));
}

/// `projection brief <binding> --sync` against a binding whose sync operation
/// is not enabled refuses typed with the enable remedy in details — a loop
/// must not spend a work slot rendering a brief the engine will refuse to
/// apply (backlog-sweep plan 03, decision 13). Complement: `projection
/// enable sync` makes the identical call succeed.
#[cfg(feature = "mem-repo")]
#[test]
fn brief_sync_refuses_sync_disabled_binding_with_remedy() {
    let tmp = TempDir::new().unwrap();
    let ws = tmp.path().join("ws");
    memstead()
        .args(["mem-repo", "init", ws.to_str().unwrap(), "--no-gitignore"])
        .assert()
        .success();
    memstead()
        .current_dir(&ws)
        .args([
            "projection",
            "init",
            "--mem",
            "ws",
            "--source",
            "../src",
            "--medium-type",
            "codebase",
            "--name",
            "code",
        ])
        .assert()
        .success();

    // Strip the scaffolded sync block — the store is operator-editable JSON;
    // direct edits take effect on the next load (documented store contract).
    let record_path = ws.join(".memstead/projections/ws/code.json");
    let mut record: serde_json::Value =
        serde_json::from_slice(&std::fs::read(&record_path).unwrap()).unwrap();
    record["operations"].as_object_mut().unwrap().remove("sync");
    std::fs::write(&record_path, serde_json::to_vec_pretty(&record).unwrap()).unwrap();

    let out = memstead()
        .current_dir(&ws)
        .args(["--json", "projection", "brief", "ws/code", "--sync"])
        .assert()
        .failure()
        .get_output()
        .stdout
        .clone();
    let envelope: serde_json::Value =
        serde_json::from_slice(&out).expect("JSON envelope on stdout");
    assert_eq!(
        envelope["code"], "PROJECTION_SYNC_NOT_ENABLED",
        "got: {envelope}"
    );
    assert_eq!(
        envelope["details"]["remedy"]["cli"], "memstead projection enable sync ws/code",
        "the one-command remedy rides details: {envelope}"
    );

    // Complement: running the named remedy makes the same call succeed.
    memstead()
        .current_dir(&ws)
        .args(["projection", "enable", "sync", "ws/code"])
        .assert()
        .success();
    memstead()
        .current_dir(&ws)
        .args(["projection", "brief", "ws/code", "--sync"])
        .assert()
        .success();
}

/// `projection brief --verify` / `--sync` without a binding id refuses with a
/// typed `PROJECTION_BRIEF_BINDING_REQUIRED` — they render one binding, never an
/// `--all` rotation.
#[cfg(feature = "mem-repo")]
#[test]
fn brief_verify_sync_require_a_binding() {
    let tmp = TempDir::new().unwrap();
    let ws = tmp.path().join("ws");
    memstead()
        .args(["mem-repo", "init", ws.to_str().unwrap(), "--no-gitignore"])
        .assert()
        .success();

    for flag in ["--verify", "--sync"] {
        let out = memstead()
            .current_dir(&ws)
            .args(["--json", "projection", "brief", flag])
            .assert()
            .failure()
            .get_output()
            .stdout
            .clone();
        let env: Value = serde_json::from_slice(&out).unwrap();
        assert_eq!(env["code"], "PROJECTION_BRIEF_BINDING_REQUIRED");
        assert_ne!(env["code"], "INTERNAL");
    }
}

/// `projection brief` on an unknown binding id refuses `PROJECTION_NOT_FOUND`
/// (NotFound exit) — never a generic/internal leak.
#[cfg(feature = "mem-repo")]
#[test]
fn brief_missing_binding_refuses() {
    let tmp = TempDir::new().unwrap();
    let ws = tmp.path().join("ws");
    memstead()
        .args(["mem-repo", "init", ws.to_str().unwrap(), "--no-gitignore"])
        .assert()
        .success();

    let out = memstead()
        .current_dir(&ws)
        .args(["--json", "projection", "brief", "engine/nope"])
        .assert()
        .failure()
        .get_output()
        .stdout
        .clone();
    let env: Value = serde_json::from_slice(&out).unwrap();
    assert_eq!(env["code"], "PROJECTION_NOT_FOUND");
    assert_ne!(env["code"], "INTERNAL");
}

/// `projection brief` outside a workspace refuses with the shared,
/// single-sourced `WORKSPACE_NOT_INITIALISED` code — never a generic/internal
/// leak. Runs on both build flavours (no engine is built before the check).
#[test]
fn brief_outside_workspace_is_typed() {
    let tmp = TempDir::new().unwrap();
    let out = memstead()
        .current_dir(tmp.path())
        .args(["--json", "projection", "brief", "engine/graph"])
        .assert()
        .failure()
        .get_output()
        .stdout
        .clone();
    let env: Value = serde_json::from_slice(&out).unwrap();
    assert_eq!(env["code"], "WORKSPACE_NOT_INITIALISED");
    assert_ne!(env["code"], "INTERNAL");
}

// ── migrate: gen-1 root-folder path (folded from the retired `pipeline migrate`) ──

/// A gen-1 root-folder workspace (`scopes|projections|ingests/` at the root)
/// migrates straight to a v1 binding in one `projection migrate` pass (D10,
/// gen-1 path — folded from the retired `pipeline migrate` command).
#[test]
fn migrate_gen1_root_folder_promotes_to_v2_binding() {
    let tmp = TempDir::new().unwrap();
    let root = tmp.path();
    write_store(root, "workspace.toml", "");

    let write_root = |rel: &str, contents: &str| {
        let path = root.join(rel);
        std::fs::create_dir_all(path.parent().unwrap()).unwrap();
        std::fs::write(path, contents).unwrap();
    };
    write_root(
        "scopes/engine/src.json",
        r#"{"type":"codebase","scope":{"tree":[{"path":"../public/**/*.rs","mode":"allow"}]}}"#,
    );
    write_root(
        "projections/engine/graph.json",
        r#"{"intent":"the engine graph","sources":[{"scope_ref":"src"}],"destinations":[{"mem":"engine"}]}"#,
    );
    write_root(
        "ingests/engine-graph.json",
        r#"{"projection":"engine/graph","mode":"discovery","trigger":"loop","batch_size":20,"deny_paths":[]}"#,
    );

    let output = memstead()
        .current_dir(root)
        .args(["--json", "projection", "migrate"])
        .assert()
        .success()
        .get_output()
        .stdout
        .clone();
    let env: Value = serde_json::from_slice(&output).unwrap();
    assert_eq!(env["migrated"], 1);
    assert_eq!(env["bindings"][0], "engine/graph");

    // The projection was promoted to a v2 binding in the `.memstead/` store,
    // the split scope folded inline (medium half from the derived pointer,
    // facet half from the tree).
    let b = read_binding(root);
    assert_eq!(b.version, 2);
    assert_eq!(b.destination_mem, "engine");
    assert_eq!(b.sources.len(), 1);
    assert_eq!(b.sources[0].name, "src");
    assert_eq!(b.sources[0].pointer, "../public");
    assert_eq!(
        b.operations.build.as_ref().unwrap().mode,
        BuildMode::Discovery
    );
    // The merged flat ingest was consumed; the intermediate mediums/facets
    // materialization was folded inline and its trees removed.
    assert!(!root.join(".memstead/ingests/engine-graph.json").exists());
    assert!(!root.join(".memstead/mediums").exists());
    assert!(!root.join(".memstead/facets").exists());
}

/// Criterion-2 fixture proofs, end to end through the CLI: a genuine v1
/// THREE-FILE store (medium + facet + `version:1` binding) with a live
/// `#synced` watermark migrates to one v2 record — medium+facet content
/// folded under the facet's name byte-verbatim, trees removed — the status
/// surface reports the SAME synced state before-keyed and after, and a
/// second migrate run changes zero bytes.
#[test]
fn migrate_v1_three_file_store_preserves_watermark_and_is_byte_idempotent() {
    let tmp = TempDir::new().unwrap();
    let root = tmp.path();

    // Workspace adapter + destination folder mount (status needs a real mem).
    write_store(
        root,
        "workspace.toml",
        "format = \"memstead-git-branch-2\"\n\n[persistence_adapter]\nname = \"file-two-layer\"\n",
    );
    write_store(
        root,
        "state/mounts.json",
        r#"{"format":"memstead-mounts-3","mounts":[{"mem":"engine","schema":"default@1.0.0","storage":{"type":"folder","path":"engine-mem"},"capability":"write","lifecycle":"eager","cross_linkable":false}]}"#,
    );

    // The v1 THREE-FILE store: standalone medium + facet, and a version-1
    // binding referencing the facet by name.
    write_store(
        root,
        "mediums/engine/source-tree.json",
        r#"{"name":"source-tree","type":"codebase","pointer":"src","change_detection":"git"}"#,
    );
    write_store(
        root,
        "facets/engine/source-tree.json",
        r#"{"name":"source-tree","medium":"source-tree","scope":[{"path":"src/**/*.rs","mode":"allow"}]}"#,
    );
    write_store(
        root,
        "projections/engine/graph.json",
        r#"{"version":1,"intent":"model the engine","source_facets":["source-tree"],"reference_mems":[],"destination_mem":"engine","deny_paths":[],"coverage_semantics":"exhaustive","operations":{"build":{"mode":"discovery","trigger":"loop","batch_size":20},"sync":{"trigger":"loop","batch_size":20}}}"#,
    );

    // The fixture declares git change-detection, so give it a real git root:
    // since 2026-08-21 a declared `git` is probed rather than trusted, and a
    // tree with no `.git` resolves to `none` (a declaration cannot conjure a
    // signal the checkout does not have). Without this the source renders
    // `signal none` and the assertion below reads as a migration failure when
    // the watermark is in fact preserved.
    let src = root.join("src");
    std::fs::create_dir_all(&src).unwrap();
    git(&src, &["init", "-q", "."]);

    // A live watermark keyed `<binding>/<source>#synced` in the destination
    // mem's config — the load-bearing key migration must keep resolving.
    let watermark = "0123456789abcdef0123456789abcdef01234567";
    let mem_meta = root.join("engine-mem").join(".memstead");
    std::fs::create_dir_all(&mem_meta).unwrap();
    std::fs::write(
        mem_meta.join("config.json"),
        format!(
            r#"{{"format":1,"schema":"default@1.0.0","syncState":{{"engine/graph/source-tree#synced":"{watermark}"}}}}"#
        ),
    )
    .unwrap();
    std::fs::create_dir_all(root.join("src")).unwrap();

    // Migrate: the v1 leg folds the three files into one v2 record.
    let out = memstead()
        .current_dir(root)
        .args(["--json", "projection", "migrate"])
        .assert()
        .success()
        .get_output()
        .stdout
        .clone();
    let env: Value = serde_json::from_slice(&out).unwrap();
    assert_eq!(env["migrated"], 1);
    assert_eq!(env["bindings"][0], "engine/graph");

    // One v2 record: facet name preserved byte-verbatim as the source name,
    // medium half + facet half folded in, no invented fields.
    let b = read_binding(root);
    assert_eq!(b.version, 2);
    assert_eq!(b.sources.len(), 1);
    assert_eq!(b.sources[0].name, "source-tree");
    assert_eq!(b.sources[0].pointer, "src");
    assert_eq!(b.sources[0].change_detection.as_deref(), Some("git"));
    assert_eq!(b.sources[0].scope.len(), 1);
    assert!(
        b.operations.sync.is_some(),
        "operations block carried whole"
    );
    // The emptied trees are gone.
    assert!(!root.join(".memstead/mediums").exists());
    assert!(!root.join(".memstead/facets").exists());

    // The watermark resolves identically after migration: the status surface
    // reports the recorded token under the preserved source name.
    let status = memstead()
        .current_dir(root)
        .args(["status"])
        .assert()
        .success()
        .get_output()
        .stdout
        .clone();
    let status = String::from_utf8_lossy(&status).to_string();
    assert!(
        status.contains(&format!("source-tree: signal git, synced {watermark}")),
        "watermark must resolve under the preserved source name, got:\n{status}"
    );

    // A second migrate run changes zero bytes and reports nothing to do.
    let before_bytes = std::fs::read(root.join(".memstead/projections/engine/graph.json")).unwrap();
    let out = memstead()
        .current_dir(root)
        .args(["--json", "projection", "migrate"])
        .assert()
        .success()
        .get_output()
        .stdout
        .clone();
    let env: Value = serde_json::from_slice(&out).unwrap();
    assert_eq!(env["migrated"], 0);
    assert_eq!(env["already_v2"], 1);
    let after_bytes = std::fs::read(root.join(".memstead/projections/engine/graph.json")).unwrap();
    assert_eq!(before_bytes, after_bytes, "re-run must be byte-idempotent");
    let mem_config = std::fs::read_to_string(mem_meta.join("config.json")).unwrap();
    assert!(mem_config.contains(watermark), "mem syncState untouched");
}

/// `--dry-run` on a gen-1 root-folder workspace previews the promotion without
/// materializing the gen-2 store or touching the root-folder layout.
#[test]
fn migrate_gen1_dry_run_writes_nothing() {
    let tmp = TempDir::new().unwrap();
    let root = tmp.path();
    write_store(root, "workspace.toml", "");
    let write_root = |rel: &str, contents: &str| {
        let path = root.join(rel);
        std::fs::create_dir_all(path.parent().unwrap()).unwrap();
        std::fs::write(path, contents).unwrap();
    };
    write_root(
        "scopes/engine/src.json",
        r#"{"type":"codebase","scope":{"tree":[{"path":"../public/**/*.rs","mode":"allow"}]}}"#,
    );
    write_root(
        "projections/engine/graph.json",
        r#"{"intent":"the engine graph","sources":[{"scope_ref":"src"}],"destinations":[{"mem":"engine"}]}"#,
    );
    write_root(
        "ingests/engine-graph.json",
        r#"{"projection":"engine/graph","mode":"discovery","trigger":"loop","batch_size":20,"deny_paths":[]}"#,
    );

    let output = memstead()
        .current_dir(root)
        .args(["--json", "projection", "migrate", "--dry-run"])
        .assert()
        .success()
        .get_output()
        .stdout
        .clone();
    let env: Value = serde_json::from_slice(&output).unwrap();
    assert_eq!(env["dry_run"], true);
    assert_eq!(env["migrated"], 1);
    // Nothing materialized under `.memstead/` (no gen-2 store written).
    assert!(
        !root
            .join(".memstead/projections/engine/graph.json")
            .exists()
    );
    assert!(!root.join(".memstead/mediums/engine/src.json").exists());
}

/// The absent-destination remedy must work in the workspace the reader is
/// standing in. `memstead mem init` is mem-repo-only, so in the
/// filesystem-mem shape `memstead quickstart` produces it refuses — the
/// brief there must name the repointing fix instead. The mem-repo variant
/// of this test cannot catch that, which is why this one exists.
#[test]
fn brief_absent_destination_remedy_suits_the_workspace_shape() {
    let tmp = TempDir::new().unwrap();
    let repo = tmp.path().join("app");
    std::fs::create_dir_all(repo.join("src")).unwrap();
    std::fs::write(repo.join("src/a.rs"), b"pub fn a() {}\n").unwrap();
    memstead()
        .current_dir(&repo)
        .args(["quickstart", "--repo", ".", "--agent", "claude-code"])
        .assert()
        .success();

    // Repoint the binding at a mem that is not there.
    let record = repo.join(".memstead/projections/app/app.json");
    let mut binding: Value = serde_json::from_slice(&std::fs::read(&record).unwrap()).unwrap();
    binding["destination_mem"] = Value::String("ghost".into());
    std::fs::write(&record, serde_json::to_vec_pretty(&binding).unwrap()).unwrap();

    let out = String::from_utf8(
        memstead()
            .current_dir(&repo)
            .args(["projection", "brief", "app/app"])
            .assert()
            .success()
            .get_output()
            .stdout
            .clone(),
    )
    .unwrap();
    assert!(
        out.contains("This mem does not exist in this workspace yet"),
        "the absence must be named:\n{out}",
    );
    assert!(
        !out.contains("memstead mem init"),
        "`mem init` refuses in a filesystem-mem workspace — the brief must not \
         name it here:\n{out}",
    );
    // The only assertion that matters: FOLLOW the remedy, verbatim, and the
    // brief's own mandate must then succeed. Two earlier versions of this
    // message were each defensible as prose and each left the reader stuck
    // — one naming a command that refuses in this shape, one naming a field
    // whose edit does not move the record, so every anchored write still
    // failed INVALID_ANCHOR.
    let remedy = out
        .lines()
        .find(|l| l.contains("does not exist in this workspace yet"))
        .expect("the remedy line");
    let commands: Vec<&str> = remedy
        .split('`')
        .skip(1)
        .step_by(2)
        .filter(|c| c.starts_with("rm ") || c.starts_with("memstead "))
        .collect();
    assert!(
        commands.len() >= 2,
        "the remedy must carry runnable commands, got {commands:?} from: {remedy}",
    );
    for command in &commands {
        let run = std::process::Command::new("sh")
            .arg("-c")
            .arg(command.replace("memstead ", &format!("{} ", memstead_bin().display())))
            .current_dir(&repo)
            .output()
            .expect("shell runs");
        assert!(
            run.status.success(),
            "the remedy's command must run: {command}\n{}",
            String::from_utf8_lossy(&run.stderr),
        );
    }

    // …and now the anchored write the brief mandates lands.
    memstead()
        .current_dir(&repo)
        .args([
            "create",
            "--type",
            "concept",
            "--title",
            "After Remedy",
            "--section",
            "definition=d",
            "--section",
            "explanation=e",
            "--anchor",
            r#"{"artifact":"src/a.rs","grain":"file","class":"anchored","source":"app"}"#,
        ])
        .assert()
        .success();
}

/// A source pointer that resolves to nothing on disk is named as such.
/// The brief tells the agent to read from it; an absent tree is
/// indistinguishable from an empty one unless the brief says so.
#[test]
fn brief_names_a_source_that_does_not_resolve() {
    let tmp = TempDir::new().unwrap();
    let repo = tmp.path().join("app2");
    std::fs::create_dir_all(repo.join("src")).unwrap();
    std::fs::write(repo.join("src/a.rs"), b"pub fn a() {}\n").unwrap();
    memstead()
        .current_dir(&repo)
        .args(["quickstart", "--repo", ".", "--agent", "claude-code"])
        .assert()
        .success();

    let record = repo.join(".memstead/projections/app2/app2.json");
    let mut binding: Value = serde_json::from_slice(&std::fs::read(&record).unwrap()).unwrap();
    binding["sources"][0]["pointer"] = Value::String("no-such-tree".into());
    std::fs::write(&record, serde_json::to_vec_pretty(&binding).unwrap()).unwrap();

    let out = String::from_utf8(
        memstead()
            .current_dir(&repo)
            .args(["projection", "brief", "app2/app2"])
            .assert()
            .success()
            .get_output()
            .stdout
            .clone(),
    )
    .unwrap();
    assert!(
        out.contains("`no-such-tree`") && out.contains("does not resolve to anything on disk"),
        "the brief must print the pointer and name its absence:\n{out}",
    );
}

/// The brief says a wrong `source` name "usually refuses" because the path
/// no longer joins — and that it is NOT refused when the path resolves
/// workspace-relative anyway. Both halves, so the sentence cannot drift
/// back into promising a gate that the legacy tolerance deliberately does
/// not provide.
#[test]
fn an_undeclared_anchor_source_refuses_on_the_path_but_is_tolerated_when_it_resolves() {
    let tmp = TempDir::new().unwrap();
    let repo = tmp.path().join("app3");
    std::fs::create_dir_all(repo.join("src")).unwrap();
    std::fs::write(repo.join("src/a.rs"), b"pub fn a() {}\n").unwrap();
    memstead()
        .current_dir(&repo)
        .args(["quickstart", "--repo", ".", "--agent", "claude-code"])
        .assert()
        .success();

    // Source-relative path + undeclared name: the join fails, so it refuses.
    let out = memstead()
        .current_dir(&repo)
        .args([
            "--json", "create", "--type", "concept", "--title", "Probe",
            "--section", "definition=d", "--section", "explanation=e",
            "--anchor",
            r#"{"artifact":"nowhere/a.rs","grain":"file","class":"anchored","source":"not-declared"}"#,
        ])
        .assert()
        .failure()
        .get_output()
        .stdout
        .clone();
    let env: Value = serde_json::from_slice(&out).expect("refusal must emit JSON");
    assert_eq!(env["code"], "INVALID_ANCHOR");

    // …but a path that resolves workspace-relative is written even with an
    // undeclared name. This is the documented legacy tolerance, not an
    // oversight — a brief that promised a refusal here would be wrong.
    memstead()
        .current_dir(&repo)
        .args([
            "create",
            "--type",
            "concept",
            "--title",
            "Tolerated",
            "--section",
            "definition=d",
            "--section",
            "explanation=e",
            "--anchor",
            r#"{"artifact":"src/a.rs","grain":"file","class":"anchored","source":"not-declared"}"#,
        ])
        .assert()
        .success();
}

/// A binding scaffolded before its mem exists still renders — `projection
/// init` deliberately allows that order — but the brief SAYS the destination
/// is not there and names the command that creates it. The agent's mandate is
/// to mutate that mem; discovering its absence on the first create means the
/// surface that sent it said something untrue.
///
/// Fixture needs `mem-repo init`, which the lean build does not carry.
#[cfg(feature = "mem-repo")]
#[test]
fn brief_names_a_destination_mem_that_does_not_exist_yet() {
    let tmp = TempDir::new().unwrap();
    let ws = tmp.path().join("ws");
    memstead()
        .args(["mem-repo", "init", ws.to_str().unwrap(), "--no-gitignore"])
        .assert()
        .success();
    memstead()
        .current_dir(&ws)
        .args([
            "projection",
            "init",
            "--mem",
            "absent-mem",
            "--source",
            "../src",
            "--medium-type",
            "codebase",
            "--name",
            "code",
        ])
        .assert()
        .success();

    let out = String::from_utf8(
        memstead()
            .current_dir(&ws)
            .args(["projection", "brief", "absent-mem/code"])
            .assert()
            .success()
            .get_output()
            .stdout
            .clone(),
    )
    .unwrap();
    assert!(
        out.contains("This mem does not exist in this workspace yet"),
        "the brief must name the absent destination:\n{out}",
    );
    assert!(
        !out.contains("<name@version>"),
        "the remedy must name a concrete pin, not a placeholder the reader has \
         to fetch vocabulary for:\n{out}",
    );

    // Follow the remedy verbatim — the sibling filesystem-shape test earned
    // this method three times over. Wording assertions passed while every
    // wrong version of this message shipped; running it is what caught them.
    let remedy = out
        .lines()
        .find(|l| l.contains("does not exist in this workspace yet"))
        .expect("the remedy line");
    let spans: Vec<&str> = remedy
        .split('`')
        .skip(1)
        .step_by(2)
        .filter(|c| c.starts_with("memstead "))
        .collect();
    // The sentence names the bare verb (`memstead mem init`) to say it
    // refuses on its own, then gives the full invocation. A mention that is a
    // proper prefix of an actual command is not a command — running it would
    // fail on missing arguments and prove nothing about the remedy.
    let commands: Vec<&str> = spans
        .iter()
        .copied()
        .filter(|c| {
            !spans
                .iter()
                .any(|o| o != c && o.starts_with(&format!("{c} ")))
        })
        .collect();
    assert!(
        !commands.is_empty(),
        "the remedy must carry runnable commands, got {spans:?} from: {remedy}",
    );
    for command in &commands {
        let run = std::process::Command::new("sh")
            .arg("-c")
            .arg(command.replace("memstead ", &format!("{} ", memstead_bin().display())))
            .current_dir(&ws)
            .output()
            .expect("shell runs");
        assert!(
            run.status.success(),
            "the remedy's command must run: {command}\n{}",
            String::from_utf8_lossy(&run.stderr),
        );
    }

    // …and the mem the brief said was missing is now there, described as
    // present by the same block that reported it absent.
    let after = String::from_utf8(
        memstead()
            .current_dir(&ws)
            .args(["projection", "brief", "absent-mem/code"])
            .assert()
            .success()
            .get_output()
            .stdout
            .clone(),
    )
    .unwrap();
    assert!(
        !after.contains("This mem does not exist in this workspace yet"),
        "after the remedy the destination must be present:\n{after}",
    );
    assert!(
        after.contains("absent-mem") && after.contains("schema:"),
        "the Destination block must describe the created mem:\n{after}",
    );
}

/// A refusal names `projection enable <op>` as the remedy. Over a medium
/// whose capability row cannot carry the operation, that remedy refuses too
/// — so the reader is bounced from run-time refusal to enable to capability
/// gap with nothing they can do. The gap must be the answer at the first
/// refusal, and the remedy must survive where it IS honest. Both halves, run.
#[test]
fn absent_sync_names_the_enable_remedy_only_where_the_medium_can_carry_it() {
    let tmp = TempDir::new().unwrap();

    // (a) a web source: sync is out of scope, so no remedy may be offered.
    let web = tmp.path().join("web-ws");
    std::fs::create_dir_all(&web).unwrap();
    memstead()
        .current_dir(&web)
        .args(["quickstart", "--name", "web-check"])
        .assert()
        .success();
    memstead()
        .current_dir(&web)
        .args([
            "projection",
            "init",
            "--mem",
            "web-check",
            "--source",
            "https://example.com/docs",
            "--medium-type",
            "web",
        ])
        .assert()
        .success();
    let out = memstead()
        .current_dir(&web)
        .args(["--json", "projection", "brief", "web-check/docs", "--sync"])
        .assert()
        .failure()
        .get_output()
        .stdout
        .clone();
    let env: Value = serde_json::from_slice(&out).expect("refusal must emit JSON");
    assert_eq!(env["code"], "PROJECTION_CAPABILITY_UNSUPPORTED");
    let message = env["message"].as_str().unwrap_or_default();
    assert!(
        !message.contains("projection enable"),
        "a remedy that would itself refuse must not be offered:\n{message}",
    );
    assert!(
        message.contains("cannot carry one"),
        "the capability gap must be named:\n{message}",
    );

    // (b) a codebase source with its sync block stripped: the remedy is real,
    // and running it verbatim makes the same brief render.
    let repo = tmp.path().join("code-ws");
    std::fs::create_dir_all(repo.join("src")).unwrap();
    std::fs::write(repo.join("src/a.rs"), b"pub fn a() {}\n").unwrap();
    memstead()
        .current_dir(&repo)
        .args(["quickstart", "--repo", ".", "--agent", "claude-code"])
        .assert()
        .success();
    let record = repo.join(".memstead/projections/code-ws/code-ws.json");
    let mut binding: Value = serde_json::from_slice(&std::fs::read(&record).unwrap()).unwrap();
    binding["operations"]
        .as_object_mut()
        .unwrap()
        .remove("sync");
    std::fs::write(&record, serde_json::to_vec_pretty(&binding).unwrap()).unwrap();

    let out = memstead()
        .current_dir(&repo)
        .args(["--json", "projection", "brief", "code-ws/code-ws", "--sync"])
        .assert()
        .failure()
        .get_output()
        .stdout
        .clone();
    let env: Value = serde_json::from_slice(&out).expect("refusal must emit JSON");
    assert_eq!(env["code"], "PROJECTION_SYNC_NOT_ENABLED");
    let remedy = env["details"]["remedy"]["cli"]
        .as_str()
        .expect("the remedy command")
        .to_string();
    let run = std::process::Command::new("sh")
        .arg("-c")
        .arg(remedy.replace("memstead ", &format!("{} ", memstead_bin().display())))
        .current_dir(&repo)
        .output()
        .expect("shell runs");
    assert!(
        run.status.success(),
        "the remedy must run: {remedy}\n{}",
        String::from_utf8_lossy(&run.stderr),
    );
    memstead()
        .current_dir(&repo)
        .args(["projection", "brief", "code-ws/code-ws", "--sync"])
        .assert()
        .success();
}

// ── AC4: absent-operation-block refusal + `projection enable` remedy ─────────

/// D6/AC4: `projection brief` on a binding with **no build block** refuses with
/// the `projection enable build <binding>` remedy, and that command — run
/// verbatim — makes the same brief succeed.
#[test]
fn brief_refuses_absent_build_then_enable_build_remedy_succeeds() {
    let tmp = advance_workspace();
    let root = tmp.path();
    // Strip the build block — a verify-only binding (verify has no mutating
    // operation to gate, so an absent block is never a refusal and this is a
    // legal build-less shape).
    write_store(
        root,
        "projections/engine/graph.json",
        r#"{"version":2,"intent":"model the engine","sources":[{"name":"source-tree","type":"codebase","pointer":"src","change_detection":"git","scope":[{"path":"src/**/*.rs","mode":"allow"}]}],"reference_mems":[],"destination_mem":"engine","deny_paths":[],"coverage_semantics":"exhaustive","operations":{"verify":{"trigger":"manual","batch_size":20}}}"#,
    );

    // brief refuses with the one-command remedy.
    let out = memstead()
        .current_dir(root)
        .args(["--json", "projection", "brief", "engine/graph"])
        .assert()
        .failure()
        .get_output()
        .stdout
        .clone();
    let env: Value = serde_json::from_slice(&out).expect("brief refusal must emit JSON");
    assert_eq!(env["code"], "PROJECTION_BUILD_NOT_ENABLED");
    assert!(
        env["message"]
            .as_str()
            .unwrap_or("")
            .contains("memstead projection enable build engine/graph"),
        "message must carry the verbatim remedy: {env}",
    );

    // The cited command, run verbatim, enables build.
    memstead()
        .current_dir(root)
        .args(["projection", "enable", "build", "engine/graph"])
        .assert()
        .success();

    // The same brief now succeeds.
    memstead()
        .current_dir(root)
        .args(["projection", "brief", "engine/graph"])
        .assert()
        .success();
}

/// D6/AC4: `projection advance` on a binding with **no sync block** refuses with
/// the `projection enable sync <binding>` remedy, and that command — run
/// verbatim — makes the same advance succeed.
#[test]
fn advance_refuses_absent_sync_then_enable_sync_remedy_succeeds() {
    let tmp = advance_workspace();
    let root = tmp.path();
    // Strip the sync block so the advance (sync) path has none to run.
    write_store(
        root,
        "projections/engine/graph.json",
        r#"{"version":2,"intent":"model the engine","sources":[{"name":"source-tree","type":"codebase","pointer":"src","change_detection":"git","scope":[{"path":"src/**/*.rs","mode":"allow"}]}],"reference_mems":[],"destination_mem":"engine","deny_paths":[],"coverage_semantics":"exhaustive","operations":{"build":{"mode":"discovery","trigger":"loop","batch_size":20}}}"#,
    );
    assert!(read_binding(root).operations.sync.is_none());

    // advance (the sync path) refuses with the one-command remedy.
    let out = memstead()
        .current_dir(root)
        .args([
            "--json",
            "projection",
            "advance",
            "engine/graph",
            "--dispositions",
            "{}",
        ])
        .assert()
        .failure()
        .get_output()
        .stdout
        .clone();
    let env: Value = serde_json::from_slice(&out).expect("advance refusal must emit JSON");
    assert_eq!(env["code"], "PROJECTION_SYNC_NOT_ENABLED");
    assert!(
        env["message"]
            .as_str()
            .unwrap_or("")
            .contains("memstead projection enable sync engine/graph"),
        "message must carry the verbatim remedy: {env}",
    );

    // The cited command, run verbatim, enables sync.
    memstead()
        .current_dir(root)
        .args(["projection", "enable", "sync", "engine/graph"])
        .assert()
        .success();

    // The same advance now succeeds (empty dispositions re-present the slice).
    memstead()
        .current_dir(root)
        .args([
            "projection",
            "advance",
            "engine/graph",
            "--dispositions",
            "{}",
        ])
        .assert()
        .success();
}

/// Verify-path resolution succeeds with **no verify block** (defaults, never a
/// refusal): a build-only binding renders its brief clean.
#[test]
fn brief_succeeds_with_no_verify_block() {
    let tmp = advance_workspace();
    // The migrated binding is build-only (no verify). Its brief renders.
    memstead()
        .current_dir(tmp.path())
        .args(["projection", "brief", "engine/graph"])
        .assert()
        .success();
}

// ── AC12: `projection migrate` consumes reconcile-cursors.json (D10) ─────────

/// D10/AC12: `projection migrate` seeds the destination binding's `#synced`
/// token from a `reconcile-cursors.json` entry whose absolute-keyed path
/// resolves to the binding's medium pointer, then deletes the cursor file.
#[test]
fn migrate_consumes_reconcile_cursors_seeds_synced_and_deletes_it() {
    let tmp = TempDir::new().unwrap();
    let root = tmp.path();

    // Workspace adapter + a folder-mounted `engine` mem (so set_mem_sync_state
    // has a writable mem with a loaded config).
    write_store(
        root,
        "workspace.toml",
        "format = \"memstead-git-branch-2\"\n\n[persistence_adapter]\nname = \"file-two-layer\"\n",
    );
    write_store(
        root,
        "state/mounts.json",
        r#"{"format":"memstead-mounts-3","mounts":[{"mem":"engine","schema":"default@1.0.0","storage":{"type":"folder","path":"engine-mem"},"capability":"write","lifecycle":"eager","cross_linkable":false}]}"#,
    );
    let mem_meta = root.join("engine-mem").join(".memstead");
    std::fs::create_dir_all(&mem_meta).unwrap();
    std::fs::write(
        mem_meta.join("config.json"),
        br#"{"format":1,"schema":"default@1.0.0"}"#,
    )
    .unwrap();

    // A real source dir the medium pointer resolves to.
    let src = root.join("src");
    std::fs::create_dir_all(&src).unwrap();
    std::fs::write(src.join("a.rs"), "x").unwrap();

    // Gen-2 store: medium (codebase → `src`), facet, projection, flat ingest.
    write_store(
        root,
        "mediums/engine/src.json",
        r#"{"name":"src","type":"codebase","pointer":"src"}"#,
    );
    write_store(
        root,
        "facets/engine/source-tree.json",
        r#"{"name":"source-tree","medium":"src","scope":[{"path":"src/**/*.rs","mode":"allow"}]}"#,
    );
    write_store(
        root,
        "projections/engine/graph.json",
        r#"{"intent":"engine graph","source_facets":["source-tree"],"reference_mems":[],"destination_mem":"engine"}"#,
    );
    write_store(
        root,
        "ingests/engine-graph.json",
        r#"{"projection":"engine/graph","mode":"discovery","trigger":"loop","batch_size":20}"#,
    );

    // A skill-written reconcile-cursors.json keyed to `src`'s absolute path.
    let src_abs = std::fs::canonicalize(&src).unwrap();
    write_store(
        root,
        "reconcile-cursors.json",
        &format!(r#"{{"engine:{}":"cafebabe0000"}}"#, src_abs.display()),
    );

    // Migrate.
    memstead()
        .current_dir(root)
        .args(["projection", "migrate"])
        .assert()
        .success();

    // The `#synced` baseline was seeded from the cursor's sha, on the mem config.
    let cfg: Value =
        serde_json::from_slice(&std::fs::read(mem_meta.join("config.json")).unwrap()).unwrap();
    assert_eq!(
        cfg["syncState"]["engine/graph/source-tree#synced"], "cafebabe0000",
        "migrate seeded #synced from the absolute-keyed cursor sha: {cfg}",
    );

    // The cursor file was consumed (deleted).
    assert!(
        !root.join(".memstead/reconcile-cursors.json").exists(),
        "reconcile-cursors.json must be deleted by the migration",
    );
}

/// A cursorless migrate leaves the binding never-synced and writes no baseline.
#[test]
fn migrate_without_cursor_leaves_never_synced() {
    let tmp = migrated_build_only_workspace();
    let root = tmp.path();
    // No reconcile-cursors.json existed → no #synced token anywhere. The
    // migrate succeeded (asserted by the helper) and left no cursor artifact.
    assert!(!root.join(".memstead/reconcile-cursors.json").exists());
}

// ── `brief --all --operation` (operation-aware rotation) ────────────────────

/// A mem-repo workspace with one scaffolded binding `ws/code` over a real
/// sibling `src/` dir (init defaults: build `trigger: loop`, sync + verify
/// `trigger: manual`). Returns the TempDir and the workspace path.
#[cfg(feature = "mem-repo")]
fn operation_workspace() -> (TempDir, std::path::PathBuf) {
    let tmp = TempDir::new().unwrap();
    let src = tmp.path().join("src");
    std::fs::create_dir_all(&src).unwrap();
    std::fs::write(src.join("a.rs"), "x").unwrap();
    let ws = tmp.path().join("ws");
    memstead()
        .args(["mem-repo", "init", ws.to_str().unwrap(), "--no-gitignore"])
        .assert()
        .success();
    memstead()
        .current_dir(&ws)
        .args([
            "projection",
            "init",
            "--mem",
            "ws",
            "--source",
            "../src",
            "--medium-type",
            "codebase",
            "--name",
            "code",
        ])
        .assert()
        .success();
    (tmp, ws)
}

/// Rewrite one operation block's `trigger` on the scaffolded `ws/code` binding.
#[cfg(feature = "mem-repo")]
fn set_trigger(ws: &Path, op: &str, trigger: &str) {
    let path = ws.join(".memstead/projections/ws/code.json");
    let mut v: Value = serde_json::from_slice(&std::fs::read(&path).unwrap()).unwrap();
    v["operations"][op]["trigger"] = Value::String(trigger.to_string());
    std::fs::write(&path, serde_json::to_vec(&v).unwrap()).unwrap();
}

/// `brief --all` without `--operation` keeps the classic build rotation
/// (back-compat for the ingest router) and the JSON output gains the additive
/// `operation` field next to `brief` — explicit `--operation build` behaves
/// identically.
#[cfg(feature = "mem-repo")]
#[test]
fn brief_all_defaults_to_build_and_names_the_operation() {
    let (_tmp, ws) = operation_workspace();

    let out = memstead()
        .current_dir(&ws)
        .args(["--json", "projection", "brief", "--all"])
        .assert()
        .success()
        .get_output()
        .stdout
        .clone();
    let env: Value = serde_json::from_slice(&out).unwrap();
    assert_eq!(env["operation"], "build", "additive operation field: {env}");
    let brief = env["brief"].as_str().expect("brief must stay a string");
    assert!(
        brief.contains("## Situation"),
        "default rotation renders the build brief; got:\n{brief}"
    );

    // Explicit `--operation build` — same rotation, same brief shape.
    let out = memstead()
        .current_dir(&ws)
        .args([
            "--json",
            "projection",
            "brief",
            "--all",
            "--operation",
            "build",
        ])
        .assert()
        .success()
        .get_output()
        .stdout
        .clone();
    let env: Value = serde_json::from_slice(&out).unwrap();
    assert_eq!(env["operation"], "build");
    assert!(env["brief"].as_str().unwrap().contains("## Situation"));
}

/// `--operation any` honours the per-operation eligibility gate (`trigger:
/// loop` in the declaration): with build flipped to manual and verify to loop,
/// the rotation selects the verify pair and dispatches to the verify renderer,
/// naming the operation in the JSON output.
#[cfg(feature = "mem-repo")]
#[test]
fn brief_all_any_dispatches_to_the_loop_declared_operation() {
    let (_tmp, ws) = operation_workspace();
    set_trigger(&ws, "build", "manual");
    set_trigger(&ws, "verify", "loop");

    let out = memstead()
        .current_dir(&ws)
        .args([
            "--json",
            "projection",
            "brief",
            "--all",
            "--operation",
            "any",
        ])
        .assert()
        .success()
        .get_output()
        .stdout
        .clone();
    let env: Value = serde_json::from_slice(&out).unwrap();
    assert_eq!(
        env["operation"], "verify",
        "manual build is ineligible; loop verify is due (never verified): {env}"
    );
    assert!(
        env["brief"]
            .as_str()
            .unwrap()
            .contains("## Verify — measure fidelity, do not mutate"),
        "the verify renderer produced the brief: {env}"
    );
}

/// A loop-declared sync pair with an unmoved source and no open findings is
/// not due — the rotation yields the quiet `skipped` outcome, not a brief.
#[cfg(feature = "mem-repo")]
#[test]
fn brief_all_sync_yields_quietly_when_nothing_due() {
    let (_tmp, ws) = operation_workspace();
    set_trigger(&ws, "sync", "loop");

    let out = memstead()
        .current_dir(&ws)
        .args([
            "--json",
            "projection",
            "brief",
            "--all",
            "--operation",
            "sync",
        ])
        .assert()
        .success()
        .get_output()
        .stdout
        .clone();
    let env: Value = serde_json::from_slice(&out).unwrap();
    assert_eq!(
        env["skipped"],
        Value::Bool(true),
        "never-synced + no findings → sync is not due: {env}"
    );
}

/// `--operation` binds to the `--all` rotation: without `--all` it is a usage
/// error, and it conflicts with the single-binding `--sync` / `--verify` modes.
#[cfg(feature = "mem-repo")]
#[test]
fn brief_operation_flag_requires_all_and_conflicts_with_group_c() {
    let (_tmp, ws) = operation_workspace();

    // Named binding + --operation, no --all → clap usage error.
    memstead()
        .current_dir(&ws)
        .args(["projection", "brief", "ws/code", "--operation", "any"])
        .assert()
        .failure();

    // --operation conflicts with --sync / --verify.
    for flag in ["--sync", "--verify"] {
        memstead()
            .current_dir(&ws)
            .args(["projection", "brief", "--all", "--operation", "any", flag])
            .assert()
            .failure();
    }
}

/// A plain `--all` render is a pure read: it mints no scheduler state and
/// repeats byte-identically; `--consume` is the act that takes the rotation
/// slot. The JSON envelope also discloses the (binding, op) pairs the filter
/// admits but the bindings never loop-declare (`not_rotated`).
#[cfg(feature = "mem-repo")]
#[test]
fn brief_all_is_pure_without_consume_and_advances_with_it() {
    let (tmp, ws) = operation_workspace();
    // A second build-loop binding so the rotation has two pairs to move
    // between: `ws/code#build` < `ws/code2#build`.
    let src2 = tmp.path().join("src2");
    std::fs::create_dir_all(&src2).unwrap();
    std::fs::write(src2.join("b.rs"), "y").unwrap();
    memstead()
        .current_dir(&ws)
        .args([
            "projection",
            "init",
            "--mem",
            "ws",
            "--source",
            "../src2",
            "--medium-type",
            "codebase",
            "--name",
            "code2",
        ])
        .assert()
        .success();

    let cursor_path = ws.join(".memstead.cache/ingest/ingest-cursor.json");
    let render = |consume: bool| -> Value {
        let mut args = vec![
            "--json",
            "projection",
            "brief",
            "--all",
            "--operation",
            "any",
        ];
        if consume {
            args.push("--consume");
        }
        let out = memstead()
            .current_dir(&ws)
            .args(&args)
            .assert()
            .success()
            .get_output()
            .stdout
            .clone();
        serde_json::from_slice(&out).unwrap()
    };

    // Two peeks: a brief renders, but no scheduler state appears.
    for _ in 0..2 {
        let env = render(false);
        assert_eq!(env["operation"], "build", "peek renders a brief: {env}");
        assert!(
            !cursor_path.exists(),
            "a plain --all render must not mint the rotation cursor"
        );
        // Sync and verify stay manual on both bindings — the filter admits
        // them, the declarations don't, and the envelope says so.
        let not_rotated = env["not_rotated"].as_array().expect("not_rotated array");
        assert_eq!(not_rotated.len(), 4, "2 bindings x (sync, verify): {env}");
    }

    // Consume: the slot is taken, the cursor lands on the first pair.
    render(true);
    let cursor: Value = serde_json::from_slice(&std::fs::read(&cursor_path).unwrap()).unwrap();
    assert_eq!(cursor["last"], "ws/code#build");

    // A peek between consumes leaves the cursor untouched...
    let bytes_before = std::fs::read(&cursor_path).unwrap();
    render(false);
    assert_eq!(
        std::fs::read(&cursor_path).unwrap(),
        bytes_before,
        "peek left the cursor byte-identical"
    );

    // ...and the next consume advances to the pair the peek would have shown.
    render(true);
    let cursor: Value = serde_json::from_slice(&std::fs::read(&cursor_path).unwrap()).unwrap();
    assert_eq!(cursor["last"], "ws/code2#build");
}

/// `--consume` binds to the `--all` rotation: on a named-binding render it is
/// a usage error (a single-binding brief has no rotation slot to take).
#[cfg(feature = "mem-repo")]
#[test]
fn brief_consume_requires_all() {
    let (_tmp, ws) = operation_workspace();
    memstead()
        .current_dir(&ws)
        .args(["projection", "brief", "ws/code", "--consume"])
        .assert()
        .failure();
}

// ── verify: prepared-hash backfill + deterministic drift ─────────────────────

/// `advance_workspace` plus a verify operation on the binding and an anchors
/// sidecar carrying one HASH-LESS `anchored` anchor on `src/a.rs` — the
/// fixture for the verify command's backfill/adjudication legs.
fn verify_workspace() -> TempDir {
    let tmp = advance_workspace();
    let root = tmp.path();
    write_store(
        root,
        "projections/engine/graph.json",
        r#"{"version":2,"intent":"model the engine","sources":[{"name":"source-tree","type":"codebase","pointer":"src","change_detection":"git","scope":[{"path":"src/**/*.rs","mode":"allow"}]}],"reference_mems":[],"destination_mem":"engine","deny_paths":[],"coverage_semantics":"exhaustive","operations":{"build":{"mode":"discovery","trigger":"loop","batch_size":20},"sync":{"trigger":"manual","batch_size":20},"verify":{"trigger":"manual","batch_size":20,"adjudication_cap":50,"full_resync_every":20}}}"#,
    );
    std::fs::write(
        root.join("engine-mem").join(".memstead").join("anchors.json"),
        r#"{"version":1,"entities":{"engine--covers-a":[{"artifact":"src/a.rs","grain":"file","class":"anchored","hash_stability":"stable"}]}}"#,
    )
    .unwrap();
    tmp
}

/// End-to-end through the CLI (separate processes): the first `projection
/// verify` backfills the hash-less anchor's prepared-content hash into the
/// sidecar (`hash_backfilled: 1`); a re-run backfills nothing (idempotent);
/// after a source change a verify adjudicates `drifted` deterministically —
/// no queued deferral, no LLM leg.
#[test]
fn verify_backfills_hashless_anchor_then_adjudicates_drift() {
    let tmp = verify_workspace();
    let root = tmp.path();

    // (1) First verify: the hash-less anchored anchor gains its prepared hash.
    let out = memstead()
        .current_dir(root)
        .args(["--json", "projection", "verify", "engine/graph"])
        .assert()
        .success()
        .get_output()
        .stdout
        .clone();
    let env: Value = serde_json::from_slice(&out).unwrap();
    assert_eq!(
        env["hash_backfilled"], 1,
        "one hash-less anchor backfilled: {env}"
    );
    assert_eq!(env["backlog"], 0, "backfill queues nothing: {env}");
    let sidecar = std::fs::read_to_string(root.join("engine-mem/.memstead/anchors.json")).unwrap();
    assert!(
        sidecar.contains("\"hash\""),
        "the sidecar now records the prepared-content hash: {sidecar}"
    );

    // (2) Idempotent: a second verify observes an empty worklist.
    let out = memstead()
        .current_dir(root)
        .args(["--json", "projection", "verify", "engine/graph"])
        .assert()
        .success()
        .get_output()
        .stdout
        .clone();
    let env: Value = serde_json::from_slice(&out).unwrap();
    assert_eq!(env["hash_backfilled"], 0, "backfill happens once: {env}");
    assert_eq!(
        env["report"]["anchors"]["resolves"], 1,
        "the recorded hash matches the source — the anchor resolves: {env}"
    );

    // (3) The anchored artifact changes; verify adjudicates drift
    //     deterministically from the hash comparison alone.
    let src = root.join("src");
    std::fs::write(src.join("a.rs"), "one-drifted").unwrap();
    git(&src, &["add", "-A"]);
    git(&src, &["commit", "-qm", "drift"]);

    let out = memstead()
        .current_dir(root)
        .args(["--json", "projection", "verify", "engine/graph"])
        .assert()
        .success()
        .get_output()
        .stdout
        .clone();
    let env: Value = serde_json::from_slice(&out).unwrap();
    assert_eq!(
        env["hash_backfilled"], 0,
        "a recorded hash is never overwritten: {env}"
    );
    assert_eq!(
        env["report"]["anchors"]["drifted"], 1,
        "stable-medium hash mismatch → deterministic drifted: {env}"
    );
    assert_eq!(
        env["report"]["findings_by_class"]["drifted"], 1,
        "the drift lands as a durable finding: {env}"
    );
    assert_eq!(
        env["backlog"], 0,
        "nothing queued — the hash leg needs no sampling: {env}"
    );
}

/// `projection verify --full` measures completely: the JSON decision is
/// `forced` (full-enumeration walk, scheduler bypassed, cap unlimited), the
/// criterion-level backfill still happens, nothing queues, and the rendered
/// report states the full measurement with no sampling caveat. Without the
/// flag, the sampled behavior over the same workspace is what it was.
#[test]
fn verify_full_walks_everything_and_reports_forced() {
    let tmp = verify_workspace();
    let root = tmp.path();

    let out = memstead()
        .current_dir(root)
        .args(["--json", "projection", "verify", "engine/graph", "--full"])
        .assert()
        .success()
        .get_output()
        .stdout
        .clone();
    let env: Value = serde_json::from_slice(&out).unwrap();
    assert_eq!(
        env["full_resync"]["state"], "forced",
        "an explicit full measurement reports the forced walk: {env}"
    );
    assert_eq!(
        env["hash_backfilled"], 1,
        "--full includes the prepared-hash backfill: {env}"
    );
    assert_eq!(env["backlog"], 0, "cap unlimited — nothing queued: {env}");

    // Human-readable mode states the full measurement up front.
    let out = memstead()
        .current_dir(root)
        .args(["projection", "verify", "engine/graph", "--full"])
        .assert()
        .success()
        .get_output()
        .stdout
        .clone();
    let text = String::from_utf8(out).unwrap();
    assert!(
        text.contains("Full measurement (`--full`)"),
        "the rendered report leads with the full-measurement statement: {text}"
    );
    assert!(
        text.contains("not sampled"),
        "no sampling caveat — the figures are stated as computed: {text}"
    );

    // A no-flag run over the same workspace still succeeds on the sampled
    // path (byte-compatible economics; the scheduled decision, not forced).
    let out = memstead()
        .current_dir(root)
        .args(["--json", "projection", "verify", "engine/graph"])
        .assert()
        .success()
        .get_output()
        .stdout
        .clone();
    let env: Value = serde_json::from_slice(&out).unwrap();
    assert_ne!(
        env["full_resync"]["state"], "forced",
        "a no-flag run never reports a forced walk: {env}"
    );
}

/// REFUSAL — `verify --full` over a non-enumerable (web) medium refuses with
/// the existing typed capability error, exit-coded as validation, and renders
/// no report: a fabricated-complete report is never an answer.
#[test]
fn verify_full_refuses_non_enumerable_medium() {
    let tmp = verify_workspace();
    let root = tmp.path();
    write_store(
        root,
        "projections/engine/manual.json",
        r#"{"version":2,"intent":"the manual","sources":[{"name":"manual","type":"web","pointer":"https://example.com/docs","scope":[]}],"reference_mems":[],"destination_mem":"engine","deny_paths":[],"coverage_semantics":"curated","operations":{"verify":{"trigger":"manual","batch_size":20}}}"#,
    );

    let out = memstead()
        .current_dir(root)
        .args(["--json", "projection", "verify", "engine/manual", "--full"])
        .assert()
        .failure()
        .get_output()
        .stdout
        .clone();
    let env: Value = serde_json::from_slice(&out).unwrap();
    assert_eq!(
        env["code"], "PROJECTION_CAPABILITY_UNSUPPORTED",
        "the existing typed capability error: {env}"
    );
    assert_eq!(env["details"]["medium_type"], "web");
    assert!(
        env["message"]
            .as_str()
            .unwrap_or("")
            .contains("non-enumerable"),
        "the refusal states why: {env}"
    );
}

// ---------------------------------------------------------------------------
// CI gate — `projection verify --fail-on-findings`
// ---------------------------------------------------------------------------

/// The three-outcome contract, all three demonstrated against the same
/// fixture so the codes are provably pairwise distinct: a completed clean run
/// exits 0, a completed run with a seeded drift exits **6**, and an
/// operational failure keeps its own typed code (3, not found). The whole
/// point of a dedicated findings code is that a CI job can tell "the mem
/// drifted" from "the engine could not run" — that distinction is what these
/// assertions pin.
#[test]
fn gate_exits_zero_clean_six_on_findings_and_typed_code_on_error() {
    let tmp = verify_workspace();
    let root = tmp.path();

    // (1) Clean fixture in gate mode → 0. (Runs once ungated first so the
    //     hash backfill has landed and the anchor adjudicates deterministically.)
    memstead()
        .current_dir(root)
        .args(["--json", "projection", "verify", "engine/graph"])
        .assert()
        .success();
    let out = memstead()
        .current_dir(root)
        .args([
            "--json",
            "projection",
            "verify",
            "engine/graph",
            "--fail-on-findings",
        ])
        .assert()
        .success()
        .get_output()
        .stdout
        .clone();
    let env: Value = serde_json::from_slice(&out).unwrap();
    assert_eq!(
        env["rollup"]["findings_total"], 0,
        "the fixture is clean before the drift is seeded: {env}"
    );
    assert_eq!(
        env["rollup"]["verdict"], "clean",
        "a substantive pass with no findings is clean: {env}"
    );

    // (2) Seed a drift in the anchored artifact → the dedicated findings code.
    let src = root.join("src");
    std::fs::write(src.join("a.rs"), "one-drifted").unwrap();
    git(&src, &["add", "-A"]);
    git(&src, &["commit", "-qm", "drift"]);

    let assertion = memstead()
        .current_dir(root)
        .args([
            "--json",
            "projection",
            "verify",
            "engine/graph",
            "--fail-on-findings",
        ])
        .assert()
        .code(6);
    let stdout = assertion.get_output().stdout.clone();
    let text = String::from_utf8_lossy(&stdout);

    // (3) An operational failure over the same workspace keeps its own code,
    //     and it is not 6 — that is the distinction the gate exists to draw.
    memstead()
        .current_dir(root)
        .args([
            "--json",
            "projection",
            "verify",
            "engine/nonexistent",
            "--fail-on-findings",
        ])
        .assert()
        .code(3);

    // Criterion 2: the report is emitted before the findings exit fires. In
    // `--json` mode stdout carries both the report envelope and the typed
    // error envelope, so a pipeline consumer can read either.
    assert!(
        text.contains("memstead-verify/v1"),
        "the report envelope lands before the gate fails: {text}"
    );
    assert!(
        text.contains("PROJECTION_VERIFY_FINDINGS"),
        "the typed error envelope still reaches stdout: {text}"
    );
}

/// An unreadable anchors sidecar is an operational failure, not findings.
///
/// The regression this pins was live: the anchor readers degrade a malformed
/// sidecar to "no anchors", so a fidelity pass read every artifact as
/// uncovered, recorded that as findings, and exited 6 — a red CI build
/// blaming the mem for a file the engine could not parse, with nothing on
/// stderr. The distinction the whole exit-code contract rests on is that 6
/// means the measurement SUCCEEDED; one made over an unreadable input did not.
#[test]
fn an_unreadable_anchors_sidecar_refuses_and_never_returns_the_findings_code() {
    let tmp = verify_workspace();
    let root = tmp.path();
    std::fs::write(root.join("engine-mem/.memstead/anchors.json"), "{ broken").unwrap();
    // Three ways to be unreadable, and the first fix caught only this one.
    // A grade found the other two still producing a confident "every
    // artifact uncovered" and exit 6, so they are pinned here beside it.

    let assertion = memstead()
        .current_dir(root)
        .args([
            "--json",
            "projection",
            "verify",
            "engine/graph",
            "--fail-on-findings",
        ])
        .assert()
        .code(5);
    let out = String::from_utf8(assertion.get_output().stdout.clone()).unwrap();
    let env: Value = serde_json::from_str(&out).unwrap();
    assert_eq!(env["code"], "ANCHORS_SIDECAR_UNREADABLE", "{env}");
    assert_eq!(env["details"]["mem"], "engine", "{env}");

    // Ungated too: the refusal is about the measurement being untrustworthy,
    // not about the gate flag.
    memstead()
        .current_dir(root)
        .args(["--json", "projection", "verify", "engine/graph"])
        .assert()
        .code(5);

    // An EMPTY sidecar. `AnchorSidecar::from_bytes` tolerates whitespace-only
    // bytes as "no anchors" — right for a reader, wrong here: an interrupted
    // write leaves exactly this state, and it is not a mem that never had
    // anchors.
    std::fs::write(root.join("engine-mem/.memstead/anchors.json"), "   \n").unwrap();
    memstead()
        .current_dir(root)
        .args([
            "--json",
            "projection",
            "verify",
            "engine/graph",
            "--fail-on-findings",
        ])
        .assert()
        .code(5);
}

/// A source directory that exists but cannot be entered refuses, rather than
/// enumerating nothing and calling the result drift.
///
/// The guard used to test existence alone, so an unreadable tree walked past
/// it: the pass enumerated zero artifacts, every anchor came back
/// unresolvable, and the verdict blamed a mem that had not moved — with the
/// report's own denominator saying `non-enumerable` two screens down.
#[cfg(unix)]
#[test]
fn an_unreadable_source_directory_refuses_rather_than_reporting_drift() {
    use std::os::unix::fs::PermissionsExt;

    let tmp = verify_workspace();
    let root = tmp.path();
    let src = root.join("src");
    let restore = std::fs::metadata(&src).unwrap().permissions();
    std::fs::set_permissions(&src, std::fs::Permissions::from_mode(0o000)).unwrap();

    let assertion = memstead()
        .current_dir(root)
        .args([
            "--json",
            "projection",
            "verify",
            "engine/graph",
            "--fail-on-findings",
        ])
        .assert()
        .code(5);
    let out = String::from_utf8(assertion.get_output().stdout.clone()).unwrap();
    let env: Value = serde_json::from_str(&out).unwrap();
    assert_eq!(env["code"], "SOURCE_UNREACHABLE", "{env}");

    std::fs::set_permissions(&src, restore).unwrap();
}

/// A binding declaring `change_detection: "git"` over a tree with no `.git`
/// cannot support a green verdict.
///
/// This is the CI shape the guide's `fetch-depth: 0` advice circles: a
/// `git archive`, a Docker `COPY`, a vendored drop. The declaration used to
/// be honoured without probing, so the capability row asserted a signal that
/// could not be read and the rollup called the pass "substantive on every
/// axis" while `source_head` was empty and no baseline was written.
#[test]
fn a_declared_git_binding_without_a_git_root_cannot_verdict_clean() {
    let tmp = verify_workspace();
    let root = tmp.path();
    std::fs::remove_dir_all(root.join("src/.git")).unwrap();

    let out = memstead()
        .current_dir(root)
        .args(["--json", "projection", "verify", "engine/graph"])
        .assert()
        .success()
        .get_output()
        .stdout
        .clone();
    let env: Value = serde_json::from_slice(&out).unwrap();
    assert_eq!(
        env["rollup"]["verdict"], "inconclusive",
        "a git binding with no git root is not a clean bill of health: {env}"
    );
    assert!(
        !env["rollup"]["blind_spots"].as_array().unwrap().is_empty(),
        "the blindness is named: {env}"
    );
}

/// The gate is opt-in: a bare `projection verify` over a drifted fixture
/// exits 0 exactly as it always has. This is the compatibility promise — a
/// silent default flip would break every existing consumer, including this
/// project's own loops.
#[test]
fn gate_is_opt_in_bare_verify_still_exits_zero_with_findings() {
    let tmp = verify_workspace();
    let root = tmp.path();

    memstead()
        .current_dir(root)
        .args(["--json", "projection", "verify", "engine/graph"])
        .assert()
        .success();

    let src = root.join("src");
    std::fs::write(src.join("a.rs"), "one-drifted").unwrap();
    git(&src, &["add", "-A"]);
    git(&src, &["commit", "-qm", "drift"]);

    let out = memstead()
        .current_dir(root)
        .args(["--json", "projection", "verify", "engine/graph"])
        .assert()
        .success()
        .get_output()
        .stdout
        .clone();
    let env: Value = serde_json::from_slice(&out).unwrap();
    assert_eq!(
        env["report"]["findings_by_class"]["drifted"], 1,
        "the drift IS present — the ungated run simply does not gate on it: {env}"
    );
    assert_eq!(
        env["rollup"]["verdict"], "drifted",
        "the verdict reports the drift even ungated: {env}"
    );
}

/// The human report opens with the rollup verdict and the concrete actions —
/// making the fidelity-contract page's long-standing claim true.
#[test]
fn human_report_opens_with_verdict_and_actions() {
    let tmp = verify_workspace();
    let root = tmp.path();

    memstead()
        .current_dir(root)
        .args(["--json", "projection", "verify", "engine/graph"])
        .assert()
        .success();

    let src = root.join("src");
    std::fs::write(src.join("a.rs"), "one-drifted").unwrap();
    git(&src, &["add", "-A"]);
    git(&src, &["commit", "-qm", "drift"]);

    let out = memstead()
        .current_dir(root)
        .args(["projection", "verify", "engine/graph"])
        .assert()
        .success()
        .get_output()
        .stdout
        .clone();
    let text = String::from_utf8_lossy(&out);
    let verdict_at = text.find("**Verdict: DRIFTED**").unwrap_or_else(|| {
        panic!("the report opens with the rollup verdict: {text}");
    });
    let provenance_at = text
        .find("Coverage semantics")
        .expect("the denominator-provenance block still renders");
    assert!(
        verdict_at < provenance_at,
        "the verdict comes BEFORE the provenance a reader used to open on: {text}"
    );
    assert!(
        text.contains("**Do next:**"),
        "the rollup carries top concrete actions: {text}"
    );
}

/// The machine payload carries the pinned version marker, in the house style
/// the two existing external envelopes established. A consumer asserts this
/// before parsing, so a future shape change fails loudly.
#[test]
fn verify_json_carries_the_pinned_format_marker() {
    let tmp = verify_workspace();
    let root = tmp.path();

    let out = memstead()
        .current_dir(root)
        .args(["--json", "projection", "verify", "engine/graph"])
        .assert()
        .success()
        .get_output()
        .stdout
        .clone();
    let env: Value = serde_json::from_slice(&out).unwrap();
    assert_eq!(
        env["format"], "memstead-verify/v1",
        "the external contract is versioned: {env}"
    );
    assert!(
        env["rollup"]["verdict"].is_string(),
        "the rollup ships in the envelope, not only in the markdown: {env}"
    );
    assert!(
        env["report"]["findings_by_class"].is_object(),
        "the closed finding-class vocabulary still ships: {env}"
    );

    // Every field the guide names as contract, asserted by name. A grade
    // found six of these documented and pinned by nothing: a rename would
    // reshape the `v1` payload and falsify the guide while the marker kept
    // saying `memstead-verify/v1`, which is exactly the silent break the
    // marker exists to prevent. `is_null()` rather than a value check —
    // the point is that the key survives a refactor, not what it holds.
    for field in [
        "verdict",
        "findings_total",
        "because",
        "blind_spots",
        "actions",
    ] {
        assert!(
            !env["rollup"][field].is_null(),
            "rollup.{field} is documented as contract but missing: {env}"
        );
    }
    for facet in env["report"]["capabilities"].as_array().unwrap() {
        for field in [
            "facet",
            "medium_type",
            "enumerable",
            "change_signal",
            "base_version_retrievable",
            "anchor_namespace",
            "signal",
        ] {
            assert!(
                !facet[field].is_null(),
                "capabilities[].{field} is documented as contract but missing: {facet}"
            );
        }
    }
    for facet in env["report"]["freshness"].as_array().unwrap() {
        for field in ["facet", "signal", "change_detectable"] {
            assert!(
                !facet[field].is_null(),
                "freshness[].{field} is documented as contract but missing: {facet}"
            );
        }
        // `synced` and `verified` are legitimately null when never recorded,
        // so the !is_null idiom above cannot cover them — the KEY has to be
        // present. The guide documents both as contract; a rename would
        // falsify it while the marker still said `memstead-verify/v1`.
        for field in ["synced", "verified"] {
            assert!(
                facet.get(field).is_some(),
                "freshness[].{field} is documented as contract but the key is gone: {facet}"
            );
        }
    }
    // The denominator is INTERNALLY tagged on `kind`. Pinned because the
    // guide documents that exact shape as external contract, and serde's
    // default for an enum is externally tagged — dropping the
    // `#[serde(tag = "kind")]` attribute would silently reshape a payload
    // consumers branch on, while still passing an `is_object()` check.
    let denom = &env["report"]["coverage"]["denominator"];
    assert!(
        denom.is_object(),
        "the denominator union still ships: {env}"
    );
    assert_eq!(
        denom["kind"], "enumerated",
        "denominator is internally tagged on `kind`, as the guide documents: {env}"
    );
    assert!(
        denom["count"].is_number(),
        "an enumerated denominator carries its count alongside the tag: {env}"
    );
}

// ── graph-medium fidelity: a two-mem graph→graph binding, end to end ────────
//
// The S1b pilot drove a source change through a graph binding end-to-end and
// then watched a deliberately stale anchor over the changed entity go
// unflagged: anchor resolution 0/0, coverage 0/0, drift undetected, while the
// capability matrix claimed full parity. This fixture is that scenario,
// re-run through the CLI as separate processes — it cannot pass silently again.

/// A workspace with two folder mems: `srcmem` (the source graph) and `dest`
/// (the destination), bound by a graph-medium binding scoped to the whole
/// source mem. `dest` holds two entities anchored at source entities, both
/// hash-less so the first verify backfills them — the same shape the codebase
/// fixture uses, proving the backfill path is namespace-agnostic.
fn graph_binding_workspace() -> TempDir {
    let tmp = TempDir::new().unwrap();
    let root = tmp.path();

    write_store(
        root,
        "workspace.toml",
        "format = \"memstead-git-branch-2\"\n\n[persistence_adapter]\nname = \"file-two-layer\"\n",
    );
    write_store(
        root,
        "state/mounts.json",
        r#"{"format":"memstead-mounts-3","mounts":[
            {"mem":"srcmem","schema":"default@1.0.0","storage":{"type":"folder","path":"src-mem"},"capability":"write","lifecycle":"eager","cross_linkable":false},
            {"mem":"dest","schema":"default@1.0.0","storage":{"type":"folder","path":"dest-mem"},"capability":"write","lifecycle":"eager","cross_linkable":false}
        ]}"#,
    );

    // A graph source selects entities, so its scope is the entity vocabulary.
    // `deny_paths` stays empty — a glob deny is illegal over this namespace.
    write_store(
        root,
        "projections/dest/mirror.json",
        r#"{"version":2,"intent":"mirror srcmem into dest","sources":[{"name":"src-graph","type":"graph","pointer":"srcmem","scope":[{"path":"*","mode":"allow"}]}],"reference_mems":[],"destination_mem":"dest","deny_paths":[],"coverage_semantics":"exhaustive","prune":{"guarantee":"conflict-flag"},"operations":{"build":{"mode":"discovery","trigger":"loop","batch_size":20},"sync":{"trigger":"manual","batch_size":20},"verify":{"trigger":"manual","batch_size":20,"adjudication_cap":50,"full_resync_every":20}}}"#,
    );

    // `concept` with definition/explanation is a real `default@1.0.0` type with
    // its real required sections. An earlier draft wrote `type: decision`,
    // which that schema does not declare — the raw-markdown read path tolerates
    // it while `memstead create` refuses it, so the fixture would have been
    // passing on an asymmetry rather than on the behaviour under test.
    let entity = |dir: &Path, slug: &str, ty: &str, title: &str, body: &str| {
        std::fs::write(
            dir.join(format!("{slug}.md")),
            format!(
                "---\ntype: {ty}\n---\n\n# {title}\n\n## Definition\n\n{title} is a fixture concept.\n\n## Explanation\n\n{body}\n"
            ),
        )
        .unwrap();
    };

    // Source mem: three entities. `gamma` is deliberately unprojected — it must
    // surface as an uncovered member of S(D), which a 0/0 denominator could
    // never do.
    let src_mem = root.join("src-mem");
    std::fs::create_dir_all(src_mem.join(".memstead")).unwrap();
    std::fs::write(
        src_mem.join(".memstead").join("config.json"),
        r#"{"format":1,"schema":"default@1.0.0"}"#,
    )
    .unwrap();
    entity(&src_mem, "alpha", "concept", "Alpha", "Alpha body.");
    entity(&src_mem, "beta", "concept", "Beta", "Beta body.");
    entity(&src_mem, "gamma", "concept", "Gamma", "Gamma body.");

    // Destination mem: two entities, each anchored at a source ENTITY (not a
    // path), hash-less so the first verify backfills.
    let dest_mem = root.join("dest-mem");
    std::fs::create_dir_all(dest_mem.join(".memstead")).unwrap();
    std::fs::write(
        dest_mem.join(".memstead").join("config.json"),
        r#"{"format":1,"schema":"default@1.0.0"}"#,
    )
    .unwrap();
    entity(
        &dest_mem,
        "from-alpha",
        "decision",
        "From alpha",
        "Mirrors alpha.",
    );
    entity(
        &dest_mem,
        "from-beta",
        "decision",
        "From beta",
        "Mirrors beta.",
    );
    std::fs::write(
        dest_mem.join(".memstead").join("anchors.json"),
        r#"{"version":1,"entities":{
            "dest--from-alpha":[{"artifact":"srcmem--alpha","grain":"entity","class":"anchored","hash_stability":"stable"}],
            "dest--from-beta":[{"artifact":"srcmem--beta","grain":"entity","class":"anchored","hash_stability":"stable"}]
        }}"#,
    )
    .unwrap();

    tmp
}

/// Criterion 1 + 2, positively, through the CLI: a graph binding's verify
/// reports a REAL enumerated denominator (the source mem's in-scope entities),
/// surfaces the unprojected source entity as uncovered, backfills its entity
/// anchors, and — after one source entity changes — adjudicates that anchor
/// `drifted` while the untouched one still resolves.
#[test]
fn graph_binding_verify_enumerates_and_detects_entity_drift() {
    let tmp = graph_binding_workspace();
    let root = tmp.path();

    // (1) First verify: a real denominator, and the hash-less entity anchors
    //     gain their prepared hashes.
    let out = memstead()
        .current_dir(root)
        .args(["--json", "projection", "verify", "dest/mirror"])
        .assert()
        .success()
        .get_output()
        .stdout
        .clone();
    let env: Value = serde_json::from_slice(&out).unwrap();

    assert_eq!(
        env["report"]["coverage"]["denominator"]["kind"], "enumerated",
        "a graph source enumerates for real — not the 'no S(D) denominator' bail: {env}"
    );
    assert_eq!(
        env["report"]["coverage"]["denominator"]["count"], 3,
        "S(D) is the source mem's three in-scope entities: {env}"
    );
    assert_eq!(
        env["hash_backfilled"], 2,
        "both hash-less ENTITY anchors backfill, exactly as path anchors do: {env}"
    );

    // (2) Idempotent, and the unprojected source entity is a real gap.
    let out = memstead()
        .current_dir(root)
        .args(["--json", "projection", "verify", "dest/mirror"])
        .assert()
        .success()
        .get_output()
        .stdout
        .clone();
    let env: Value = serde_json::from_slice(&out).unwrap();
    assert_eq!(env["hash_backfilled"], 0, "backfill happens once: {env}");
    assert_eq!(
        env["report"]["anchors"]["resolves"], 2,
        "both entity anchors resolve against the live graph — not 'unobserved': {env}"
    );
    let body = serde_json::to_string(&env).unwrap();
    assert!(
        body.contains("srcmem--gamma"),
        "the unprojected source entity surfaces as an uncovered member of S(D): {env}"
    );

    // (3) The pilot's move: change ONE source entity. Its anchor must drift.
    std::fs::write(
        root.join("src-mem").join("alpha.md"),
        "---\ntype: decision\n---\n\n# Alpha\n\n## Decision\n\nAlpha body, rewritten.\n",
    )
    .unwrap();

    let out = memstead()
        .current_dir(root)
        .args(["--json", "projection", "verify", "dest/mirror"])
        .assert()
        .success()
        .get_output()
        .stdout
        .clone();
    let env: Value = serde_json::from_slice(&out).unwrap();
    assert_eq!(
        env["report"]["anchors"]["drifted"], 1,
        "the stale-pinned anchor over the CHANGED source entity is drifted — \
         this is the pilot failure that went unflagged: {env}"
    );
    assert_eq!(
        env["report"]["anchors"]["resolves"], 1,
        "the anchor over the untouched entity still resolves: {env}"
    );
}

/// Criterion 1's exclude clause: `projection exclude` gates on S(D)
/// membership, so a genuine entity of the source mem is accepted and a
/// non-member is refused. Before graph enumeration, S(D) was empty and the
/// gate refused *every* id — the command was unusable over a graph binding.
#[test]
fn graph_binding_exclude_accepts_a_real_source_entity() {
    let tmp = graph_binding_workspace();
    let root = tmp.path();

    memstead()
        .current_dir(root)
        .args([
            "--json",
            "projection",
            "exclude",
            "dest/mirror",
            "--exclusions",
            r#"{"srcmem--gamma": "out of scope for this mem"}"#,
        ])
        .assert()
        .success();

    // The complement: an id that is not in S(D) is still refused.
    memstead()
        .current_dir(root)
        .args([
            "--json",
            "projection",
            "exclude",
            "dest/mirror",
            "--exclusions",
            r#"{"srcmem--not-a-real-entity": "typo"}"#,
        ])
        .assert()
        .failure();
}

/// Criterion 2's complement, at its sharpest: an **unmounted source mem** must
/// refuse, not resolve as a mem full of deleted entities.
///
/// Every entity anchor into an absent mem misses the store and observes as
/// ABSENT — a definite `orphaned`, not an honest "unobserved". The pass would
/// report drift, instruct the reader to repoint or unset anchors that are
/// perfectly fine, and — because `orphaned` is the one state satisfying
/// prune's all-orphaned gate — let prune propose deleting the destination
/// entities. The path mediums have always refused a vanished source; the graph
/// medium needs the same refusal for a worse consequence.
#[test]
fn an_unmounted_graph_source_refuses_instead_of_reporting_deletions() {
    let tmp = graph_binding_workspace();
    let root = tmp.path();

    // Baseline: mounted, the anchors resolve.
    memstead()
        .current_dir(root)
        .args(["--json", "projection", "verify", "dest/mirror"])
        .assert()
        .success();

    // Now unmount the source mem, leaving the binding pointing at it.
    write_store(
        root,
        "state/mounts.json",
        r#"{"format":"memstead-mounts-3","mounts":[
            {"mem":"dest","schema":"default@1.0.0","storage":{"type":"folder","path":"dest-mem"},"capability":"write","lifecycle":"eager","cross_linkable":false}
        ]}"#,
    );

    let out = memstead()
        .current_dir(root)
        .args(["--json", "projection", "verify", "dest/mirror"])
        .assert()
        .failure()
        .get_output()
        .stdout
        .clone();
    let env: Value = serde_json::from_slice(&out).unwrap();
    assert_eq!(
        env["code"], "SOURCE_UNREACHABLE",
        "an absent source mem is a typed refusal, not a measurement: {env}"
    );
    let body = serde_json::to_string(&env).unwrap();
    assert!(
        !body.contains("orphaned"),
        "nothing is scored orphaned — an unmounted mem must never be \
         indistinguishable from a deleted one: {env}"
    );

    // The polarity that matters more, and that verify's refusal does not
    // cover: PRUNE reaches anchor resolution by its own path, so the sync
    // brief must not propose deleting entities whose source is merely
    // unmounted. An earlier fix guarded only `run_verify`, and this test
    // asserted only the block above — it passed while the brief went on
    // recommending the deletion of every destination entity.
    let brief = String::from_utf8(
        memstead()
            .current_dir(root)
            .args(["projection", "brief", "dest/mirror", "--sync"])
            .assert()
            .get_output()
            .stdout
            .clone(),
    )
    .unwrap();
    assert!(
        !brief.contains("artifact(s) gone"),
        "nothing is reported as gone from the source when the mem is merely \
         unmounted — a data-loss suggestion to the sole maintenance writer: {brief}"
    );
}

/// Criterion 5's complement, on the path that matters: a graph facet carrying
/// a scope pattern nothing interprets must be REFUSED WHEN IT RUNS, not only
/// when it is edited.
///
/// Scaffolding the right shape protects only bindings this engine wrote. Every
/// graph binding scaffolded before the entity vocabulary existed carries the
/// path glob `**/*`, and hand-editing the record is a route the CLI's own
/// name-collision refusal points people at. Left unguarded, such a binding ran
/// clean over an S(D) of zero and recorded a `#verified` baseline for a
/// measurement that never happened.
#[test]
fn a_graph_scope_nothing_interprets_is_refused_on_the_run_path() {
    let tmp = graph_binding_workspace();
    let root = tmp.path();

    // Hand-edit the binding to the pre-vocabulary path glob.
    let binding = root.join(".memstead/projections/dest/mirror.json");
    let text = std::fs::read_to_string(&binding).unwrap();
    std::fs::write(
        &binding,
        text.replace(
            r#"{"path":"*","mode":"allow"}"#,
            r#"{"path":"**/*","mode":"allow"}"#,
        ),
    )
    .unwrap();

    // Every run path refuses — not just the edit paths that call
    // `validate_binding`. Verify is the one that used to record a `#verified`
    // baseline over an empty walk.
    for args in [
        vec!["--json", "projection", "verify", "dest/mirror"],
        vec!["--json", "projection", "brief", "dest/mirror"],
    ] {
        let out = memstead()
            .current_dir(root)
            .args(&args)
            .assert()
            .failure()
            .get_output()
            .stdout
            .clone();
        let env: Value = serde_json::from_slice(&out).unwrap();
        assert_eq!(
            env["code"], "PROJECTION_SCOPE_UNINTERPRETABLE",
            "`{args:?}` must refuse a scope nothing interprets: {env}"
        );
        let msg = env["message"].as_str().unwrap_or_default();
        assert!(
            msg.contains("type:") && msg.contains("id:"),
            "the refusal names the legal forms rather than leaving them to be \
             found: {env}"
        );
    }
}

/// Criterion 3's complement, second clause: a capability the matrix CLAIMS but
/// the pass could not deliver renders as a degradation, never as silence. The
/// degradation block only ever spoke for media already marked non-enumerable,
/// so an enumerable medium whose walk came back empty printed
/// `Degradations: (none)` beside a report with no denominator.
#[test]
fn an_empty_walk_on_an_enumerable_medium_renders_a_degradation() {
    let tmp = graph_binding_workspace();
    let root = tmp.path();

    // A well-formed selector that legitimately matches nothing — no
    // uninterpretable-scope hole involved.
    let binding = root.join(".memstead/projections/dest/mirror.json");
    let text = std::fs::read_to_string(&binding).unwrap();
    std::fs::write(
        &binding,
        text.replace(
            r#"{"path":"*","mode":"allow"}"#,
            r#"{"path":"type:nosuchtype","mode":"allow"}"#,
        ),
    )
    .unwrap();

    let out = String::from_utf8(
        memstead()
            .current_dir(root)
            .args(["projection", "verify", "dest/mirror"])
            .assert()
            .get_output()
            .stdout
            .clone(),
    )
    .unwrap();

    assert!(
        out.contains("enumeration-empty"),
        "the unavailable enumeration is named as a degradation: {out}"
    );
    assert!(
        !out.contains("_(none)_") || !out.contains("## Degradations\n\n_(none)_"),
        "the Degradations block is not silent about it: {out}"
    );
}

/// Criteria 1 and 3's complements, in the shape that hid them: a MIXED
/// binding, where one facet walks and another does not.
///
/// Both guards were binding-level — the `--full` refusal tested the union of
/// every facet's walk, and the degradation flag was computed over that same
/// union while being rendered per facet. One facet with artifacts therefore
/// spoke for a sibling that had none: `--full` returned clean over a scope
/// nobody looked at, and the Degradations block stayed silent about a
/// capability the matrix claimed and the pass never delivered.
#[test]
fn an_empty_facet_is_not_excused_by_a_sibling_that_walked() {
    let tmp = graph_binding_workspace();
    let root = tmp.path();

    // Add a second, path-medium facet that DOES walk, alongside a graph facet
    // narrowed to a well-formed selector matching nothing.
    std::fs::create_dir_all(root.join("code")).unwrap();
    std::fs::write(root.join("code").join("a.rs"), "fn a() {}\n").unwrap();
    write_store(
        root,
        "projections/dest/mirror.json",
        r#"{"version":2,"intent":"mixed","sources":[
            {"name":"src-graph","type":"graph","pointer":"srcmem","scope":[{"path":"type:nosuchtype","mode":"allow"}]},
            {"name":"code-facet","type":"filesystem","pointer":"code","change_detection":"mtime","scope":[{"path":"code/**/*","mode":"allow"}]}
        ],"reference_mems":[],"destination_mem":"dest","deny_paths":[],"coverage_semantics":"exhaustive","operations":{"build":{"mode":"discovery","trigger":"loop","batch_size":20},"sync":{"trigger":"manual","batch_size":20},"verify":{"trigger":"manual","batch_size":20,"adjudication_cap":50,"full_resync_every":20}}}"#,
    );

    // (1) `--full` must refuse, naming the empty facet — not pass because the
    //     sibling produced a non-empty union.
    let out = memstead()
        .current_dir(root)
        .args(["--json", "projection", "verify", "dest/mirror", "--full"])
        .assert()
        .failure()
        .get_output()
        .stdout
        .clone();
    let env: Value = serde_json::from_slice(&out).unwrap();
    assert_eq!(
        env["code"], "PROJECTION_CAPABILITY_UNSUPPORTED",
        "a full measurement refuses when any enumerable facet walked nothing: {env}"
    );
    assert_eq!(
        env["details"]["facet"], "src-graph",
        "the refusal names the facet that walked nothing, not the whole binding: {env}"
    );

    // (2) A plain pass measures what it can — and says what it could not.
    let out = String::from_utf8(
        memstead()
            .current_dir(root)
            .args(["projection", "verify", "dest/mirror"])
            .assert()
            .get_output()
            .stdout
            .clone(),
    )
    .unwrap();
    assert!(
        out.contains("enumeration-empty:`src-graph`"),
        "the empty facet is named as a degradation even though a sibling \
         walked: {out}"
    );
    assert!(
        !out.contains("enumeration-empty:`code-facet`"),
        "the facet that DID walk is not accused of walking nothing: {out}"
    );
}

/// Criterion 4's complement, on the path a grade found: the brief must never
/// instruct an agent to write a scope the engine then refuses.
///
/// An unscoped facet's remedy was medium-agnostic — "write `**/*` in the facet
/// scope" — printed at a graph source whose run path refuses exactly that as
/// not an entity selector. The engine told the agent to do the one thing it
/// would reject. This asserts the round trip: whatever the brief tells you to
/// write must actually run.
#[test]
fn the_unscoped_remedy_is_one_the_medium_accepts() {
    let tmp = graph_binding_workspace();
    let root = tmp.path();

    let binding = root.join(".memstead/projections/dest/mirror.json");
    let text = std::fs::read_to_string(&binding).unwrap();
    std::fs::write(
        &binding,
        text.replace(r#""scope":[{"path":"*","mode":"allow"}]"#, r#""scope":[]"#),
    )
    .unwrap();

    let brief = String::from_utf8(
        memstead()
            .current_dir(root)
            .args(["projection", "brief", "dest/mirror"])
            .assert()
            .get_output()
            .stdout
            .clone(),
    )
    .unwrap();
    assert!(
        brief.contains("unscoped facet"),
        "the unscoped facet is reported: {brief}"
    );
    assert!(
        !brief.contains("write `**/*`"),
        "a graph source is never told to write a path glob — the engine refuses \
         that scope, so printing it is an instruction to fail: {brief}"
    );
    assert!(
        brief.contains("write `*` in the"),
        "the remedy names a selector this medium actually accepts: {brief}"
    );

    // The round trip: take the brief's advice and the binding must RUN.
    std::fs::write(
        &binding,
        std::fs::read_to_string(&binding)
            .unwrap()
            .replace(r#""scope":[]"#, r#""scope":[{"path":"*","mode":"allow"}]"#),
    )
    .unwrap();
    memstead()
        .current_dir(root)
        .args(["--json", "projection", "verify", "dest/mirror"])
        .assert()
        .success();
}

/// Criterion 5's complement, second clause, for the medium it was left on. A
/// `web` facet has no scope vocabulary at all, so any rule is uninterpretable —
/// yet the declaration gate checked graph alone and the brief printed
/// `Paths: **/*` at the agent as selection. Fixing the medium where a defect
/// was demonstrated and leaving its twin standing is how this class survived a
/// round.
#[test]
fn a_web_facet_cannot_carry_scope_either() {
    let tmp = graph_binding_workspace();
    let root = tmp.path();

    write_store(
        root,
        "projections/dest/web.json",
        r#"{"version":2,"intent":"web","sources":[{"name":"web-facet","type":"web","pointer":"https://example.com","scope":[{"path":"**/*","mode":"allow"}]}],"reference_mems":[],"destination_mem":"dest","deny_paths":[],"operations":{"build":{"mode":"discovery","trigger":"loop","batch_size":20}}}"#,
    );

    let out = memstead()
        .current_dir(root)
        .args(["--json", "projection", "brief", "dest/web"])
        .assert()
        .failure()
        .get_output()
        .stdout
        .clone();
    let env: Value = serde_json::from_slice(&out).unwrap();
    assert_eq!(
        env["code"], "PROJECTION_SCOPE_UNINTERPRETABLE",
        "a web facet's scope rule is refused, not printed as selection: {env}"
    );
}

/// Criterion 6 proper: build→sync→verify over a graph binding whose source mem
/// is **git-branch backed**, so a real snapshot token and a real changed slice
/// exist. The folder-mem fixture above cannot reach this — a folder mount
/// tracks no head, so its graph source can only ever report "snapshot missing",
/// which pins the token's *absence* rather than the token.
///
/// This pins the working change-detection half the plan requires stay
/// observably unchanged: the snapshot token appears in the findings key, the
/// changed slice names the modified source entity in the sync brief, and
/// `advance` writes the baseline forward.
///
/// Gated on `mem-repo`: `--storage git-branch` refuses without it, so the
/// true-lean flavour (which omits the feature) cannot host this fixture. The
/// folder-mem graph tests above run in every flavour and carry the coverage
/// and drift criteria; this one adds the git-backed change-detection half.
#[cfg(feature = "mem-repo")]
#[test]
fn graph_binding_over_a_git_backed_source_pins_token_slice_and_baseline() {
    let tmp = TempDir::new().unwrap();
    let root = tmp.path();

    // A mem-repo workspace — the shape `--storage git-branch` requires.
    std::process::Command::new("git")
        .args(["init", "-q", "mem-repo"])
        .current_dir(root)
        .output()
        .unwrap();
    write_store(
        root,
        "workspace.toml",
        "format = \"memstead-git-branch-2\"\n\n[persistence_adapter]\nname = \"file-two-layer\"\n",
    );

    let run = |args: &[&str]| {
        memstead()
            .current_dir(root)
            .args(args)
            .assert()
            .success()
            .get_output()
            .stdout
            .clone()
    };

    run(&[
        "workspace",
        "allow-create",
        "*",
        "--schema",
        "default@1.0.0",
    ]);
    run(&[
        "mem",
        "init",
        "srcmem",
        "--schema",
        "default@1.0.0",
        "--storage",
        "git-branch",
    ]);
    run(&[
        "mem",
        "init",
        "dest",
        "--schema",
        "default@1.0.0",
        "--storage",
        "git-branch",
    ]);

    for title in ["Alpha", "Beta", "Gamma"] {
        run(&[
            "create",
            "--mem",
            "srcmem",
            "--title",
            title,
            "--type",
            "concept",
            "--section",
            &format!("definition={title} is a fixture concept."),
            "--section",
            &format!("explanation=Body of {title}."),
        ]);
    }

    write_store(
        root,
        "projections/dest/mirror.json",
        r#"{"version":2,"intent":"mirror srcmem into dest","sources":[{"name":"src-graph","type":"graph","pointer":"srcmem","scope":[{"path":"*","mode":"allow"}]}],"reference_mems":[],"destination_mem":"dest","deny_paths":[],"coverage_semantics":"exhaustive","operations":{"build":{"mode":"discovery","trigger":"loop","batch_size":20},"sync":{"trigger":"manual","batch_size":20},"verify":{"trigger":"manual","batch_size":20,"adjudication_cap":50,"full_resync_every":20}}}"#,
    );

    // (1) BUILD: the build leg of a graph binding is a discovery brief plus
    //     agent writes — there is no `projection build` command. Render the
    //     brief the agent works from, then make the write it prescribes:
    //     a destination entity anchored at a source ENTITY. That anchor is
    //     what verify measures coverage and drift against below, so the
    //     chain is genuinely build→sync→verify in one workspace rather than
    //     a verify fixture with the build hand-seeded on disk.
    let build_brief = String::from_utf8(run(&["projection", "brief", "dest/mirror"])).unwrap();
    assert!(
        build_brief.contains("**src-graph** (graph, primary)"),
        "the build brief names the graph source: {build_brief}"
    );
    assert!(
        build_brief.contains("Entities: *"),
        "a graph source's scope renders on the entity axis, not as `Paths`: {build_brief}"
    );
    assert!(
        build_brief.contains("memstead_search mem=srcmem"),
        "the brief hands the agent an executable route to the source baseline \
         — a changed slice alone is a delta with no baseline: {build_brief}"
    );
    assert!(
        !build_brief.contains("Paths:"),
        "no path-glob guidance is rendered for an entity-namespace source: {build_brief}"
    );

    run(&[
        "create",
        "--mem",
        "dest",
        "--title",
        "From alpha",
        "--type",
        "concept",
        "--section",
        "definition=Mirrors the alpha concept.",
        "--section",
        "explanation=Written from the build brief.",
        "--anchor",
        r#"{"artifact":"srcmem--alpha","grain":"entity","class":"anchored","source":"src-graph"}"#,
    ]);

    // (2) VERIFY: a real enumerated denominator AND a real snapshot token.
    //     The token is the half a folder-mem source can never produce.
    let env: Value =
        serde_json::from_slice(&run(&["--json", "projection", "verify", "dest/mirror"])).unwrap();
    assert_eq!(
        env["report"]["coverage"]["denominator"]["count"], 3,
        "the git-backed source mem's three entities are S(D): {env}"
    );
    // The build leg's write is what verify measures: the entity it anchored is
    // covered, the two it did not are gaps. Without this the build leg would
    // be decorative — a brief rendered and a write nothing checks.
    let uncovered = serde_json::to_string(&env["report"]).unwrap();
    assert!(
        uncovered.contains("srcmem--beta") && uncovered.contains("srcmem--gamma"),
        "the two unprojected source entities are gaps: {env}"
    );
    assert!(
        !env["report"]["coverage"]["uncovered"]
            .as_array()
            .map(|a| a.iter().any(|v| v == "srcmem--alpha"))
            .unwrap_or(false),
        "the entity the build leg anchored is NOT a gap — the write is measured: {env}"
    );

    let source_head = env["key"]["source_head"].as_str().unwrap().to_string();
    let token = source_head
        .strip_prefix("src-graph=")
        .expect("the findings key carries the per-source snapshot token")
        .to_string();
    assert_eq!(
        token.len(),
        40,
        "the graph snapshot token is the source mem's head SHA, not an empty \
         placeholder: {source_head}"
    );

    // (3) SYNC: with that token recorded as the baseline, a change to one
    //     source entity must surface as the changed slice — the half the
    //     brief steers by.
    run(&[
        "mem",
        "set-sync-state",
        "dest",
        "dest/mirror/src-graph#synced",
        &token,
    ]);
    run(&[
        "update",
        "srcmem--alpha",
        "--auto-hash",
        "--section",
        "explanation=Alpha body, rewritten.",
    ]);

    let brief = String::from_utf8(run(&["projection", "brief", "dest/mirror"])).unwrap();
    assert!(
        brief.contains("Source changes since the last sync"),
        "the source moved, so the brief presents a changed slice: {brief}"
    );
    assert!(
        brief.contains("srcmem--alpha"),
        "the changed slice names the modified source ENTITY: {brief}"
    );
    assert!(
        !brief.contains("srcmem--beta") && !brief.contains("srcmem--gamma"),
        "only the changed entity is in the slice — a delta, not the whole source: {brief}"
    );

    // (4) ADVANCE: disposing the whole slice completes the pass and writes the
    //     baseline forward to the source's new head.
    let env: Value = serde_json::from_slice(&run(&[
        "--json",
        "projection",
        "advance",
        "dest/mirror",
        "--dispositions",
        r#"{"srcmem--alpha": "worked"}"#,
    ]))
    .unwrap();
    assert_eq!(
        env["completed"], true,
        "the slice's only artifact is disposed — the pass completes: {env}"
    );

    assert_eq!(
        env["tokens_written"],
        serde_json::json!(["dest/mirror/src-graph#synced"]),
        "a completed pass writes the per-source baseline token: {env}"
    );

    let dump: Value = serde_json::from_slice(&run(&["--json", "workspace", "dump"])).unwrap();
    let sync_state = dump["mems"]
        .as_array()
        .unwrap()
        .iter()
        .find(|m| m["name"] == "dest")
        .and_then(|m| m["sync_state"].as_object())
        .expect("the destination mem carries sync state")
        .clone();

    let synced = sync_state["dest/mirror/src-graph#synced"].as_str().unwrap();
    assert_ne!(
        synced, token,
        "the #synced baseline advanced past the head the pass started on: {sync_state:?}"
    );
    assert_eq!(
        synced.len(),
        40,
        "it advanced to a real head SHA: {sync_state:?}"
    );

    // The #verified baseline is a DIFFERENT key and legitimately still holds
    // the head verify ran at — advancing sync must not move it. Asserting the
    // two independently is the point: one dump-wide substring check would
    // have read verify's untouched token as a failure to advance sync.
    assert_eq!(
        sync_state["dest/mirror/src-graph#verified"]
            .as_str()
            .unwrap(),
        token,
        "verify's baseline stays at the head it measured: {sync_state:?}"
    );
}