memstead-mcp 0.8.0

MCP server for Memstead — exposes the typed entity-graph engine over JSON-RPC stdio. Default build produces the full `memstead-mcp` binary (multi-mem, git-backed); `--no-default-features` builds the lean folder + archive 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
#![cfg(feature = "mem-repo")]
//! Wire-shape characterization for the MCP tool surface.
//!
//! This suite pins the bytes the server emits in `result.content[]` and
//! `result.structured_content` for representative tool calls. Both server
//! implementations live in this crate, gated by `mem-repo`: each
//! flavour's pin runs against its own (`FilesystemMcpServer` for the
//! lean build, `McpServer` for the full build).
//!
//! Harness drives the real `memstead-mcp` binary over stdio — same path agents
//! exercise — so the bytes captured here are the agent-visible contract.
//! Per-test spawn cost is acceptable (boot is <500ms); the harness sends
//! the full MCP handshake then multiple `tools/call` requests down one
//! pipe before tearing the child down.
//!
//! Adding a new pin:
//!   1. Pick a tool + path (success or specific error variant).
//!   2. Seed the workspace with enough state to reach that path (or
//!      reuse the empty-mounts fixture below for pure error paths).
//!   3. Call `harness.call_tool(...)`, assert on `code`, `message`
//!      contents, and `structured_content` shape.
//!   4. If the path is flavor-specific, gate on `mem-repo`.

use std::io::{BufRead, BufReader, Write};
use std::path::Path;
use std::process::{Child, ChildStdin, ChildStdout, Command, Stdio};
use std::time::{Duration, Instant};

use serde_json::{Value, json};
use tempfile::TempDir;

const WORKSPACE_TOML_BODY: &str = "format = \"memstead-git-branch-2\"\n\n\
[persistence_adapter]\nname = \"file-two-layer\"\n";

const MOUNTS_JSON_BODY_EMPTY: &str = r#"{ "format": "memstead-mounts-3", "mounts": [] }"#;

fn memstead_mcp_bin() -> &'static str {
    env!("CARGO_BIN_EXE_memstead-mcp")
}

/// Seed a minimal workspace at `root`. No mounts — sufficient for any
/// pure-error path that doesn't depend on graph state.
fn seed_empty_workspace(root: &Path) {
    let memstead = root.join(".memstead");
    std::fs::create_dir_all(memstead.join("state")).unwrap();
    std::fs::write(memstead.join("workspace.toml"), WORKSPACE_TOML_BODY).unwrap();
    std::fs::write(
        memstead.join("state").join("mounts.json"),
        MOUNTS_JSON_BODY_EMPTY,
    )
    .unwrap();
}

/// Seed a full-flavor workspace at `root` with git-branch backed mems.
/// Each `(mem_name, schema_pin)` produces:
/// - a branch `refs/heads/<name>` and a config blob on `__SYSTEM` (via
///   `init_real_mem_repo`)
/// - a corresponding `MountStorage::GitBranch` entry in `mounts.json`
///   so the full boot path's persistence adapter sees the mem as a
///   writable mount.
///
/// Without the mounts.json entries the engine boots with zero mounts
/// even when git-branch refs exist on disk — boot doesn't auto-discover
/// mem branches; the materialisation runs out-of-band via
/// `memstead mem-repo init`. The seed shortcuts that by writing the
/// state file directly.
fn seed_full_workspace(root: &Path, mems: &[(&str, &str)]) {
    seed_full_workspace_with_toml(root, mems, WORKSPACE_TOML_BODY);
}

/// Variant of [`seed_full_workspace`] that accepts a custom
/// `workspace.toml` body. Used by tests that need `[[mem_management.*]]`
/// rules (those rules live in workspace.toml and are not state-managed).
fn seed_full_workspace_with_toml(root: &Path, mems: &[(&str, &str)], workspace_toml: &str) {
    use memstead_base::WorkspaceStoreAdapter;
    use memstead_schema::SchemaRef;

    memstead_git_branch::test_support::init_real_mem_repo(root, mems);

    let memstead = root.join(".memstead");
    std::fs::create_dir_all(memstead.join("state")).unwrap();
    std::fs::write(memstead.join("workspace.toml"), workspace_toml).unwrap();

    let gitdir = root.join("mem-repo").join(".git");
    let mounts: Vec<memstead_base::Mount> = mems
        .iter()
        .map(|(name, schema)| {
            let pin: SchemaRef = schema.parse().unwrap();
            memstead_base::Mount {
                mem: (*name).to_string(),
                schema: Some(pin),
                storage: memstead_base::MountStorage::GitBranch {
                    gitdir: gitdir.clone(),
                    branch: (*name).to_string(),
                },
                capability: memstead_base::MountCapability::Write,
                lifecycle: memstead_base::MountLifecycle::Eager,
                cross_linkable: true,
                migration_target: None,
            }
        })
        .collect();

    let workspace = memstead_base::Workspace {
        mounts,
        settings: memstead_base::WorkspaceSettings::default(),
    };
    memstead_base::FileWorkspaceStore::new()
        .save_state(root, &workspace)
        .unwrap();
}

/// JSON-RPC harness over a spawned `memstead-mcp` child. Construct with
/// [`WireHarness::start`], drive with [`WireHarness::call_tool`], drop
/// to tear the child down.
struct WireHarness {
    child: Option<Child>,
    stdin: Option<ChildStdin>,
    reader: BufReader<ChildStdout>,
    next_id: i64,
}

impl WireHarness {
    /// Spawn the binary in `cwd`, send `initialize` + `notifications/initialized`.
    /// Panics on any handshake failure — these tests assume the binary
    /// boots; a regression there belongs in [`boot.rs`], not here.
    fn start(cwd: &Path) -> Self {
        Self::start_with_args(cwd, &[])
    }

    /// Spawn `memstead-mcp` with caller-supplied CLI args (e.g.
    /// `--operator-mode`) before the standard handshake.
    fn start_with_args(cwd: &Path, args: &[&str]) -> Self {
        let mut cmd = Command::new(memstead_mcp_bin());
        cmd.current_dir(cwd)
            .args(args)
            .stdin(Stdio::piped())
            .stdout(Stdio::piped())
            .stderr(Stdio::piped());
        let mut child = cmd
            .spawn()
            .expect("spawn memstead-mcp — confirm the binary built before running tests");
        let stdin = child.stdin.take().expect("child stdin");
        let stdout = child.stdout.take().expect("child stdout");
        let mut harness = Self {
            child: Some(child),
            stdin: Some(stdin),
            reader: BufReader::new(stdout),
            next_id: 0,
        };
        harness.handshake();
        harness
    }

    fn handshake(&mut self) {
        let id = self.send_request(
            "initialize",
            json!({
                "protocolVersion": "2024-11-05",
                "capabilities": {},
                "clientInfo": { "name": "wire-shape-test", "version": "0" }
            }),
        );
        let _ = self.read_response(id, Duration::from_secs(10));
        // Spec: the client signals it's ready with this notification.
        // The server's tool surface is only legally callable after.
        self.send_notification("notifications/initialized", json!({}));
    }

    fn send_request(&mut self, method: &str, params: Value) -> i64 {
        self.next_id += 1;
        let id = self.next_id;
        let body = json!({
            "jsonrpc": "2.0",
            "id": id,
            "method": method,
            "params": params,
        });
        let line = serde_json::to_string(&body).unwrap();
        let stdin = self.stdin.as_mut().expect("stdin open");
        writeln!(stdin, "{line}").expect("write request");
        stdin.flush().expect("flush");
        id
    }

    fn send_notification(&mut self, method: &str, params: Value) {
        let body = json!({
            "jsonrpc": "2.0",
            "method": method,
            "params": params,
        });
        let line = serde_json::to_string(&body).unwrap();
        let stdin = self.stdin.as_mut().expect("stdin open");
        writeln!(stdin, "{line}").expect("write notification");
        stdin.flush().expect("flush");
    }

    fn read_response(&mut self, want_id: i64, timeout: Duration) -> Value {
        let deadline = Instant::now() + timeout;
        let mut line = String::new();
        loop {
            if Instant::now() >= deadline {
                panic!("no JSON-RPC response with id={want_id} within {timeout:?}");
            }
            line.clear();
            match self.reader.read_line(&mut line) {
                Ok(0) => panic!("stdout EOF before id={want_id} reply"),
                Ok(_) => {
                    let trimmed = line.trim();
                    if trimmed.is_empty() {
                        continue;
                    }
                    let value: Value = match serde_json::from_str(trimmed) {
                        Ok(v) => v,
                        Err(_) => continue, // skip non-JSON lines (server logs leaking, etc.)
                    };
                    if value.get("id").and_then(|v| v.as_i64()) == Some(want_id) {
                        return value;
                    }
                    // Different id (e.g. server-initiated notification or
                    // out-of-order reply) — keep reading.
                }
                Err(_) => panic!("stdout read error before id={want_id} reply"),
            }
        }
    }

    /// Send `tools/call` and return the JSON-RPC `result` value (the
    /// `CallToolResult` envelope from rmcp). On JSON-RPC error replies
    /// the `error` field is returned wrapped under `_jsonrpc_error` so
    /// the caller can branch.
    fn call_tool(&mut self, name: &str, arguments: Value) -> Value {
        let id = self.send_request(
            "tools/call",
            json!({ "name": name, "arguments": arguments }),
        );
        let response = self.read_response(id, Duration::from_secs(15));
        if let Some(err) = response.get("error") {
            return json!({ "_jsonrpc_error": err });
        }
        response
            .get("result")
            .cloned()
            .expect("tools/call response must carry `result`")
    }
}

impl Drop for WireHarness {
    fn drop(&mut self) {
        drop(self.stdin.take());
        if let Some(mut child) = self.child.take() {
            let _ = child.kill();
            let _ = child.wait();
        }
    }
}

// ---------------------------------------------------------------------------
// Lean-flavor pins (FilesystemMcpServer)
// ---------------------------------------------------------------------------
//
// Run with `cargo nextest run --no-default-features -p memstead-mcp wire_shape`.

/// Shared assertion shape: every error envelope must carry `isError=true`,
/// the expected typed `code`, and a `message` matching the per-flavor
/// pinned text. Pre-extraction the two server files own independent
/// mappers (`FilesystemMcpServer::engine_op_error` vs
/// `McpServer::engine_err_unified`) — message text DRIFTS between them
/// today (see `lean_memstead_entity_*` vs `full_memstead_entity_*`). The
/// wire-byte-identity contract is *per-flavor*, not inter-flavor, so
/// each pin records its own server's current bytes.
fn assert_error_envelope(result: &Value, expected_code: &str, expected_message: &str) {
    let is_error = result
        .get("isError")
        .and_then(Value::as_bool)
        .unwrap_or(false);
    assert!(is_error, "expected isError=true on error path: {result}");

    let structured = result
        .get("structuredContent")
        .expect("structuredContent missing — wire envelope drifted");
    let code = structured
        .get("code")
        .and_then(Value::as_str)
        .expect("structured.code missing");
    assert_eq!(
        code, expected_code,
        "code drifted; structured payload = {structured}"
    );
    let msg = structured
        .get("message")
        .and_then(Value::as_str)
        .unwrap_or_default();
    assert_eq!(
        msg, expected_message,
        "message bytes drifted from pinned shape"
    );
}

// ---------------------------------------------------------------------------
// Full-flavor pins (McpServer)
// ---------------------------------------------------------------------------

/// Full pin: same input as the lean test, intentionally separate
/// assertion because the full mapper (`engine_err_unified` in
/// `server.rs`) emits a different message string than the lean mapper
/// for `ENTITY_NOT_FOUND`. These strings DIVERGE — the snapshot suite
/// captures both as today's truth until the casing is reconciled.
#[test]
fn full_memstead_entity_emits_typed_envelope_for_missing_id() {
    let tmp = TempDir::new().unwrap();
    seed_empty_workspace(tmp.path());
    // Full boot checks `<workspace>/mem-repo/.git` shape on startup —
    // seed a real bare repo with `main` + `__MEMSTEAD` refs.
    memstead_git_branch::test_support::init_real_mem_repo(tmp.path(), &[]);

    let mut harness = WireHarness::start(tmp.path());
    let result = harness.call_tool("memstead_entity", json!({ "id": "specs--does-not-exist" }));
    // Full mapper formats with capital "Entity not found" — diverges
    // from lean's "entity not found" (engine Display verbatim).
    // Recorded as inter-flavor drift; not fixed here.
    assert_error_envelope(
        &result,
        "ENTITY_NOT_FOUND",
        "Entity not found: specs--does-not-exist",
    );
}

// ---------------------------------------------------------------------------
// Success-path pins — pin envelope SHAPE, not exact content
// ---------------------------------------------------------------------------
//
// Success responses carry markdown content (often dependent on dynamic
// state like mem counts or schema version names). Pinning every byte
// would couple the suite to schema metadata. Instead these pins fix the
// envelope shape — `isError` absent or false, `content[0].type == text`,
// `text` carries the expected anchor sections — so a contract-shape
// regression (wrong content type, missing isError flag, structured_content
// in the wrong place) trips loudly; cosmetic prose changes do not.

fn assert_success_envelope(result: &Value) -> String {
    let is_error = result
        .get("isError")
        .and_then(Value::as_bool)
        .unwrap_or(false);
    assert!(!is_error, "expected success but got isError=true: {result}");
    let content = result
        .get("content")
        .and_then(Value::as_array)
        .expect("content[] missing — wire envelope drifted");
    assert!(
        !content.is_empty(),
        "content[] empty — wire envelope drifted"
    );
    let first = &content[0];
    let kind = first
        .get("type")
        .and_then(Value::as_str)
        .unwrap_or_default();
    assert_eq!(kind, "text", "content[0].type drifted: {first}");
    first
        .get("text")
        .and_then(Value::as_str)
        .unwrap_or_default()
        .to_string()
}

/// Full pin: same input through the full server. Full discovers mems
/// via the git-branch refs in `mem-repo/.git/`, so the seed seeds a
/// `demo` branch with the default schema pinned in `__SYSTEM`.
#[test]
fn full_memstead_search_succeeds_on_empty_seeded_workspace() {
    let tmp = TempDir::new().unwrap();
    seed_full_workspace(tmp.path(), &[("demo", "default@1.0.0")]);

    let mut harness = WireHarness::start(tmp.path());
    let result = harness.call_tool("memstead_search", json!({}));
    let text = assert_success_envelope(&result);
    for marker in ["_total: 0", "_returned: 0", "_offset: 0"] {
        assert!(
            text.contains(marker),
            "search response missing {marker:?}: {text:?}"
        );
    }
}

/// Full pin: full flavor's `memstead_overview` against the proper full seed
/// (git-branch refs + matching `mounts.json` entries) emits the
/// canonical anchors AND lists the seeded mem. Adding the full-only
/// `## Lifecycle Namespaces` anchor (the lean overview omits it
/// entirely — lean has no mem-creation rules) is part of the pin so
/// the test trips if full accidentally drops that section.
#[test]
fn full_memstead_overview_succeeds_on_empty_seeded_workspace() {
    let tmp = TempDir::new().unwrap();
    seed_full_workspace(tmp.path(), &[("demo", "default@1.0.0")]);

    let mut harness = WireHarness::start(tmp.path());
    let result = harness.call_tool("memstead_overview", json!({}));
    let text = assert_success_envelope(&result);
    for anchor in [
        "## Mems",
        "## Schemas",
        "## Communities",
        "## Lifecycle Namespaces",
    ] {
        assert!(
            text.contains(anchor),
            "full overview missing {anchor:?}: {text:?}"
        );
    }
    assert!(
        text.contains("demo"),
        "full overview missing mem name: {text:?}"
    );
}

// ---------------------------------------------------------------------------
// `memstead_schema` error pin — both flavors emit `ENTITY_NOT_FOUND` for
// names that don't match the workspace's pinned schema. Helps confirm
// the pre-extraction message divergence story applies symmetrically
// across tools, not just `memstead_entity`.
// ---------------------------------------------------------------------------

/// Full pin: same input on a full-seeded single-mem workspace. Per-flavor
/// message bytes are recorded independently; the lean flavor appends
/// `" — workspace pins default@1.0.0"` to the message, the full flavor
/// emits only `"schema not found: \"<name>\""`. Recorded drift, pending
/// reconciliation.
#[test]
fn full_memstead_schema_unknown_name_emits_entity_not_found() {
    let tmp = TempDir::new().unwrap();
    seed_full_workspace(tmp.path(), &[("demo", "default@1.0.0")]);

    let mut harness = WireHarness::start(tmp.path());
    let result = harness.call_tool("memstead_schema", json!({ "name": "not-a-schema" }));
    assert_error_envelope(
        &result,
        "ENTITY_NOT_FOUND",
        "schema not found: \"not-a-schema\"",
    );
}

// ---------------------------------------------------------------------------
// Mutation pins — `memstead_create` success + UNKNOWN_ENTITY_TYPE error
// ---------------------------------------------------------------------------
//
// Success path: the create response carries a JSON body on
// `structured_content` whose `id` field is the slugified id, plus
// `title`, `mem`, `content_hash`, `commit_sha`, and `warnings`. The
// pins assert on field PRESENCE + the deterministic `id` slug; the
// hashes / commit shas are content-derived and pinning them would
// couple the suite to the markdown render exactly.

fn assert_create_success_shape(result: &Value, expected_id: &str, expected_mem: &str) {
    let _text = assert_success_envelope(result);
    let body = result
        .get("structuredContent")
        .expect("structuredContent missing on create success");
    for field in ["id", "title", "mem", "_hash", "warnings"] {
        assert!(
            body.get(field).is_some(),
            "create response missing {field:?}: {body}"
        );
    }
    assert_eq!(
        body.get("id").and_then(Value::as_str),
        Some(expected_id),
        "create id drifted from slug rule: {body}"
    );
    assert_eq!(
        body.get("mem").and_then(Value::as_str),
        Some(expected_mem),
        "create response mem drifted: {body}"
    );
}

/// Full pin: same as lean. The slug rule (`<mem>--<lower-kebab>`) is
/// engine-internal so the expected id matches the lean pin.
#[test]
fn full_memstead_create_returns_typed_success_envelope() {
    let tmp = TempDir::new().unwrap();
    seed_full_workspace(tmp.path(), &[("demo", "default@1.0.0")]);

    let mut harness = WireHarness::start(tmp.path());
    let result = harness.call_tool(
        "memstead_create",
        json!({
            "title": "First",
            "entity_type": "spec",
            "sections": { "identity": "the identity", "purpose": "the purpose" },
        }),
    );
    assert_create_success_shape(&result, "demo--first", "demo");
}

/// Full pin: same input. Pre-extraction the full mapper
/// (`engine_err_unified`) also wraps `UNKNOWN_ENTITY_TYPE`; this pin
/// trips if full drops the recovery payload during the lift.
#[test]
fn full_memstead_create_unknown_type_emits_typed_envelope() {
    let tmp = TempDir::new().unwrap();
    seed_full_workspace(tmp.path(), &[("demo", "default@1.0.0")]);

    let mut harness = WireHarness::start(tmp.path());
    let result = harness.call_tool(
        "memstead_create",
        json!({ "title": "X", "entity_type": "totally-not-a-type" }),
    );

    let is_error = result
        .get("isError")
        .and_then(Value::as_bool)
        .unwrap_or(false);
    assert!(is_error, "expected isError on unknown type: {result}");
    let structured = result
        .get("structuredContent")
        .expect("structuredContent missing");
    assert_eq!(
        structured.get("code").and_then(Value::as_str),
        Some("UNKNOWN_ENTITY_TYPE"),
        "code drifted: {structured}"
    );
    let msg = structured
        .get("message")
        .and_then(Value::as_str)
        .unwrap_or_default();
    assert!(
        msg.contains("totally-not-a-type"),
        "message missing rejected type name: {msg:?}"
    );
    assert!(
        msg.contains("Declared types:") || msg.contains("declared types:"),
        "message missing declared-types prefix: {msg:?}"
    );
}

// ---------------------------------------------------------------------------
// `memstead_health` success pins
// ---------------------------------------------------------------------------

/// Full pin: full `memstead_health` returns a richer envelope with
/// `writable_mems` populated when the engine sees writable mounts.
#[test]
fn full_memstead_health_succeeds_on_seeded_workspace() {
    let tmp = TempDir::new().unwrap();
    seed_full_workspace(tmp.path(), &[("demo", "default@1.0.0")]);

    let mut harness = WireHarness::start(tmp.path());
    let result = harness.call_tool("memstead_health", json!({}));
    let _ = assert_success_envelope(&result);
    let body = result
        .get("structuredContent")
        .expect("structuredContent missing on health success");
    assert!(
        body.get("writable_mems").is_some(),
        "full health response missing writable_mems: {body}"
    );
}

/// A bad
/// `since` cursor on `memstead_changes_since` returns the typed `INVALID_CURSOR`
/// — not the `MEM_ERROR` catch-all — with the offending SHA untruncated
/// in `details.since`, so a sync loop branches cleanly (typed → re-seed).
#[test]
fn full_memstead_changes_since_bad_cursor_returns_invalid_cursor() {
    let tmp = TempDir::new().unwrap();
    seed_full_workspace(tmp.path(), &[("demo", "default@1.0.0")]);
    let mut harness = WireHarness::start(tmp.path());

    let bad = "deadbeefdeadbeefdeadbeefdeadbeefdeadbeef";
    let result = harness.call_tool(
        "memstead_changes_since",
        json!({ "mem": "demo", "since": bad }),
    );
    let is_error = result
        .get("isError")
        .and_then(Value::as_bool)
        .unwrap_or(false);
    assert!(is_error, "a bad since cursor must error: {result}");
    let sc = result
        .get("structuredContent")
        .expect("structuredContent missing on error envelope");
    assert_eq!(
        sc.get("code").and_then(Value::as_str),
        Some("INVALID_CURSOR"),
        "bad since must carry the typed INVALID_CURSOR code, not MEM_ERROR: {sc}",
    );
    assert_eq!(
        sc.get("details")
            .and_then(|d| d.get("since"))
            .and_then(Value::as_str),
        Some(bad),
        "the offending SHA must ride untruncated in details.since: {sc}",
    );
}

/// The default writable
/// mem is stable. After the seed mem `demo`, creating a second
/// writable mem `aaa` (which sorts ahead alphabetically) must NOT
/// retarget omitted-`mem` writes — a subsequent `memstead_create` with
/// `mem` omitted still lands in `demo`. The default is discoverable
/// on `memstead_health.default_writable_mem`, and an explicit `mem`
/// always wins. Pre-fix the resolver read `writable_mems().iter().next()`
/// off an unordered `HashSet`, so the second mem silently retargeted
/// the default.
#[test]
fn full_default_writable_mem_is_stable_after_second_mem() {
    const TOML: &str = "\
format = \"memstead-git-branch-2\"\n\
\n\
[persistence_adapter]\n\
name = \"file-two-layer\"\n\
\n\
[[mem_management.create]]\n\
pattern = \"*\"\n\
schemas = [\"default@1.0.0\"]\n\
";
    let tmp = TempDir::new().unwrap();
    seed_full_workspace_with_toml(tmp.path(), &[("demo", "default@1.0.0")], TOML);
    let mut harness = WireHarness::start(tmp.path());

    let sections = json!({ "identity": "the identity", "purpose": "the purpose" });

    // Baseline: an omitted-`mem` create lands in the seed `demo`.
    let c1 = harness.call_tool(
        "memstead_create",
        json!({ "title": "First", "entity_type": "spec", "sections": sections }),
    );
    assert_create_success_shape(&c1, "demo--first", "demo");

    // Bring up a second writable mem whose name sorts ahead of `demo`.
    let cv = harness.call_tool(
        "memstead_mem_create",
        json!({ "name": "aaa", "location": "mems/aaa", "schema": "default@1.0.0" }),
    );
    let _ = assert_success_envelope(&cv);

    // The omitted-`mem` create STILL lands in `demo`, not `aaa` —
    // adding a mem did not move the default.
    let c2 = harness.call_tool(
        "memstead_create",
        json!({ "title": "Second", "entity_type": "spec", "sections": sections }),
    );
    assert_create_success_shape(&c2, "demo--second", "demo");

    // The default is discoverable on the read surface.
    let health = harness.call_tool("memstead_health", json!({}));
    let hbody = health
        .get("structuredContent")
        .expect("structuredContent missing on health success");
    assert_eq!(
        hbody.get("default_writable_mem").and_then(Value::as_str),
        Some("demo"),
        "memstead_health must name the stable default: {hbody}",
    );

    // Explicit `mem` always wins, regardless of the default.
    let c3 = harness.call_tool(
        "memstead_create",
        json!({ "mem": "aaa", "title": "Third", "entity_type": "spec", "sections": sections }),
    );
    assert_create_success_shape(&c3, "aaa--third", "aaa");
}

// ---------------------------------------------------------------------------
// Multi-step mutation pins — exercise the read-then-write contract
// ---------------------------------------------------------------------------
//
// The optimistic-locking contract is central to safe mutations: every
// `memstead_update` / `memstead_delete` / `memstead_rename` requires `expected_hash`
// from a prior read, and a stale hash trips `HASH_MISMATCH` with the
// current on-disk hash on `details.current`. These pins exercise the
// full read-then-write loop through the wire.

/// Issue an `memstead_create` call and return `(id, content_hash)` so a
/// subsequent mutation can target it with the right `expected_hash`.
/// Panics on any create failure — used as a fixture by mutation tests.
///
/// The engine
/// refuses on missing required sections, so the helper seeds the
/// `spec` type's required `identity` + `purpose` sections.
fn create_and_get_id_hash(harness: &mut WireHarness, title: &str) -> (String, String) {
    let result = harness.call_tool(
        "memstead_create",
        json!({
            "title": title,
            "entity_type": "spec",
            "sections": {
                "identity": "seed identity",
                "purpose": "seed purpose",
            },
        }),
    );
    let body = result
        .get("structuredContent")
        .expect("create response missing structuredContent");
    let id = body
        .get("id")
        .and_then(Value::as_str)
        .expect("create response missing id")
        .to_string();
    let hash = body
        .get("_hash")
        .and_then(Value::as_str)
        .expect("create response missing content_hash")
        .to_string();
    (id, hash)
}

/// Shared assertion for HASH_MISMATCH envelopes. `details.current` must
/// carry the actual on-disk hash; `details.id` must echo the rejected id.
/// `details.is_stub` indicates whether the entity is a stub (no body) —
/// pinned so callers know to branch on it for stub-aware recovery.
fn assert_hash_mismatch_envelope(result: &Value, expected_id: &str, expected_current: &str) {
    let is_error = result
        .get("isError")
        .and_then(Value::as_bool)
        .unwrap_or(false);
    assert!(is_error, "expected isError=true on stale hash: {result}");
    let structured = result
        .get("structuredContent")
        .expect("structuredContent missing");
    assert_eq!(
        structured.get("code").and_then(Value::as_str),
        Some("HASH_MISMATCH"),
        "code drifted: {structured}"
    );
    let details = structured
        .get("details")
        .expect("HASH_MISMATCH must carry details");
    assert_eq!(
        details.get("id").and_then(Value::as_str),
        Some(expected_id),
        "details.id drifted: {details}"
    );
    assert_eq!(
        details.get("current").and_then(Value::as_str),
        Some(expected_current),
        "details.current drifted: {details}"
    );
    assert!(
        details.get("is_stub").is_some(),
        "details.is_stub missing — recovery payload contract drifted: {details}"
    );
}

/// Full pin: same multi-step flow exercises full's mapper.
#[test]
fn full_memstead_update_stale_hash_emits_typed_envelope() {
    let tmp = TempDir::new().unwrap();
    seed_full_workspace(tmp.path(), &[("demo", "default@1.0.0")]);

    let mut harness = WireHarness::start(tmp.path());
    let (id, real_hash) = create_and_get_id_hash(&mut harness, "Locked");

    let stale_hash = "0".repeat(64);
    let result = harness.call_tool(
        "memstead_update",
        json!({
            "id": id,
            "expected_hash": stale_hash,
            "sections": { "identity": "new body" },
        }),
    );
    assert_hash_mismatch_envelope(&result, &id, &real_hash);
}

/// Full pin: same. Full response shape may differ subtly (extra fields
/// like commit_sha) — the pin only requires the rotated hash.
#[test]
fn full_memstead_update_succeeds_and_rotates_hash() {
    let tmp = TempDir::new().unwrap();
    seed_full_workspace(tmp.path(), &[("demo", "default@1.0.0")]);

    let mut harness = WireHarness::start(tmp.path());
    let (id, original_hash) = create_and_get_id_hash(&mut harness, "Updatable");

    let result = harness.call_tool(
        "memstead_update",
        json!({
            "id": id,
            "expected_hash": original_hash,
            "sections": { "identity": "rewritten body" },
        }),
    );
    let _ = assert_success_envelope(&result);
    let body = result
        .get("structuredContent")
        .expect("structuredContent missing on update success");
    let new_hash = body
        .get("_hash")
        .and_then(Value::as_str)
        .expect("update response missing content_hash");
    assert_ne!(
        new_hash, original_hash,
        "content_hash did not rotate after section rewrite: {body}"
    );
}

/// Full pin: same flow; full's ENTITY_NOT_FOUND message text uses
/// capital "Entity" per the previously-recorded inter-flavor drift.
#[test]
fn full_memstead_delete_succeeds_and_entity_becomes_unreadable() {
    let tmp = TempDir::new().unwrap();
    seed_full_workspace(tmp.path(), &[("demo", "default@1.0.0")]);

    let mut harness = WireHarness::start(tmp.path());
    let (id, hash) = create_and_get_id_hash(&mut harness, "Doomed");

    let del = harness.call_tool(
        "memstead_delete",
        json!({ "id": id, "expected_hash": hash }),
    );
    let _ = assert_success_envelope(&del);

    let read = harness.call_tool("memstead_entity", json!({ "id": id }));
    assert_error_envelope(
        &read,
        "ENTITY_NOT_FOUND",
        &format!("Entity not found: {id}"),
    );
}

// ---------------------------------------------------------------------------
// `memstead_relate` success pins
// ---------------------------------------------------------------------------

/// Full pin: same flow, but the response field names differ from lean:
/// full emits `rel_type` (not `type`), `source: "explicit"` (carries the
/// edge source), `_mem_schema`, and `commit_sha` — but **omits**
/// `action`. The lean surface has `type` and `action` instead. Both
/// shapes are pinned per-flavor, pending reconciliation of which schema
/// wins.
#[test]
fn full_memstead_relate_returns_typed_success_envelope() {
    let tmp = TempDir::new().unwrap();
    seed_full_workspace(tmp.path(), &[("demo", "default@1.0.0")]);

    let mut harness = WireHarness::start(tmp.path());
    let (from, _) = create_and_get_id_hash(&mut harness, "Source");
    let (to, _) = create_and_get_id_hash(&mut harness, "Target");

    let result = harness.call_tool(
        "memstead_relate",
        json!({ "relations": [{ "from": from, "to": to, "type": "USES" }] }),
    );
    let _ = assert_success_envelope(&result);
    let body = result
        .get("structuredContent")
        .expect("structuredContent missing on relate success");
    let entry = body
        .get("results")
        .and_then(|r| r.get(0))
        .expect("plural envelope carries results[0]");
    assert_eq!(
        entry.get("from").and_then(Value::as_str),
        Some(from.as_str()),
        "relate `from` drifted: {body}"
    );
    assert_eq!(
        entry.get("to").and_then(Value::as_str),
        Some(to.as_str()),
        "relate `to` drifted: {body}"
    );
    // Full uses `rel_type` (not `type`). USES (not REFERENCES) — explicit
    // author of REFERENCES is refused under the default schema's
    // `alias_target_rel_type` pointer; this test pins the envelope
    // shape, not the rel-type specifically.
    assert_eq!(
        entry.get("rel_type").and_then(Value::as_str),
        Some("USES"),
        "full relate `rel_type` drifted: {body}"
    );
    assert!(
        body.get("type").is_none(),
        "full must not carry `type` (lean field name): {body}"
    );
    // `action` rides the per-entry result, not the top level — the same
    // place the lean surface puts it. (This assertion once recorded
    // "full omits `action`, lean carries it"; that drift closed with the
    // plural relate envelope, and the twin pin in `wire_shape_lean.rs`
    // now asserts the matching per-entry shape.)
    assert_eq!(
        entry.get("action").and_then(Value::as_str),
        Some("added"),
        "full relate `action` drifted: {body}"
    );
    assert!(
        body.get("action").is_none(),
        "`action` belongs inside results[], never at the top level: {body}"
    );
}

// ---------------------------------------------------------------------------
// `memstead_rename` pins — success + RENAME_NO_OP
// ---------------------------------------------------------------------------

/// Full pin: same flow.
#[test]
fn full_memstead_rename_returns_typed_success_envelope() {
    let tmp = TempDir::new().unwrap();
    seed_full_workspace(tmp.path(), &[("demo", "default@1.0.0")]);

    let mut harness = WireHarness::start(tmp.path());
    let (id, hash) = create_and_get_id_hash(&mut harness, "Old Title");

    let result = harness.call_tool(
        "memstead_rename",
        json!({ "id": id, "new_title": "New Title", "expected_hash": hash }),
    );
    let _ = assert_success_envelope(&result);
    let body = result
        .get("structuredContent")
        .expect("structuredContent missing on rename success");
    assert_eq!(
        body.get("old_id").and_then(Value::as_str),
        Some(id.as_str()),
        "old_id drifted: {body}"
    );
    assert_eq!(
        body.get("new_id").and_then(Value::as_str),
        Some("demo--new-title"),
        "new_id drifted from slug rule: {body}"
    );
}

/// Full pin: full renames-to-same-slug succeed but ride a typed
/// `TITLE_NORMALIZED_TO_SLUG_NOOP` warning on the response so an agent
/// can detect the degenerate case from `details.warnings[]`. The lean
/// surface omits the warning entirely (see the lean pin above).
#[test]
fn full_memstead_rename_same_slug_emits_typed_warning() {
    let tmp = TempDir::new().unwrap();
    seed_full_workspace(tmp.path(), &[("demo", "default@1.0.0")]);

    let mut harness = WireHarness::start(tmp.path());
    let (id, hash) = create_and_get_id_hash(&mut harness, "First");

    let result = harness.call_tool(
        "memstead_rename",
        json!({ "id": id, "new_title": "First", "expected_hash": hash }),
    );
    let _ = assert_success_envelope(&result);
    let body = result
        .get("structuredContent")
        .expect("structuredContent missing");
    assert_eq!(
        body.get("old_id").and_then(Value::as_str),
        Some(id.as_str()),
    );
    assert_eq!(
        body.get("new_id").and_then(Value::as_str),
        Some(id.as_str()),
    );
    let warnings = body
        .get("warnings")
        .and_then(Value::as_array)
        .expect("full rename success must carry warnings[]");
    let codes: Vec<&str> = warnings
        .iter()
        .filter_map(|w| w.get("code").and_then(Value::as_str))
        .collect();
    assert!(
        codes.contains(&"TITLE_NORMALIZED_TO_SLUG_NOOP"),
        "expected TITLE_NORMALIZED_TO_SLUG_NOOP warning, got codes={codes:?}: {body}"
    );
}

// ---------------------------------------------------------------------------
// `memstead_reload` (full-only) success pin
// ---------------------------------------------------------------------------
//
// The lean filesystem-mem server doesn't expose memstead_reload —
// drift-reload is a mem-repo concept (sibling writer commits a new
// HEAD; engine re-derives memo state). Pinning is full-only.

/// Full pin: `memstead_reload` on a quiescent workspace returns a success
/// envelope. The detailed report shape (changes count, etc.) is
/// engine-state-dependent; the pin is on the envelope's success flag
/// and presence of the report on `structured_content`.
#[test]
fn full_memstead_reload_returns_typed_success_envelope() {
    let tmp = TempDir::new().unwrap();
    seed_full_workspace(tmp.path(), &[("demo", "default@1.0.0")]);

    let mut harness = WireHarness::start(tmp.path());
    let result = harness.call_tool("memstead_reload", json!({}));
    let _ = assert_success_envelope(&result);
    assert!(
        result.get("structuredContent").is_some(),
        "reload response missing structuredContent: {result}"
    );
}

// ---------------------------------------------------------------------------
// `memstead_delete` HAS_INCOMING_REFS pin — multi-step (create×2 → relate → delete)
// ---------------------------------------------------------------------------
//
// The recovery payload contract: `details.referrers[]` carries
// `{from_id, rel_type, mem, capability: "write"}` for each Write-Mem
// referrer so the agent can rewrite the offending references without a
// follow-up `memstead_entity` call. Both flavors emit this shape today.

fn assert_has_incoming_refs_envelope(result: &Value, expected_target: &str, expected_source: &str) {
    let is_error = result
        .get("isError")
        .and_then(Value::as_bool)
        .unwrap_or(false);
    assert!(
        is_error,
        "expected isError on delete with referrers: {result}"
    );
    let structured = result
        .get("structuredContent")
        .expect("structuredContent missing");
    assert_eq!(
        structured.get("code").and_then(Value::as_str),
        Some("HAS_INCOMING_REFS"),
        "code drifted: {structured}"
    );
    let details = structured
        .get("details")
        .expect("details missing on HAS_INCOMING_REFS");
    assert_eq!(
        details.get("id").and_then(Value::as_str),
        Some(expected_target),
        "details.id drifted: {details}"
    );
    let referrers = details
        .get("referrers")
        .and_then(Value::as_array)
        .expect("details.referrers[] missing");
    assert!(
        !referrers.is_empty(),
        "details.referrers[] is empty: {details}"
    );
    let first = &referrers[0];
    assert_eq!(
        first.get("from_id").and_then(Value::as_str),
        Some(expected_source),
        "referrer.from_id drifted: {first}"
    );
    assert_eq!(
        first.get("capability").and_then(Value::as_str),
        Some("write"),
        "referrer.capability drifted: {first}"
    );
    let rel_types = first
        .get("rel_types")
        .and_then(Value::as_array)
        .unwrap_or_else(|| panic!("referrer.rel_types missing: {first}"));
    assert!(
        !rel_types.is_empty(),
        "referrer.rel_types must carry ≥1 entry: {first}"
    );
    assert!(
        first.get("mem").and_then(Value::as_str).is_some(),
        "referrer.mem missing: {first}"
    );
}

/// Full pin: same multi-step flow.
#[test]
fn full_memstead_delete_with_incoming_refs_emits_typed_envelope() {
    let tmp = TempDir::new().unwrap();
    seed_full_workspace(tmp.path(), &[("demo", "default@1.0.0")]);

    let mut harness = WireHarness::start(tmp.path());
    let (source, _) = create_and_get_id_hash(&mut harness, "Referrer");
    let (target, target_hash) = create_and_get_id_hash(&mut harness, "Referenced");

    let relate = harness.call_tool(
        "memstead_relate",
        json!({ "relations": [{ "from": source, "to": target, "type": "USES" }] }),
    );
    let _ = assert_success_envelope(&relate);

    let del = harness.call_tool(
        "memstead_delete",
        json!({ "id": target, "expected_hash": target_hash }),
    );
    assert_has_incoming_refs_envelope(&del, &target, &source);
}

// ---------------------------------------------------------------------------
// `memstead_changes_since` success pins
// ---------------------------------------------------------------------------
//
// Lean and full use STRUCTURALLY different change-feeds: lean reads
// timestamp-keyed entries from `.memstead/changes.jsonl`; full reads git
// commits between `since` and HEAD. The two response envelopes
// diverge — each pin records its flavor's shape per-flavor.

/// Full pin: `memstead_changes_since` reads git history. Passing the
/// canonical empty-tree SHA returns every entity as `added`. The
/// response carries a richer envelope (`changes[]`, head_sha,
/// changed_files counts) compared to lean's flat `{since, count,
/// entries}` shape. **Drift recorded** — neither shape is canonical
/// yet.
#[test]
fn full_memstead_changes_since_returns_typed_success_envelope() {
    let tmp = TempDir::new().unwrap();
    seed_full_workspace(tmp.path(), &[("demo", "default@1.0.0")]);

    let mut harness = WireHarness::start(tmp.path());
    let _ = create_and_get_id_hash(&mut harness, "First");

    // Canonical git empty-tree SHA → "give me every entity as added".
    let empty_tree = "4b825dc642cb6eb9a060e54bf8d69288fbee4904";
    let result = harness.call_tool(
        "memstead_changes_since",
        json!({ "mem": "demo", "since": empty_tree }),
    );
    let _ = assert_success_envelope(&result);
    let body = result
        .get("structuredContent")
        .expect("structuredContent missing on changes_since success");
    // Full's response shape is distinct from lean — pin presence of
    // `changes` (the per-entity event list on full) rather than lean's
    // `entries`. The exact richer fields (head_sha, etc.) are not
    // pinned here so the envelope can evolve under non-extraction
    // plans without tripping this test; the lift cannot drop
    // `changes[]` though.
    assert!(
        body.get("changes").is_some(),
        "full changes_since response missing `changes[]`: {body}"
    );
    // Lean-style `entries[]` must NOT appear on full — these are
    // distinct envelopes today.
    assert!(
        body.get("entries").is_none(),
        "full response unexpectedly carries lean's `entries[]`: {body}"
    );
}

/// Engine-tier rename
/// detection via commit notes. Relying on
/// gix's content-similarity scorer alone, over wide cursor
/// windows, pairs unrelated entities X↔Y if their content happens to
/// be more similar than the actual rename pair X↔Z — a memo rename
/// followed by adjacent unrelated commits reproduces this.
///
/// Instead the engine walks `agent_notes_since` first and uses
/// the authoritative `memstead: rename A → B` map to override gix's
/// pairing. Reproducer: rename one entity, make several unrelated
/// commits, poll `changes_since` over the wide cursor window
/// (empty-tree → HEAD). Exactly one `renamed` event with the
/// correct from/to pair must surface, regardless of any
/// content-similarity coincidences across the other commits.
#[test]
fn full_memstead_changes_since_wide_window_uses_authoritative_rename_map() {
    let tmp = TempDir::new().unwrap();
    seed_full_workspace(tmp.path(), &[("demo", "default@1.0.0")]);

    let mut harness = WireHarness::start(tmp.path());

    // Step 1: seed the workspace with all the entities that exist
    // BEFORE the cursor — pre-rename adjacent entities and the
    // rename target. Then capture the cursor SHA. Anything that
    // happens after this is "inside the polling window".
    let (rename_id, _) = create_and_get_id_hash(&mut harness, "Leading And Trailing Whitespace");
    // Adjacent unrelated entities — bodies share enough lexical
    // mass with the rename target that gix's similarity scorer can
    // mispair them over the wide window (the F16 trip).
    let (other_a, _) = create_and_get_id_hash(&mut harness, "Adjacent Memo Alpha");
    let (other_b, _) = create_and_get_id_hash(&mut harness, "Adjacent Memo Beta");

    // Re-read the rename target so we have a fresh hash for the
    // rename call (the post-create hash, which is still current
    // because nothing has touched the target since).
    let entity_read = harness.call_tool("memstead_entity", json!({ "id": rename_id }));
    let entity_text = assert_success_envelope(&entity_read);
    // Extract `_hash` from the markdown frontmatter — wire-shape
    // helper isn't worth threading; a substring sniff is enough.
    let pre_hash = entity_text
        .lines()
        .find_map(|l| l.strip_prefix("_hash: "))
        .map(|s| s.trim_matches('"').to_string())
        .expect("entity text must carry _hash");

    // Step 2: capture cursor SHA by recording the most recent
    // create's commit_sha — that's the workspace head right after
    // the last seed entity landed, so it's the boundary between
    // "pre-window" and "in-window" commits. The agent contract
    // is to keep `commit_sha` from every mutation response and pass
    // it back as `since` for the next poll.
    let last_seed_create = harness.call_tool("memstead_entity", json!({ "id": other_b }));
    let _ = assert_success_envelope(&last_seed_create);
    // Use memstead_changes_since with empty-tree to find the latest
    // commit's SHA at the current HEAD — the response carries `head`.
    let cursor_capture = harness.call_tool(
        "memstead_changes_since",
        json!({
            "mem": "demo",
            "since": "4b825dc642cb6eb9a060e54bf8d69288fbee4904",
        }),
    );
    let _ = assert_success_envelope(&cursor_capture);
    let head_sha = cursor_capture
        .get("structuredContent")
        .and_then(|c| c.get("head"))
        .and_then(Value::as_str)
        .expect("changes_since must echo head for cursor capture")
        .to_string();

    // Step 3: inside the polling window — touch unrelated entities
    // (so the diff has Update events) and rename the target.
    let entity_a_read = harness.call_tool("memstead_entity", json!({ "id": other_a }));
    let a_text = assert_success_envelope(&entity_a_read);
    let other_a_hash = a_text
        .lines()
        .find_map(|l| l.strip_prefix("_hash: "))
        .map(|s| s.trim_matches('"').to_string())
        .expect("entity_a missing _hash");
    let update_a = harness.call_tool(
        "memstead_update",
        json!({
            "id": other_a,
            "expected_hash": other_a_hash,
            "sections": {
                "identity": "Some adjacent content overlapping with the rename target.",
            },
        }),
    );
    let _ = assert_success_envelope(&update_a);

    // Now rename the target.
    let renamed = harness.call_tool(
        "memstead_rename",
        json!({
            "id": rename_id,
            "new_title": "Whitespace Memo Renamed",
            "expected_hash": pre_hash,
        }),
    );
    let renamed_body = renamed
        .get("structuredContent")
        .expect("rename response missing body");
    let new_id = renamed_body
        .get("new_id")
        .and_then(Value::as_str)
        .expect("rename response missing new_id")
        .to_string();

    // Step 4: changes_since from the captured cursor.
    let feed = harness.call_tool(
        "memstead_changes_since",
        json!({ "mem": "demo", "since": head_sha }),
    );
    let _ = assert_success_envelope(&feed);
    let body = feed
        .get("structuredContent")
        .expect("changes_since missing structuredContent");
    let changes = body
        .get("changes")
        .and_then(Value::as_array)
        .expect("changes_since missing changes[]");

    // Exactly one Renamed event with the right pair. Other actions
    // (`updated` on adjacents) may also surface — the pin is "no
    // false-positive renames coming from gix-similarity scoring".
    let renames: Vec<&Value> = changes
        .iter()
        .filter(|ev| ev.get("action").and_then(Value::as_str) == Some("renamed"))
        .collect();
    assert_eq!(
        renames.len(),
        1,
        "wide-window changes_since must surface exactly one renamed event; \
         got {}. changes={:#?}",
        renames.len(),
        changes,
    );
    let only_rename = renames[0];
    assert_eq!(
        only_rename.get("from_id").and_then(Value::as_str),
        Some(rename_id.as_str()),
        "renamed.from_id drifted: {only_rename}",
    );
    assert_eq!(
        only_rename.get("to_id").and_then(Value::as_str),
        Some(new_id.as_str()),
        "renamed.to_id drifted: {only_rename}",
    );

    // Unrelated entities must NOT surface as `renamed` (the F16
    // class of false-positive). Their action should be `updated`
    // (other_a was updated, other_b was untouched and so doesn't
    // appear at all).
    for ev in changes {
        let action = ev.get("action").and_then(Value::as_str).unwrap_or_default();
        if action == "renamed" {
            continue;
        }
        let id = ev.get("id").and_then(Value::as_str).unwrap_or_default();
        let from_id = ev
            .get("from_id")
            .and_then(Value::as_str)
            .unwrap_or_default();
        let to_id = ev.get("to_id").and_then(Value::as_str).unwrap_or_default();
        assert_ne!(id, other_b.as_str(), "other_b mispaired: {ev}");
        assert_ne!(from_id, other_b.as_str(), "other_b as rename source: {ev}");
        assert_ne!(to_id, other_b.as_str(), "other_b as rename target: {ev}");
    }
}

/// `include_notes: false` strips notes + memstead_ref from the
/// wire response even though the engine populates them
/// unconditionally — the parameter is renderer-side filtering, not
/// an engine-side trigger.
#[test]
fn full_memstead_changes_since_include_notes_false_strips_notes_and_memstead_ref() {
    let tmp = TempDir::new().unwrap();
    seed_full_workspace(tmp.path(), &[("demo", "default@1.0.0")]);

    let mut harness = WireHarness::start(tmp.path());
    let _ = create_and_get_id_hash(&mut harness, "Noteless");

    let empty_tree = "4b825dc642cb6eb9a060e54bf8d69288fbee4904";
    let result = harness.call_tool(
        "memstead_changes_since",
        json!({ "mem": "demo", "since": empty_tree, "include_notes": false }),
    );
    let _ = assert_success_envelope(&result);
    let body = result
        .get("structuredContent")
        .expect("structuredContent missing");
    assert!(
        body.get("notes").is_none(),
        "include_notes: false must strip notes[] from the wire: {body}",
    );
    assert!(
        body.get("memstead_ref").is_none(),
        "include_notes: false must strip memstead_ref from the wire: {body}",
    );
}

/// `memstead_entity` ships
/// rendered markdown on the text channel and the structured
/// envelope on `structured_content`. With an empty structured
/// channel, agents wanting `_hash`, sections, or
/// relations would parse the text-channel markdown by string-scraping.
#[test]
fn full_memstead_entity_returns_structured_envelope_alongside_markdown() {
    let tmp = TempDir::new().unwrap();
    seed_full_workspace(tmp.path(), &[("demo", "default@1.0.0")]);

    let mut harness = WireHarness::start(tmp.path());
    let (id, hash) = create_and_get_id_hash(&mut harness, "Structured Subject");

    let result = harness.call_tool("memstead_entity", json!({ "id": id }));
    let _ = assert_success_envelope(&result);

    // Text channel: rendered markdown — preserved for terminal /
    // prose consumers.
    let text = result
        .get("content")
        .and_then(Value::as_array)
        .and_then(|arr| arr.first())
        .and_then(|c| c.get("text"))
        .and_then(Value::as_str)
        .expect("entity response missing text-channel markdown");
    assert!(
        text.contains("# Structured Subject"),
        "text channel must carry rendered markdown: {text}",
    );

    // Structured channel: typed envelope — agents branch on fields
    // without parsing the text channel.
    let body = result
        .get("structuredContent")
        .expect("memstead_entity must populate structured_content");
    assert_eq!(
        body.get("_hash").and_then(Value::as_str),
        Some(hash.as_str()),
        "structured._hash must match the create response's content_hash: {body}",
    );
    assert_eq!(body.get("id").and_then(Value::as_str), Some(id.as_str()),);
    assert_eq!(body.get("mem").and_then(Value::as_str), Some("demo"),);
    assert_eq!(
        body.get("type").and_then(Value::as_str),
        Some("spec"),
        "structured.type drifted: {body}",
    );
    assert!(
        body.get("sections").and_then(Value::as_object).is_some(),
        "structured.sections must be a JSON object: {body}",
    );
    assert!(
        body.get("relationships")
            .and_then(Value::as_array)
            .is_some(),
        "structured.relationships must be a JSON array: {body}",
    );
    assert!(
        body.get("_tokens").and_then(Value::as_u64).is_some(),
        "structured._tokens must be a non-negative integer: {body}",
    );
}

/// `memstead_search` ships
/// rendered markdown on the text channel and the structured
/// `SearchResultEnvelope` on `structured_content`. Without it,
/// agents would have to parse the markdown prose to recover scores,
/// score breakdowns, or facet counts.
#[test]
fn full_memstead_search_returns_structured_envelope_alongside_markdown() {
    let tmp = TempDir::new().unwrap();
    seed_full_workspace(tmp.path(), &[("demo", "default@1.0.0")]);

    let mut harness = WireHarness::start(tmp.path());
    let _ = create_and_get_id_hash(&mut harness, "Authorization Flow");
    let _ = create_and_get_id_hash(&mut harness, "Anchor Memo");

    let result = harness.call_tool("memstead_search", json!({ "query": { "any": ["Anchor"] } }));
    let _ = assert_success_envelope(&result);

    // Text channel — rendered markdown (rendered prose with scores,
    // headings, etc.).
    let text = result
        .get("content")
        .and_then(Value::as_array)
        .and_then(|arr| arr.first())
        .and_then(|c| c.get("text"))
        .and_then(Value::as_str)
        .expect("search response missing text-channel markdown");
    assert!(
        text.contains("_total:"),
        "text channel must carry rendered markdown frontmatter: {text}",
    );

    // Structured channel — _-prefixed counters at the top level,
    // hits[] with the per-hit shape (score and friends).
    let body = result
        .get("structuredContent")
        .expect("memstead_search must populate structured_content");
    assert!(
        body.get("_total").and_then(Value::as_u64).is_some(),
        "structured._total must be present: {body}",
    );
    assert!(
        body.get("_returned").and_then(Value::as_u64).is_some(),
        "structured._returned must be present: {body}",
    );
    assert!(
        body.get("_offset").and_then(Value::as_u64).is_some(),
        "structured._offset must be present: {body}",
    );
    assert!(
        body.get("_total_tokens").and_then(Value::as_u64).is_some(),
        "structured._total_tokens must be present: {body}",
    );
    let hits = body
        .get("hits")
        .and_then(Value::as_array)
        .expect("structured.hits must be an array");
    assert!(!hits.is_empty(), "expected ≥1 hit: {body}");
    let hit = &hits[0];
    assert!(
        hit.get("id").and_then(Value::as_str).is_some(),
        "hit.id missing: {hit}",
    );
    assert!(
        hit.get("score").and_then(Value::as_f64).is_some(),
        "hit.score must be a float (no precision loss vs engine f32): {hit}",
    );
}

/// `relationships` carry typed shape — `rel_type`, `target`,
/// `source: explicit`, plus optional `description` per posture.
#[test]
fn full_memstead_entity_structured_relationships_carry_typed_shape() {
    let tmp = TempDir::new().unwrap();
    seed_full_workspace(tmp.path(), &[("demo", "default@1.0.0")]);

    let mut harness = WireHarness::start(tmp.path());
    let (from, _) = create_and_get_id_hash(&mut harness, "Rel Source");
    let (to, _) = create_and_get_id_hash(&mut harness, "Rel Target");
    let _ = harness.call_tool(
        "memstead_relate",
        json!({ "relations": [{ "from": from, "to": to, "type": "PART_OF" }] }),
    );

    let result = harness.call_tool("memstead_entity", json!({ "id": from }));
    let body = result
        .get("structuredContent")
        .expect("missing structured_content");
    let relationships = body
        .get("relationships")
        .and_then(Value::as_array)
        .expect("structured.relationships must be an array");
    assert!(
        !relationships.is_empty(),
        "expected ≥1 relationship after relate: {body}",
    );
    let rel = &relationships[0];
    assert_eq!(rel.get("rel_type").and_then(Value::as_str), Some("PART_OF"),);
    assert_eq!(rel.get("target").and_then(Value::as_str), Some(to.as_str()),);
    assert_eq!(
        rel.get("source").and_then(Value::as_str),
        Some("explicit"),
        "structured.relationships[].source pinned to `explicit`: {rel}",
    );
}

/// `include_notes: true` carries the per-commit feed. The
/// rename note must surface alongside the renamed change event,
/// proving the engine populates both from the same walk.
#[test]
fn full_memstead_changes_since_include_notes_true_carries_notes_and_rename_note() {
    let tmp = TempDir::new().unwrap();
    seed_full_workspace(tmp.path(), &[("demo", "default@1.0.0")]);

    let mut harness = WireHarness::start(tmp.path());
    let (id, hash) = create_and_get_id_hash(&mut harness, "Renaming Subject");
    let renamed = harness.call_tool(
        "memstead_rename",
        json!({
            "id": id,
            "new_title": "After Rename",
            "expected_hash": hash,
        }),
    );
    let _ = assert_success_envelope(&renamed);

    let empty_tree = "4b825dc642cb6eb9a060e54bf8d69288fbee4904";
    let feed = harness.call_tool(
        "memstead_changes_since",
        json!({ "mem": "demo", "since": empty_tree, "include_notes": true }),
    );
    let _ = assert_success_envelope(&feed);
    let body = feed
        .get("structuredContent")
        .expect("structuredContent missing");
    let notes = body
        .get("notes")
        .and_then(Value::as_array)
        .expect("include_notes: true must surface notes[]");
    assert!(
        notes
            .iter()
            .any(|n| { n.get("tool_verb").and_then(Value::as_str) == Some("rename") }),
        "rename note missing from notes[]: {body}",
    );
}

// ---------------------------------------------------------------------------
// Stub-family pins — auto-stub create + STUB_NOT_UPDATABLE / STUB_NOT_RENAMABLE
// ---------------------------------------------------------------------------
//
// Stubs are entities present in the store but with no body/type — they
// surface when `memstead_relate` targets an absent id (auto-stub) or when
// a delete demotes an entity with read-only referrers. The typed-stub
// error variants (`STUB_NOT_UPDATABLE`, `STUB_NOT_RENAMABLE`,
// `STUB_CANNOT_RELATE`) tell the agent to promote the stub via
// `memstead_create` before mutating. The auto-stub side rides a
// `AUTO_STUB_CREATED` warning on the relate response.

/// Full pin: same multi-step flow.
#[test]
fn full_auto_stub_then_update_emits_typed_envelope() {
    let tmp = TempDir::new().unwrap();
    seed_full_workspace(tmp.path(), &[("demo", "default@1.0.0")]);

    let mut harness = WireHarness::start(tmp.path());
    let (source, _) = create_and_get_id_hash(&mut harness, "Source");
    let stub_id = "demo--ghost";

    let relate = harness.call_tool(
        "memstead_relate",
        json!({ "relations": [{ "from": source, "to": stub_id, "type": "USES" }] }),
    );
    let _ = assert_success_envelope(&relate);
    let body = relate
        .get("structuredContent")
        .expect("structuredContent missing on relate");
    let warnings = body
        .get("warnings")
        .and_then(Value::as_array)
        .expect("relate-to-absent-target must carry warnings[]");
    let codes: Vec<&str> = warnings
        .iter()
        .filter_map(|w| w.get("code").and_then(Value::as_str))
        .collect();
    assert!(
        codes.contains(&"AUTO_STUB_CREATED"),
        "expected AUTO_STUB_CREATED warning, got codes={codes:?}: {body}"
    );

    let update = harness.call_tool(
        "memstead_update",
        json!({
            "id": stub_id,
            "expected_hash": "",
            "sections": { "identity": "promotion-attempt" },
        }),
    );
    let is_error = update
        .get("isError")
        .and_then(Value::as_bool)
        .unwrap_or(false);
    assert!(is_error, "expected isError on stub update: {update}");
    let structured = update
        .get("structuredContent")
        .expect("structuredContent missing");
    assert_eq!(
        structured.get("code").and_then(Value::as_str),
        Some("STUB_NOT_UPDATABLE"),
        "code drifted: {structured}"
    );
}

/// Full pin: same.
#[test]
fn full_rename_stub_emits_typed_envelope() {
    let tmp = TempDir::new().unwrap();
    seed_full_workspace(tmp.path(), &[("demo", "default@1.0.0")]);

    let mut harness = WireHarness::start(tmp.path());
    let (source, _) = create_and_get_id_hash(&mut harness, "Source");
    let stub_id = "demo--ghost";

    let _ = harness.call_tool(
        "memstead_relate",
        json!({ "relations": [{ "from": source, "to": stub_id, "type": "USES" }] }),
    );

    let rename = harness.call_tool(
        "memstead_rename",
        json!({ "id": stub_id, "new_title": "Promoted", "expected_hash": "" }),
    );
    let is_error = rename
        .get("isError")
        .and_then(Value::as_bool)
        .unwrap_or(false);
    assert!(is_error, "expected isError on stub rename: {rename}");
    let structured = rename
        .get("structuredContent")
        .expect("structuredContent missing");
    assert_eq!(
        structured.get("code").and_then(Value::as_str),
        Some("STUB_NOT_RENAMABLE"),
        "code drifted: {structured}"
    );
}

// ---------------------------------------------------------------------------
// `memstead_relate` STUB_CANNOT_RELATE — relate FROM an auto-stub source
// ---------------------------------------------------------------------------
//
// Stubs have no entity_type and cannot author edges. Bootstrap: relate
// to an absent target → engine auto-stubs that target. Then try to
// relate FROM the stub → STUB_CANNOT_RELATE. The agent's recovery is
// `memstead_create` to promote the stub.

/// Full pin.
#[test]
fn full_relate_from_stub_emits_typed_envelope() {
    let tmp = TempDir::new().unwrap();
    seed_full_workspace(tmp.path(), &[("demo", "default@1.0.0")]);

    let mut harness = WireHarness::start(tmp.path());
    let (source, _) = create_and_get_id_hash(&mut harness, "Real");
    let stub_id = "demo--ghost";

    let _ = harness.call_tool(
        "memstead_relate",
        json!({ "relations": [{ "from": source, "to": stub_id, "type": "USES" }] }),
    );

    let result = harness.call_tool(
        "memstead_relate",
        json!({ "relations": [{ "from": stub_id, "to": source, "type": "USES" }] }),
    );
    let is_error = result
        .get("isError")
        .and_then(Value::as_bool)
        .unwrap_or(false);
    assert!(is_error, "expected isError on relate-from-stub: {result}");
    let structured = result
        .get("structuredContent")
        .expect("structuredContent missing");
    assert_eq!(
        structured.get("code").and_then(Value::as_str),
        Some("STUB_CANNOT_RELATE"),
        "code drifted: {structured}"
    );
}

// ---------------------------------------------------------------------------
// Full-only mem-lifecycle pin — `memstead_mem_create` success
// ---------------------------------------------------------------------------

/// Full pin: with a permissive `[[mem_management.create]]` rule in
/// `workspace.toml`, `memstead_mem_create` succeeds and registers a new
/// mem. Response shape carries the new mem's identity so the agent
/// can chain follow-up mutations.
#[test]
fn full_memstead_mem_create_returns_typed_success_envelope() {
    // The mem-management matcher tests the candidate against the
    // pattern. The candidate is the mem NAME (not the location
    // path) so a wildcard pattern admits any name. The location lives
    // on disk at the operator's discretion.
    const WORKSPACE_TOML_WITH_CREATE_RULE: &str = "\
format = \"memstead-git-branch-2\"\n\
\n\
[persistence_adapter]\n\
name = \"file-two-layer\"\n\
\n\
[[mem_management.create]]\n\
pattern = \"*\"\n\
schemas = [\"default@1.0.0\"]\n\
";

    let tmp = TempDir::new().unwrap();
    seed_full_workspace_with_toml(
        tmp.path(),
        &[("demo", "default@1.0.0")],
        WORKSPACE_TOML_WITH_CREATE_RULE,
    );

    let mut harness = WireHarness::start(tmp.path());
    let result = harness.call_tool(
        "memstead_mem_create",
        json!({
            "name": "fresh",
            "location": "mems/fresh",
            "schema": "default@1.0.0",
        }),
    );
    let _ = assert_success_envelope(&result);
    let body = result
        .get("structuredContent")
        .expect("structuredContent missing on mem_create success");
    // The exact response field set is engine-derived; the pin
    // checks the bare minimum: the new mem's name is echoed back so
    // the agent can chain follow-up mutations against it.
    assert!(
        body.get("name").is_some() || body.get("mem").is_some(),
        "mem_create response missing name/mem: {body}"
    );
}

/// Full pin: with permissive `[[mem_management.create]]` and `.delete]]`
/// rules, `memstead_mem_delete` against an existing mem returns a success
/// envelope. The pin checks the success flag and presence of
/// `structured_content` — exact response fields are engine-derived.
#[test]
fn full_memstead_mem_delete_returns_typed_success_envelope() {
    const WORKSPACE_TOML_WITH_LIFECYCLE_RULES: &str = "\
format = \"memstead-git-branch-2\"\n\
\n\
[persistence_adapter]\n\
name = \"file-two-layer\"\n\
\n\
[[mem_management.create]]\n\
pattern = \"*\"\n\
schemas = [\"default@1.0.0\"]\n\
\n\
[[mem_management.delete]]\n\
pattern = \"*\"\n\
";

    let tmp = TempDir::new().unwrap();
    seed_full_workspace_with_toml(
        tmp.path(),
        &[("demo", "default@1.0.0")],
        WORKSPACE_TOML_WITH_LIFECYCLE_RULES,
    );

    let mut harness = WireHarness::start(tmp.path());

    // Create a fresh mem first so we have something to delete that
    // is not the seeded `demo` (which has a real git-branch ref).
    let create = harness.call_tool(
        "memstead_mem_create",
        json!({
            "name": "ephemeral",
            "location": "mems/ephemeral",
            "schema": "default@1.0.0",
        }),
    );
    let _ = assert_success_envelope(&create);

    // Now delete it. The MCP wrapper hardcodes `delete_files: true`,
    // so this is always destructive.
    let del = harness.call_tool("memstead_mem_delete", json!({ "name": "ephemeral" }));
    let _ = assert_success_envelope(&del);
    assert!(
        del.get("structuredContent").is_some(),
        "mem_delete response missing structuredContent: {del}"
    );
}

/// MCP parity for the CLI
/// F7 regression. `memstead_mem_delete` (always destructive) scrubs the
/// deleted mem's dangling `[cross_mem_links]` grant but PRESERVES
/// the exact-name `[[mem_management.create]]` /
/// `[[mem_management.delete]]` allowlist rules — they are
/// forward-looking permissions for the name. So a follow-up
/// `memstead_mem_create` of the same name succeeds without re-granting.
/// The cross-link grant points OUT of the deleted mem
/// (`ephemeral → demo`) so the delete's own `MEM_REFERENCED_BY_POLICY`
/// gate (which fires only when another mem grants the target) stays
/// clear.
#[test]
fn full_mem_delete_preserves_allowlist_rules_so_recreate_succeeds() {
    const WORKSPACE_TOML: &str = "\
format = \"memstead-git-branch-2\"\n\
\n\
[persistence_adapter]\n\
name = \"file-two-layer\"\n\
\n\
[cross_mem_links]\n\
ephemeral = [\"demo\"]\n\
\n\
[[mem_management.create]]\n\
pattern = \"ephemeral\"\n\
schemas = [\"default@1.0.0\"]\n\
\n\
[[mem_management.delete]]\n\
pattern = \"ephemeral\"\n\
";

    let tmp = TempDir::new().unwrap();
    seed_full_workspace_with_toml(tmp.path(), &[("demo", "default@1.0.0")], WORKSPACE_TOML);

    let mut harness = WireHarness::start(tmp.path());

    // Create `ephemeral` — admitted by the exact-name create rule.
    let create = harness.call_tool(
        "memstead_mem_create",
        json!({
            "name": "ephemeral",
            "location": "mems/ephemeral",
            "schema": "default@1.0.0",
        }),
    );
    let _ = assert_success_envelope(&create);

    // Destructive delete — admitted by the exact-name delete rule.
    let del = harness.call_tool("memstead_mem_delete", json!({ "name": "ephemeral" }));
    let _ = assert_success_envelope(&del);

    // The exact-name create + delete allowlist rules survive the delete.
    let after =
        std::fs::read_to_string(tmp.path().join(".memstead").join("workspace.toml")).unwrap();
    assert_eq!(
        after.matches("pattern = \"ephemeral\"").count(),
        2,
        "delete must preserve the create+delete allowlist rules; got:\n{after}",
    );
    // The deleted mem's own dangling cross-link grant is scrubbed.
    assert!(
        !after.contains("ephemeral = [\"demo\"]"),
        "delete must scrub the deleted mem's dangling cross-link grant; got:\n{after}",
    );

    // Re-create the same name — succeeds with no fresh allow-create.
    let recreate = harness.call_tool(
        "memstead_mem_create",
        json!({
            "name": "ephemeral",
            "location": "mems/ephemeral",
            "schema": "default@1.0.0",
        }),
    );
    let _ = assert_success_envelope(&recreate);
}

/// Item 01 pin: `memstead-mcp --operator-mode` plumbs the bypass through
/// the MCP boundary. With zero `[[mem_management.create]]` /
/// `[[mem_management.delete]]` rules, an operator-mode server can
/// still `memstead_mem_create` and `memstead_mem_delete` a fresh mem;
/// a server booted without the flag against the same workspace
/// returns `MEM_PATH_NOT_ALLOWED` reason=`no_allowlist_configured`.
#[test]
fn full_operator_mode_bypasses_empty_allowlist_via_mcp() {
    // Workspace.toml carries no `[mem_management]` section at all —
    // every agent-mode lifecycle call rejects with the
    // `no_allowlist_configured` envelope. Operator-mode admits the
    // call regardless.
    const WORKSPACE_TOML_NO_RULES: &str = "\
format = \"memstead-git-branch-2\"\n\
\n\
[persistence_adapter]\n\
name = \"file-two-layer\"\n\
";

    let tmp = TempDir::new().unwrap();
    seed_full_workspace_with_toml(
        tmp.path(),
        &[("demo", "default@1.0.0")],
        WORKSPACE_TOML_NO_RULES,
    );

    // Agent-mode: rejected.
    {
        let mut harness = WireHarness::start(tmp.path());
        let agent_attempt = harness.call_tool(
            "memstead_mem_create",
            json!({
                "name": "fresh",
                "location": "mems/fresh",
                "schema": "default@1.0.0",
            }),
        );
        let is_error = agent_attempt
            .get("isError")
            .and_then(Value::as_bool)
            .unwrap_or(false);
        assert!(
            is_error,
            "agent-mode create against empty allowlist must error: {agent_attempt}"
        );
        let structured = agent_attempt
            .get("structuredContent")
            .expect("structuredContent missing on agent-mode envelope");
        assert_eq!(
            structured.get("code").and_then(Value::as_str),
            Some("MEM_PATH_NOT_ALLOWED"),
            "agent-mode rejection must carry MEM_PATH_NOT_ALLOWED: {structured}"
        );
        assert_eq!(
            structured
                .get("details")
                .and_then(|d| d.get("reason"))
                .and_then(Value::as_str),
            Some("no_allowlist_configured"),
            "details.reason drifted: {structured}"
        );
    }

    // Operator-mode: same call succeeds.
    {
        let mut harness = WireHarness::start_with_args(tmp.path(), &["--operator-mode"]);
        let create = harness.call_tool(
            "memstead_mem_create",
            json!({
                "name": "fresh",
                "location": "mems/fresh",
                "schema": "default@1.0.0",
            }),
        );
        let _ = assert_success_envelope(&create);

        // And the matching delete also succeeds — both gates are bypassed.
        let del = harness.call_tool("memstead_mem_delete", json!({ "name": "fresh" }));
        let _ = assert_success_envelope(&del);
    }
}

/// Item 01 pin: `memstead_overview` surfaces the operator-mode posture so
/// anyone reading the engine's output can confirm the bypass is in
/// force. The disclosure lives under `## Lifecycle Namespaces`, where
/// the allowlist policy itself is rendered — colocating the policy
/// and its bypass posture keeps the surface coherent.
#[test]
fn full_memstead_overview_surfaces_operator_mode_bypass() {
    const WORKSPACE_TOML: &str = "\
format = \"memstead-git-branch-2\"\n\
\n\
[persistence_adapter]\n\
name = \"file-two-layer\"\n\
";

    let tmp = TempDir::new().unwrap();
    seed_full_workspace_with_toml(tmp.path(), &[("demo", "default@1.0.0")], WORKSPACE_TOML);

    // Agent-mode overview omits the bypass disclosure.
    {
        let mut harness = WireHarness::start(tmp.path());
        let overview = harness.call_tool("memstead_overview", json!({}));
        let text = assert_success_envelope(&overview);
        assert!(
            !text.contains("--operator-mode"),
            "agent-mode overview must NOT mention operator-mode: {text}"
        );
    }

    // Operator-mode overview names the bypass and the gates it
    // shorts.
    {
        let mut harness = WireHarness::start_with_args(tmp.path(), &["--operator-mode"]);
        let overview = harness.call_tool("memstead_overview", json!({}));
        let text = assert_success_envelope(&overview);
        assert!(
            text.contains("--operator-mode"),
            "operator-mode overview must mention the flag: {text}"
        );
        assert!(
            text.contains("MEM_REFERENCED_BY_POLICY"),
            "operator-mode overview must name the bypassed safeguard: {text}"
        );
    }
}

/// Item 03 pin: `memstead_mem_create` against a mem-repo workspace
/// produces a `mounts.json` whose new git-branch entry carries the
/// fully-qualified `refs/heads/<leaf>` form for the `branch` field.
/// Pre-fix the writer already produced the long form; this pin guards
/// against a regression that re-introduces the short-form drift the
/// older committed `mounts.json` files used to carry (and which made
/// every fresh-workspace rebuild produce noise-only diffs against the
/// legacy shape).
#[test]
fn full_memstead_mem_create_writes_refs_heads_branch_in_mounts_json() {
    const WORKSPACE_TOML_WITH_CREATE_RULE: &str = "\
format = \"memstead-git-branch-2\"\n\
\n\
[persistence_adapter]\n\
name = \"file-two-layer\"\n\
\n\
[[mem_management.create]]\n\
pattern = \"*\"\n\
schemas = [\"default@1.0.0\"]\n\
\n\
[[mem_management.create]]\n\
pattern = \"namespace/*\"\n\
schemas = [\"default@1.0.0\"]\n\
";

    let tmp = TempDir::new().unwrap();
    seed_full_workspace_with_toml(
        tmp.path(),
        &[("demo", "default@1.0.0")],
        WORKSPACE_TOML_WITH_CREATE_RULE,
    );

    let mut harness = WireHarness::start(tmp.path());

    // Flat-layout create — branch_leaf is the bare name.
    let flat = harness.call_tool(
        "memstead_mem_create",
        json!({
            "name": "fresh",
            "location": "mems/fresh",
            "schema": "default@1.0.0",
        }),
    );
    let _ = assert_success_envelope(&flat);

    // Hierarchical paths are first-class. `name = "namespace/scoped"`
    // IS the full identifier — there is no separate `path` wire field.
    let hier = harness.call_tool(
        "memstead_mem_create",
        json!({
            "name": "namespace/scoped",
            "location": "mems/scoped",
            "schema": "default@1.0.0",
        }),
    );
    let _ = assert_success_envelope(&hier);

    let mounts_json_path = tmp
        .path()
        .join(".memstead")
        .join("state")
        .join("mounts.json");
    let on_disk = std::fs::read_to_string(&mounts_json_path)
        .expect("mounts.json must exist after mem_create");
    assert!(
        on_disk.contains("\"branch\": \"refs/heads/fresh\""),
        "flat-layout mem must persist refs/heads/<name>, got: {on_disk}"
    );
    assert!(
        on_disk.contains("\"branch\": \"refs/heads/namespace/scoped\""),
        "hierarchical mem must persist refs/heads/<full-name>, got: {on_disk}"
    );
    // `mounts.json` carries the full hierarchical name as the mem
    // identifier (not the bare leaf).
    assert!(
        on_disk.contains("\"mem\": \"namespace/scoped\""),
        "hierarchical mem identity is the full path in mounts.json, got: {on_disk}"
    );
}

// ---------------------------------------------------------------------------
// Typed envelope coverage for description-posture + wikilink-without-
// relation errors. Both used to fall through to the wildcard
// `_ => INTERNAL` arm in `engine_err_unified`; the match is now
// exhaustive, and these reproducers pin the typed wire shape.
// ---------------------------------------------------------------------------

/// `memstead_relate` on a rel-type whose schema declares
/// `per_edge_description: forbidden` (REFERENCES in default@1.0.0) with a
/// description ships `code: DESCRIPTION_NOT_PERMITTED` + structured
/// `details.{rel_type,from_id,to_id}` — not a bare `INTERNAL`.
#[test]
fn full_memstead_relate_with_forbidden_description_emits_typed_envelope() {
    let tmp = TempDir::new().unwrap();
    seed_full_workspace(tmp.path(), &[("demo", "default@1.0.0")]);

    let mut harness = WireHarness::start(tmp.path());
    let (from, _) = create_and_get_id_hash(&mut harness, "Forbid Source");
    let (to, _) = create_and_get_id_hash(&mut harness, "Forbid Target");

    let result = harness.call_tool(
        "memstead_relate",
        json!({ "relations": [{ "from": from,
            "to": to,
            "type": "REFERENCES",
            "description": "should be refused" }] }),
    );
    let is_error = result
        .get("isError")
        .and_then(Value::as_bool)
        .unwrap_or(false);
    assert!(
        is_error,
        "expected isError=true on description-forbidden relate: {result}",
    );
    let structured = result
        .get("structuredContent")
        .expect("structuredContent missing on description-forbidden relate");
    assert_eq!(
        structured.get("code").and_then(Value::as_str),
        Some("DESCRIPTION_NOT_PERMITTED"),
        "wire code regressed to non-typed: {structured}",
    );
    let details = structured
        .get("details")
        .expect("DESCRIPTION_NOT_PERMITTED must carry details");
    assert_eq!(
        details.get("rel_type").and_then(Value::as_str),
        Some("REFERENCES"),
        "details.rel_type drifted: {details}",
    );
    assert_eq!(
        details.get("from_id").and_then(Value::as_str),
        Some(from.as_str()),
        "details.from_id drifted: {details}",
    );
    assert_eq!(
        details.get("to_id").and_then(Value::as_str),
        Some(to.as_str()),
        "details.to_id drifted: {details}",
    );
}

/// `memstead_update` that introduces a body wiki-link without a backing relation
/// ships `code: WIKILINK_WITHOUT_RELATION` + structured `details.{from_id,
/// missing[]}` listing each unbacked link's `section_key` and `target_id`.
/// A bare `INTERNAL` here would train agents to treat the
/// recoverable input error as an engine bug.
#[test]
fn full_memstead_update_body_wikilink_auto_synthesises_alias_relation() {
    // Under the default schema's `alias_target_rel_type: REFERENCES`
    // pointer, a body wiki-link no longer trips `WIKILINK_WITHOUT_RELATION`:
    // the alias-synthesis pass emits the REFERENCES relation first,
    // the mutation succeeds, and the relation is observable on the
    // entity afterward. Schemas without the pointer continue to surface
    // the typed `WIKILINK_WITHOUT_RELATION` envelope — that path is
    // covered by a fixture-schema test in the engine crate.
    let tmp = TempDir::new().unwrap();
    seed_full_workspace(tmp.path(), &[("demo", "default@1.0.0")]);

    let mut harness = WireHarness::start(tmp.path());
    let (source, source_hash) = create_and_get_id_hash(&mut harness, "WikiSource");
    let (target, _) = create_and_get_id_hash(&mut harness, "WikiTarget");

    let result = harness.call_tool(
        "memstead_update",
        json!({
            "id": source,
            "expected_hash": source_hash,
            "sections": {
                "identity": format!("see [[{target}]] for context"),
            },
        }),
    );
    let is_error = result
        .get("isError")
        .and_then(Value::as_bool)
        .unwrap_or(false);
    assert!(
        !is_error,
        "alias-synthesis must satisfy the validator and let the body land: {result}",
    );

    // The entity now carries the auto-emitted REFERENCES relation.
    let entity = harness.call_tool("memstead_entity", json!({ "id": source }));
    let relationships = entity
        .get("structuredContent")
        .and_then(|sc| sc.get("relationships"))
        .and_then(Value::as_array)
        .expect("relationships[] missing from structured envelope");
    let has_ref = relationships.iter().any(|r| {
        r.get("rel_type").and_then(Value::as_str) == Some("REFERENCES")
            && r.get("target").and_then(Value::as_str) == Some(target.as_str())
    });
    assert!(
        has_ref,
        "REFERENCES → target must surface in relationships[]; got {relationships:?}",
    );
}

// ---------------------------------------------------------------------------
// MCP wire tests for the six
// `memstead_workspace_*` tools wrapping the engine-located
// `workspace_config_edit` writers. Closes the F7 dynamic-mem-
// lifecycle gap from MCP — an agent can now grant, mutate, revoke,
// and delete without dropping to CLI.
// ---------------------------------------------------------------------------

const TIER_C_WORKSPACE_TOML: &str = "\
format = \"memstead-git-branch-2\"\n\
\n\
[persistence_adapter]\n\
name = \"file-two-layer\"\n\
\n\
[[mem_management.create]]\n\
pattern = \"*\"\n\
schemas = [\"default@1.0.0\"]\n\
\n\
[[mem_management.delete]]\n\
pattern = \"*\"\n\
";

/// `memstead_workspace_grant_cross_link` writes the
/// `[cross_mem_links]` section. Round-trip: invoke the tool, read
/// `.memstead/workspace.toml` back, assert the grant appears.
#[test]
fn full_memstead_workspace_grant_cross_link_round_trip() {
    let tmp = TempDir::new().unwrap();
    seed_full_workspace_with_toml(
        tmp.path(),
        &[("source", "default@1.0.0"), ("target", "default@1.0.0")],
        TIER_C_WORKSPACE_TOML,
    );

    let mut harness = WireHarness::start(tmp.path());
    let result = harness.call_tool(
        "memstead_workspace_grant_cross_link",
        json!({ "from": "source", "to": "target" }),
    );
    let _ = assert_success_envelope(&result);

    let body =
        std::fs::read_to_string(tmp.path().join(".memstead").join("workspace.toml")).unwrap();
    assert!(
        body.contains("[cross_mem_links]"),
        "grant must write the cross_mem_links section; got:\n{body}",
    );
    assert!(
        body.contains("source = [\"target\"]"),
        "grant must record the source → [target] entry; got:\n{body}",
    );
}

/// `memstead_workspace_grant_cross_link` is idempotent.
/// Re-granting an existing grant returns success with
/// `GRANT_ALREADY_PRESENT` warning and leaves the file unchanged.
#[test]
fn full_memstead_workspace_grant_cross_link_idempotent_with_warning() {
    let tmp = TempDir::new().unwrap();
    seed_full_workspace_with_toml(
        tmp.path(),
        &[("source", "default@1.0.0"), ("target", "default@1.0.0")],
        TIER_C_WORKSPACE_TOML,
    );
    let mut harness = WireHarness::start(tmp.path());
    let _ = harness.call_tool(
        "memstead_workspace_grant_cross_link",
        json!({ "from": "source", "to": "target" }),
    );
    let body_before =
        std::fs::read_to_string(tmp.path().join(".memstead").join("workspace.toml")).unwrap();
    let result = harness.call_tool(
        "memstead_workspace_grant_cross_link",
        json!({ "from": "source", "to": "target" }),
    );
    let text = assert_success_envelope(&result);
    let body_after =
        std::fs::read_to_string(tmp.path().join(".memstead").join("workspace.toml")).unwrap();
    assert_eq!(
        body_before, body_after,
        "duplicate grant must not rewrite the file",
    );
    let structured = result
        .get("structuredContent")
        .expect("structuredContent missing");
    let warnings = structured
        .get("warnings")
        .and_then(Value::as_array)
        .expect("warnings array missing");
    assert!(
        warnings
            .iter()
            .any(|w| w.get("code").and_then(Value::as_str) == Some("GRANT_ALREADY_PRESENT")),
        "duplicate grant must emit GRANT_ALREADY_PRESENT in the warnings array; got:\n{structured}\n(text: {text})",
    );
}

/// `memstead_workspace_revoke_cross_link` of an absent grant
/// is idempotent: returns success with `GRANT_NOT_FOUND` warning.
#[test]
fn full_memstead_workspace_revoke_cross_link_idempotent_when_absent() {
    let tmp = TempDir::new().unwrap();
    seed_full_workspace_with_toml(
        tmp.path(),
        &[("source", "default@1.0.0"), ("target", "default@1.0.0")],
        TIER_C_WORKSPACE_TOML,
    );
    let mut harness = WireHarness::start(tmp.path());
    let result = harness.call_tool(
        "memstead_workspace_revoke_cross_link",
        json!({ "from": "source", "to": "target" }),
    );
    let _ = assert_success_envelope(&result);
    let structured = result
        .get("structuredContent")
        .expect("structuredContent missing");
    let warnings = structured
        .get("warnings")
        .and_then(Value::as_array)
        .expect("warnings array missing");
    assert!(
        warnings
            .iter()
            .any(|w| w.get("code").and_then(Value::as_str) == Some("GRANT_NOT_FOUND")),
        "no-op revoke must emit GRANT_NOT_FOUND in the warnings array; got:\n{structured}",
    );
}

/// `memstead_workspace_allow_create` writes a new rule.
/// Round-trip: invoke the tool, parse the workspace TOML, assert
/// the new rule appears in `[[mem_management.create]]`.
#[test]
fn full_memstead_workspace_allow_create_round_trip() {
    // Seed with empty rules — exercise the "append first rule" path.
    const EMPTY_TOML: &str = "\
format = \"memstead-git-branch-2\"\n\
\n\
[persistence_adapter]\n\
name = \"file-two-layer\"\n\
";
    let tmp = TempDir::new().unwrap();
    seed_full_workspace_with_toml(tmp.path(), &[("seed", "default@1.0.0")], EMPTY_TOML);

    let mut harness = WireHarness::start(tmp.path());
    let result = harness.call_tool(
        "memstead_workspace_allow_create",
        json!({
            "pattern": "exec-*",
            "schemas": ["default@1.0.0"],
        }),
    );
    let _ = assert_success_envelope(&result);

    let body =
        std::fs::read_to_string(tmp.path().join(".memstead").join("workspace.toml")).unwrap();
    assert!(
        body.contains("[[mem_management.create]]"),
        "allow_create must write the section header; got:\n{body}",
    );
    assert!(
        body.contains("pattern = \"exec-*\""),
        "allow_create must record the pattern; got:\n{body}",
    );
}

/// MCP F3 — re-adding an existing `allow_create` pattern with a
/// different `schemas` set is refused with `RULE_EXISTS_SCHEMAS_DIFFER`
/// (not a deceptive success echoing a change that did not land); the
/// stored pins are unchanged, and an identical re-add stays the no-op.
#[test]
fn full_allow_create_differing_schemas_refused_stored_unchanged() {
    const EMPTY_TOML: &str = "\
format = \"memstead-git-branch-2\"\n\
\n\
[persistence_adapter]\n\
name = \"file-two-layer\"\n\
";
    let tmp = TempDir::new().unwrap();
    seed_full_workspace_with_toml(tmp.path(), &[("seed", "default@1.0.0")], EMPTY_TOML);

    let mut harness = WireHarness::start(tmp.path());

    // First add pins `scratch` to software@0.1.0.
    let first = harness.call_tool(
        "memstead_workspace_allow_create",
        json!({ "pattern": "scratch", "schemas": ["software@0.1.0"] }),
    );
    let _ = assert_success_envelope(&first);

    // Re-add with a different schema set → typed refusal, not success.
    let differ = harness.call_tool(
        "memstead_workspace_allow_create",
        json!({ "pattern": "scratch", "schemas": ["nonexistent@9.9.9"] }),
    );
    assert!(
        differ
            .get("isError")
            .and_then(Value::as_bool)
            .unwrap_or(false),
        "differing-schemas re-add must be an error envelope: {differ}",
    );
    let structured = differ
        .get("structuredContent")
        .expect("structured payload present");
    assert_eq!(
        structured["code"], "RULE_EXISTS_SCHEMAS_DIFFER",
        "payload: {structured}"
    );
    assert_eq!(
        structured["details"]["stored_schemas"],
        json!(["software@0.1.0"]),
        "refusal names the stored schemas: {structured}",
    );
    assert_eq!(
        structured["details"]["requested_schemas"],
        json!(["nonexistent@9.9.9"]),
        "refusal names the requested schemas: {structured}",
    );
    assert!(
        structured["details"]["recovery"]
            .as_str()
            .is_some_and(|s| s.contains("revoke")),
        "refusal points at the revoke-then-readd recovery: {structured}",
    );

    // The stored rule is unchanged — still software@0.1.0.
    let body =
        std::fs::read_to_string(tmp.path().join(".memstead").join("workspace.toml")).unwrap();
    assert!(
        body.contains("software@0.1.0"),
        "stored pins stay put; got:\n{body}"
    );
    assert!(
        !body.contains("nonexistent@9.9.9"),
        "rejected pins not written; got:\n{body}"
    );

    // An identical re-add is still the idempotent no-op (success).
    let same = harness.call_tool(
        "memstead_workspace_allow_create",
        json!({ "pattern": "scratch", "schemas": ["software@0.1.0"] }),
    );
    let _ = assert_success_envelope(&same);
}

/// Dynamic mem lifecycle end-to-end via MCP only. Mirrors the
/// workflow named
/// in the tool descriptions: create a target mem, grant the
/// source mem permission to link into it, revoke the grant, then
/// delete the target. No CLI calls.
#[test]
fn full_f7_dynamic_mem_lifecycle_completes_via_mcp_only() {
    let tmp = TempDir::new().unwrap();
    seed_full_workspace_with_toml(
        tmp.path(),
        &[("source", "default@1.0.0")],
        TIER_C_WORKSPACE_TOML,
    );

    let mut harness = WireHarness::start_with_args(tmp.path(), &["--operator-mode"]);

    // 1. Create the target mem.
    let create = harness.call_tool(
        "memstead_mem_create",
        json!({
            "name": "target",
            "location": "mems/target",
            "schema": "default@1.0.0",
        }),
    );
    let _ = assert_success_envelope(&create);

    // 2. Grant source → target permission.
    let grant = harness.call_tool(
        "memstead_workspace_grant_cross_link",
        json!({ "from": "source", "to": "target" }),
    );
    let _ = assert_success_envelope(&grant);

    // 3. Revoke the grant before deleting (otherwise step 4 would
    //    refuse with MEM_REFERENCED_BY_POLICY — the safeguard the
    //    policy-check gates on delete_files=true).
    let revoke = harness.call_tool(
        "memstead_workspace_revoke_cross_link",
        json!({ "from": "source", "to": "target" }),
    );
    let _ = assert_success_envelope(&revoke);

    // 4. Delete the target mem. delete_files=true now succeeds
    //    because the cross-link grant was revoked in step 3.
    let delete = harness.call_tool("memstead_mem_delete", json!({ "name": "target" }));
    let _ = assert_success_envelope(&delete);
}

// ---------------------------------------------------------------------------
// Friction ledger (agent-trust plan 08) — the dual-surface fixture.
// ---------------------------------------------------------------------------

/// One fixture drives both surfaces: a refused MCP call (through the
/// REAL dispatch seam — the spawned binary's `call_tool`) and a
/// refused CLI call each append one ledger entry (values from closed
/// engine-defined vocabularies only — the module's privacy rule);
/// successful calls on both surfaces append nothing; the wire-served
/// `include: ["friction"]` axis reports the combined counts.
///
/// The CLI binary is resolved from the mcp binary's target directory —
/// both are built by the canonical workspace test surface
/// (`run-tests.sh`, workspace-wide nextest).
#[test]
fn friction_ledger_records_both_surfaces_and_serves_the_axis() {
    let tmp = TempDir::new().unwrap();
    seed_empty_workspace(tmp.path());
    let ledger_path = tmp
        .path()
        .join(".memstead")
        .join("state")
        .join("friction")
        .join("refusals.jsonl");
    let entries = |path: &Path| -> Vec<Value> {
        std::fs::read_to_string(path)
            .unwrap_or_default()
            .lines()
            .map(|l| serde_json::from_str(l).expect("every ledger line parses"))
            .collect()
    };

    let cli_bin = Path::new(memstead_mcp_bin())
        .parent()
        .expect("binary has a parent dir")
        .join("memstead");
    assert!(
        cli_bin.exists(),
        "memstead CLI binary not built — run the workspace test surface (run-tests.sh)"
    );

    // Refused MCP call through the real wire: unknown mem.
    let mut harness = WireHarness::start(tmp.path());
    let refused = harness.call_tool(
        "memstead_entity",
        json!({ "id": "ghost--entity", "sections": [] }),
    );
    assert_eq!(refused["isError"], true, "{refused}");
    let after_mcp = entries(&ledger_path);
    assert_eq!(after_mcp.len(), 1, "one entry per refused MCP call");
    assert_eq!(after_mcp[0]["surface"], "mcp");
    assert_eq!(after_mcp[0]["verb"], "memstead_entity");
    assert_eq!(
        after_mcp[0]["code"], refused["structuredContent"]["code"],
        "ledger code matches the served refusal"
    );
    assert!(after_mcp[0]["ts"].as_u64().unwrap() > 0);

    // Refused CLI call against the SAME workspace/ledger.
    let out = Command::new(&cli_bin)
        .current_dir(tmp.path())
        .args(["--json", "entity", "ghost--entity"])
        .output()
        .expect("run memstead CLI");
    assert!(!out.status.success(), "CLI fixture call must refuse");
    let after_cli = entries(&ledger_path);
    assert_eq!(after_cli.len(), 2, "one entry per refused CLI call");
    assert_eq!(after_cli[1]["surface"], "cli");
    assert_eq!(after_cli[1]["verb"], "entity");

    // Successful calls on both surfaces append nothing.
    let ok = harness.call_tool("memstead_health", json!({}));
    assert!(ok["isError"] != true, "{ok}");
    let ok_cli = Command::new(&cli_bin)
        .current_dir(tmp.path())
        .args(["--json", "health"])
        .output()
        .expect("run memstead CLI");
    assert!(ok_cli.status.success());
    assert_eq!(
        entries(&ledger_path).len(),
        2,
        "successful calls append nothing"
    );

    // The wire-served include axis reports the combined counts.
    let served = harness.call_tool("memstead_health", json!({ "include": ["friction"] }));
    assert!(served["isError"] != true, "{served}");
    let axis = &served["structuredContent"]["friction"];
    assert_eq!(axis["total"], 2, "{served}");
    assert_eq!(axis["by_verb"]["mcp:memstead_entity"], 1);
    assert_eq!(axis["by_verb"]["cli:entity"], 1);
    assert_eq!(axis["recent_24h"]["total"], 2);
}

// ---------------------------------------------------------------------------
// Negative findings (agent-trust plan 10) — the fourth ingest type.
// ---------------------------------------------------------------------------

/// ingest@0.5.0's `negative_finding`: a conformant entity writes via
/// MCP and via the CLI against the same process mem; malformed
/// variants refuse with the standard typed conformance errors; and
/// the type's leaf declaration keeps edge-less findings out of the
/// orphan axis (they surface as a leaf population instead).
#[test]
fn negative_finding_writes_on_both_surfaces_and_is_leaf_exempt() {
    let tmp = TempDir::new().unwrap();
    seed_full_workspace(tmp.path(), &[("proc", "ingest@0.5.0")]);
    let mut harness = WireHarness::start(tmp.path());

    // Legal via MCP: all three required sections.
    let ok = harness.call_tool(
        "memstead_create",
        json!({
            "title": "No rollback runbook in the source tree",
            "entity_type": "negative_finding",
            "mem": "proc",
            "sections": {
                "sought": "A rollback runbook for failed deploys.",
                "search_path": "Full read of docs/ops; grep for rollback and revert across docs/.",
                "finding": "Nothing — deploys are documented forward-only."
            }
        }),
    );
    assert!(
        ok["isError"] != true,
        "legal negative_finding must land: {ok}"
    );
    assert_eq!(
        ok["structuredContent"]["id"], "proc--no-rollback-runbook-in-the-source-tree",
        "{ok}"
    );

    // Illegal via MCP: missing required sections → typed refusal.
    let missing = harness.call_tool(
        "memstead_create",
        json!({
            "title": "Half a finding",
            "entity_type": "negative_finding",
            "mem": "proc",
            "sections": { "sought": "Something." }
        }),
    );
    assert_eq!(missing["isError"], true, "{missing}");
    assert_eq!(
        missing["structuredContent"]["code"], "MISSING_REQUIRED_SECTION",
        "{missing}"
    );

    // CLI against the SAME workspace: legal write.
    let cli_bin = Path::new(memstead_mcp_bin())
        .parent()
        .expect("binary has a parent dir")
        .join("memstead");
    assert!(cli_bin.exists(), "memstead CLI binary not built");
    let out = Command::new(&cli_bin)
        .current_dir(tmp.path())
        .args([
            "--json",
            "create",
            "--mem",
            "proc",
            "--title",
            "No SLA stated for the batch queue",
            "--type",
            "negative_finding",
            "--section",
            "sought=A latency or delivery SLA for the batch queue.",
            "--section",
            "search_path=Skim of the queue chapter; grep for SLA and latency across docs/.",
            "--section",
            "finding=Nothing — the queue is documented without service guarantees.",
        ])
        .output()
        .expect("run memstead CLI");
    assert!(
        out.status.success(),
        "legal CLI negative_finding must land: {}",
        String::from_utf8_lossy(&out.stdout)
    );

    // CLI illegal variant: unknown section → typed refusal.
    let bad = Command::new(&cli_bin)
        .current_dir(tmp.path())
        .args([
            "--json",
            "create",
            "--mem",
            "proc",
            "--title",
            "Bad finding",
            "--type",
            "negative_finding",
            "--section",
            "sought=X.",
            "--section",
            "search_path=Y.",
            "--section",
            "finding=Z.",
            "--section",
            "bogus_section=nope",
        ])
        .output()
        .expect("run memstead CLI");
    assert!(!bad.status.success());
    let body: Value = serde_json::from_slice(&bad.stdout).expect("CLI --json refusal parses");
    assert_eq!(body["code"], "UNKNOWN_SECTION", "{body}");

    // Leaf exemption: both findings are edge-less, yet the orphan
    // axis lists neither — they surface as the leaf population.
    let health = harness.call_tool("memstead_health", json!({ "include": ["orphans"] }));
    assert!(health["isError"] != true, "{health}");
    let orphans = serde_json::to_string(&health["structuredContent"]["orphans"]).unwrap();
    assert!(
        !orphans.contains("no-rollback-runbook") && !orphans.contains("no-sla-stated"),
        "leaf-typed negative findings must not appear as orphans: {orphans}"
    );
    let leaf = &health["structuredContent"]["leaf_entities_by_type"];
    assert_eq!(leaf["ingest@0.5.0:negative_finding"], 2, "{health}");
}

/// The `open_questions` axis over the wire (agent-trust plan 11):
/// include-gated (absent without the include), an empty workspace
/// serves an empty axis rather than an error, no leaf is `INTERNAL`,
/// and an unknown `mem` scope refuses typed.
#[test]
fn open_questions_axis_is_include_gated_and_refuses_unknown_mem_typed() {
    let tmp = TempDir::new().unwrap();
    seed_full_workspace(tmp.path(), &[("specs", "default@1.3.0")]);
    let mut harness = WireHarness::start(tmp.path());

    // Without the include: no axis key.
    let plain = harness.call_tool("memstead_health", json!({}));
    assert!(plain["isError"] != true, "{plain}");
    assert!(
        plain["structuredContent"].get("open_questions").is_none(),
        "axis must be include-gated: {plain}"
    );

    // With the include on a hole-free mem: an empty axis, not an error.
    let served = harness.call_tool("memstead_health", json!({ "include": ["open_questions"] }));
    assert!(served["isError"] != true, "{served}");
    let axis = &served["structuredContent"]["open_questions"];
    assert_eq!(axis["_item_cap"], 20, "{served}");
    assert_eq!(axis["specs"]["total_open"], 0, "{served}");
    assert_eq!(axis["specs"]["stubs"]["count"], 0);
    assert!(
        !serde_json::to_string(&served)
            .unwrap()
            .contains("\"INTERNAL\""),
        "no leaf of the axis is INTERNAL: {served}"
    );

    // Unknown mem scope refuses typed.
    let ghost = harness.call_tool(
        "memstead_health",
        json!({ "include": ["open_questions"], "mem": "ghost" }),
    );
    assert_eq!(ghost["isError"], true, "{ghost}");
    assert_eq!(ghost["structuredContent"]["code"], "UNKNOWN_MEM", "{ghost}");
}

/// The `stale_derivations` axis over the wire (agent-trust plan 12):
/// include-gated (absent without the include), a mem with no declared
/// derivation rel-types serves an empty list rather than an error, no
/// leaf is `INTERNAL`, and an unknown `mem` scope refuses typed.
#[test]
fn stale_derivations_axis_is_include_gated_and_refuses_unknown_mem_typed() {
    let tmp = TempDir::new().unwrap();
    seed_full_workspace(tmp.path(), &[("specs", "default@1.3.0")]);
    let mut harness = WireHarness::start(tmp.path());

    let plain = harness.call_tool("memstead_health", json!({}));
    assert!(plain["isError"] != true, "{plain}");
    assert!(
        plain["structuredContent"]
            .get("stale_derivations")
            .is_none(),
        "axis must be include-gated: {plain}"
    );

    let served = harness.call_tool(
        "memstead_health",
        json!({ "include": ["stale_derivations"] }),
    );
    assert!(served["isError"] != true, "{served}");
    let axis = &served["structuredContent"]["stale_derivations"];
    assert_eq!(
        axis["specs"],
        json!([]),
        "undeclared schema → empty list: {served}"
    );
    assert!(
        !serde_json::to_string(&served)
            .unwrap()
            .contains("\"INTERNAL\""),
        "no leaf is INTERNAL: {served}"
    );

    let ghost = harness.call_tool(
        "memstead_health",
        json!({ "include": ["stale_derivations"], "mem": "ghost" }),
    );
    assert_eq!(ghost["isError"], true, "{ghost}");
    assert_eq!(ghost["structuredContent"]["code"], "UNKNOWN_MEM", "{ghost}");
}

// ---------------------------------------------------------------------------
// Provenance at mutation (agent-trust plan 13) — the record half.
// ---------------------------------------------------------------------------

/// The checks axis serves the four derived states, and the
/// independence gate refuses to manufacture identity from transport:
/// the recorded `(actor, client)` pair names the surface a record
/// arrived through, not who acted, so until a caller-declared
/// identity exists (caller-identity follow-up) every ok-checked
/// entity is `unconfirmable` — same-surface author+check is never
/// `self_checked`, cross-surface author/check is never
/// `confirmed_independent`. Both categories stay in the wire shape
/// as explicit empties.
#[test]
fn checks_health_axis_serves_unconfirmable_without_caller_identity() {
    let tmp = TempDir::new().unwrap();
    seed_full_workspace(tmp.path(), &[("specs", "default@1.3.0")]);
    let mut harness = WireHarness::start(tmp.path());
    let cli_bin = Path::new(memstead_mcp_bin())
        .parent()
        .expect("binary has a parent dir")
        .join("memstead");

    // Four entities, all authored via MCP (same recorded author
    // identity: agent + the harness client).
    for title in [
        "Alpha Claim",
        "Beta Claim",
        "Gamma Claim",
        "Delta Claim",
        "Epsilon Claim",
        "Zeta Claim",
    ] {
        let created = harness.call_tool(
            "memstead_create",
            json!({
                "title": title,
                "entity_type": "spec",
                "mem": "specs",
                "sections": { "identity": "I.", "purpose": "P." },
                "role": "author"
            }),
        );
        assert!(created["isError"] != true, "{created}");
    }

    // Alpha: ok-checked via MCP as checker — same transport as the
    // author, but transport is not identity: without a
    // caller-declared identity (caller-identity follow-up) the gate
    // cannot establish sameness → unconfirmable.
    let r = harness.call_tool(
        "memstead_check",
        json!({ "entity": "specs--alpha-claim", "verdict": "ok", "role": "checker" }),
    );
    assert!(r["isError"] != true, "{r}");

    // Beta: ok-checked via the CLI as checker — a different recorded
    // transport pair (cli + memstead-cli client), which does NOT
    // establish a different actor → unconfirmable, never a false
    // acquittal via transport.
    let out = Command::new(&cli_bin)
        .current_dir(tmp.path())
        .args([
            "--json",
            "--role",
            "checker",
            "check",
            "specs--beta-claim",
            "--verdict",
            "ok",
        ])
        .output()
        .expect("run memstead CLI check");
    assert!(
        out.status.success(),
        "{}",
        String::from_utf8_lossy(&out.stdout)
    );

    // Gamma: ok-checked with NO role — records honestly, but an
    // unspecified-role check cannot confirm independence.
    let r = harness.call_tool(
        "memstead_check",
        json!({ "entity": "specs--gamma-claim", "verdict": "ok" }),
    );
    assert!(r["isError"] != true, "{r}");

    // Epsilon: ok-checked, then edited — the axis serves check_stale.
    let r = harness.call_tool(
        "memstead_check",
        json!({ "entity": "specs--epsilon-claim", "verdict": "ok", "role": "checker" }),
    );
    assert!(r["isError"] != true, "{r}");
    let read = harness.call_tool("memstead_entity", json!({ "id": "specs--epsilon-claim" }));
    let eps_hash = read["structuredContent"]["_hash"]
        .as_str()
        .unwrap()
        .to_string();
    let r = harness.call_tool(
        "memstead_update",
        json!({
            "id": "specs--epsilon-claim",
            "expected_hash": eps_hash,
            "sections": { "purpose": "P2." },
            "role": "author"
        }),
    );
    assert!(r["isError"] != true, "{r}");

    // Zeta: failed check — the axis serves check_failed.
    let r = harness.call_tool(
        "memstead_check",
        json!({ "entity": "specs--zeta-claim", "verdict": "failed", "role": "checker" }),
    );
    assert!(r["isError"] != true, "{r}");

    // Delta stays never-checked.
    let health = harness.call_tool("memstead_health", json!({ "include": ["checks"] }));
    assert!(health["isError"] != true, "{health}");
    let axis = &health["structuredContent"]["checks"]["specs"];
    assert_eq!(axis["checked_ok"], 3, "{axis}");
    assert_eq!(axis["check_stale"], 1, "{axis}");
    assert_eq!(axis["check_failed"], 1, "{axis}");
    assert!(axis["never_checked"].as_u64().unwrap() >= 1, "{axis}");
    let gate = &axis["independence"];
    // Transport is not identity: until a caller-declared identity
    // exists (caller-identity follow-up) every ok-checked entity is
    // unconfirmable; self_checked / confirmed_independent stay as
    // categories whose empty lists are a statement.
    assert_eq!(gate["self_checked"]["items"], json!([]), "{gate}");
    assert_eq!(gate["confirmed_independent"]["items"], json!([]), "{gate}");
    assert_eq!(
        gate["unconfirmable"]["items"],
        json!([
            "specs--alpha-claim",
            "specs--beta-claim",
            "specs--gamma-claim"
        ]),
        "{gate}"
    );

    // CLI parity: the same axis through `memstead health`.
    let out = Command::new(&cli_bin)
        .current_dir(tmp.path())
        .args(["--json", "health", "--include", "checks"])
        .output()
        .expect("run memstead CLI health");
    assert!(
        out.status.success(),
        "{}",
        String::from_utf8_lossy(&out.stdout)
    );
    let v: Value = serde_json::from_slice(&out.stdout).unwrap();
    assert_eq!(
        v["checks"]["specs"]["independence"]["unconfirmable"]["items"],
        json!([
            "specs--alpha-claim",
            "specs--beta-claim",
            "specs--gamma-claim"
        ]),
        "{v}"
    );
}

#[test]
fn check_operation_records_derives_state_and_mutates_nothing() {
    let tmp = TempDir::new().unwrap();
    seed_full_workspace(tmp.path(), &[("specs", "default@1.3.0")]);
    let mut harness = WireHarness::start(tmp.path());
    let cli_bin = Path::new(memstead_mcp_bin())
        .parent()
        .expect("binary has a parent dir")
        .join("memstead");
    assert!(cli_bin.exists(), "memstead CLI binary not built");

    // Author an entity. It starts never-checked.
    let created = harness.call_tool(
        "memstead_create",
        json!({
            "title": "Checked Claim",
            "entity_type": "spec",
            "mem": "specs",
            "sections": { "identity": "I.", "purpose": "P." },
            "role": "author"
        }),
    );
    assert!(created["isError"] != true, "{created}");
    let hash = created["structuredContent"]["_hash"]
        .as_str()
        .unwrap()
        .to_string();
    let commit_before = created["structuredContent"]["commit_sha"]
        .as_str()
        .unwrap()
        .to_string();

    let read = harness.call_tool(
        "memstead_entity",
        json!({ "id": "specs--checked-claim", "include_provenance": true }),
    );
    assert_eq!(
        read["structuredContent"]["mutation_provenance"]["check_state"], "never_checked",
        "{read}"
    );

    // Refusal complements before any check lands: illegal verdict
    // (vocabulary named), unknown entity.
    let bad = harness.call_tool(
        "memstead_check",
        json!({ "entity": "specs--checked-claim", "verdict": "passed" }),
    );
    assert_eq!(bad["isError"], true, "{bad}");
    assert_eq!(bad["structuredContent"]["code"], "INVALID_VERDICT", "{bad}");
    assert!(
        serde_json::to_string(&bad["structuredContent"]["details"]["allowed"])
            .unwrap()
            .contains("failed"),
        "vocabulary named: {bad}"
    );
    let missing = harness.call_tool(
        "memstead_check",
        json!({ "entity": "specs--no-such-entity", "verdict": "ok" }),
    );
    assert_eq!(missing["isError"], true, "{missing}");
    assert_eq!(
        missing["structuredContent"]["code"], "ENTITY_NOT_FOUND",
        "{missing}"
    );

    // Check as checker, verdict ok → checked_ok.
    let checked = harness.call_tool(
        "memstead_check",
        json!({
            "entity": "specs--checked-claim",
            "verdict": "ok",
            "method": "diffed against source spec",
            "role": "checker"
        }),
    );
    assert!(checked["isError"] != true, "{checked}");
    assert_eq!(checked["structuredContent"]["check_state"], "checked_ok");
    assert_eq!(checked["structuredContent"]["role"], "checker");

    // Checking mutates nothing: entity `_hash` unchanged, mem history
    // gained no commit (the create's commit is still HEAD), markdown
    // untouched.
    let read = harness.call_tool(
        "memstead_entity",
        json!({ "id": "specs--checked-claim", "include_provenance": true }),
    );
    let sc = &read["structuredContent"];
    assert_eq!(
        sc["_hash"].as_str().unwrap(),
        hash,
        "check must not touch _hash"
    );
    assert_eq!(
        sc["mutation_provenance"]["check_state"], "checked_ok",
        "{sc}"
    );
    let last = &sc["mutation_provenance"]["last_check"];
    assert_eq!(last["verdict"], "ok");
    assert_eq!(last["role"], "checker");
    assert_eq!(last["method"], "diffed against source spec");
    let gitdir = tmp.path().join("mem-repo").join(".git");
    let head = Command::new("git")
        .args([
            "--git-dir",
            gitdir.to_str().unwrap(),
            "rev-parse",
            "refs/heads/specs",
        ])
        .output()
        .expect("git rev-parse");
    assert_eq!(
        String::from_utf8_lossy(&head.stdout).trim(),
        commit_before,
        "a check must not produce a mem commit"
    );

    // Entity edit → check_stale (computed by hash comparison, never
    // stamped).
    let updated = harness.call_tool(
        "memstead_update",
        json!({
            "id": "specs--checked-claim",
            "expected_hash": hash,
            "sections": { "purpose": "P2." },
            "role": "author"
        }),
    );
    assert!(updated["isError"] != true, "{updated}");
    let read = harness.call_tool(
        "memstead_entity",
        json!({ "id": "specs--checked-claim", "include_provenance": true }),
    );
    assert_eq!(
        read["structuredContent"]["mutation_provenance"]["check_state"], "check_stale",
        "{read}"
    );

    // Re-check via the CLI (verb parity, session --role) → checked_ok.
    let out = Command::new(&cli_bin)
        .current_dir(tmp.path())
        .args([
            "--json",
            "--role",
            "verifier",
            "check",
            "specs--checked-claim",
            "--verdict",
            "ok",
        ])
        .output()
        .expect("run memstead CLI check");
    assert!(
        out.status.success(),
        "CLI check must land: {}",
        String::from_utf8_lossy(&out.stdout)
    );
    let v: Value = serde_json::from_slice(&out.stdout).unwrap();
    assert_eq!(v["check_state"], "checked_ok", "{v}");
    assert_eq!(v["role"], "verifier");
    let read = harness.call_tool(
        "memstead_entity",
        json!({ "id": "specs--checked-claim", "include_provenance": true }),
    );
    assert_eq!(
        read["structuredContent"]["mutation_provenance"]["check_state"], "checked_ok",
        "{read}"
    );

    // A failed verdict serves check_failed — and supersession never
    // erases: the ledger keeps every record.
    let failed = harness.call_tool(
        "memstead_check",
        json!({ "entity": "specs--checked-claim", "verdict": "failed", "role": "checker" }),
    );
    assert!(failed["isError"] != true, "{failed}");
    assert_eq!(failed["structuredContent"]["check_state"], "check_failed");
    let ledger = std::fs::read_to_string(
        tmp.path()
            .join(".memstead")
            .join("state")
            .join("checks")
            .join("checks.jsonl"),
    )
    .expect("check ledger exists");
    assert_eq!(
        ledger.lines().count(),
        3,
        "append-only: every check kept: {ledger}"
    );

    // CLI illegal-verdict refusal parity.
    let out = Command::new(&cli_bin)
        .current_dir(tmp.path())
        .args([
            "--json",
            "check",
            "specs--checked-claim",
            "--verdict",
            "maybe",
        ])
        .output()
        .expect("run memstead CLI check");
    assert!(!out.status.success());
    let v: Value = serde_json::from_slice(&out.stdout).unwrap();
    assert_eq!(v["code"], "INVALID_VERDICT", "{v}");
}

#[test]
fn declared_roles_are_recorded_in_append_only_history_on_both_backends() {
    let tmp = TempDir::new().unwrap();
    seed_full_workspace(tmp.path(), &[("specs", "default@1.3.0")]);
    let mut harness = WireHarness::start(tmp.path());

    // MCP create-as-author.
    let created = harness.call_tool(
        "memstead_create",
        json!({
            "title": "Derived Conclusion",
            "entity_type": "spec",
            "mem": "specs",
            "sections": { "identity": "I.", "purpose": "P." },
            "role": "author"
        }),
    );
    assert!(created["isError"] != true, "{created}");
    let hash = created["structuredContent"]["_hash"]
        .as_str()
        .unwrap()
        .to_string();

    // MCP illegal role → typed refusal naming the vocabulary.
    let bad = harness.call_tool(
        "memstead_create",
        json!({
            "title": "Nope",
            "entity_type": "spec",
            "mem": "specs",
            "sections": { "identity": "I.", "purpose": "P." },
            "role": "reviewer"
        }),
    );
    assert_eq!(bad["isError"], true, "{bad}");
    assert_eq!(bad["structuredContent"]["code"], "INVALID_ROLE", "{bad}");
    assert!(
        serde_json::to_string(&bad["structuredContent"]["details"]["allowed"])
            .unwrap()
            .contains("checker"),
        "vocabulary named: {bad}"
    );

    // CLI update-as-checker against the SAME workspace.
    let cli_bin = Path::new(memstead_mcp_bin())
        .parent()
        .expect("binary has a parent dir")
        .join("memstead");
    assert!(cli_bin.exists(), "memstead CLI binary not built");
    let out = Command::new(&cli_bin)
        .current_dir(tmp.path())
        .args([
            "--json",
            "--role",
            "checker",
            "update",
            "specs--derived-conclusion",
            "--expected-hash",
            &hash,
            "--append",
            "purpose= Checked.",
        ])
        .output()
        .expect("run memstead CLI");
    assert!(
        out.status.success(),
        "checker update must land: {}",
        String::from_utf8_lossy(&out.stdout)
    );

    // A mutation WITHOUT a role — no trailer, never defaulted.
    let plain = harness.call_tool(
        "memstead_create",
        json!({
            "title": "Plain Entity",
            "entity_type": "spec",
            "mem": "specs",
            "sections": { "identity": "I.", "purpose": "P." }
        }),
    );
    assert!(plain["isError"] != true, "{plain}");

    // CLI illegal role → typed refusal.
    let bad_cli = Command::new(&cli_bin)
        .current_dir(tmp.path())
        .args(["--json", "--role", "boss", "entity", "specs--plain-entity"])
        .output()
        .expect("run memstead CLI");
    assert!(!bad_cli.status.success());
    let v: Value = serde_json::from_slice(&bad_cli.stdout).unwrap();
    assert_eq!(v["code"], "INVALID_ROLE", "{v}");
    assert!(
        v["message"]
            .as_str()
            .unwrap()
            .contains("author, checker, verifier"),
        "vocabulary named: {v}"
    );

    // The append-only record: commit trailers carry exactly the
    // declared roles, and the role-less commit carries none.
    let log = Command::new("git")
        .arg("--git-dir")
        .arg(tmp.path().join("mem-repo").join(".git"))
        .args(["log", "--format=%H%n%B%n---", "refs/heads/specs"])
        .output()
        .expect("git log");
    let log = String::from_utf8_lossy(&log.stdout).to_string();
    let commits: Vec<&str> = log.split("\n---").collect();
    let author_commit = commits
        .iter()
        .find(|c| c.contains("create specs--derived-conclusion"))
        .expect("create commit present");
    assert!(
        author_commit.contains("Role: author"),
        "author role recorded: {author_commit}"
    );
    let checker_commit = commits
        .iter()
        .find(|c| c.contains("update specs--derived-conclusion"))
        .expect("update commit present");
    assert!(
        checker_commit.contains("Role: checker"),
        "checker role recorded: {checker_commit}"
    );
    let plain_commit = commits
        .iter()
        .find(|c| c.contains("create specs--plain-entity"))
        .expect("plain create commit present");
    assert!(
        !plain_commit.contains("Role:"),
        "unspecified role records NO trailer: {plain_commit}"
    );

    // Folder-backend parity: a quickstart (folder) workspace's JSONL
    // ledger records the same shape for the same operations.
    let folder = TempDir::new().unwrap();
    let ws = folder.path().join("plainws");
    std::fs::create_dir_all(&ws).unwrap();
    let ok = Command::new(&cli_bin)
        .current_dir(&ws)
        .args(["quickstart"])
        .output()
        .expect("quickstart");
    assert!(
        ok.status.success(),
        "{}",
        String::from_utf8_lossy(&ok.stderr)
    );
    let ok = Command::new(&cli_bin)
        .current_dir(&ws)
        .args([
            "--role",
            "verifier",
            "create",
            "--title",
            "Ledger Roled",
            "--type",
            "memo",
            "--section",
            "claim=Recorded.",
            "--section",
            "context=Role test.",
        ])
        .output()
        .expect("folder create");
    assert!(
        ok.status.success(),
        "{}",
        String::from_utf8_lossy(&ok.stdout)
    );
    let ok = Command::new(&cli_bin)
        .current_dir(&ws)
        .args([
            "--role",
            "checker",
            "update",
            "plainws--ledger-roled",
            "--force",
            "--section",
            "claim=Checked.",
        ])
        .output()
        .expect("folder update");
    assert!(
        ok.status.success(),
        "{}",
        String::from_utf8_lossy(&ok.stdout)
    );
    let ledger =
        std::fs::read_to_string(ws.join("plainws").join(".memstead").join("changes.jsonl"))
            .or_else(|_| std::fs::read_to_string(ws.join(".memstead").join("changes.jsonl")));
    let ledger = match ledger {
        Ok(l) => l,
        Err(_) => {
            // Quickstart mem dir name derives from the folder; find it.
            let mut found = String::new();
            for entry in std::fs::read_dir(&ws).unwrap().flatten() {
                let p = entry.path().join(".memstead").join("changes.jsonl");
                if p.exists() {
                    found = std::fs::read_to_string(p).unwrap();
                    break;
                }
            }
            found
        }
    };
    assert!(
        ledger.contains("\"role\":\"verifier\""),
        "folder ledger records the create role: {ledger}"
    );
    assert!(
        ledger.contains("\"role\":\"checker\""),
        "folder ledger records the update role: {ledger}"
    );

    // ---- Serve half: the entity read's opt-in provenance block. ----

    // Default read: byte-unchanged — no mutation_provenance key.
    let plain_read = harness.call_tool(
        "memstead_entity",
        json!({ "id": "specs--derived-conclusion" }),
    );
    assert!(plain_read["isError"] != true, "{plain_read}");
    assert!(
        plain_read["structuredContent"]
            .get("mutation_provenance")
            .is_none(),
        "default entity reads carry no provenance block: {plain_read}"
    );

    // Opt-in read: created-by author, last-modified-by checker — the
    // criterion-1 fixture retrieved end to end.
    let read = harness.call_tool(
        "memstead_entity",
        json!({ "id": "specs--derived-conclusion", "include_provenance": true }),
    );
    assert!(read["isError"] != true, "{read}");
    let prov = &read["structuredContent"]["mutation_provenance"];
    assert_eq!(prov["created_by"]["role"], "author", "{prov}");
    assert_eq!(prov["last_modified_by"]["role"], "checker", "{prov}");
    assert!(
        prov["created_by"]["client"].as_str().is_some(),
        "identity recorded: {prov}"
    );
    assert!(prov["created_by"]["timestamp"].as_i64().unwrap() > 0);
    // Identities compared across operations — the gate primitive:
    // both records carry actor identity, distinct roles.
    assert_ne!(
        prov["created_by"]["role"], prov["last_modified_by"]["role"],
        "author≠checker distinguishable from records"
    );

    // The role-less entity serves `unspecified` — recorded absence,
    // never defaulted to a real role.
    let read = harness.call_tool(
        "memstead_entity",
        json!({ "id": "specs--plain-entity", "include_provenance": true }),
    );
    let prov = &read["structuredContent"]["mutation_provenance"];
    assert_eq!(prov["created_by"]["role"], "unspecified", "{prov}");

    // Immutability complement: reading provenance changes nothing —
    // `_hash` identical before/after, and the checker update did not
    // rewrite the creation record (append-only history is the
    // storage; no verb edits past provenance).
    let hash_now = read_hash_of(&mut harness, "specs--derived-conclusion");
    let reread = harness.call_tool(
        "memstead_entity",
        json!({ "id": "specs--derived-conclusion", "include_provenance": true }),
    );
    assert_eq!(
        reread["structuredContent"]["_hash"], hash_now,
        "provenance reads are pure"
    );
    assert_eq!(
        reread["structuredContent"]["mutation_provenance"]["created_by"]["role"], "author",
        "the later checker update never altered the creation record"
    );

    // CLI parity on the SAME mem-repo workspace…
    let out = Command::new(&cli_bin)
        .current_dir(tmp.path())
        .args([
            "--json",
            "entity",
            "specs--derived-conclusion",
            "--provenance",
        ])
        .output()
        .expect("run memstead CLI");
    assert!(out.status.success());
    let v: Value = serde_json::from_slice(&out.stdout).unwrap();
    assert_eq!(
        v["mutation_provenance"]["created_by"]["role"], "author",
        "{v}"
    );
    assert_eq!(
        v["mutation_provenance"]["last_modified_by"]["role"],
        "checker"
    );

    // …and on the FOLDER workspace (backend parity: same shape for
    // the same operation sequence).
    let out = Command::new(&cli_bin)
        .current_dir(&ws)
        .args(["--json", "entity", "plainws--ledger-roled", "--provenance"])
        .output()
        .expect("run memstead CLI");
    assert!(
        out.status.success(),
        "{}",
        String::from_utf8_lossy(&out.stdout)
    );
    let v: Value = serde_json::from_slice(&out.stdout).unwrap();
    let p = &v["mutation_provenance"];
    assert_eq!(p["created_by"]["role"], "verifier", "folder parity: {v}");
    assert_eq!(
        p["last_modified_by"]["role"], "checker",
        "folder parity: {v}"
    );
    assert!(p["created_by"]["timestamp"].as_i64().unwrap() > 0);
}

/// Current `_hash` of an entity via a plain read.
fn read_hash_of(harness: &mut WireHarness, id: &str) -> Value {
    let r = harness.call_tool("memstead_entity", json!({ "id": id }));
    r["structuredContent"]["_hash"].clone()
}