memstead-base 0.26.1

Engine internals for Memstead — store, parser, validators, mem lifecycle, workspace policy. Published as a dependency of the memstead-cli and memstead-mcp products, not as a supported library — pre-1.0, no API stability promise.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135
3136
3137
3138
3139
3140
3141
3142
3143
3144
3145
3146
3147
3148
3149
3150
3151
3152
3153
3154
3155
3156
3157
3158
3159
3160
3161
3162
3163
3164
3165
3166
3167
3168
3169
3170
3171
3172
3173
3174
3175
3176
3177
3178
3179
3180
3181
3182
3183
3184
3185
3186
3187
3188
3189
3190
3191
3192
3193
3194
3195
3196
3197
3198
3199
3200
3201
3202
3203
3204
3205
3206
3207
3208
3209
3210
3211
3212
3213
3214
3215
3216
3217
3218
3219
3220
3221
3222
3223
3224
3225
3226
3227
3228
3229
3230
3231
3232
3233
3234
3235
3236
3237
3238
3239
3240
3241
3242
3243
3244
3245
3246
3247
3248
3249
3250
3251
3252
3253
3254
3255
3256
3257
3258
3259
3260
3261
3262
3263
3264
3265
3266
3267
3268
3269
3270
3271
3272
3273
3274
3275
3276
3277
3278
3279
3280
3281
3282
3283
3284
3285
3286
3287
3288
3289
3290
3291
3292
3293
3294
3295
3296
3297
3298
3299
3300
3301
3302
3303
3304
3305
3306
3307
3308
3309
3310
3311
3312
3313
3314
3315
3316
3317
3318
3319
3320
3321
3322
3323
3324
3325
3326
3327
3328
3329
3330
3331
3332
3333
3334
3335
3336
3337
3338
3339
3340
3341
3342
3343
3344
3345
3346
3347
3348
3349
3350
3351
3352
3353
3354
3355
3356
3357
3358
3359
3360
3361
3362
3363
3364
3365
3366
3367
3368
3369
3370
3371
3372
3373
3374
3375
3376
3377
3378
3379
3380
3381
3382
3383
3384
3385
3386
3387
3388
3389
3390
3391
3392
3393
3394
3395
3396
3397
3398
3399
3400
3401
3402
3403
3404
3405
3406
3407
3408
3409
3410
3411
3412
3413
3414
3415
3416
3417
3418
3419
3420
3421
3422
3423
3424
3425
3426
3427
3428
3429
3430
3431
3432
3433
3434
3435
3436
3437
3438
3439
3440
3441
3442
3443
3444
3445
3446
3447
3448
3449
3450
3451
3452
3453
3454
3455
3456
3457
3458
3459
3460
3461
3462
3463
3464
3465
3466
3467
3468
3469
3470
3471
3472
3473
3474
3475
3476
3477
3478
3479
3480
3481
3482
3483
3484
3485
3486
3487
3488
3489
3490
3491
3492
3493
3494
3495
3496
3497
3498
3499
3500
3501
3502
3503
3504
3505
3506
3507
3508
3509
3510
3511
3512
3513
3514
3515
3516
3517
3518
3519
3520
3521
3522
3523
3524
3525
3526
3527
3528
3529
3530
3531
3532
3533
3534
3535
3536
3537
3538
3539
3540
3541
3542
3543
3544
3545
3546
3547
3548
3549
3550
3551
3552
3553
3554
3555
3556
3557
3558
3559
3560
3561
3562
3563
3564
3565
3566
3567
3568
3569
3570
3571
3572
3573
3574
3575
3576
3577
3578
3579
3580
3581
3582
3583
3584
3585
3586
3587
3588
3589
3590
3591
3592
3593
3594
3595
3596
3597
3598
3599
3600
3601
3602
3603
3604
3605
3606
3607
3608
3609
3610
3611
3612
3613
3614
3615
3616
3617
3618
3619
3620
3621
3622
3623
3624
//! Engine error envelopes.
//!
//! `EngineError` lifts the typed payloads every consumer pattern-matches
//! on (`BackendError` via `#[from]`, `ValidationError` from the runtime
//! validator, `SlugError` from the slug helper, `ParseError` from the
//! markdown parser). `BootError` is the smaller envelope produced by
//! `Engine::from_workspace_root` and its full counterpart — the failure
//! modes specific to layout detection, workspace-store load, per-mount
//! backend instantiation, and engine construction.

use std::fmt;
use std::path::PathBuf;

use crate::backend::BackendError;
use crate::entity::EntityId;
use crate::entity::id::SlugError;
use crate::entity::parser::ParseError;
use crate::runtime_validator::{MissingRequiredField, ValidationError};

/// Maximum items rendered inline before truncation kicks in. Picked to
/// keep the typical fanout (1–25 items) on one terminal line while
/// still bounding pathological cases (200+ referrers on a hub entity)
/// to a constant prefix plus a count.
pub const INLINE_LIST_CAP: usize = 3;

/// Every payload key an update recognises as mutation content, in one place.
///
/// WHY a constant: four surfaces hand-copied this list and all four disagreed.
/// The `EMPTY_UPDATE` message named seven keys, its own `details` payload
/// named six (dropping `relations_unset`), the CLI's copy named six, and the
/// MCP copies named eight after one of them was corrected. An agent recovering
/// from the refusal was told, on the CLI, that `anchors` is not a recognised
/// mutation key: false, and false about exactly the flow anchors exist for.
/// The refusal now reads its own list, and so does every surface that repeats
/// it.
pub const RECOGNISED_MUTATION_KEYS: &[&str] = &[
    "sections",
    "append_sections",
    "patch_sections",
    "metadata",
    "metadata_unset",
    "declare_relations",
    "relations_unset",
    "anchors",
    "anchors_unset",
];

/// One blocked-direction summary entry for
/// [`EngineError::RenameBlockedByCrossMemPolicy`]. Pairs the
/// referrer's mem with the renaming entity's mem (the edge's
/// actual `referrer → renamed` direction post-rewrite) and the count
/// of distinct referrers in that mem that would emit the blocked
/// rewrite.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct BlockedReferrer {
    /// Referrer's mem — `from_mem` in the propagated edge's
    /// actual direction.
    pub from_mem: String,
    /// Renaming entity's mem — `to_mem` in the propagated edge's
    /// actual direction. Always the same value across every
    /// `blocked_referrers` entry of a single rename refusal.
    pub to_mem: String,
    /// Distinct referrers in `from_mem` that would emit the
    /// blocked rewrite.
    pub count: usize,
}

impl fmt::Display for BlockedReferrer {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(
            f,
            "{} → {} ({} referrer{})",
            self.from_mem,
            self.to_mem,
            self.count,
            if self.count == 1 { "" } else { "s" }
        )
    }
}

fn format_blocked_referrers(items: &[BlockedReferrer]) -> String {
    format_inline_list_overflow(items, "blocked_referrers")
}

/// Occupant rendering for [`EngineError::AlreadyExists`]: a real
/// entity renders its quoted title; a stub renders as "a stub" (with
/// its title when it has one — a titleless stub must never render as
/// an empty title).
/// The prose for [`EngineError::ProcessMemNotEligible`]: which of the
/// three eligibility conditions the named mem failed, and what would pass.
fn process_mem_not_eligible_message(
    mem: &str,
    process_mem: &str,
    reason: &str,
    schema: &Option<String>,
) -> String {
    let why = match reason {
        "self_pairing" => "a mem cannot be its own process mem".to_string(),
        "not_mounted" => "no mounted mem carries that name".to_string(),
        _ => format!(
            "it is pinned to `{}`, and a process mem must be pinned to an `{}@*` schema",
            schema.as_deref().unwrap_or("<no schema>"),
            crate::binding_run::PROCESS_MEM_SCHEMA_NAME
        ),
    };
    format!(
        "process mem '{process_mem}' is not eligible for mem '{mem}': {why}. Declare a mounted \
         `{}@*` mem, or clear the declaration to pair by the binding-name convention",
        crate::binding_run::PROCESS_MEM_SCHEMA_NAME
    )
}

fn render_occupant(existing_title: &str, existing_is_stub: bool) -> String {
    match (existing_is_stub, existing_title.is_empty()) {
        (true, true) => "a stub".to_string(),
        (true, false) => format!("a stub titled '{existing_title}'"),
        (false, _) => format!("'{existing_title}'"),
    }
}

/// Render a structured-list payload onto the text-mirror message. The
/// first [`INLINE_LIST_CAP`] items appear inline, comma-separated; when
/// the list is longer, the suffix " +N more — see details.<field>"
/// points the agent at the structured channel's typed list under
/// `field`. Empty input renders as an empty string. The function is
/// generic over any [`fmt::Display`] item — wrap structs in a small
/// `Display` newtype if their default rendering is too verbose for the
/// text channel.
pub fn format_inline_list_overflow<T: fmt::Display>(items: &[T], field: &str) -> String {
    if items.is_empty() {
        return String::new();
    }
    let head: Vec<String> = items
        .iter()
        .take(INLINE_LIST_CAP)
        .map(|i| i.to_string())
        .collect();
    let inline = head.join(", ");
    if items.len() > INLINE_LIST_CAP {
        let extra = items.len() - INLINE_LIST_CAP;
        format!("{inline} +{extra} more — see details.{field}")
    } else {
        inline
    }
}

/// One resolution-source line on [`EngineError::SchemaNotFound`]'s
/// `details.sources` payload.
///
/// The schema registry consults sources in a fixed order — local
/// storage (the mem's own storage backend), built-in (compiled into
/// the engine binary), remote (a registry, reserved) — and records
/// what each held for the pinned *name* so an agent or operator can
/// tell *where* a pin failed: missing from local authoring, absent
/// from the shipped catalogue, or past the not-yet-wired remote. The
/// `local_storage`/`builtin` lines report a wrong-version partial
/// match (right name, wrong version) through `pinned_version_match`.
#[derive(Debug, Clone, PartialEq, Eq, serde::Serialize)]
pub struct SchemaSourceDiagnostic {
    /// Stable source label: `"local_storage"`, `"builtin"`, or
    /// `"remote"`. Agents may branch on it.
    pub source: &'static str,
    /// Versions of the pinned *name* this source held, ascending.
    /// Empty when the source carried nothing for that name — or was
    /// not enumerated (today only `remote`, see `status`).
    pub versions_found: Vec<String>,
    /// `true` when the pinned exact version is among `versions_found`.
    /// Always `false` across every source on a genuine not-found (the
    /// fixed resolution order means a match on any source would have
    /// resolved); a lone `true` here signals right-name/wrong-version.
    pub pinned_version_match: bool,
    /// Non-enumerable status for sources that do not list versions —
    /// today only `remote`, which reports `"not_configured"`. `None`
    /// for the enumerable `local_storage`/`builtin` sources.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub status: Option<&'static str>,
}

impl SchemaSourceDiagnostic {
    /// Build the fixed-order source diagnostics for a failed pin.
    ///
    /// `consulted` is the resolution set the call site actually
    /// searched: at boot it is the workspace-authored schemas layered
    /// over the built-ins; at the create/migration sites it is the
    /// set that path consulted (built-in alone, or workspace + built-in
    /// for the migration resolver). The `builtin` line is recomputed
    /// from the static catalogue so it is honest regardless of what the
    /// caller passed; anything in `consulted` the built-in set does not
    /// carry is attributed to `local_storage`. `remote` is always the
    /// reserved `not_configured` slot.
    pub fn for_failed_pin(
        name: &str,
        requested: &semver::Version,
        consulted: &[std::sync::Arc<memstead_schema::Schema>],
    ) -> Vec<Self> {
        use std::collections::BTreeSet;
        let builtin: BTreeSet<semver::Version> = memstead_schema::builtins::load_builtin_schemas()
            .map(|set| {
                set.iter()
                    .filter(|s| s.manifest.name == name)
                    .map(|s| s.version.clone())
                    .collect()
            })
            .unwrap_or_default();
        let local: BTreeSet<semver::Version> = consulted
            .iter()
            .filter(|s| s.manifest.name == name)
            .map(|s| s.version.clone())
            .filter(|v| !builtin.contains(v))
            .collect();
        let to_strings =
            |set: &BTreeSet<semver::Version>| set.iter().map(|v| v.to_string()).collect::<Vec<_>>();
        vec![
            Self {
                source: "local_storage",
                pinned_version_match: local.contains(requested),
                versions_found: to_strings(&local),
                status: None,
            },
            Self {
                source: "builtin",
                pinned_version_match: builtin.contains(requested),
                versions_found: to_strings(&builtin),
                status: None,
            },
            Self {
                source: "remote",
                versions_found: Vec::new(),
                pinned_version_match: false,
                status: Some("not_configured"),
            },
        ]
    }
}

/// One mem's part of an operation over several mems, as a partial
/// failure reports it.
#[derive(Debug, Clone, PartialEq, Eq, serde::Serialize)]
pub struct PartialMem {
    pub mem: String,
    /// The operation's commit to this mem is in storage.
    pub landed: bool,
    /// Why this mem's part failed; set on the mem that failed.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub error: Option<String>,
    pub items: Vec<PartialItem>,
}

/// One entity an operation over several mems writes.
#[derive(Debug, Clone, PartialEq, Eq, serde::Serialize)]
pub struct PartialItem {
    /// The entity's id as storage has it now.
    pub id: String,
    pub landed: bool,
    /// The entity's content hash now; `None` when it does not exist.
    pub current_hash: Option<String>,
}

/// Errors surfaced by [`Engine`].
///
/// `Backend` lifts [`BackendError`] verbatim through a `#[from]`
/// conversion so the engine layer's error envelope preserves the
/// backend's typed `Sealed` / `HashMismatch` payloads. The MCP layer
/// branches on the discriminant when mapping into the typed `code`
/// field of its error envelope.
#[derive(Debug, thiserror::Error)]
pub enum EngineError {
    /// `Engine::from_mounts` received two mounts naming the same
    /// mem. Configuration error: the persistence adapter or
    /// caller produced a malformed mount list.
    #[error("duplicate mem in mount list: {0}")]
    DuplicateMem(String),
    /// No mount in this engine names the requested mem. Surfaced
    /// before reaching any backend so callers can distinguish
    /// "wrong mem name" from "backend failure".
    #[error("unknown mem: {name}")]
    UnknownMem {
        name: String,
        /// The mems mounted when it was raised: the recovery set.
        known_mems: Vec<String>,
        /// The writable ones among them, for a call that writes.
        writable_mems: Vec<String>,
    },
    /// The mem left the mount roster during this engine's lifetime (it
    /// was unregistered or deleted by another process and the roster
    /// reconciliation unmounted it). Cached ids and hashes for it are
    /// void; `memstead_health` lists what is mounted now. Typed code
    /// `MEM_UNMOUNTED`.
    #[error(
        "mem `{mem}` was unmounted: it left the mount roster since this engine booted, so \
         nothing of it is served any more — drop cached ids and hashes for it and re-read \
         the roster (memstead_health)"
    )]
    MemUnmounted { mem: String },
    /// The mem exists in the workspace but failed its mem-level boot
    /// step and is quarantined — it serves nothing until repaired
    /// (degrade, never disappear; quarantine is not tolerance).
    /// `reason_message` is the underlying typed failure verbatim, its
    /// final clause the repair command; after the repair,
    /// `memstead_reload` re-attaches the mem without a restart.
    #[error(
        "mem '{mem}' is quarantined — it failed to attach at boot and serves nothing until \
         repaired: [{reason_code}] {reason_message}. After repairing, run memstead_reload \
         (or `memstead reload`) to bring it back into service."
    )]
    MemQuarantined {
        mem: String,
        reason_code: String,
        reason_message: String,
    },
    /// Mutation rejected because the mount declares
    /// [`MountCapability::ReadOnly`]. Surfaced before reaching the
    /// backend so the typed `Sealed` payload from the archive
    /// backend never triggers — capability gating runs first.
    #[error("mem {0} is mounted read-only; mutations rejected")]
    ReadOnlyMount(String),
    /// A check could not be persisted — either the engine has no
    /// workspace root (in-memory engines have no durable check
    /// store) or the ledger append failed. A check the caller
    /// believes recorded but was not is worse than a refusal, so
    /// recording is never best-effort.
    #[error("check not recorded: {reason}")]
    CheckNotRecorded { reason: String },
    /// Entity type is not declared in the pinned schema for this
    /// mem. Carries the declared types (sorted) and a fuzzy
    /// suggestion so the agent can recover without re-reading the
    /// schema. `schema_ref` is the pinned `<name>@<version>`.
    #[error(
        "unknown entity type '{name}' in schema '{schema_ref}'. Declared types: [{}]{}",
        declared.join(", "),
        suggestion.as_deref().map(|s| format!(". Did you mean '{s}'?")).unwrap_or_default()
    )]
    UnknownType {
        name: String,
        schema_ref: String,
        declared: Vec<String>,
        suggestion: Option<String>,
    },
    /// Title slug is empty / invalid.
    #[error("title is invalid: {0}")]
    InvalidTitle(#[from] SlugError),
    /// Create attempted against an id already present in the store.
    /// Names the occupant's title — distinct titles can derive the
    /// same slug, so the id alone does not tell the caller which
    /// entity holds it. `existing_is_stub` marks a stub occupant
    /// (reachable via rename; the create path adopts stubs instead
    /// of refusing).
    #[error(
        "entity already exists: {id} — occupied by {}",
        render_occupant(existing_title, *existing_is_stub)
    )]
    AlreadyExists {
        id: String,
        existing_title: String,
        existing_is_stub: bool,
    },
    /// Write refused: the entity as written would violate a
    /// block-tier declared constraint of its type (`severity: block`
    /// in the schema's `constraints`). Warn-tier violations warn
    /// instead (`WarningHint::ConstraintUnsatisfied`) — same
    /// evaluation, tier decided by the declaration. `violations`
    /// restates each violated declaration so the caller can repair
    /// without re-fetching the schema.
    #[error(
        "write refused: {entity_id} ({entity_type}) violates {n} block-tier declared constraint(s) — first: {first}",
        n = violations.len(),
        first = violations.first().map(|v| v.describe()).unwrap_or_default(),
    )]
    ConstraintUnsatisfied {
        entity_type: String,
        entity_id: String,
        violations: Vec<crate::ops::health::UnsatisfiedConstraint>,
    },
    /// Write refused: a section body violates its schema-declared
    /// markdown format (`content` / `item_pattern` / `table` on the
    /// section, `format_severity: block`). The code and recovery
    /// payload come from the violation itself
    /// (`SECTION_CONTENT_MISMATCH` / `SECTION_ITEM_PATTERN_MISMATCH`
    /// / `INVALID_TABLE_COLUMNS`, or `SECTION_CONTENT_INVALID` for a
    /// reserved setext heading); the payload echoes the declared
    /// `example` where one exists — for an agent, a conforming
    /// example outperforms any grammar string.
    #[error("write refused: {entity_id} ({entity_type}) — {}", violation.describe())]
    SectionFormatRefused {
        entity_type: String,
        entity_id: String,
        violation: crate::section_format::SectionFormatViolation,
    },
    /// Write refused: the entity's final edge set leaves a
    /// block-tier `required_outgoing` block unsatisfied
    /// (`severity: block` on the block). The default warn tier keeps
    /// the long-standing warning behavior; this refusal exists only
    /// where a schema explicitly promoted the block. Shares the
    /// `MISSING_REQUIRED_OUTGOING` code and `missing` payload shape
    /// with the warning — one condition, one vocabulary, tier decided
    /// by the declaration.
    #[error(
        "write refused: {entity_id} ({entity_type}) leaves {n} block-tier `required_outgoing` block(s) unsatisfied",
        n = missing.len(),
    )]
    RequiredOutgoingUnsatisfied {
        entity_type: String,
        entity_id: String,
        missing: Vec<crate::ops::MissingRequiredOutgoingBlock>,
    },
    /// A retype refused: every problem the target type has with the
    /// entity's sections, metadata, edges, and block-tier constraints,
    /// reported together (the report-all contract), with the target's
    /// declared sections, its catch-all, and a proposed `section_map`
    /// as the recovery payload. The wire code is the one shared code
    /// when every problem carries the same one (`UNKNOWN_SECTION`,
    /// `INVALID_REL_SHAPE`, …) and `RETYPE_REFUSED` when they mix.
    #[error(
        "retype of {id} from '{from_type}' to '{to_type}' refused: {} problem(s) — {}",
        problems.len(),
        problems.iter().map(|p| p.message()).collect::<Vec<_>>().join("; ")
    )]
    RetypeRefused {
        id: String,
        from_type: String,
        to_type: String,
        problems: Vec<crate::engine::outcomes::RetypeProblem>,
        target_sections: Vec<String>,
        target_catch_all: Option<String>,
        proposed_section_map: std::collections::BTreeMap<String, String>,
    },
    /// The entity already has the requested type.
    #[error("retype of {id} is a no-op: it already has type '{entity_type}'")]
    RetypeNoOp { id: String, entity_type: String },
    /// A check's structured finding does not match the fixed wrapper
    /// shape (`code` and `message` required and non-empty, `section`
    /// and `evidence` optional, no other keys). Nothing is appended.
    #[error("check finding refused: {reason}")]
    InvalidCheckFinding { reason: String },
    /// A deferred (lazy, unloaded) mem's storage could not be enumerated,
    /// so its edges into the entity could not be re-checked. The retype
    /// refuses rather than assuming those edges fit the target type.
    #[error(
        "retype of {id} refused: referrers in mem '{mem}' cannot be probed ({reason}); load the \
         mem (or repair its storage) and retry"
    )]
    RetypeReferrerUnprobeable {
        id: String,
        mem: String,
        reason: String,
    },
    /// Mutation rejected because the named entity is not in the
    /// store. Distinct from `UnknownMem`: the mem exists, the
    /// entity does not.
    #[error("entity not found: {id}")]
    NotFound {
        id: String,
        /// Ids of entities whose id ends with, or whose slug contains,
        /// the one asked for; at most five.
        suggestions: Vec<String>,
    },
    /// Optimistic-locking failure: the caller's `expected_hash` does
    /// not match the entity's current `content_hash` in the store.
    /// `current` is the live hash — pass it as `expected_hash` after
    /// re-reading to retry. `is_stub` is set when the entity is a
    /// stub (no body, no content_hash); the corrective action is to
    /// pass `expected_hash: ""` rather than re-read via `memstead_entity`.
    /// Surfaces on `details.is_stub` so MCP callers branch on the
    /// structured payload instead of parsing the message text — pre-fix
    /// the wire emitted `(current: )` with an empty paren that
    /// misdirected toward hash-recovery for a stub-shaped entity.
    /// A content-changing mutation of a real entity stated no hash.
    /// The engine's one refusal for that case on every surface.
    #[error(
        "expected_hash is required to change {id}: read the entity first and pass its `_hash`, \
         or preview with a dry run. Only an update that changes no content (anchors only) and a \
         stub need none."
    )]
    ExpectedHashRequired { id: String },
    #[error("{}", _hash_mismatch_msg(id, current, *is_stub))]
    HashMismatch {
        id: String,
        current: String,
        is_stub: bool,
    },
    /// Refusal to delete or rename an entity because other entities
    /// in **Write-Mems** still reference it. There is no force flag
    /// or escape hatch — the agent removes the offending references
    /// (via `memstead_relate --remove` or `memstead_update`) before retrying.
    /// `referrers` carries the typed referrer info (source id,
    /// rel-type, source mem) so the response payload describes the
    /// full surface in one round-trip. ReadOnly-mount referrers are
    /// excluded from this list — they are handled by the residual-
    /// stub demotion path on the destructive mutation.
    #[error(
        "entity {id} has {n} incoming reference(s) in write mems ({inline}); remove them first via memstead_relate --remove or memstead_update",
        n = referrers.len(),
        inline = format_inline_list_overflow(referrers, "referrers"),
    )]
    HasIncomingRefs {
        id: String,
        referrers: Vec<ReferrerInfo>,
    },
    /// Refusal to delete a mem because entities in other Write-Mems
    /// still reference entities inside it. Mirrors entity-level
    /// [`Self::HasIncomingRefs`] at the mem granularity — the
    /// edge-graph axis. Revoking a workspace-level grant only closes
    /// the policy axis; this check closes the actual-edge axis so a
    /// mem delete that would orphan cross-mem edges refuses with
    /// the typed envelope listing every offending `(from_id, rel_type,
    /// source_mem)` triple. No force flag — the operator must
    /// `memstead_relate --remove` (or `memstead_update` to drop the section)
    /// on each referrer first, then retry. ReadOnly-mount referrers
    /// stay out of this list and route through the residual-stub
    /// demotion path on the destructive mutation, same posture as the
    /// entity-level variant.
    #[error(
        "mem `{mem}` has {n} incoming reference(s) in write mems ({inline}); remove them first via memstead_relate --remove or memstead_update",
        n = referrers.len(),
        inline = format_inline_list_overflow(referrers, "referrers"),
    )]
    MemHasIncomingRefs {
        mem: String,
        referrers: Vec<ReferrerInfo>,
    },
    /// Relate across mems rejected because the workspace's
    /// `[cross_mem_links]` policy (or the per-create-rule
    /// `default_cross_links` synthesis) does not permit `from_mem →
    /// to_mem`. Agents adjust the policy or pick a same-mem
    /// target. The hint points at the workspace `[cross_mem_links]`
    /// section.
    #[error(
        "cross-mem link from mem `{from_mem}` to mem `{to_mem}` is not allowed by the workspace `[cross_mem_links]` policy"
    )]
    CrossMemLinkNotAllowed { from_mem: String, to_mem: String },
    /// Any add-shaped cross-mem edge write (`memstead_relate`,
    /// `memstead_create.relations[]`, `memstead_update.declare_relations`,
    /// or a body wiki-link) to a target whose mem is mounted
    /// `MountCapability::ReadOnly` and the target is absent —
    /// judged against the mem's real storage, so an unloaded (lazy)
    /// read-only mem answers without loading and the refusal never
    /// fires for an entity storage actually contains. Auto-stub
    /// is unavailable across the engine/ReadOnly-mem boundary (the
    /// engine cannot persist a stub in a mem it has no write access
    /// to), and a read-only mem never gains the entity later — the
    /// target must already exist before the link is written.
    #[error(
        "cross-mem link target {target_id} is absent in read-only mem `{target_mem}` — auto-stub is unavailable across the read-only boundary; the target must exist before linking"
    )]
    CrossMemTargetNotFound {
        target_id: String,
        target_mem: String,
    },
    /// An entity id arrived without its mem prefix (`slug` where
    /// `mem--slug` is the grammar) and could not be resolved to one
    /// entity: either no mounted mem carries an entity of that slug,
    /// or more than one does. `candidates` names every full id that
    /// carries the slug so the caller can pick one; empty when none
    /// does. A short id that exactly one mounted mem carries never
    /// reaches this error — the verb resolves it and announces the
    /// resolution as `SHORT_ID_RESOLVED`.
    #[error(
        "entity id `{id}` has no mem prefix (the grammar is `mem--slug`){}",
        if candidates.is_empty() { " and no mounted mem carries an entity of that slug".to_string() } else { format!(" and more than one mounted mem carries it: {}", candidates.join(", ")) }
    )]
    EntityIdMissingMem { id: String, candidates: Vec<String> },
    /// `memstead_relate` across mems pinning schemas with different
    /// *names* refused because the source schema's
    /// `cross_mem_relationships:` section declares no entry for the
    /// target schema's domain. Each source schema must explicitly
    /// enumerate outbound cross-mem edges per target domain; the
    /// absence here means the source schema does not speak the target
    /// domain's vocabulary. Eligibility is name-based — a declaration
    /// covers every version of the named target schema. The agent's
    /// recovery is to declare the rel-type in the source schema's
    /// `cross_mem_relationships:` section under the target's bare
    /// schema name (`to_schema: <name>`).
    ///
    /// Orthogonal to the `cross_mem_links` permission policy:
    /// vocabulary and permission fire independently. A policy-admissible
    /// edge that violates vocabulary surfaces here; a vocabulary-admissible
    /// edge that violates policy surfaces as
    /// [`Self::CrossMemLinkNotAllowed`].
    #[error(
        "cross-mem edge {rel_type} from `{from_id}` (schema {source_schema}) to `{to_id}` (schema {target_schema}) is not declared in {source_schema}'s `cross_mem_relationships:` section"
    )]
    CrossMemEdgeNotDeclared {
        source_schema: String,
        target_schema: String,
        rel_type: String,
        from_id: String,
        to_id: String,
    },
    /// `memstead_update` received repair-shaped input (`relations_unset`)
    /// for an entity that currently passes the conformance check.
    /// Repair-powers gate on evidence — a conformance failure on the
    /// target entity — and a conformant entity has the focused tools
    /// instead: `memstead_relate(remove)` detaches an edge, the additive
    /// `memstead_update` params evolve content. The entity is not
    /// modified.
    #[error(
        "repair input refused for {id}: the entity currently passes the conformance check — {recovery}"
    )]
    RepairNotNeeded { id: String, recovery: String },
    /// Rename where the new title would slugify to the existing id.
    /// Surfaced as a typed no-op so callers don't loop on a degenerate
    /// retry.
    #[error(
        "rename would not change the id of {id} — new title {new_title:?} produces the same slug"
    )]
    RenameNoOp { id: String, new_title: String },
    /// `memstead_update` / `memstead_batch_update` payload parsed cleanly but
    /// carries no recognised mutation content — every mutation map is
    /// empty and no relations are declared. Distinct from
    /// `UPDATE_NOOP` (a warning that fires when mutation content was
    /// provided but matched the current state): `EMPTY_UPDATE` is
    /// keyed on "no mutation content provided at all", and refuses
    /// before any mutation work runs so a misspelled/omitted mutation
    /// key doesn't silently land as `succeeded: 1, write_id: ""`.
    #[error(
        "no mutation content for {id}: payload carries an id but every mutation map is empty \
         (recognised keys: {})",
        RECOGNISED_MUTATION_KEYS.join(", ")
    )]
    EmptyUpdate { id: String },
    /// `memstead_rename` cannot proceed because one or more cross-mem
    /// referrers would emit a propagated rewrite whose direction the
    /// workspace's `cross_mem_links` policy does not permit. The
    /// engine refuses the rename up-front (before any write); the
    /// agent's recovery is either to grant the missing direction in
    /// `[cross_mem_links]` or to drop the offending edges first.
    ///
    /// Each `blocked_referrers` entry names a single blocked direction
    /// (`from_mem → to_mem`) — the referrer's mem and the
    /// renaming entity's mem, respectively — together with the
    /// count of distinct referrers in that mem that would emit the
    /// blocked rewrite. The direction is the edge's actual direction
    /// post-rewrite (`referrer → renamed`), which is what the policy
    /// gates.
    #[error(
        "rename blocked: cross-mem rewrite from referrer mem(s) into `{from_mem}` is not permitted by `[cross_mem_links]` — blocked: {} — grant the missing direction or rewrite the blocked referrers manually",
        format_blocked_referrers(blocked_referrers)
    )]
    RenameBlockedByCrossMemPolicy {
        from_mem: String,
        blocked_referrers: Vec<BlockedReferrer>,
    },
    /// `memstead_create` / `memstead_update` / `memstead_batch_update` refused
    /// because the post-mutation entity's section bodies contain
    /// inline wiki-links to targets that have no corresponding
    /// explicit relation in `entity.relationships`. Strict
    /// wiki-link / relation invariant: every body wiki-link must
    /// have a backing relation. The agent's recovery is
    /// `memstead_relate <this-entity> REFERENCES <target>` (or a more
    /// specific rel-type) for each missing entry, then re-issue
    /// the mutation. `missing` enumerates each violation as a
    /// `(section_key, target_id)` pair so the agent can fix every
    /// surviving link in one pass. This validator is gated behind
    /// the workspace's reference-coherence migration completion
    /// marker; workspaces that haven't been migrated continue
    /// running the permissive auto-stub regime.
    #[error(
        "post-mutation body of {from_id} has {n} wiki-link(s) without a backing relation ({inline}) — declare the relation(s) via memstead_relate first (REFERENCES or a more specific rel-type), then retry",
        n = missing.len(),
        inline = format_inline_list_overflow(missing, "missing"),
    )]
    WikiLinkWithoutRelation {
        from_id: String,
        missing: Vec<MissingWikiLink>,
    },
    /// `memstead_relate --remove` refused because the source entity's
    /// section bodies still contain `[[<target>]]` (or
    /// `[[<mem>:<target>]]`) wiki-links pointing at the relation's
    /// target. Removing the explicit relation while body links
    /// survive would violate the strict wiki-link/relation invariant
    /// (inline links require a backing relation). The agent's
    /// recovery is `memstead_update <source-id>` with section content
    /// that drops the wiki-link tokens, then re-issue `memstead_relate
    /// --remove`. `body_links` enumerates the surviving section keys
    /// so the agent can patch them in one pass.
    #[error(
        "cannot remove {rel_type} {from_id} → {to_id}: source body still contains wiki-link(s) to the target in section(s) {inline} — drop them via memstead_update before removing the relation",
        inline = format_inline_list_overflow(body_links, "body_links"),
    )]
    RelationHasBodyLinks {
        from_id: String,
        to_id: String,
        rel_type: String,
        body_links: Vec<String>,
    },
    /// An operation over several mems landed in part: at least one
    /// mem committed, then another mem's part failed, on a storage
    /// error (`failure_cause: "storage"`) or because its head was no
    /// longer the one the operation pinned (`"drift"`). What committed
    /// is durable and the engine's view is level with it; the failed
    /// mem holds nothing of the operation. `mems` states, for every mem
    /// the operation writes and every entity it writes there, whether
    /// it landed and the entity's hash as it is now.
    ///
    /// An entity rename lands the renamed entity's own mem last, so
    /// after a partial failure the entity is still under the id the
    /// caller named, with the hash the caller sent: the identical call
    /// completes the rename. A batch is completed by sending the items
    /// reported as not landed. The code keeps the name it had when
    /// only renames reported it.
    #[error(
        "the operation landed in part: mem `{failed_mem}` failed ({failure_cause}) after {committed_mems:?} committed; details.mems states what landed"
    )]
    RenamePartialFailure {
        committed_mems: Vec<String>,
        failed_mem: String,
        failure_cause: String,
        mems: Vec<PartialMem>,
    },
    /// A folder mem's commit is decided and not yet applied: its commit
    /// record is durable, an error cut off the move of its files into
    /// place, and completing it at once failed as well (the fault
    /// persists). The write is neither failed nor finished, so no
    /// existing code reports it truthfully: resending the call would
    /// write twice, and the store does not show the write yet. The
    /// next operation on the mem completes the commit before it does
    /// anything else and names the completed files in an
    /// `INTERRUPTED_COMMIT_COMPLETED` warning.
    #[error(
        "the write to mem `{mem}` is decided and not yet applied ({detail}) — do not resend it; the next operation on the mem completes it first"
    )]
    CommitNotApplied { mem: String, detail: String },
    /// The engine's view of a mem cannot take this write, so nothing was
    /// written. No other code says this: the caller's hash may even
    /// match the view, so `HASH_MISMATCH` would be false, and the
    /// failure behind it belongs to the view, not to this write. The
    /// named mem is the one whose view cannot take it: the mem being
    /// written, a mem whose entity the write relates to, or, for a write
    /// whose guard reads every mem, any mem. `cause` says why, and the
    /// message and `details.cause` name the repair for that cause
    /// ([`StaleCause`]).
    #[error("{}", stale_view_message(mem, *cause, detail))]
    StaleView {
        mem: String,
        cause: StaleCause,
        detail: String,
    },
    /// `memstead_relate` source is a stub — stubs have no `entity_type`
    /// and cannot author edges. The agent must promote the stub to a
    /// real entity via `memstead_create` (stub adoption preserves any
    /// incoming references) before relating. Pre-fix surfaced as the
    /// cryptic `UnknownType { name: "" }`.
    #[error("source entity {id} is a stub — promote it to a real entity via memstead_create first")]
    StubCannotRelate { id: String },
    /// `memstead_update` target is a stub — stubs have no body, no
    /// metadata, no schema-resolved type to validate against. The
    /// agent must promote the stub to a real entity via `memstead_create`
    /// (stub adoption preserves any incoming references) before
    /// updating. Without this variant the case surfaces as the cryptic
    /// `UnknownType { name: "" }` cascade — identical symptom to the
    /// one `StubCannotRelate` replaces on `memstead_relate`.
    #[error("entity {id} is a stub — promote it to a real entity via memstead_create first")]
    StubNotUpdatable { id: String },
    /// `memstead_rename` target is a stub — stubs do not have a title to
    /// rename (their title is derived from the id). Same recovery
    /// path as [`Self::StubNotUpdatable`].
    #[error(
        "entity {id} is a stub — promote it to a real entity via memstead_create before renaming"
    )]
    StubNotRenamable { id: String },
    /// An `EntityId` reaching a write path (notably `memstead_relate to=`)
    /// does not match the wiki-link grammar
    /// (`^[a-z0-9-]+(/[a-z0-9-]+)*$` for the slug; `^[a-z0-9-]+$` for
    /// the mem). The gate prevents an auto-stub being created at a
    /// malformed id — once present, that stub would fail any
    /// downstream wiki-link parse that referenced it.
    #[error("entity id '{id}' is malformed: {reason}")]
    InvalidEntityId { id: String, reason: String },
    /// An entity id longer than the engine accepts.
    #[error("entity id is too long: {length} characters, the limit is {max}")]
    EntityIdTooLong {
        id: String,
        length: usize,
        max: usize,
    },
    /// A body wiki-link target in a section body failed the strict
    /// slug-form grammar gate. The invariant is that every wiki-link target reaching
    /// `entity.relationships` carries a grammar-valid `EntityId` — the
    /// alias-synthesis pass would otherwise emit a relation pointing
    /// at a literal id (e.g. `mem--Knowledge Graph`) that no
    /// downstream wiki-link parse could ever resolve. `raw` is the
    /// input between brackets (after alias / `.md` strip); `suggested`
    /// is the `title_to_slug`-derived slug-form the agent lifts
    /// directly into the retry (omitted when the input has no
    /// meaningful canonical form — empty, all-punctuation, all-emoji);
    /// `section` is the section key whose body carried the link;
    /// `source` is a stable discriminator (`"body_link"`) future-
    /// proofed against additional ingress surfaces.
    #[error("body wiki-link target '{raw}' in section '{section}' is not slug-form: {reason}")]
    InvalidWikiLinkTarget {
        raw: String,
        suggested: Option<String>,
        section: String,
        link_source: String,
        reason: String,
    },
    /// A body wiki-link's Tier-2 mem prefix `[[mem:slug]]` failed
    /// the mem-name grammar (`^[a-z0-9-]+(/[a-z0-9-]+)*$`). Distinct
    /// from `InvalidWikiLinkTarget` because the recovery is different
    /// — mem names are fixed identifiers in the workspace, not
    /// free-form text the agent can mechanically slugify; the agent
    /// correlates the bad prefix against the workspace's known mems
    /// rather than reaching for `title_to_slug`.
    #[error(
        "body wiki-link mem prefix '{raw}' in section '{section}' is not a valid mem name: {reason}"
    )]
    InvalidWikiLinkMem {
        raw: String,
        section: String,
        reason: String,
    },
    /// `memstead_update` was asked to apply more than one section-
    /// mutation mode (`sections`, `append_sections`,
    /// `patch_sections`) to the same key. The request is ambiguous
    /// and rejected before any disk write. `modes` lists the
    /// conflicting modes for the key in canonical order.
    #[error("conflicting section modes for {section}: {modes:?}")]
    ConflictingSectionModes { section: String, modes: Vec<String> },
    /// Adding the proposed edge would close a cycle in an
    /// acyclic-declared subgraph. Carries the existing back-path
    /// `[from, …, current, target's intermediates, … from]` so MCP
    /// envelopes ship the cycle's shape without a follow-up
    /// `memstead_search`. Truncated at
    /// [`RELATIONSHIP_CYCLE_PATH_CAP`] entries. A refusal from a
    /// declared acyclicity SET additionally carries the set and one
    /// rel-type per hop of the path (the path may mix the set's
    /// rel-types); single-rel-type refusals keep their byte-identical
    /// payload (both extras absent).
    #[error("{}", _relationship_cycle_msg(rel_type, from, to, acyclic_set.as_deref()))]
    RelationshipCycle {
        rel_type: String,
        from: EntityId,
        to: EntityId,
        existing_path: Vec<EntityId>,
        path_truncated: bool,
        /// The declared acyclicity set, on set refusals only.
        acyclic_set: Option<Vec<String>>,
        /// One rel-type per hop of `existing_path`, on set refusals
        /// only (truncated alongside the path).
        existing_path_rel_types: Option<Vec<String>>,
    },
    /// `memstead_update` received the same metadata key in both `metadata`
    /// (set) and `metadata_unset` lists. The request is ambiguous and
    /// rejected before any disk write — the caller picks which map the
    /// key belongs in. `keys` lists every overlapping key in alphabetical
    /// order so a single envelope describes the full conflict.
    #[error("metadata keys appear in both set and unset: {keys:?}")]
    SetAndUnsetConflict { keys: Vec<String> },
    /// `metadata_unset` targeted a required field. Carries the
    /// recovery payload so the agent reads the field's purpose,
    /// allowed values, and type-level write rules from the envelope
    /// rather than re-fetching the schema.
    ///
    /// Also fires from `memstead_create` when the
    /// caller did not supply a required metadata field that the
    /// schema does not auto-fill (`default_value` / `init_timestamp`
    /// / `auto_timestamp` all absent). Pre-fix the create path
    /// surfaced this as a `MISSING_REQUIRED_FIELD` warning and let
    /// the entity land with a placeholder — silently corrupted the
    /// export-then-install round-trip when the placeholder was
    /// invalid for the install-time strict validator. The refusal
    /// fires once per call on the first missing field (declaration
    /// order); subsequent fields surface on the next attempt.
    #[error("{}", _required_field_unset_msg(field, entity_type, *on_create))]
    RequiredFieldUnset {
        field: String,
        entity_type: String,
        /// Schema-supplied description of the field.
        field_description: Option<String>,
        /// Allowed enum values when the unset field is enum-typed;
        /// empty when the field is free-form.
        enum_values: Vec<String>,
        /// Type-level `write_rules` for the entity type.
        type_write_rules: Vec<String>,
        /// Path discriminator: `true` when the
        /// create path constructed the variant (caller didn't supply
        /// the field), `false` when the update path constructed it
        /// (caller passed `metadata_unset: ["field"]` against a
        /// required field). The typed code stays `REQUIRED_FIELD_UNSET`
        /// on both paths; only the rendered prose differs.
        ///
        /// Not exposed on the `details` payload — agents already
        /// branch on the typed code; the new field is for the prose
        /// dispatch only.
        on_create: bool,
        /// Multi-field
        /// accumulator on the create path. Every required-no-default
        /// field that was unset, in schema declaration order. Empty
        /// on the unset path (where the agent targets one field by
        /// definition and the singular fields above are authoritative);
        /// always non-empty (and at least a singleton echo of the
        /// singular fields) on the create path.
        ///
        /// Surfaces on `details.missing[]` so an agent fixes every
        /// missing field in one round-trip. `details.field` and
        /// `details.missing[0].field` agree on the first-missing
        /// entry, keeping the back-compat singular-field shape.
        missing: Vec<MissingRequiredField>,
    },
    /// `memstead_create`: one or more required sections for the entity's
    /// type were absent or whitespace-only in the request. Pre-fix
    /// the create path surfaced this as `MISSING_REQUIRED_SECTION`
    /// warnings and wrote the entity with empty placeholders for
    /// the missing sections; the resulting on-disk state failed the
    /// install-time strict validator, breaking the export-then-
    /// install round-trip. The refusal carries every missing section
    /// (one entry per affected key) plus the type-level `type_guidance`
    /// map so the agent has a single round-trip recovery via re-call
    /// with the missing content filled in.
    ///
    /// Loader / health / `memstead_update` paths keep their permissive
    /// posture — a legacy on-disk entity created when this gate was
    /// a warning continues to load, surface in health, and accept
    /// partial updates. The refusal is a write-boundary gate, not a
    /// global invariant.
    #[error("missing {missing_count} required section(s) for type '{entity_type}'")]
    MissingRequiredSection {
        entity_type: String,
        /// Echoed for diagnostics; equals `sections.len()`.
        missing_count: usize,
        /// One entry per missing required section, in schema
        /// declaration order. Each entry mirrors the shape of the
        /// pre-fix `WarningHint::MissingRequiredSection` warning so
        /// agents reading the recovery payload don't branch on
        /// surface (refusal vs warning).
        sections: Vec<crate::runtime_validator::MissingRequiredSection>,
        /// Type-level `write_rules` keyed by `entity_type`. Map shape
        /// matches the mutation-response top-level `type_guidance`
        /// the warning-surface ships so a single decoder reads
        /// guidance from either path.
        type_guidance: std::collections::BTreeMap<String, Vec<String>>,
        /// Cross-gate pre-announcement: what the metadata gate
        /// (`REQUIRED_FIELD_UNSET`) will also demand once the sections
        /// are fixed — computed in the same validation pass so a first
        /// write learns both gates' demands in one refusal. Element
        /// shape matches `RequiredFieldUnset::missing[]` so the same
        /// decoder reads both. Rides `details.pre_announced` on the
        /// wire, and only when non-empty — a refusal from a body
        /// failing only the section gate is byte-identical to the
        /// pre-announcement-free shape. Best-effort by contract: what
        /// is announced is true; gates that cannot run against the
        /// broken body are not forced. Empty on surfaces that report
        /// each gate separately anyway (the integrity linter).
        pre_announced_missing_fields: Vec<MissingRequiredField>,
    },
    /// `patch_sections` targeted a key whose section body is
    /// absent from the entity (or has never been authored).
    #[error("patch target section is empty: {section}")]
    PatchSectionEmpty { section: String },
    /// `patch_sections` provided an `old` substring that does not
    /// appear in the section's current body. Carries a truncated
    /// snapshot of the current content so the caller can surface
    /// the actual state to the operator, and the sections whose
    /// bodies DO contain the substring — the one-call recovery when
    /// the patch simply targeted the wrong section.
    #[error("patch `old` substring not found in {section}")]
    PatchOldNotFound {
        section: String,
        current_content: String,
        truncated: bool,
        found_in_sections: Vec<String>,
    },
    /// `UNTERMINATED_FENCE_IN_STORED_BODY`: the entity on disk already ends a
    /// section inside an open code fence, and this write does not resolve it.
    ///
    /// The state is not the caller's doing: the generator closes every fence
    /// it emits, so it can only arrive by hand-authoring, a folder mem edited
    /// outside the engine, or sibling-committed branch state. But the closer
    /// is appended AFTER the already-absorbed bytes, so a write here would
    /// seal the swallowed sections inside a legitimately closed fence, and no
    /// later pass can tell them from prose the author meant to fence. The
    /// freeze is unrecoverable through the engine, which is why this refuses
    /// rather than warns.
    ///
    /// The way out is replace mode on the named section: that value passes
    /// the `UNTERMINATED_FENCE` guard, so it cannot leave a fence open, and
    /// the caller can lift the swallowed content back out of it. Its sibling
    /// [`ValidationError::UnterminatedFence`] refuses the same condition in
    /// content the caller supplies.
    #[error(
        "entity '{id}' section '{section}' ends inside an unterminated `{fence}` code fence, and \
         this update does not replace it. Writing now would close the fence around content that \
         belongs to other sections and make the loss permanent. Replace section '{section}' with \
         a corrected body in the same call."
    )]
    UnterminatedFenceInStoredBody {
        id: String,
        section: String,
        fence: String,
        swallowed: Vec<String>,
    },
    /// Schema-strictness rejection from the runtime validator
    /// (`UNKNOWN_SECTION`, `UNKNOWN_METADATA`, `INVALID_ENUM_VALUE`).
    #[error("schema validation: {0}")]
    Validation(#[from] ValidationError),
    /// Re-parse of the freshly-generated markdown failed. Should
    /// never happen — the generator's contract is that its output
    /// round-trips through `parse_markdown`. Surfaces if a future
    /// generator change breaks that invariant.
    #[error("parse-after-write failed: {0}")]
    ParseAfterWrite(String),
    /// A wrapped parse error for completeness; today only the
    /// parse-after-write variant above is constructed in the create
    /// path.
    #[error("parse error: {0}")]
    Parse(#[from] ParseError),
    /// A backend operation failed. Inner error carries the typed
    /// payload (e.g. `Sealed`, `Io`, `Path`). A backend's commit-tip
    /// CAS conflict never lands here: the `From` impl below maps
    /// [`BackendError::HashMismatch`] onto [`Self::HashMismatch`] so the
    /// wire carries one `HASH_MISMATCH` code for both detection levels.
    #[error(transparent)]
    Backend(BackendError),
    /// A mem's schema pin did not resolve. `sources` carries the
    /// fixed-order resolution diagnostics (local storage / built-in /
    /// remote) so the caller can tell *where* the pin failed and spot a
    /// right-name/wrong-version partial match; it surfaces under
    /// `details.sources`. Empty `sources` marks an internal lookup miss
    /// (an already-resolved schema absent from the engine's per-mem
    /// map), not a genuine source-resolution failure.
    ///
    /// The MESSAGE summarises the trail — which sources were searched
    /// and whether the name was found at other versions — so the
    /// distinction between a wrong-version pin and a never-installed
    /// package reaches consumers that never open `details` (a reported
    /// autonomous loop burned five rounds on the payload-only shape).
    /// `install_hint` (set by [`EngineError::with_schema_install_probe`]
    /// where a workspace root is known) names the authoring package
    /// that exists in the working tree but was never installed, and
    /// the message then points at `memstead schema install`.
    #[error("{}", schema_not_found_message(mem, pin, sources, install_hint))]
    SchemaNotFound {
        mem: String,
        pin: String,
        sources: Vec<SchemaSourceDiagnostic>,
        /// Path to an authoring package in the working tree whose
        /// manifest name matches the pin's name while NO source holds
        /// any version of that name — i.e. the package was authored
        /// but never installed. `None` when no such package exists,
        /// when the name is installed at other versions (a version
        /// mismatch is a different fix), or when no workspace root
        /// was available to probe.
        install_hint: Option<String>,
    },
    /// A sealed schema package carried inside a mem archive could not
    /// be loaded — the archive's own `.memstead/schema/` tree is
    /// broken. Deliberately NOT `SchemaNotFound`: the package is right
    /// here, so the recovery is never "obtain the schema and install
    /// it". The message quotes the loader's own diagnosis and the
    /// refusal leaves nothing mounted and nothing staged; only the
    /// publisher can fix it.
    #[error(
        "mem {mem}: the schema {pin} embedded in the archive could not be loaded: {reason} — \
         the package is inside the archive, so this is the publisher's to fix; nothing was \
         staged or mounted"
    )]
    EmbeddedSchemaInvalid {
        mem: String,
        pin: String,
        reason: String,
    },
    /// A schema package handed to `install_schema` failed validation —
    /// the loader's semantic checks or the section-heading round-trip
    /// gate. The engine refuses to seal an invalid schema onto
    /// `__MEMSTEAD`: install time is the last moment the author can
    /// act, because a schema already sealed keeps loading even when a
    /// later rule would refuse it.
    #[error("schema package '{name}@{version}' failed validation: {message}")]
    SchemaPackageInvalid {
        name: String,
        version: String,
        message: String,
    },
    /// `memstead_schema::builtins::load_builtin_schemas` itself failed.
    /// Surfaces during `Engine::from_mounts`; should never trip in
    /// practice (the built-in catalogue is statically embedded), but
    /// the failure path is preserved so a future on-disk catalogue
    /// switch lifts cleanly.
    #[error("built-in schema catalogue failed to load: {0}")]
    SchemaResolverInit(String),
    /// Generic mem-level error message — used by accessors that
    /// surface "mem exists, but the requested resource is not
    /// available for this backend" (e.g. `gitdir_for` against a
    /// folder mount, `worktree_for` against a git-branch mount).
    #[error("mem error: {0}")]
    Mem(String),
    /// `register_writable_mem` rejected because `name` is already
    /// registered (writable OR read-only). `source_origin` is the
    /// human-readable description of the colliding registration,
    /// rendered via [`MemOrigin::render_source`] for writable
    /// entries or a stand-in for read-only ones.
    #[error("mem name collision: {name} is already registered ({source_origin})")]
    MemNameCollision { name: String, source_origin: String },
    /// `set_mem_process_mem` refused the declared pairing: the named
    /// process mem is not mounted (`not_mounted`), is not pinned to an
    /// `ingest@*` schema (`not_ingest_schema`, with the pin it carries
    /// in `schema`), or is the mem itself (`self_pairing`). Typed code
    /// `PROCESS_MEM_NOT_ELIGIBLE`.
    #[error("{}", process_mem_not_eligible_message(.mem, .process_mem, .reason, .schema))]
    ProcessMemNotEligible {
        mem: String,
        process_mem: String,
        reason: &'static str,
        schema: Option<String>,
    },
    /// Lifecycle orchestrator rejected the input. Carries a single
    /// free-form message — the orchestrator's typed payload (note
    /// length, malformed path, etc.) is the message text.
    #[error("invalid input: {0}")]
    InvalidInput(String),
    /// A mem's anchors sidecar does not parse: its anchors are unknown, not
    /// absent.
    #[error("the anchors sidecar of mem `{mem}` could not be read ({reason})")]
    AnchorsSidecarUnreadable { mem: String, reason: String },
    /// A query that resolves to more than one entity where one is needed.
    #[error("ambiguous query: {} candidates match `{query}`", candidates.len())]
    AmbiguousQuery {
        query: String,
        candidates: Vec<serde_json::Value>,
    },
    /// The context of an entity that resolved could not be computed.
    #[error("could not compute context for `{id}`")]
    ContextNotComputable { id: String },
    /// A call that acts on installed read-mems only, given a writable one.
    #[error("`{mem}` is a writable mem, not an installed read-mem")]
    MemNotReadOnly { mem: String },
    /// A git operation on a mem, or a workspace, with no git branch behind
    /// it: a folder or archive mount, or a workspace with no git-branch
    /// mems at all (`mem` absent).
    #[error("{}", match mem {
        Some(m) => format!("mem '{m}' is not git-backed: `{operation}` requires a git-branch mount"),
        None => format!("this workspace has no git-branch mems: `{operation}` requires a mem-repo workspace"),
    })]
    NotGitBacked {
        mem: Option<String>,
        operation: String,
    },
    /// A command that needs a mem-repo workspace, run on a filesystem-mem
    /// one.
    #[error(
        "the workspace at {path} is filesystem-shaped; this command needs a mem-repo workspace"
    )]
    UnsupportedWorkspaceShape { path: String },
    /// A schema pin (`name@version`) that does not parse.
    #[error("invalid schema pin {pin:?}: {reason}")]
    InvalidSchemaPin {
        pin: String,
        reason: String,
        /// The schema names the asking surface could resolve.
        available: Vec<String>,
    },
    /// A chunk asked for past the end of a chunked response.
    #[error("Chunk {chunk} does not exist. Content has {total} chunk{}.", if *total == 1 { "" } else { "s" })]
    ChunkOutOfRange { chunk: usize, total: usize },
    /// An update template whose `title` or `entity_type` differs from the
    /// entity it targets: an update renames or retypes nothing.
    #[error(
        "template `{field}` {template:?} differs from the entity's current {field} {current:?}; an update cannot change it."
    )]
    TemplateIdentityMismatch {
        id: String,
        field: String,
        template: String,
        current: String,
    },
    /// A call that needs a writable mem, in a workspace that mounts none.
    #[error("no writable mem loaded")]
    NoWritableMem,
    /// A call that needs the one writable mem, where several are mounted.
    #[error("multiple writable mems loaded ({})", mems.join(", "))]
    AmbiguousMem { mems: Vec<String> },
    /// A type selection naming types the schema does not declare.
    #[error("unknown entity type(s): [{}]; declared types: [{}]", unknown.join(", "), declared.join(", "))]
    UnknownTypes {
        schema_ref: String,
        unknown: Vec<String>,
        declared: Vec<String>,
    },
    /// A schema asked for by name that no mounted, workspace-installed or
    /// built-in schema carries.
    #[error("schema not found: {name:?}")]
    UnknownSchema {
        name: String,
        available: Vec<String>,
    },
    /// A `target_schema` argument that does not parse as a schema pin.
    #[error("invalid target_schema {raw:?}: {reason}")]
    InvalidTargetSchema { raw: String, reason: String },
    /// Merge-conflict listing/resolution targeted a mem whose backend
    /// cannot acquire git merge conflicts through supported use — the
    /// git-branch mem-repo is engine-managed, archives and in-memory
    /// sketches have no user-git seam at all. Only folder mems live in
    /// the user's own repository where an ordinary merge can write
    /// conflict markers into entity files. Typed code
    /// `CONFLICT_RESOLVE_UNSUPPORTED_BACKEND`.
    #[error(
        "mem `{mem}` is not folder-backed — its storage cannot acquire git merge \
         conflicts through supported use; `conflicts` operations apply to folder mems only"
    )]
    MergeConflictUnsupportedBackend { mem: String },
    /// Conflict resolution targeted an entity whose file carries no git
    /// merge-conflict markers — nothing to resolve. Distinct from
    /// `NotFound` so an agent can tell "already clean" from "no such
    /// entity". Typed code `NOT_CONFLICTED`.
    #[error(
        "entity `{id}` is not conflicted — its file carries no git merge-conflict \
         markers; nothing to resolve"
    )]
    NotConflicted { id: String },
    /// `conflicts resolve --side merged` on a file with a conflict block
    /// that covers more than the engine-stamped `last_modified` key: a
    /// body section, or another frontmatter key (`created_date`
    /// included). Such a block is a content judgement, made by choosing
    /// `ours` or `theirs`. Nothing is written; the file stays in
    /// conflict. `details` names the block's frontmatter `key` or body
    /// `section`.
    #[error(
        "entity `{id}` has a conflict block on {} — only a conflict on `last_modified` alone resolves `merged`; choose `--side ours` or `--side theirs` for it",
        conflict_location(key.as_deref(), section.as_deref())
    )]
    ConflictNotTimestampOnly {
        id: String,
        key: Option<String>,
        section: Option<String>,
    },
    /// `memstead_fetch` / `memstead_pull` / `memstead_push` named a remote that is
    /// not configured on the workspace's mem-repo. Typed code
    /// `UNKNOWN_REMOTE`. Recovery: configure the remote via
    /// `memstead mem-repo remote-add <name> <url>`.
    #[error(
        "unknown remote: {0} — no remote of that name is configured on the mem-repo; add it with `memstead mem-repo remote-add {0} <url>`"
    )]
    UnknownRemote(String),
    /// A remote that IS configured on the mem-repo could not be reached
    /// (the host does not resolve, the connection is refused, the URL
    /// names no repository). Typed code `REMOTE_UNREACHABLE`, apart from
    /// `UNKNOWN_REMOTE` because the repair differs: reach the URL (the
    /// network, the address), or re-point the remote, rather than add
    /// one. `details` names the remote, its configured URL and the first
    /// line of git's answer.
    #[error(
        "remote `{remote}` is configured ({url}) but could not be reached: {detail} — check the URL and the network, or re-point it with `memstead mem-repo remote-add {remote} <url>`"
    )]
    RemoteUnreachable {
        remote: String,
        url: String,
        detail: String,
    },
    /// `memstead_pull` refused because the local branch has diverged from
    /// the remote-tracking ref — fast-forward is impossible without
    /// losing local commits. Recovery: run `memstead branch-reset` to the
    /// remote-tracking ref (if the local commits are dispensable) or
    /// run a replay workflow to rewrite them onto the new remote tip.
    /// Typed code `LOCAL_DIVERGENCE`.
    #[error(
        "mem `{mem}`'s local branch has diverged from `{remote_ref}` — pull cannot fast-forward without losing local commits; rebase / replay first or run memstead branch-reset"
    )]
    LocalDivergence { mem: String, remote_ref: String },
    /// `memstead_push` refused because the push would not be a fast-forward
    /// against the remote and the caller did not pass `force: true`.
    /// Typed code `NON_FAST_FORWARD`. Recovery: re-fetch + replay, or
    /// re-issue with `force: true` (warning: rewrites the remote's
    /// view of the branch — other peers will see the rewrite).
    #[error(
        "push to remote `{remote}` for mem `{mem}` is not a fast-forward; rebase / replay locally or pass `force: true` to overwrite the remote"
    )]
    NonFastForward { mem: String, remote: String },
    /// `memstead_push` refused because the local state failed pre-push
    /// schema validation. The remote was not contacted. Recovery: fix
    /// the schema violations (use `memstead_health` to find them) and
    /// retry. Typed code `LOCAL_INVALID_STATE`.
    #[error(
        "mem `{mem}` failed pre-push schema validation; remote `{remote}` was not contacted: {detail}"
    )]
    LocalInvalidState {
        mem: String,
        remote: String,
        detail: String,
    },
    /// `memstead_pull` (or any future merge path that consumes fetched
    /// commits) refused because the prospective post-merge tree
    /// contains entities that fail schema validation. The branch
    /// pointer was not moved. `violations` carries one entry per
    /// offending entity — typically `(relative_path, parse_error)`
    /// pairs rendered as strings — so the caller can surface the
    /// remediation surface without re-walking the tree. Typed code
    /// `SCHEMA_VIOLATION_IN_FETCH`.
    #[error(
        "mem `{mem}` would fail schema validation at `{ref_name}` — {n} violation(s); fix the remote or replay locally first",
        n = violations.len(),
    )]
    SchemaViolationInFetch {
        mem: String,
        ref_name: String,
        violations: Vec<String>,
    },
    /// `memstead_branch_reset` refused because at least one commit that
    /// would be discarded by the reset is already reachable from a
    /// `refs/remotes/*` ref (the engine's definition of "pushed").
    /// `pushed_shas` lists the offending commits. The agent's
    /// recovery is to pick a target SHA that does not strand a pushed
    /// commit, or to push the pre-reset state under a different
    /// branch name first. Typed code: `PUSHED_COMMITS_PROTECTED`.
    #[error(
        "branch_reset refused: {} pushed commit(s) would be discarded ({}); pick a target that preserves the pushed segment or push the pre-reset state under a different branch first",
        pushed_shas.len(),
        pushed_shas.join(", "),
    )]
    PushedCommitsProtected {
        mem: String,
        target_sha: String,
        pushed_shas: Vec<String>,
    },
    /// `branch_reset` refused because the live branch head no longer
    /// matches the head the caller observed (`expected_head`) — a
    /// sibling writer advanced the mem, and resetting now would discard
    /// that foreign work. Optimistic concurrency for history rewrites;
    /// the caller re-reads and re-decides. Typed code:
    /// `BRANCH_RESET_HEAD_MOVED`.
    #[error(
        "branch_reset refused: '{mem}' has advanced past the observed head (expected {expected}, live {current}) — the span now contains foreign commits; reload and review the accumulated delta instead"
    )]
    BranchResetHeadMoved {
        mem: String,
        expected: String,
        current: String,
    },
    /// `memstead_diff` (or any future ref-comparing op) received a ref
    /// that does not resolve against the workspace's mem-repo.
    /// Carries the ref string verbatim so the caller can fix the
    /// input. Typed code `UNKNOWN_REF`.
    #[error("unknown ref: {0}")]
    UnknownRef(String),
    /// A proposal merge's disposition file does not cover the brief:
    /// it lacks slots for entities the brief lists, or names entities
    /// the brief does not. Typed code `PROPOSAL_DISPOSITIONS_INCOMPLETE`;
    /// `details.missing` and `details.unexpected` list them.
    #[error(
        "the disposition file does not cover the brief of fork '{fork}'{}: re-render the brief \
         (`memstead proposal brief {fork} --out <file>`) and fill every slot",
        proposal_incomplete_summary(.missing, .unexpected)
    )]
    ProposalDispositionsIncomplete {
        fork: String,
        missing: Vec<String>,
        unexpected: Vec<String>,
    },
    /// `adopt` on an entity the target moved since the ancestor. Typed
    /// code `PROPOSAL_CONFLICT`; `details.slug` and `details.kind` name
    /// the entity and the conflict kind.
    #[error(
        "entity '{slug}' of fork '{fork}' is in conflict with the target ({kind}): `adopt` is \
         withheld; supply the merged body under `adopt_with_changes`, or reject it"
    )]
    ProposalConflict {
        fork: String,
        slug: String,
        kind: String,
    },
    /// The disposition file was rendered against a branch tip that has
    /// moved since. Typed code `PROPOSAL_STALE`; `details.side` says
    /// which branch (`target` or `fork`), `details.recorded` and
    /// `details.current` carry both shas.
    #[error(
        "the disposition file of fork '{fork}' was rendered against the {side} tip {recorded}, \
         and that branch now stands at {current}: re-render the brief (`memstead proposal \
         brief {fork} --out <file>`) and fill it again"
    )]
    ProposalStale {
        fork: String,
        side: String,
        recorded: String,
        current: String,
    },
    /// An adopted entity's last fork commit carries no `Identity:`
    /// trailer, so the merge has no proposer to record. Typed code
    /// `PROPOSAL_UNATTRIBUTED`; `details.slug` and `details.sha` name
    /// the entity and the commit.
    #[error(
        "entity '{slug}' of fork '{fork}' was last touched by commit {sha}, which carries no \
         Identity trailer: a merge never invents an author, so re-commit it on the fork under \
         an identity (`--identity`) or reject it"
    )]
    ProposalUnattributed {
        fork: String,
        slug: String,
        sha: String,
    },
    /// An adopted entity links an entity the same disposition file
    /// rejects, and the target mem holds no entity under that slug, so
    /// the merge would land the edge on a dangling stub and the target
    /// would read `UNRESOLVED_STUB` the moment the merge reported
    /// success. Typed code `PROPOSAL_LINKS_REJECTED_ENTITY`;
    /// `details.slug`, `details.rel_type` and `details.target` name the
    /// adopted entity, the edge and the rejected target.
    #[error(
        "entity '{slug}' of fork '{fork}' links '{target}' via {rel_type}, and the same file \
         rejects '{target}' while the target mem holds no entity under that slug: the merge \
         would land a dangling stub. Adopt '{target}' too, or `adopt_with_changes` '{slug}' \
         with a `relations` list that leaves the edge out, or reject '{slug}'"
    )]
    ProposalLinksRejected {
        fork: String,
        slug: String,
        rel_type: String,
        target: String,
    },
    /// `memstead_changes_since` received a `rename_similarity` value
    /// outside the allowed range. Maps to wire code `INVALID_INPUT`
    /// with `details.allowed_range: [min, max]` and
    /// `details.requested`. Promoted from the prior silent-clamp + LIMIT_CLAMPED warning so
    /// nonsense inputs surface as recoverable refusal rather than
    /// silent rounding.
    #[error("rename_similarity {requested} outside allowed range [{allowed_min}, {allowed_max}]")]
    RenameSimilarityOutOfRange {
        requested: f32,
        allowed_min: f32,
        allowed_max: f32,
    },
    /// `memstead_changes_since` / `memstead changes --since` was given a `since`
    /// commit cursor the mem's git repository can't resolve — a
    /// malformed prefix or a well-formed-but-absent 40-hex. Surfaces the
    /// `INVALID_CURSOR` code (the documented contract for this op, which
    /// the CLI previously leaked as the `MEM_ERROR` catch-all) so a
    /// sync loop branches cleanly: `INVALID_CURSOR` → re-seed from the
    /// empty-tree sentinel; `MEM_ERROR` → genuine backend fault.
    /// `details.since` carries the offending cursor untruncated.
    #[error(
        "commit cursor '{since}' is not a known commit in mem '{mem}' — pass the `head` a prior memstead_changes_since call returned, or the empty-tree sentinel to re-seed. A mutation's `write_id` is an identity, not a cursor"
    )]
    InvalidChangesCursor { mem: String, since: String },
    /// `memstead_changes_since` / `memstead changes --since` on a
    /// folder-backed (or in-memory) mem was given a `since` that is not
    /// an RFC3339 timestamp. These backends key the change ledger off
    /// timestamps and compare lexically, so before this refusal a
    /// mutation's `write_id` — fixed-width hex that sorts below every
    /// timestamp — silently replayed the whole history. Shares the
    /// `INVALID_CURSOR` code with the git-backed variant so a sync
    /// loop's branch (`INVALID_CURSOR` → re-seed) is backend-agnostic.
    /// `details.since` carries the offending cursor untruncated.
    #[error(
        "changes cursor '{since}' is not an RFC3339 timestamp — on mem '{mem}' pass the `since` a prior memstead_changes_since call returned (the ledger's latest `ts`), or the empty string / empty-tree sentinel to read from the beginning. A mutation's `write_id` is an identity, not a cursor"
    )]
    InvalidTimestampCursor { mem: String, since: String },
    /// `review_mark_diff` was called on a mem with no review mark set.
    /// Marklessness is a first-class, known-from-the-roster state — the
    /// diff surface refuses typed rather than silently equating "no
    /// mark" with "no changes".
    #[error(
        "mem '{mem}' has no review mark — set one first, or read the full history via changes_since"
    )]
    ReviewMarkNotSet { mem: String },
    /// Mem config is missing a required field that the engine
    /// itself would normally populate (today: `version` at mem
    /// init). Surfaced on the export path — pre-fix this collapsed
    /// to `INTERNAL` with a misleading `.memstead/config.json` reference
    /// that doesn't match the mem-repo backend's blob layout.
    /// Recovery: run `memstead mem set-version <mem> <version>` to
    /// populate the field, then retry the export.
    #[error(
        "mem `{mem}` config is missing required field(s) {missing_fields:?} — \
         set via `memstead mem set-version {mem} <version>` (e.g. 0.1.0)"
    )]
    MemConfigIncomplete {
        mem: String,
        missing_fields: Vec<String>,
    },
    /// `memstead_relate` (or a `declare_relations` entry) targeted a
    /// rel-type whose schema declares `per_edge_description:
    /// required` without supplying a description. Recovery: re-issue
    /// the call with `--description "<text>"` describing why this
    /// particular edge exists (the rel-type's name documents the
    /// kind of edge; the description documents the instance).
    #[error(
        "rel-type `{rel_type}` declares `per_edge_description: required` — \
         {from_id} → {to_id} needs a description; re-issue with \
         `--description \"<text>\"`."
    )]
    MissingRequiredDescription {
        rel_type: String,
        from_id: String,
        to_id: String,
    },
    /// `memstead_relate` (or a `declare_relations` entry) supplied a
    /// description for a rel-type whose schema declares
    /// `per_edge_description: forbidden`. Recovery: drop the
    /// `description` parameter — the rel-type's name describes the
    /// edge; per-edge text is not permitted on this rel-type.
    #[error(
        "rel-type `{rel_type}` declares `per_edge_description: forbidden` — \
         {from_id} → {to_id} cannot carry a description; drop the \
         `--description` argument."
    )]
    DescriptionNotPermitted {
        rel_type: String,
        from_id: String,
        to_id: String,
    },
    /// `memstead_relate` (or a `declare_relations` / `memstead_create`'s
    /// inline `relations:` entry) targeted a rel-type whose schema
    /// declares `manual_authoring: forbidden`. The rel-type is
    /// reserved for engine-emitted synthesis (the body-link →
    /// relation alias machinery, typically). Recovery: don't author
    /// the relation explicitly; instead author a body wiki-link
    /// `[[target]]` in the source's section content, which the
    /// engine surfaces as the appropriate alias relation
    /// automatically.
    #[error(
        "rel-type `{rel_type}` declares `manual_authoring: forbidden` — \
         {from_id} → {to_id} cannot be authored explicitly; this rel-type \
         is reserved for engine-emitted synthesis via the body-link → \
         relation alias path. {guidance}"
    )]
    RelationManualAuthoringForbidden {
        rel_type: String,
        from_id: String,
        to_id: String,
        guidance: String,
    },
    /// Full-text search is unavailable in the current engine build —
    /// `Engine::search` is callable on every target so JS / FFI
    /// consumers don't need to re-shape their call sites, but `wasm32`
    /// builds omit the tantivy index entirely (its native-only
    /// transitives — `getrandom 0.2` without `js`, `memmap2`, `rayon`,
    /// `zstd-sys` — block WASM compilation). Browser consumers route
    /// queries to the bridge's `memstead_search` endpoint. The MCP layer
    /// maps this to typed code `SEARCH_UNAVAILABLE_IN_WASM`.
    #[error(
        "full-text search is unavailable in this engine build (wasm32); \
         route search queries to the bridge's memstead_search endpoint"
    )]
    SearchUnavailable,
    /// `memstead export --format markdown --mem-name <V>` was called
    /// against a mem whose active backend doesn't support markdown
    /// regeneration in place (today: every backend other than
    /// `folder`). Pre-fix this collapsed to a silent
    /// `ExportResult { written: 0, unchanged: 0 }` masquerading as
    /// success. Recovery: use `--format mem` to produce a portable
    /// `.mem` archive, which every backend supports.
    #[error(
        "mem `{mem}` is on backend `{active_backend}`; `memstead export --format markdown` \
         is supported only on backends [{}] — use `--format mem` to produce a portable \
         `.mem` archive instead",
        supported_backends.join(", ")
    )]
    MarkdownExportUnsupportedBackend {
        mem: String,
        active_backend: String,
        supported_backends: Vec<String>,
    },
    /// A `memstead_create` / `memstead_update` `anchors[]` element was
    /// malformed — an unknown provenance class or grain, a missing artifact
    /// reference, a content hash on a class without hash semantics, or a
    /// grain the resolving medium's namespace cannot express. The whole
    /// mutation refuses and the entity is not written; the wrapped
    /// [`crate::anchor::AnchorValidationError`] carries the recovery
    /// `details` (offending field, bad value, allowed set). Typed code
    /// `INVALID_ANCHOR`.
    #[error("invalid anchor: {0}")]
    InvalidAnchor(#[from] crate::anchor::AnchorValidationError),
    /// An error raised while a batch act processed one entity: the
    /// proposal merge rehearsing an adopted body through the write
    /// gate, or any act that walks several entities and refuses on one
    /// of them. Generic by design: `entity` is the entity the act was
    /// on, in the caller's own naming (a slug, an id), `stage` is the
    /// step it was in (the proposal merge says `landing` for the fork's
    /// version and `amend` for the owner's body), and `source` is the
    /// refusal itself. The wire code stays the source's own
    /// ([`Self::code`] delegates), `details` is the source's payload
    /// with `entity` and `stage` added (a key the source already set is
    /// never overwritten), and the message is the source's under a
    /// `<entity> (<stage>): ` prefix. Built with [`Self::in_entity`].
    #[error("{entity} ({stage}): {source}")]
    InEntity {
        entity: String,
        stage: String,
        source: Box<EngineError>,
    },
}

/// `details` with `entity` and `stage` added, the payload shape of
/// [`EngineError::InEntity`]: a key the source payload already carries
/// keeps its value. A payload that is not an object (no variant renders
/// one today) is kept whole under `source_details`. Shared by the
/// engine's [`EngineError::details`] and the surfaces that build their
/// own per-variant payloads, so the wrapper adds the same two keys
/// everywhere.
pub fn scope_details_to_entity(
    details: serde_json::Value,
    entity: &str,
    stage: &str,
) -> serde_json::Value {
    let mut map = match details {
        serde_json::Value::Object(map) => map,
        serde_json::Value::Null => serde_json::Map::new(),
        other => {
            let mut map = serde_json::Map::new();
            map.insert("source_details".to_string(), other);
            map
        }
    };
    map.entry("entity")
        .or_insert_with(|| serde_json::Value::String(entity.to_string()));
    map.entry("stage")
        .or_insert_with(|| serde_json::Value::String(stage.to_string()));
    serde_json::Value::Object(map)
}

/// Typed payload for a single Write-Mem referrer in
/// [`EngineError::HasIncomingRefs`]. Captures the (from_id, rel_types,
/// mem) triple the surface envelope projects so consumers can reason
/// about the offending edges without a follow-up `memstead_entity` call.
/// The mem is always a Write-Mem — ReadOnly referrers are
/// partitioned out before this struct is constructed and surfaced via
/// the residual-stub warning channel instead.
///
/// Per-source deduplication: when one source entity has multiple
/// edges of different rel-types pointing at the deletion target, the
/// engine collapses them into a single `ReferrerInfo` whose
/// `rel_types` list carries every edge type. A prior shape
/// emitted one entry per edge, making a source-with-N-edges look
/// like N distinct referrers in the error message and structured
/// payload.
#[derive(Debug, Clone, serde::Serialize)]
pub struct ReferrerInfo {
    pub from_id: String,
    pub rel_types: Vec<String>,
    pub mem: String,
}

/// Inline rendering on the text mirror. Single rel-type renders as
/// just the referring entity id; multiple rel-types append the
/// `×N [REL1, REL2]` annotation so the count and the offending
/// edge-types stay visible without parsing the structured payload.
impl fmt::Display for ReferrerInfo {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        if self.rel_types.len() <= 1 {
            f.write_str(&self.from_id)
        } else {
            write!(
                f,
                "{} ×{} [{}]",
                self.from_id,
                self.rel_types.len(),
                self.rel_types.join(", ")
            )
        }
    }
}

/// One body wiki-link that violates the strict wiki-link /
/// relation invariant. Surfaces inside
/// [`EngineError::WikiLinkWithoutRelation::missing`].
#[derive(Debug, Clone, serde::Serialize, PartialEq, Eq)]
pub struct MissingWikiLink {
    /// Section key of the entity body where the unbacked
    /// wiki-link appears.
    pub section_key: String,
    /// EntityId target of the unbacked wiki-link.
    pub target_id: String,
}

/// Inline rendering pairs the section key with the unbacked target id
/// so an agent reading only the text mirror can see both where the link
/// lives and what it points at without decoding the structured payload.
impl fmt::Display for MissingWikiLink {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(f, "{}→{}", self.section_key, self.target_id)
    }
}

/// The clause a `PROPOSAL_DISPOSITIONS_INCOMPLETE` message carries:
/// which slots are missing, which are unexpected.
fn proposal_incomplete_summary(missing: &[String], unexpected: &[String]) -> String {
    let mut parts: Vec<String> = Vec::new();
    if !missing.is_empty() {
        parts.push(format!("missing {}", missing.join(", ")));
    }
    if !unexpected.is_empty() {
        parts.push(format!("not in the brief {}", unexpected.join(", ")));
    }
    if parts.is_empty() {
        String::new()
    } else {
        format!(" ({})", parts.join("; "))
    }
}

impl EngineError {
    /// Stable, surface-independent error code token.
    ///
    /// Each surface (MCP envelope, CLI envelope) maps
    /// the variant to its wire shape; the code returned here is the
    /// canonical name agents key on. Add a new code here when a new
    /// variant lands; do not invent ad-hoc strings inside the
    /// per-surface mapping.
    pub fn code(&self) -> &'static str {
        match self {
            EngineError::DuplicateMem(_) => "DUPLICATE_MEM",
            EngineError::UnknownMem { .. } => "UNKNOWN_MEM",
            EngineError::MemUnmounted { .. } => "MEM_UNMOUNTED",
            EngineError::MemQuarantined { .. } => "MEM_QUARANTINED",
            EngineError::UnknownRef(_) => "UNKNOWN_REF",
            EngineError::ProposalDispositionsIncomplete { .. } => {
                "PROPOSAL_DISPOSITIONS_INCOMPLETE"
            }
            EngineError::ProposalConflict { .. } => "PROPOSAL_CONFLICT",
            EngineError::ProposalStale { .. } => "PROPOSAL_STALE",
            EngineError::ProposalUnattributed { .. } => "PROPOSAL_UNATTRIBUTED",
            EngineError::ProposalLinksRejected { .. } => "PROPOSAL_LINKS_REJECTED_ENTITY",
            EngineError::UnknownRemote(_) => "UNKNOWN_REMOTE",
            EngineError::RemoteUnreachable { .. } => "REMOTE_UNREACHABLE",
            EngineError::LocalDivergence { .. } => "LOCAL_DIVERGENCE",
            EngineError::NonFastForward { .. } => "NON_FAST_FORWARD",
            EngineError::LocalInvalidState { .. } => "LOCAL_INVALID_STATE",
            EngineError::SchemaViolationInFetch { .. } => "SCHEMA_VIOLATION_IN_FETCH",
            EngineError::PushedCommitsProtected { .. } => "PUSHED_COMMITS_PROTECTED",
            EngineError::BranchResetHeadMoved { .. } => "BRANCH_RESET_HEAD_MOVED",
            EngineError::ReadOnlyMount(_) => "READ_ONLY_MOUNT",
            EngineError::CheckNotRecorded { .. } => "CHECK_NOT_RECORDED",
            EngineError::UnknownType { .. } => "UNKNOWN_ENTITY_TYPE",
            EngineError::InvalidTitle(_) => "INVALID_TITLE",
            EngineError::AlreadyExists { .. } => "ENTITY_ALREADY_EXISTS",
            EngineError::ConstraintUnsatisfied { .. } => "CONSTRAINT_UNSATISFIED",
            EngineError::RequiredOutgoingUnsatisfied { .. } => "MISSING_REQUIRED_OUTGOING",
            EngineError::SectionFormatRefused { violation, .. } => violation.code(),
            EngineError::NotFound { .. } => "ENTITY_NOT_FOUND",
            EngineError::HashMismatch { .. } => "HASH_MISMATCH",
            EngineError::ExpectedHashRequired { .. } => "EXPECTED_HASH_REQUIRED",
            EngineError::HasIncomingRefs { .. } => "HAS_INCOMING_REFS",
            EngineError::MemHasIncomingRefs { .. } => "MEM_HAS_INCOMING_REFS",
            EngineError::CrossMemLinkNotAllowed { .. } => "CROSS_MEM_LINK_NOT_ALLOWED",
            EngineError::CrossMemTargetNotFound { .. } => "CROSS_MEM_TARGET_NOT_FOUND",
            EngineError::EntityIdMissingMem { .. } => "ENTITY_ID_MISSING_MEM",
            EngineError::CrossMemEdgeNotDeclared { .. } => "CROSS_MEM_EDGE_NOT_DECLARED",
            EngineError::RepairNotNeeded { .. } => "REPAIR_NOT_NEEDED",
            EngineError::RenameNoOp { .. } => "RENAME_NO_OP",
            EngineError::RetypeRefused { problems, .. } => {
                // A section-map defect dominates: until the keys land where
                // the target declares them, nothing else about the sections
                // can be judged, and the missing-required findings it causes
                // ride along in `details.problems`.
                if problems.iter().any(|p| p.code() == "UNKNOWN_SECTION") {
                    return "UNKNOWN_SECTION";
                }
                let first = problems.first().map(|p| p.code());
                match first {
                    Some(code) if problems.iter().all(|p| p.code() == code) => code,
                    _ => "RETYPE_REFUSED",
                }
            }
            EngineError::RetypeNoOp { .. } => "RETYPE_NO_OP",
            EngineError::InvalidCheckFinding { .. } => crate::check::INVALID_CHECK_FINDING_CODE,
            EngineError::RetypeReferrerUnprobeable { .. } => "RETYPE_REFERRER_UNPROBEABLE",
            EngineError::EmptyUpdate { .. } => "EMPTY_UPDATE",
            EngineError::RenameBlockedByCrossMemPolicy { .. } => {
                "RENAME_BLOCKED_BY_CROSS_MEM_POLICY"
            }
            EngineError::RenamePartialFailure { .. } => "RENAME_PARTIAL_FAILURE",
            EngineError::CommitNotApplied { .. } => "COMMIT_NOT_APPLIED",
            EngineError::StaleView { .. } => "MEM_VIEW_STALE",
            EngineError::RelationHasBodyLinks { .. } => "RELATION_HAS_BODY_LINKS",
            EngineError::WikiLinkWithoutRelation { .. } => "WIKILINK_WITHOUT_RELATION",
            EngineError::StubCannotRelate { .. } => "STUB_CANNOT_RELATE",
            EngineError::StubNotUpdatable { .. } => "STUB_NOT_UPDATABLE",
            EngineError::StubNotRenamable { .. } => "STUB_NOT_RENAMABLE",
            EngineError::InvalidEntityId { .. } => "INVALID_ENTITY_ID",
            EngineError::EntityIdTooLong { .. } => "INVALID_ENTITY_ID",
            EngineError::InvalidWikiLinkTarget { .. } => "INVALID_WIKI_LINK_TARGET",
            EngineError::InvalidWikiLinkMem { .. } => "INVALID_MEM_NAME",
            EngineError::ConflictingSectionModes { .. } => "CONFLICTING_SECTION_MODES",
            EngineError::RelationshipCycle { .. } => "RELATIONSHIP_CYCLE",
            EngineError::SetAndUnsetConflict { .. } => "SET_AND_UNSET_CONFLICT",
            EngineError::RequiredFieldUnset { .. } => "REQUIRED_FIELD_UNSET",
            EngineError::MissingRequiredSection { .. } => "MISSING_REQUIRED_SECTION",
            EngineError::PatchSectionEmpty { .. } => "PATCH_SECTION_EMPTY",
            EngineError::PatchOldNotFound { .. } => "PATCH_OLD_NOT_FOUND",
            EngineError::UnterminatedFenceInStoredBody { .. } => {
                "UNTERMINATED_FENCE_IN_STORED_BODY"
            }
            EngineError::Validation(v) => v.code(),
            EngineError::ParseAfterWrite(_) => "PARSE_ERROR",
            EngineError::Parse(_) => "PARSE_ERROR",
            EngineError::Backend(_) => "MEM_ERROR",
            EngineError::SchemaNotFound { .. } => "SCHEMA_NOT_FOUND",
            EngineError::EmbeddedSchemaInvalid { .. } => "EMBEDDED_SCHEMA_INVALID",
            EngineError::SchemaPackageInvalid { .. } => "SCHEMA_VALIDATION_FAILED",
            EngineError::SchemaResolverInit(_) => "SCHEMA_RESOLVER_INIT_FAILED",
            EngineError::Mem(_) => "MEM_ERROR",
            EngineError::MemNameCollision { .. } => "MEM_NAME_COLLISION",
            EngineError::ProcessMemNotEligible { .. } => "PROCESS_MEM_NOT_ELIGIBLE",
            EngineError::InvalidInput(_) => "INVALID_INPUT",
            EngineError::NoWritableMem => "NO_WRITABLE_MEM",
            EngineError::AnchorsSidecarUnreadable { .. } => "ANCHORS_SIDECAR_UNREADABLE",
            EngineError::AmbiguousQuery { .. } => "AMBIGUOUS_QUERY",
            EngineError::ContextNotComputable { .. } => "CONTEXT_NOT_COMPUTABLE",
            EngineError::MemNotReadOnly { .. } => "MEM_NOT_READ_ONLY",
            EngineError::NotGitBacked { .. } => "INVALID_INPUT",
            EngineError::TemplateIdentityMismatch { .. } => "INVALID_INPUT",
            EngineError::ChunkOutOfRange { .. } => "CHUNK_OUT_OF_RANGE",
            EngineError::InvalidSchemaPin { .. } => "INVALID_INPUT",
            EngineError::UnsupportedWorkspaceShape { .. } => "UNSUPPORTED_WORKSPACE_SHAPE",
            EngineError::AmbiguousMem { .. } => "AMBIGUOUS_MEM",
            EngineError::UnknownTypes { .. } => "UNKNOWN_ENTITY_TYPE",
            EngineError::UnknownSchema { .. } => "SCHEMA_NOT_FOUND",
            EngineError::InvalidTargetSchema { .. } => "INVALID_INPUT",
            EngineError::MergeConflictUnsupportedBackend { .. } => {
                "CONFLICT_RESOLVE_UNSUPPORTED_BACKEND"
            }
            EngineError::NotConflicted { .. } => "NOT_CONFLICTED",
            EngineError::ConflictNotTimestampOnly { .. } => "CONFLICT_NOT_TIMESTAMP_ONLY",
            EngineError::RenameSimilarityOutOfRange { .. } => "INVALID_INPUT",
            EngineError::InvalidChangesCursor { .. } => "INVALID_CURSOR",
            EngineError::InvalidTimestampCursor { .. } => "INVALID_CURSOR",
            EngineError::ReviewMarkNotSet { .. } => "REVIEW_MARK_NOT_SET",
            EngineError::MemConfigIncomplete { .. } => "MEM_CONFIG_INCOMPLETE",
            EngineError::MissingRequiredDescription { .. } => "MISSING_REQUIRED_DESCRIPTION",
            EngineError::DescriptionNotPermitted { .. } => "DESCRIPTION_NOT_PERMITTED",
            EngineError::RelationManualAuthoringForbidden { .. } => {
                "RELATION_MANUAL_AUTHORING_FORBIDDEN"
            }
            EngineError::SearchUnavailable => "SEARCH_UNAVAILABLE_IN_WASM",
            EngineError::MarkdownExportUnsupportedBackend { .. } => {
                "MARKDOWN_EXPORT_UNSUPPORTED_BACKEND"
            }
            EngineError::InvalidAnchor(_) => crate::anchor::INVALID_ANCHOR_CODE,
            EngineError::InEntity { source, .. } => source.code(),
        }
    }

    /// Wrap `self` as the refusal a batch act met on `entity` during
    /// `stage`: the code and payload stay this error's, with the entity
    /// and the stage added (see [`EngineError::InEntity`]).
    pub fn in_entity(self, entity: impl Into<String>, stage: impl Into<String>) -> Self {
        EngineError::InEntity {
            entity: entity.into(),
            stage: stage.into(),
            source: Box::new(self),
        }
    }

    /// Variant-specific recovery payload, rendered as a structured
    /// JSON object that surfaces under `error.details` in MCP /
    /// CLI envelopes.
    ///
    /// Pre-fix the
    /// batch-update per-item envelope (`batch_error_envelope`)
    /// shipped `{}` for every typed code except `Validation`, while
    /// the singleton-call surfaces (`CliError::from_engine_op`,
    /// `memstead-mcp`'s `engine_err_unified`) populated structured
    /// payloads per-variant. Two envelopes, two details paths —
    /// agents' "fix from `details`" recovery loop worked
    /// differently in batch vs singleton mode. The centralised
    /// helper here gives both surfaces one source of truth.
    ///
    /// Returns an empty object for variants whose recovery payload
    /// is the message text alone (no structured fields beyond
    /// `code` + `message`).
    /// The error as a condition carried inside a successful response: its
    /// code beside its own payload keys.
    pub fn as_condition(&self) -> serde_json::Value {
        let mut v = self.details();
        if let Some(obj) = v.as_object_mut() {
            obj.insert("code".into(), serde_json::json!(self.code()));
        }
        v
    }

    pub fn details(&self) -> serde_json::Value {
        match self {
            EngineError::RetypeRefused {
                id,
                from_type,
                to_type,
                problems,
                target_sections,
                target_catch_all,
                proposed_section_map,
            } => serde_json::json!({
                "id": id,
                "from_type": from_type,
                "to_type": to_type,
                "problems": problems
                    .iter()
                    .map(|p| {
                        let mut v = serde_json::to_value(p).unwrap_or(serde_json::Value::Null);
                        if let Some(obj) = v.as_object_mut() {
                            obj.insert("code".into(), serde_json::json!(p.code()));
                            obj.insert("message".into(), serde_json::json!(p.message()));
                        }
                        v
                    })
                    .collect::<Vec<_>>(),
                "target_sections": target_sections,
                "target_catch_all": target_catch_all,
                "proposed_section_map": proposed_section_map,
            }),
            EngineError::RetypeNoOp { id, entity_type } => {
                serde_json::json!({ "id": id, "entity_type": entity_type })
            }
            EngineError::InvalidCheckFinding { reason } => serde_json::json!({
                "reason": reason,
                "shape": crate::check::CheckFinding::SHAPE,
            }),
            EngineError::RetypeReferrerUnprobeable { id, mem, reason } => {
                serde_json::json!({ "id": id, "mem": mem, "reason": reason })
            }
            EngineError::NotFound { id, suggestions } => serde_json::json!({
                "id": id,
                "suggestions": suggestions,
            }),
            EngineError::AlreadyExists {
                id,
                existing_title,
                existing_is_stub,
            } => serde_json::json!({
                "id": id,
                "existing_title": existing_title,
                "existing_is_stub": existing_is_stub,
            }),
            EngineError::MemQuarantined {
                mem,
                reason_code,
                reason_message,
            } => serde_json::json!({
                "mem": mem,
                "reason_code": reason_code,
                "reason_message": reason_message,
            }),
            EngineError::ConstraintUnsatisfied {
                entity_type,
                entity_id,
                violations,
            } => serde_json::json!({
                "entity_type": entity_type,
                "entity_id": entity_id,
                "violations": violations,
            }),
            EngineError::RequiredOutgoingUnsatisfied {
                entity_type,
                entity_id,
                missing,
            } => serde_json::json!({
                "entity_type": entity_type,
                "entity_id": entity_id,
                "missing": missing,
            }),
            EngineError::SectionFormatRefused {
                entity_type,
                entity_id,
                violation,
            } => {
                let mut v = serde_json::to_value(violation).unwrap_or_default();
                if let Some(obj) = v.as_object_mut() {
                    obj.insert("entity_type".into(), serde_json::json!(entity_type));
                    obj.insert("entity_id".into(), serde_json::json!(entity_id));
                }
                v
            }
            EngineError::RepairNotNeeded { id, recovery } => {
                serde_json::json!({ "id": id, "recovery": recovery })
            }
            // Same shape the full MCP singleton envelope ships for
            // UNKNOWN_ENTITY_TYPE — keeps the centralised helper (and
            // every consumer: batch envelopes, the integrity linter)
            // aligned with the wire payload agents already decode.
            EngineError::UnknownType {
                name,
                schema_ref,
                declared,
                suggestion,
            } => serde_json::json!({
                "name": name,
                "schema_ref": schema_ref,
                "declared": declared,
                "suggestion": suggestion,
            }),
            EngineError::ExpectedHashRequired { id } => serde_json::json!({
                "field": "expected_hash",
                "id": id,
            }),
            EngineError::HashMismatch {
                id,
                current,
                is_stub,
            } => serde_json::json!({
                "id": id,
                "current": current,
                "is_stub": is_stub,
            }),
            EngineError::HasIncomingRefs { id, referrers } => {
                let referrers_json: Vec<_> = referrers
                    .iter()
                    .map(|r| {
                        serde_json::json!({
                            "from_id": r.from_id,
                            "rel_types": r.rel_types,
                            "mem": r.mem,
                            // Only a Write-Mem referrer blocks a delete; a
                            // read-only one demotes the target to a stub.
                            "capability": "write",
                        })
                    })
                    .collect();
                serde_json::json!({ "id": id, "referrers": referrers_json })
            }
            EngineError::MemHasIncomingRefs { mem, referrers } => {
                let referrers_json: Vec<_> = referrers
                    .iter()
                    .map(|r| {
                        serde_json::json!({
                            "from_id": r.from_id,
                            "rel_types": r.rel_types,
                            "mem": r.mem,
                        })
                    })
                    .collect();
                serde_json::json!({ "mem": mem, "referrers": referrers_json })
            }
            EngineError::WikiLinkWithoutRelation { from_id, missing } => serde_json::json!({
                "from_id": from_id,
                "missing": missing,
            }),
            EngineError::RelationHasBodyLinks {
                from_id,
                to_id,
                rel_type,
                body_links,
            } => {
                serde_json::json!({
                    "from_id": from_id,
                    "to_id": to_id,
                    "rel_type": rel_type,
                    "body_links": body_links,
                })
            }
            EngineError::InvalidEntityId { id, reason } => {
                serde_json::json!({ "id": id, "reason": reason })
            }
            EngineError::EntityIdTooLong { id, length, max } => serde_json::json!({
                "id": id,
                "reason": "too_long",
                "length": length,
                "max": max,
            }),
            EngineError::InvalidWikiLinkTarget {
                raw,
                suggested,
                section,
                link_source,
                reason,
            } => {
                // Surface
                // the slug-form retry under `proposed_slug`, mirroring the
                // title gate's `INVALID_TITLE` recovery key, so an agent
                // that wrote `[[Idempotency]]` finds `idempotency` under
                // the same field it already knows. `suggested` is the
                // general hint and is sometimes a colon-form
                // (`mem:slug`) for the ambiguous-grammar case — only
                // promote it to `proposed_slug` when it's a bare slug.
                let proposed_slug = suggested
                    .as_ref()
                    .filter(|s| !s.contains(':') && !s.contains("--"));
                serde_json::json!({
                    "raw": raw,
                    "suggested": suggested,
                    "proposed_slug": proposed_slug,
                    "section": section,
                    "source": link_source,
                    "reason": reason,
                })
            }
            EngineError::InvalidWikiLinkMem {
                raw,
                section,
                reason,
            } => {
                serde_json::json!({ "raw": raw, "section": section, "reason": reason })
            }
            EngineError::ConflictingSectionModes { section, modes } => {
                serde_json::json!({ "section": section, "modes": modes })
            }
            EngineError::SetAndUnsetConflict { keys } => serde_json::json!({ "keys": keys }),
            EngineError::RequiredFieldUnset {
                field,
                entity_type,
                field_description,
                enum_values,
                type_write_rules,
                // `on_create` is a prose-dispatch
                // discriminator only; agents branch on the typed
                // `REQUIRED_FIELD_UNSET` code, not on this field.
                on_create: _,
                missing,
            } => {
                // `details.missing[]` carries every required-no-
                // default field unset on the create path so an
                // agent fixes the whole set in one retry. Each
                // entry echoes the type-level `write_rules` for
                // self-containment. Empty on the unset path.
                let missing_json: Vec<_> = missing
                    .iter()
                    .map(|m| {
                        serde_json::json!({
                            "field": m.key,
                            "description": m.description,
                            "enum_values": m.enum_values,
                            "write_rules": type_write_rules,
                        })
                    })
                    .collect();
                serde_json::json!({
                    "field": field,
                    "entity_type": entity_type,
                    "field_description": field_description,
                    "enum_values": enum_values,
                    "type_write_rules": type_write_rules,
                    "missing": missing_json,
                })
            }
            EngineError::MissingRequiredSection {
                entity_type,
                missing_count,
                sections,
                type_guidance,
                pre_announced_missing_fields,
            } => {
                let sections_json: Vec<_> = sections
                    .iter()
                    .map(|s| {
                        serde_json::json!({
                            "entity_type": s.entity_type,
                            "key": s.key,
                            "heading": s.heading,
                            "write_rules": s.write_rules,
                        })
                    })
                    .collect();
                let mut details = serde_json::json!({
                    "entity_type": entity_type,
                    "missing_count": missing_count,
                    "sections": sections_json,
                    "type_guidance": type_guidance,
                });
                // Cross-gate pre-announcement rides additionally and
                // only when non-empty: the established payload above
                // keeps its exact shape, and a single-gate refusal
                // stays byte-identical to the pre-announcement-free
                // form. Element shape mirrors `REQUIRED_FIELD_UNSET`'s
                // `details.missing[]` so one decoder reads both.
                if !pre_announced_missing_fields.is_empty() {
                    let type_rules = type_guidance.get(entity_type).cloned().unwrap_or_default();
                    let missing_json: Vec<_> = pre_announced_missing_fields
                        .iter()
                        .map(|m| {
                            serde_json::json!({
                                "field": m.key,
                                "description": m.description,
                                "enum_values": m.enum_values,
                                "write_rules": type_rules,
                            })
                        })
                        .collect();
                    details["pre_announced"] = serde_json::json!({
                        "required_field_unset": { "missing": missing_json }
                    });
                }
                details
            }
            EngineError::PatchSectionEmpty { section } => serde_json::json!({ "section": section }),
            EngineError::PatchOldNotFound {
                section,
                current_content,
                truncated,
                found_in_sections,
            } => {
                serde_json::json!({
                    "section": section,
                    "current_content": current_content,
                    "truncated": truncated,
                    "found_in_sections": found_in_sections,
                })
            }
            EngineError::RelationshipCycle {
                rel_type,
                from,
                to,
                existing_path,
                path_truncated,
                acyclic_set,
                existing_path_rel_types,
            } => {
                let path_json: Vec<_> = existing_path.iter().map(|id| id.to_string()).collect();
                let mut d = serde_json::json!({
                    "rel_type": rel_type,
                    "from": from.to_string(),
                    "to": to.to_string(),
                    "existing_path": path_json,
                    "path_truncated": path_truncated,
                });
                // Additive: only set refusals carry the set echo and
                // the per-hop rel-types; single-rel-type refusals stay
                // byte-identical.
                if let Some(set) = acyclic_set {
                    d["acyclic_set"] = serde_json::json!(set);
                }
                if let Some(rels) = existing_path_rel_types {
                    d["existing_path_rel_types"] = serde_json::json!(rels);
                }
                d
            }
            EngineError::CrossMemLinkNotAllowed { from_mem, to_mem } => {
                serde_json::json!({ "from_mem": from_mem, "to_mem": to_mem })
            }
            EngineError::EmptyUpdate { id } => {
                serde_json::json!({
                    "id": id,
                    "recognised_keys": RECOGNISED_MUTATION_KEYS,
                })
            }
            EngineError::RenameBlockedByCrossMemPolicy {
                from_mem,
                blocked_referrers,
            } => {
                let entries: Vec<_> = blocked_referrers
                    .iter()
                    .map(|r| {
                        serde_json::json!({
                            "from_mem": r.from_mem,
                            "to_mem": r.to_mem,
                            "count": r.count,
                        })
                    })
                    .collect();
                serde_json::json!({
                    "from_mem": from_mem,
                    "blocked_referrers": entries,
                })
            }
            EngineError::CrossMemTargetNotFound {
                target_id,
                target_mem,
            } => {
                serde_json::json!({ "target_id": target_id, "target_mem": target_mem })
            }
            EngineError::EntityIdMissingMem { id, candidates } => serde_json::json!({
                "id": id,
                "candidates": candidates,
                "hint": if candidates.is_empty() {
                    "write the id as `<mem>--<slug>`; no mounted mem carries this slug".to_string()
                } else {
                    format!("retry with one of the candidates: {}", candidates.join(", "))
                },
            }),
            EngineError::UnterminatedFenceInStoredBody {
                id,
                section,
                fence,
                swallowed,
            } => serde_json::json!({
                "id": id,
                "section": section,
                "fence": fence,
                "swallowed_sections": swallowed,
                "expected": format!(
                    "supply `sections` with a corrected body for '{section}': lift the swallowed \
                     content back into its own sections and close the fence"
                ),
            }),
            EngineError::Validation(v) => v.details(),
            EngineError::MissingRequiredDescription {
                rel_type,
                from_id,
                to_id,
            } => {
                serde_json::json!({
                    "rel_type": rel_type,
                    "from_id": from_id,
                    "to_id": to_id,
                })
            }
            EngineError::DescriptionNotPermitted {
                rel_type,
                from_id,
                to_id,
            } => {
                serde_json::json!({
                    "rel_type": rel_type,
                    "from_id": from_id,
                    "to_id": to_id,
                })
            }
            EngineError::RelationManualAuthoringForbidden {
                rel_type,
                from_id,
                to_id,
                guidance,
            } => serde_json::json!({
                "rel_type": rel_type,
                "from_id": from_id,
                "to_id": to_id,
                "guidance": guidance,
            }),
            EngineError::MarkdownExportUnsupportedBackend {
                mem,
                active_backend,
                supported_backends,
            } => serde_json::json!({
                "mem": mem,
                "active_backend": active_backend,
                "supported_backends": supported_backends,
            }),
            EngineError::ReviewMarkNotSet { mem } => serde_json::json!({ "mem": mem }),
            EngineError::ProposalDispositionsIncomplete {
                fork,
                missing,
                unexpected,
            } => serde_json::json!({
                "fork": fork,
                "missing": missing,
                "unexpected": unexpected,
            }),
            EngineError::ProposalConflict { fork, slug, kind } => serde_json::json!({
                "fork": fork,
                "slug": slug,
                "kind": kind,
            }),
            EngineError::ProposalStale {
                fork,
                side,
                recorded,
                current,
            } => serde_json::json!({
                "fork": fork,
                "side": side,
                "recorded": recorded,
                "current": current,
            }),
            EngineError::ProposalUnattributed { fork, slug, sha } => serde_json::json!({
                "fork": fork,
                "slug": slug,
                "sha": sha,
            }),
            EngineError::ProposalLinksRejected {
                fork,
                slug,
                rel_type,
                target,
            } => serde_json::json!({
                "fork": fork,
                "slug": slug,
                "rel_type": rel_type,
                "target": target,
            }),
            EngineError::InvalidChangesCursor { mem, since } => serde_json::json!({
                "mem": mem,
                "since": since,
            }),
            EngineError::SchemaNotFound {
                mem,
                pin,
                sources,
                install_hint,
            } => {
                let mut details = serde_json::json!({
                    "mem": mem,
                    "pin": pin,
                    "sources": sources,
                });
                if let Some(path) = install_hint {
                    details["install_hint"] = if path == SCHEMA_INSTALL_PACKAGE_UNKNOWN {
                        serde_json::json!({
                            "command": format!("memstead schema install {path}"),
                        })
                    } else {
                        serde_json::json!({
                            "authoring_package": path,
                            "command": format!("memstead schema install {path}"),
                        })
                    };
                }
                details
            }
            EngineError::SchemaPackageInvalid {
                name,
                version,
                message,
            } => serde_json::json!({
                "schema": format!("{name}@{version}"),
                "error": message,
            }),
            EngineError::InvalidAnchor(e) => {
                serde_json::Value::Object(e.detail().into_iter().collect::<serde_json::Map<_, _>>())
            }
            EngineError::ProcessMemNotEligible {
                mem,
                process_mem,
                reason,
                schema,
            } => serde_json::json!({
                "mem": mem,
                "process_mem": process_mem,
                "reason": reason,
                "schema": schema,
                "expected_schema": format!("{}@*", crate::binding_run::PROCESS_MEM_SCHEMA_NAME),
            }),
            EngineError::InEntity {
                entity,
                stage,
                source,
            } => scope_details_to_entity(source.details(), entity, stage),
            // The payloads below were built by hand in both surface
            // mappers until the error-payload plan moved them here; each
            // carries every key either surface served.
            EngineError::DuplicateMem(name) => serde_json::json!({ "name": name }),
            EngineError::UnknownMem {
                name,
                known_mems,
                writable_mems,
            } => serde_json::json!({
                "name": name,
                "known_mems": known_mems,
                "writable_mems": writable_mems,
            }),
            EngineError::UnknownTypes {
                schema_ref,
                unknown,
                declared,
            } => serde_json::json!({
                "schema_ref": schema_ref,
                "unknown": unknown,
                "declared": declared,
            }),
            EngineError::UnknownSchema { name, available } => serde_json::json!({
                "name": name,
                "available": available,
            }),
            EngineError::InvalidTargetSchema { raw, reason } => serde_json::json!({
                "target_schema": raw,
                "reason": reason,
            }),
            EngineError::MemUnmounted { mem } => serde_json::json!({ "mem": mem }),
            EngineError::ReadOnlyMount(mem) => serde_json::json!({ "mem": mem }),
            EngineError::CheckNotRecorded { reason } => serde_json::json!({ "reason": reason }),
            EngineError::InvalidTitle(slug_err) => {
                let reason = slug_err.reason();
                match slug_err {
                    SlugError::IdTooLong { input, length, max } => serde_json::json!({
                        "reason": reason,
                        "input": input,
                        "length": length,
                        "max": max,
                    }),
                    SlugError::TitleEmpty { input } => serde_json::json!({
                        "reason": reason,
                        "input": input,
                    }),
                    SlugError::TitleHasControlChars {
                        input,
                        control_chars,
                        proposed_slug,
                    } => serde_json::json!({
                        "reason": reason,
                        "input": input,
                        "control_chars": control_chars
                            .iter()
                            .map(|c| c.escape_default().to_string())
                            .collect::<Vec<_>>(),
                        "proposed_slug": proposed_slug,
                    }),
                }
            }
            EngineError::CrossMemEdgeNotDeclared {
                source_schema,
                target_schema,
                rel_type,
                from_id,
                to_id,
            } => serde_json::json!({
                "source_schema": source_schema,
                "target_schema": target_schema,
                "rel_type": rel_type,
                "from_id": from_id,
                "to_id": to_id,
            }),
            EngineError::RenameNoOp { id, new_title } => serde_json::json!({
                "id": id,
                "new_title": new_title,
            }),
            EngineError::RenamePartialFailure {
                committed_mems,
                failed_mem,
                failure_cause,
                mems,
            } => serde_json::json!({
                "committed_mems": committed_mems,
                "failed_mem": failed_mem,
                "failure_cause": failure_cause,
                "mems": mems,
            }),
            EngineError::CommitNotApplied { mem, detail } => serde_json::json!({
                "mem": mem,
                "detail": detail,
            }),
            EngineError::StaleView { mem, cause, detail } => serde_json::json!({
                "mem": mem,
                "cause": cause.as_str(),
                "detail": detail,
            }),
            EngineError::StubCannotRelate { id }
            | EngineError::StubNotUpdatable { id }
            | EngineError::StubNotRenamable { id }
            | EngineError::NotConflicted { id } => serde_json::json!({ "id": id }),
            EngineError::ConflictNotTimestampOnly { id, key, section } => {
                let mut d = serde_json::json!({ "id": id });
                if let Some(k) = key {
                    d["key"] = serde_json::json!(k);
                }
                if let Some(s) = section {
                    d["section"] = serde_json::json!(s);
                }
                d
            }
            EngineError::ParseAfterWrite(detail)
            | EngineError::SchemaResolverInit(detail)
            | EngineError::Mem(detail) => serde_json::json!({ "detail": detail }),
            EngineError::Parse(inner) => serde_json::json!({ "detail": inner.to_string() }),
            EngineError::Backend(inner) => serde_json::json!({ "detail": inner.to_string() }),
            EngineError::EmbeddedSchemaInvalid { mem, pin, reason } => serde_json::json!({
                "mem": mem,
                "schema": pin,
                "error": reason,
            }),
            EngineError::MemNameCollision {
                name,
                source_origin,
            } => serde_json::json!({
                "name": name,
                "source": source_origin,
            }),
            EngineError::InvalidInput(message) => serde_json::json!({ "message": message }),
            EngineError::MergeConflictUnsupportedBackend { mem } => {
                serde_json::json!({ "mem": mem })
            }
            EngineError::UnknownRemote(remote) => serde_json::json!({ "remote": remote }),
            EngineError::RemoteUnreachable {
                remote,
                url,
                detail,
            } => serde_json::json!({ "remote": remote, "url": url, "detail": detail }),
            EngineError::LocalDivergence { mem, remote_ref } => serde_json::json!({
                "mem": mem,
                "remote_ref": remote_ref,
            }),
            EngineError::NonFastForward { mem, remote } => serde_json::json!({
                "mem": mem,
                "remote": remote,
            }),
            EngineError::LocalInvalidState {
                mem,
                remote,
                detail,
            } => serde_json::json!({
                "mem": mem,
                "remote": remote,
                "detail": detail,
            }),
            EngineError::SchemaViolationInFetch {
                mem,
                ref_name,
                violations,
            } => serde_json::json!({
                "mem": mem,
                "ref": ref_name,
                "violations": violations,
            }),
            EngineError::PushedCommitsProtected {
                mem,
                target_sha,
                pushed_shas,
            } => serde_json::json!({
                "mem": mem,
                "target_sha": target_sha,
                "pushed_shas": pushed_shas,
            }),
            EngineError::BranchResetHeadMoved {
                mem,
                expected,
                current,
            } => serde_json::json!({
                "mem": mem,
                "expected": expected,
                "current": current,
            }),
            EngineError::UnknownRef(raw) => serde_json::json!({ "ref": raw }),
            EngineError::RenameSimilarityOutOfRange {
                requested,
                allowed_min,
                allowed_max,
            } => serde_json::json!({
                "field": "rename_similarity",
                "requested": requested,
                "allowed_range": [allowed_min, allowed_max],
            }),
            EngineError::InvalidTimestampCursor { mem, since } => serde_json::json!({
                "mem": mem,
                "since": since,
            }),
            EngineError::MemConfigIncomplete {
                mem,
                missing_fields,
            } => serde_json::json!({
                "mem": mem,
                "missing_fields": missing_fields,
                "set_via": format!("memstead mem set-version {mem} <version>"),
            }),
            EngineError::SearchUnavailable | EngineError::NoWritableMem => serde_json::json!({}),
            EngineError::AmbiguousMem { mems } => serde_json::json!({ "mems": mems }),
            EngineError::AnchorsSidecarUnreadable { mem, reason } => serde_json::json!({
                "mem": mem,
                "reason": reason,
            }),
            EngineError::AmbiguousQuery { query, candidates } => serde_json::json!({
                "query": query,
                "candidates": candidates,
            }),
            EngineError::ContextNotComputable { id } => serde_json::json!({ "id": id }),
            EngineError::MemNotReadOnly { mem } => serde_json::json!({ "mem": mem }),
            EngineError::NotGitBacked { mem, operation } => {
                serde_json::json!({ "mem": mem, "operation": operation })
            }
            EngineError::UnsupportedWorkspaceShape { path } => serde_json::json!({ "path": path }),
            EngineError::InvalidSchemaPin {
                pin,
                reason,
                available,
            } => serde_json::json!({ "pin": pin, "reason": reason, "available": available }),
            EngineError::ChunkOutOfRange { chunk, total } => {
                serde_json::json!({ "chunk": chunk, "total": total })
            }
            EngineError::TemplateIdentityMismatch {
                id,
                field,
                template,
                current,
            } => serde_json::json!({
                "id": id,
                "field": field,
                "template": template,
                "current": current,
            }),
        }
    }

    /// Render rich, fully-inlined recovery prose for the agent-visible
    /// text channel.
    ///
    /// Warnings
    /// already render their structured payload inline via
    /// `WarningHint::Display`; pre-fix errors with rich payloads
    /// collapsed to `Display` plus `format_inline_list_overflow`'s
    /// "+N more — see details.X" pointer pointing at a structured
    /// channel the agent's MCP client doesn't surface to the model.
    /// This method gives errors the same prose-rich rendering warnings
    /// have, so `result.content[0].text` is self-recoverable.
    ///
    /// Variants whose `Display` already inlines every recovery field
    /// (no truncation, no "see details" pointer) inherit the default
    /// trait impl — they just `to_string()`. Override only the
    /// variants that need richer rendering than `Display` provides.
    ///
    /// The structured `details()` channel is unchanged; consumers
    /// branching on `code` continue to receive the typed shape. The
    /// `Display` impl stays terse for logs, tracing, panic messages,
    /// and other non-agent consumers.
    pub fn prose_render(&self) -> String {
        match self {
            // The writable mems are the recovery set for a call that
            // writes; the text channel names them as the overview and
            // health refusals always did.
            // The ids that look like the one asked for, inline, so a reader
            // of the text channel alone can retry.
            EngineError::NotFound { suggestions, .. } if !suggestions.is_empty() => {
                format!("{self}. Did you mean: {}", suggestions.join(", "))
            }
            EngineError::UnknownMem { writable_mems, .. } if !writable_mems.is_empty() => {
                format!("{self}. Writable mems: [{}]", writable_mems.join(", "))
            }
            // The echoed conforming `example` is the highest-leverage
            // part of a format refusal — inline it on the text channel
            // too, not only under `details.example`.
            EngineError::SectionFormatRefused { violation, .. } => {
                let base = self.to_string();
                match violation.example() {
                    Some(example) => {
                        format!("{base}\nA conforming example:\n{}", example.trim_end())
                    }
                    None => base,
                }
            }
            EngineError::HasIncomingRefs { id, referrers } => {
                let inline = render_referrers_inline(referrers);
                format!(
                    "entity {id} has {n} incoming reference(s) in write mems ({inline}); remove them first via memstead_relate --remove or memstead_update",
                    n = referrers.len(),
                )
            }
            EngineError::MemHasIncomingRefs { mem, referrers } => {
                let inline = render_referrers_inline(referrers);
                format!(
                    "mem `{mem}` has {n} incoming reference(s) in write mems ({inline}); remove them first via memstead_relate --remove or memstead_update",
                    n = referrers.len(),
                )
            }
            EngineError::WikiLinkWithoutRelation { from_id, missing } => {
                let inline = missing
                    .iter()
                    .map(|m| m.to_string())
                    .collect::<Vec<_>>()
                    .join(", ");
                format!(
                    "post-mutation body of {from_id} has {n} wiki-link(s) without a backing relation ({inline}) — declare the relation(s) via memstead_relate first (REFERENCES or a more specific rel-type), then retry",
                    n = missing.len(),
                )
            }
            EngineError::RelationHasBodyLinks {
                from_id,
                to_id,
                rel_type,
                body_links,
            } => {
                let inline = body_links.join(", ");
                format!(
                    "cannot remove {rel_type} {from_id} → {to_id}: source body still contains wiki-link(s) to the target in section(s) {inline} — drop them via memstead_update before removing the relation"
                )
            }
            EngineError::RelationshipCycle {
                rel_type,
                from,
                to,
                existing_path,
                path_truncated,
                acyclic_set,
                ..
            } => {
                let path_inline = if existing_path.is_empty() {
                    String::from("(unavailable)")
                } else {
                    existing_path
                        .iter()
                        .map(|id| id.to_string())
                        .collect::<Vec<_>>()
                        .join(" → ")
                };
                let trunc = if *path_truncated {
                    " (path truncated)"
                } else {
                    ""
                };
                let subgraph = match acyclic_set {
                    Some(set) => format!("[{}] acyclicity-set", set.join(", ")),
                    None => rel_type.to_string(),
                };
                format!(
                    "creating edge {rel_type} from '{from}' to '{to}' would close a cycle in the {subgraph} subgraph — existing path: {path_inline}{trunc}; remove an edge along this path to break the cycle, then retry"
                )
            }
            EngineError::RequiredFieldUnset {
                field,
                entity_type,
                field_description,
                enum_values,
                type_write_rules,
                on_create,
                missing,
            } => {
                let desc_clause = field_description
                    .as_deref()
                    .map(|d| format!(" Field purpose: {d}."))
                    .unwrap_or_default();
                let enum_clause = if enum_values.is_empty() {
                    String::new()
                } else {
                    format!(" Allowed values: {}.", enum_values.join(", "))
                };
                let rules_clause = if type_write_rules.is_empty() {
                    String::new()
                } else {
                    format!(" Type-level write_rules: {}.", type_write_rules.join("; "))
                };
                // Path-aware wording — create
                // path says "not provided"; update path says "cannot
                // unset". Display impl shares the same dispatch via
                // `_required_field_unset_msg`.
                let lead = if *on_create {
                    format!(
                        "required metadata field '{field}' not provided — type '{entity_type}' declares the field as required and has no default for it"
                    )
                } else {
                    format!("cannot unset required field '{field}' for type '{entity_type}'")
                };
                // Multi-field accumulator. On the create path,
                // append a tail-list naming every other unset
                // required field so the agent's one-shot retry
                // covers all of them. The unset path's `missing`
                // is empty (or singleton), so the clause is empty
                // there.
                let tail_clause = if missing.len() > 1 {
                    let others: Vec<&str> =
                        missing.iter().skip(1).map(|m| m.key.as_str()).collect();
                    format!(" Also unset (declaration order): {}.", others.join(", "))
                } else {
                    String::new()
                };
                format!("{lead}.{desc_clause}{enum_clause}{rules_clause}{tail_clause}")
            }
            EngineError::MissingRequiredSection {
                entity_type,
                missing_count,
                sections,
                type_guidance,
                pre_announced_missing_fields,
            } => {
                let mut out = format!(
                    "missing {missing_count} required section(s) for type '{entity_type}':"
                );
                for s in sections {
                    let rules = if s.write_rules.is_empty() {
                        String::new()
                    } else {
                        format!(" — write_rules: {}", s.write_rules.join("; "))
                    };
                    out.push_str(&format!("\n  - '{}' ({}){rules}", s.key, s.heading));
                }
                if !type_guidance.is_empty() {
                    out.push_str("\nType guidance:");
                    for (etype, rules) in type_guidance {
                        if rules.is_empty() {
                            continue;
                        }
                        out.push_str(&format!("\n  - {etype}: {}", rules.join("; ")));
                    }
                }
                // Cross-gate pre-announcement on the text channel so a
                // consumer reading only prose still fixes both gates in
                // one retry.
                if !pre_announced_missing_fields.is_empty() {
                    out.push_str(
                        "\nPre-announced — the metadata gate will also require (supply in the same retry):",
                    );
                    for m in pre_announced_missing_fields {
                        let enums = if m.enum_values.is_empty() {
                            String::new()
                        } else {
                            format!(" (one of: {})", m.enum_values.join(", "))
                        };
                        out.push_str(&format!("\n  - '{}'{enums} — {}", m.key, m.description));
                    }
                }
                out
            }
            EngineError::UnterminatedFenceInStoredBody {
                id,
                section,
                fence,
                swallowed,
            } => {
                let buried = if swallowed.is_empty() {
                    "No declared section follows it in the file yet".to_string()
                } else {
                    format!("Buried right now: {}", swallowed.join(", "))
                };
                format!(
                    "entity '{id}' section '{section}' ends inside an unterminated `{fence}` code \
                     fence. In CommonMark an open fence runs to end of text, so the sections \
                     after it were absorbed into this body on the last read and are reported as \
                     empty. {buried}. Writing now appends the closing fence AFTER those bytes, \
                     sealing them inside a legitimately fenced block where nothing can tell them \
                     from prose the author meant to fence. Replace section '{section}' with a \
                     corrected body in this same call: lift the swallowed content back into its \
                     own sections and close the fence."
                )
            }
            EngineError::Validation(v) => v.prose_render(),
            EngineError::InEntity {
                entity,
                stage,
                source,
            } => format!("{entity} ({stage}): {}", source.prose_render()),
            // Variants whose `Display` already inlines every recovery
            // field — title invariants, hash mismatch (already explains
            // the stub case), unknown mem / type (already prints
            // declared list verbatim), cross-mem gates, stubs,
            // patch errors, etc. — fall back to `Display`. Logs and
            // tracing consumers see the same string.
            _ => self.to_string(),
        }
    }
}

/// Inline-render every [`ReferrerInfo`] without the truncation suffix
/// `format_inline_list_overflow` applies. Used by
/// [`EngineError::prose_render`]'s `HasIncomingRefs` /
/// `MemHasIncomingRefs` arms — the agent text channel inlines the
/// full list so recovery doesn't depend on the structured channel.
fn render_referrers_inline(referrers: &[ReferrerInfo]) -> String {
    referrers
        .iter()
        .map(|r| r.to_string())
        .collect::<Vec<_>>()
        .join(", ")
}

/// Format the `RequiredFieldUnset` message. The same typed code
/// fires from two semantically-distinct call sites:
///
/// * The create path constructs the variant when the caller didn't
///   supply a required metadata field. The pre-fix message ("cannot
///   unset required field …") was misleading because the field was
///   never set in the first place — `on_create: true` flips the
///   wording to "required metadata field … not provided".
/// * The update path constructs the variant when the caller passed
///   `metadata_unset: ["field"]` against a required field. The
///   pre-fix wording is correct for this path — `on_create: false`
///   keeps it.
///
/// Both paths share recovery (provide the field); the typed code
/// stays `REQUIRED_FIELD_UNSET` for code-key branching consumers.
fn _relationship_cycle_msg(
    rel_type: &str,
    from: &EntityId,
    to: &EntityId,
    acyclic_set: Option<&[String]>,
) -> String {
    match acyclic_set {
        Some(set) => format!(
            "creating edge {rel_type} from '{from}' to '{to}' would close a cycle in the [{}] acyclicity-set subgraph",
            set.join(", ")
        ),
        None => format!(
            "creating edge {rel_type} from '{from}' to '{to}' would close a cycle in the {rel_type} subgraph"
        ),
    }
}

fn _required_field_unset_msg(field: &str, entity_type: &str, on_create: bool) -> String {
    if on_create {
        format!(
            "required metadata field '{field}' not provided — type '{entity_type}' declares the field as required and has no default for it"
        )
    } else {
        format!("cannot unset required field '{field}' for type '{entity_type}'")
    }
}

impl EngineError {
    /// Whether `e` is a transport's in-band remote marker
    /// (`UNKNOWN_REMOTE:` or `REMOTE_UNREACHABLE:`), which
    /// [`Self::from_transport`] lifts to its typed code.
    pub(crate) fn is_remote_marker(e: &BackendError) -> bool {
        matches!(e, BackendError::Other(msg)
            if msg.starts_with("UNKNOWN_REMOTE:") || msg.starts_with("REMOTE_UNREACHABLE:"))
    }

    /// A transport failure, lifted: the two remote markers to their typed
    /// codes, anything else as the backend error it is. The one place a
    /// transport verb's remote failure becomes an engine error.
    pub(crate) fn from_transport(e: BackendError) -> Self {
        match e {
            BackendError::Other(msg) if msg.starts_with("UNKNOWN_REMOTE:") => {
                EngineError::UnknownRemote(
                    msg.trim_start_matches("UNKNOWN_REMOTE:").trim().to_string(),
                )
            }
            BackendError::Other(msg) if msg.starts_with("REMOTE_UNREACHABLE:") => {
                let rest = msg.trim_start_matches("REMOTE_UNREACHABLE:");
                let mut parts = rest.splitn(3, '\t');
                EngineError::RemoteUnreachable {
                    remote: parts.next().unwrap_or_default().trim().to_string(),
                    url: parts.next().unwrap_or_default().trim().to_string(),
                    detail: parts.next().unwrap_or_default().trim().to_string(),
                }
            }
            other => EngineError::Backend(other),
        }
    }
}

/// Why a mem's view cannot take a write ([`EngineError::StaleView`]).
/// One code for one state class (the view cannot take it); the cause
/// names the state, and with it the repair.
#[derive(Debug, Clone, Copy, PartialEq, Eq, serde::Serialize)]
#[serde(rename_all = "snake_case")]
pub enum StaleCause {
    /// The mem changed in storage and the reload before the write
    /// failed: the view is behind storage.
    Drift,
    /// The mem is out of service (it failed to attach): it is in no view.
    OutOfService,
    /// The mem's write lock cannot be taken here, so its content cannot
    /// be held still for an operation that reads it.
    LockUnavailable,
    /// Writes a failed mutation left staged on the mem could not be
    /// discarded: a read would serve them as content that never landed.
    DiscardFailed,
}

impl StaleCause {
    /// The wire word, as in `details.cause`.
    pub fn as_str(self) -> &'static str {
        match self {
            StaleCause::Drift => "drift",
            StaleCause::OutOfService => "out_of_service",
            StaleCause::LockUnavailable => "lock_unavailable",
            StaleCause::DiscardFailed => "discard_failed",
        }
    }
}

fn conflict_location(key: Option<&str>, section: Option<&str>) -> String {
    match (key, section) {
        (Some(k), _) => format!("the frontmatter key `{k}`"),
        (None, Some(s)) => format!("the section `{s}`"),
        (None, None) => "content other than `last_modified`".to_string(),
    }
}

fn stale_view_message(mem: &str, cause: StaleCause, detail: &str) -> String {
    match cause {
        StaleCause::Drift => format!(
            "mem `{mem}` changed in storage and could not be reloaded before this write ({detail}) — nothing was written; the next operation retries the reload, resend the write then"
        ),
        StaleCause::OutOfService => format!(
            "mem `{mem}` is out of service ({detail}) — it is in no view, so a write that reads it cannot be planned; nothing was written; repair the mem and reload it, or remove it, then resend the write"
        ),
        StaleCause::LockUnavailable => format!(
            "mem `{mem}`'s write lock cannot be taken here ({detail}) — its content cannot be held still for a write that reads it; nothing was written; make the lock file reachable or unmount the mem, then resend the write"
        ),
        StaleCause::DiscardFailed => format!(
            "writes a failed mutation left staged on mem `{mem}` could not be discarded ({detail}) — nothing was written; the next operation retries the discard, resend the write then"
        ),
    }
}

/// Format the `HashMismatch` message. Stub-shaped entities have no
/// `content_hash` to compare against; rendering the empty `current:`
/// paren the way pre-fix code did misdirects an agent toward
/// hash-recovery via `memstead_entity` (which returns the same empty
/// hash). Surface the actual corrective action — pass
/// `expected_hash: ""` — instead.
/// Render the `SCHEMA_NOT_FOUND` message with its source-trail
/// summary. The trail says exactly which sources were searched and
/// what each held — never more (a source absent from `sources` is not
/// claimed searched). A right-name/wrong-version failure and a
/// never-installed failure are distinguishable from this sentence
/// alone; the structured `details.sources` stays the richer channel.
/// Empty `sources` (internal lookup miss) keeps the bare legacy
/// sentence — there was no source search to summarise.
fn schema_not_found_message(
    mem: &str,
    pin: &str,
    sources: &[SchemaSourceDiagnostic],
    install_hint: &Option<String>,
) -> String {
    let mut msg = format!("mem {mem}: schema pin {pin:?} did not resolve in any schema source");
    if sources.is_empty() {
        return msg;
    }
    let name = pin.split('@').next().unwrap_or(pin);
    let trail: Vec<String> = sources
        .iter()
        .map(|s| {
            if let Some(status) = s.status {
                format!("{} ({status})", s.source)
            } else if s.versions_found.is_empty() {
                format!("{} (nothing for {name:?})", s.source)
            } else {
                format!("{} (holds {})", s.source, s.versions_found.join(", "))
            }
        })
        .collect();
    msg.push_str(&format!(" — searched {}", trail.join(", ")));
    if let Some(hint) = install_hint
        && hint == SCHEMA_INSTALL_PACKAGE_UNKNOWN
    {
        // The caller knows install is the only remedy (a fork copies
        // the source's pin and never moves it) but not where the
        // package sits: the versions a source holds are stated, the
        // repin command is not.
        msg.push_str(&format!(
            "; the pinned version {pin} is not installed in this workspace and the pin is not \
             to be moved (a fork copies the source's pin, never re-pins): obtain the schema \
             package for {pin}, then run: memstead schema install {hint}"
        ));
    } else if let Some(path) = install_hint {
        // An authoring package of the name sits in the tree: the
        // remedy is installing it, whatever versions other sources
        // hold (the probe sets this only when none does; a fork sets
        // it whenever the package is there).
        msg.push_str(&format!(
            "; an authoring package named {name:?} exists at {path:?} but is not installed — \
             run: memstead schema install {path}"
        ));
    } else if sources.iter().any(|s| !s.versions_found.is_empty()) {
        // Right name, wrong version. The honest hint is version
        // repair, not silence: the final clause is the concrete repin
        // command against the newest version a source actually holds.
        let best = sources
            .iter()
            .flat_map(|s| &s.versions_found)
            .filter_map(|v| semver::Version::parse(v).ok())
            .max();
        msg.push_str(&format!(
            "; the name {name:?} exists at the versions listed — the pinned version is wrong, \
             or the pinned version was never installed"
        ));
        if let Some(best) = best {
            msg.push_str(&format!(
                "; repin to an installed version: run: memstead mem set-schema {mem} {name}@{best}"
            ));
        }
    } else {
        // Name unknown everywhere and no authoring package in sight —
        // the repair path is still the install path, stated without a
        // concrete package location because none exists to name.
        msg.push_str(&format!(
            "; no source holds any version of {name:?} — author or obtain the schema package, \
             then run: memstead schema install <package-dir>"
        ));
    }
    msg
}

impl EngineError {
    /// Attach the schema-install hint to a `SchemaNotFound` where a
    /// workspace root is known: probe the root's immediate
    /// subdirectories for an authoring schema package (a directory the
    /// schema loader accepts) whose manifest name matches the pin's
    /// name, and record its path when NO resolution source holds any
    /// version of that name. Any other error variant — and any
    /// `SchemaNotFound` where the name IS installed at some version
    /// (a version mismatch is a different fix), where `sources` is
    /// empty (internal miss, no source search happened), or where no
    /// candidate package exists — passes through unchanged. Read-only:
    /// the probe never writes, installs, or seals anything.
    pub fn with_schema_install_probe(self, workspace_root: Option<&std::path::Path>) -> Self {
        let (mem, pin, sources, install_hint) = match self {
            EngineError::SchemaNotFound {
                mem,
                pin,
                sources,
                install_hint,
            } => (mem, pin, sources, install_hint),
            // The per-entity wrapper of a batch act carries the probe
            // into its source.
            EngineError::InEntity {
                entity,
                stage,
                source,
            } => {
                return EngineError::InEntity {
                    entity,
                    stage,
                    source: Box::new(source.with_schema_install_probe(workspace_root)),
                };
            }
            other => return other,
        };
        let hint = if install_hint.is_some() {
            install_hint
        } else if sources.is_empty() || sources.iter().any(|s| !s.versions_found.is_empty()) {
            None
        } else {
            let name = pin.split('@').next().unwrap_or(&pin).to_string();
            workspace_root.and_then(|root| probe_authoring_package(root, &name))
        };
        EngineError::SchemaNotFound {
            mem,
            pin,
            sources,
            install_hint: hint,
        }
    }
}

/// The `install_hint` a caller passes when it knows the remedy is
/// `memstead schema install` but not where the package sits: the
/// message then names the install command with this placeholder and
/// never the repin advice. A fork copies the source's pin and never
/// moves it, so this is the fork's hint when no authoring package of
/// the name sits in the workspace tree.
pub const SCHEMA_INSTALL_PACKAGE_UNKNOWN: &str = "<package-dir>";

/// Scan `root`'s immediate subdirectories for a loadable schema
/// package whose manifest name is `name`. Hidden directories and the
/// workspace's own storage (`mem-repo`, `.memstead`) are skipped. The
/// full loader runs (error path only, so the cost is acceptable) — a
/// directory that merely LOOKS like a package but fails validation
/// produces no hint, because `memstead schema install` would refuse it
/// anyway.
pub(crate) fn probe_authoring_package(root: &std::path::Path, name: &str) -> Option<String> {
    let entries = std::fs::read_dir(root).ok()?;
    for entry in entries.flatten() {
        let path = entry.path();
        if !path.is_dir() {
            continue;
        }
        let dir_name = entry.file_name();
        let dir_name = dir_name.to_string_lossy();
        if dir_name.starts_with('.') || dir_name == "mem-repo" {
            continue;
        }
        if !path.join("schema.yaml").is_file() {
            continue;
        }
        if let Ok(schema) = memstead_schema::load_schema_from_dir(&path) {
            let (loaded_name, _) = schema.id();
            if loaded_name == name {
                return Some(path.display().to_string());
            }
        }
    }
    None
}

fn _hash_mismatch_msg(id: &str, current: &str, is_stub: bool) -> String {
    if is_stub {
        format!(
            "hash mismatch for {id} — entity is a stub (no content_hash); pass expected_hash: \"\" to operate on stubs"
        )
    } else {
        format!("hash mismatch for {id} — entity was modified concurrently (current: {current})")
    }
}

/// A schema package directory refused as authoring input: a sealed copy
/// where an authored one belongs, or a package the authoring read refuses.
#[derive(Debug, thiserror::Error)]
pub enum AuthoringPackageError {
    #[error(
        "{} is a sealed schema package (it carries `schema-format.json`, the seal marker), \
         not authoring input; validate the package's source directory instead",
        path.display()
    )]
    Sealed { path: PathBuf },
    #[error("schema at {} is invalid: {error}", path.display())]
    Invalid { path: PathBuf, error: String },
}

impl AuthoringPackageError {
    pub fn code(&self) -> &'static str {
        match self {
            AuthoringPackageError::Sealed { .. } | AuthoringPackageError::Invalid { .. } => {
                "SCHEMA_VALIDATION_FAILED"
            }
        }
    }

    pub fn details(&self) -> serde_json::Value {
        match self {
            AuthoringPackageError::Sealed { path } => serde_json::json!({
                "path": path,
                "reason": "sealed_package",
            }),
            AuthoringPackageError::Invalid { path, error } => serde_json::json!({
                "path": path,
                "error": error,
            }),
        }
    }
}

impl EngineError {
    /// Parse a schema pin, refusing one that does not parse with the one
    /// value every surface renders.
    /// The names in the refusal are the built-in catalogue's; an engine
    /// that knows more schemas parses through [`crate::Engine::parse_schema_pin`].
    pub fn parse_schema_pin(pin: &str) -> Result<memstead_schema::SchemaRef, EngineError> {
        let available = match EngineError::unknown_builtin_schema(pin) {
            EngineError::UnknownSchema { available, .. } => available,
            _ => Vec::new(),
        };
        Self::parse_schema_pin_against(pin, available)
    }

    fn parse_schema_pin_against(
        pin: &str,
        available: Vec<String>,
    ) -> Result<memstead_schema::SchemaRef, EngineError> {
        pin.parse::<memstead_schema::SchemaRef>()
            .map_err(|reason| EngineError::InvalidSchemaPin {
                pin: pin.to_string(),
                reason,
                available,
            })
    }

    /// Refuse an update template that names a title or type other than the
    /// entity's own.
    pub fn check_template_identity(
        entity: &crate::Entity,
        title: Option<&str>,
        entity_type: Option<&str>,
    ) -> Result<(), EngineError> {
        let mismatch =
            |field: &str, template: &str, current: &str| EngineError::TemplateIdentityMismatch {
                id: entity.id.to_string(),
                field: field.to_string(),
                template: template.to_string(),
                current: current.to_string(),
            };
        if let Some(t) = title
            && t != entity.title
        {
            return Err(mismatch("title", t, &entity.title));
        }
        if let Some(ty) = entity_type
            && ty != entity.entity_type
        {
            return Err(mismatch("entity_type", ty, &entity.entity_type));
        }
        Ok(())
    }
}

impl crate::Engine {
    /// Refuse a sealed package where authoring input is asked for.
    pub fn refuse_sealed_authoring_input(
        path: &std::path::Path,
    ) -> Result<(), AuthoringPackageError> {
        if path.join("schema-format.json").is_file() {
            return Err(AuthoringPackageError::Sealed {
                path: path.to_path_buf(),
            });
        }
        Ok(())
    }

    /// Load a schema package directory the way an authoring act reads it:
    /// the loader, the heading round-trip, the reserved metadata keys, the
    /// section formats, the system-message markers and the exemplar gate
    /// installation runs. A package this passes, install accepts.
    pub fn validate_authoring_package(
        path: &std::path::Path,
    ) -> Result<std::sync::Arc<memstead_schema::Schema>, AuthoringPackageError> {
        let invalid = |error: String| AuthoringPackageError::Invalid {
            path: path.to_path_buf(),
            error,
        };
        let schema = memstead_schema::load_schema_from_dir(path)
            .and_then(|s| memstead_schema::check_section_heading_roundtrip(&s).map(|()| s))
            .and_then(|s| memstead_schema::check_reserved_metadata_keys(&s).map(|()| s))
            .and_then(|s| memstead_schema::check_section_formats(&s).map(|()| s))
            .and_then(|s| memstead_schema::check_system_message_markers(&s).map(|()| s))
            .map_err(|e| invalid(e.to_string()))?;
        let schema = std::sync::Arc::new(schema);
        crate::Engine::validate_schema_exemplars(&schema).map_err(invalid)?;
        Ok(schema)
    }
}

/// Errors surfaced by [`Engine::from_workspace_root`] (the folder boot
/// path) and its git-branch counterpart (`memstead_git_branch::engine_from_workspace_root`).
///
/// The boot path layers three error sources: layout detection,
/// workspace-store load failures, per-mount backend instantiation
/// (folder + archive vs git-branch), and engine construction
/// (duplicate-mem checks). `#[from]` lifts the lower-layer types so
/// callers branch on a single error envelope.
// Variants lift lower-layer error types verbatim via `#[from]`, so the enum is
// as wide as its widest member. Boot errors are constructed at most once per
// process; boxing to equalise them would buy nothing.
#[allow(clippy::large_enum_variant)]
#[derive(Debug, thiserror::Error)]
pub enum BootError {
    /// `detect_layout` returned [`crate::Layout::Empty`] — workspace
    /// root has no recognised layout marker. Operator runs
    /// `memstead mem-repo init` rather than booting against an empty
    /// directory.
    #[error("workspace at {0} is not initialised — run `memstead mem-repo init` first")]
    NotInitialised(PathBuf),
    /// Underlying [`crate::WorkspaceStoreAdapter`] load failed
    /// (missing config file, parse error, format-mismatch).
    #[error(transparent)]
    Store(#[from] crate::workspace_store::StoreError),
    /// Per-mount backend instantiation failed. Today: a mount
    /// declared `MountStorage::GitBranch` while the folder boot path
    /// only knows folder + archive.
    #[error(transparent)]
    Instantiate(#[from] crate::workspace_store::InstantiateError),
    /// Engine construction failed (duplicate mem names, etc.).
    #[error(transparent)]
    Engine(#[from] EngineError),
}

impl BootError {
    /// Stable, surface-independent error code token (UPPER_SNAKE, per
    /// the [`EngineError::code`] convention). Every boot failure class
    /// resolves to a typed code — `INTERNAL` is not producible from
    /// this seam. The wrapped layers each own their vocabulary:
    /// store-load failures delegate to
    /// [`crate::workspace_store::StoreError::code`], backend
    /// instantiation to
    /// [`crate::workspace_store::InstantiateError::code`], engine
    /// construction to [`EngineError::code`].
    pub fn code(&self) -> &'static str {
        match self {
            // Same token the CLI's workspace walk uses — "no
            // workspace here" is one condition wherever detected.
            BootError::NotInitialised(_) => "WORKSPACE_NOT_INITIALISED",
            BootError::Store(e) => e.code(),
            BootError::Instantiate(e) => e.code(),
            BootError::Engine(e) => e.code(),
        }
    }

    /// Structured recovery payload for the boot failure, surfacing
    /// under `error.details` on `--json` envelopes. Engine-layer
    /// failures reuse [`EngineError::details`] (so e.g. a boot-time
    /// `SCHEMA_NOT_FOUND` ships the same `details.sources` trail the
    /// per-verb surfaces ship); the other layers name the offending
    /// path.
    pub fn details(&self) -> serde_json::Value {
        use crate::workspace_store::StoreError;
        match self {
            BootError::NotInitialised(path) => {
                serde_json::json!({
                    "path": path.display().to_string(),
                    "hint": { "recovery_command": "memstead mem-repo init" },
                })
            }
            BootError::Store(e) => match e {
                StoreError::NotInitialised { path }
                | StoreError::Io { path, .. }
                | StoreError::Parse { path, .. }
                | StoreError::FormatMismatch { path, .. }
                | StoreError::LegacyLayout { path, .. }
                | StoreError::UnknownBindingVersion { path, .. } => {
                    serde_json::json!({ "path": path.display().to_string() })
                }
                StoreError::LegacyProjectionStore { path } => serde_json::json!({
                    "path": path.display().to_string(),
                    "hint": { "recovery_command": "memstead projection init" },
                }),
                StoreError::Other(_) => serde_json::json!({}),
            },
            BootError::Instantiate(
                crate::workspace_store::InstantiateError::GitBranchBackendUnavailable { mem },
            ) => serde_json::json!({ "mem": mem }),
            BootError::Instantiate(crate::workspace_store::InstantiateError::MemRepoMissing {
                mem,
                gitdir,
            }) => serde_json::json!({
                "mem": mem,
                "gitdir": gitdir,
                "hint": { "recovery_command": "memstead mem-repo init --remote <url>" },
            }),
            BootError::Engine(e) => e.details(),
        }
    }

    /// The one boot-failure message every surface prints verbatim
    /// (CLI stderr / `--json`, MCP boot diagnostics), so the same
    /// broken workspace reads identically wherever it refuses. The
    /// leaf error's own message carries the repair command (or states
    /// plainly that none exists).
    pub fn surface_message(&self, workspace_root: &std::path::Path) -> String {
        format!("init engine at {}: {self}", workspace_root.display())
    }
}

impl From<BackendError> for EngineError {
    /// One `HASH_MISMATCH` for both detection levels. A mutation's commit
    /// that loses the branch race is refused in the engine's landing step
    /// with the entity's id and its hash at the new tip; this mapping is
    /// the fallback for a commit that names no entity, which carries the
    /// new tip as the mem-level conflict. Everything else stays a typed
    /// backend failure.
    fn from(e: BackendError) -> Self {
        match e {
            BackendError::HashMismatch { current } => EngineError::HashMismatch {
                id: String::new(),
                current,
                is_stub: false,
            },
            other => EngineError::Backend(other),
        }
    }
}

#[cfg(test)]
mod details_payload_tests;
#[cfg(test)]
mod inline_list_tests;
/// One value of every error, for the surface-parity tests.
#[cfg(any(test, feature = "test-support"))]
#[doc(hidden)]
pub mod samples;

/// Ids in `store` that look like the one asked for: ending with it, or
/// with `--<it>`, or whose slug contains it; at most five. The recovery
/// set an `ENTITY_NOT_FOUND` carries.
pub fn suggest_similar(store: &crate::store::Store, input: &str) -> Vec<String> {
    let needle = input.trim_start_matches("@memstead/");
    store
        .all_ids()
        .filter(|id| {
            let haystack = id.as_ref();
            haystack.ends_with(needle)
                || haystack.ends_with(&format!("--{needle}"))
                || haystack
                    .rsplit_once("--")
                    .is_some_and(|(_, slug)| slug.contains(needle))
        })
        .take(5)
        .map(|id| id.to_string())
        .collect()
}

impl EngineError {
    /// The id syntax every surface checks before it asks the engine for
    /// anything: not empty, not longer than the engine accepts.
    pub fn check_entity_id_syntax(id: &str) -> Result<(), EngineError> {
        if id.is_empty() {
            return Err(EngineError::InvalidEntityId {
                id: String::new(),
                reason: "empty".to_string(),
            });
        }
        let length = id.chars().count();
        if length > crate::ENTITY_ID_MAX_LEN {
            return Err(EngineError::EntityIdTooLong {
                id: id.to_string(),
                length,
                max: crate::ENTITY_ID_MAX_LEN,
            });
        }
        Ok(())
    }

    /// `SCHEMA_NOT_FOUND` for a schema the built-in registry does not carry
    /// (a command that installs or reads a package needs no engine), with
    /// the built-in names.
    pub fn unknown_builtin_schema(name: &str) -> EngineError {
        let mut available: Vec<String> = memstead_schema::SchemaRegistry::builtin()
            .identities()
            .into_iter()
            .map(|(n, _)| n)
            .collect();
        available.sort();
        available.dedup();
        EngineError::UnknownSchema {
            name: name.to_string(),
            available,
        }
    }
}

impl super::Engine {
    /// `SCHEMA_NOT_FOUND` for a schema asked for by name, with every name
    /// the engine can serve (mounted, workspace-installed, built-in).
    /// Parse a schema pin, refusing one that does not parse with the
    /// schema names this engine resolves (mounted, workspace-installed,
    /// built-in) in the refusal.
    pub fn parse_schema_pin(&self, pin: &str) -> Result<memstead_schema::SchemaRef, EngineError> {
        let available = match self.unknown_schema(pin) {
            EngineError::UnknownSchema { available, .. } => available,
            _ => Vec::new(),
        };
        EngineError::parse_schema_pin_against(pin, available)
    }

    pub fn unknown_schema(&self, name: &str) -> EngineError {
        let mut available: Vec<String> = self
            .schemas()
            .values()
            .map(|s| s.manifest.name.clone())
            .chain(
                self.workspace_schemas()
                    .iter()
                    .map(|s| s.manifest.name.clone()),
            )
            .chain(
                self.builtin_schemas()
                    .iter()
                    .map(|s| s.manifest.name.clone()),
            )
            .collect();
        available.sort();
        available.dedup();
        EngineError::UnknownSchema {
            name: name.to_string(),
            available,
        }
    }

    /// `ENTITY_NOT_FOUND` for `id`, with the ids that look like it.
    pub fn not_found(&self, id: &str) -> EngineError {
        EngineError::NotFound {
            id: id.to_string(),
            suggestions: suggest_similar(&self.store, id),
        }
    }

    /// `UNKNOWN_MEM` for `name`, with the mems mounted now and the
    /// writable ones among them.
    pub fn unknown_mem(&self, name: &str) -> EngineError {
        // Sorted, so the payload does not depend on mount order.
        let mut known_mems: Vec<String> = self.mounts().iter().map(|m| m.mem.clone()).collect();
        known_mems.sort();
        let mut writable_mems: Vec<String> = self
            .mounts()
            .iter()
            .filter(|m| m.capability == crate::workspace::MountCapability::Write)
            .map(|m| m.mem.clone())
            .collect();
        writable_mems.sort();
        EngineError::UnknownMem {
            name: name.to_string(),
            known_mems,
            writable_mems,
        }
    }
}