memstead-base 0.8.0

Engine internals for Memstead — store, parser, validators, filesystem-mem engine. Internal library surface consumed by the memstead binaries — pre-1.0, experimental, 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
//! 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;

/// 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).
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 (memstead.io, 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"),
            },
        ]
    }
}

/// 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: {0}")]
    UnknownMem(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>,
    },
    /// 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 },
    /// 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.
    #[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 (F15 / CLI F8). 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. 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,
    },
    /// `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, commit_sha: ""`.
    #[error(
        "no mutation content for {id} — payload carries an id but every mutation map is empty (recognised keys: sections, append_sections, patch_sections, metadata, metadata_unset, declare_relations, relations_unset)"
    )]
    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>,
    },
    /// A multi-mem `memstead_rename` partially landed: at least one
    /// mem committed successfully, then a subsequent per-mem
    /// commit aborted (typically because a sibling writer advanced
    /// the failed mem's head between the rename's snapshot and the
    /// commit attempt — the parent-ref pin tripped via
    /// `BackendError::ParentMismatch`). The committed mems' state
    /// has already landed and is durable; the failed mem's writes
    /// did not land. The agent's recovery options: retry the rename
    /// (reload the workspace first so the engine re-derives the right
    /// referrer set), or accept the partial state and reconcile
    /// manually via subsequent mutations.
    #[error(
        "rename partial-failure: mem `{failed_mem}` aborted with cause {failure_cause:?} after {committed_mems:?} already committed — reload and retry, or reconcile manually"
    )]
    RenamePartialFailure {
        committed_mems: Vec<String>,
        failed_mem: String,
        failure_cause: 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. Pre-Item-02 surfaced as the cryptic
    /// `UnknownType { name: "" }` cascade — identical symptom to the
    /// one `StubCannotRelate` was added to replace 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 },
    /// 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.
    #[error(
        "creating edge {rel_type} from '{from}' to '{to}' would close a cycle in the {rel_type} subgraph"
    )]
    RelationshipCycle {
        rel_type: String,
        from: EntityId,
        to: EntityId,
        existing_path: Vec<EntityId>,
        path_truncated: bool,
    },
    /// `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>>,
    },
    /// `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.
    #[error("patch `old` substring not found in {section}")]
    PatchOldNotFound {
        section: String,
        current_content: String,
        truncated: bool,
    },
    /// 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`, `HashMismatch`, `Io`).
    #[error(transparent)]
    Backend(#[from] 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 },
    /// 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),
    /// `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}")]
    UnknownRemote(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),
    /// `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 a commit_sha from a prior mutation, or the empty-tree sentinel to re-seed"
    )]
    InvalidChangesCursor { 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. F1.
    #[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),
}

/// 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)
    }
}

impl EngineError {
    /// Stable, surface-independent error code token.
    ///
    /// Each surface (MCP envelope, CLI envelope, UniFFI binding) 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::MemQuarantined { .. } => "MEM_QUARANTINED",
            EngineError::UnknownRef(_) => "UNKNOWN_REF",
            EngineError::UnknownRemote(_) => "UNKNOWN_REMOTE",
            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::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::CrossMemEdgeNotDeclared { .. } => "CROSS_MEM_EDGE_NOT_DECLARED",
            EngineError::RepairNotNeeded { .. } => "REPAIR_NOT_NEEDED",
            EngineError::RenameNoOp { .. } => "RENAME_NO_OP",
            EngineError::EmptyUpdate { .. } => "EMPTY_UPDATE",
            EngineError::RenameBlockedByCrossMemPolicy { .. } => {
                "RENAME_BLOCKED_BY_CROSS_MEM_POLICY"
            }
            EngineError::RenamePartialFailure { .. } => "RENAME_PARTIAL_FAILURE",
            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::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::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::InvalidInput(_) => "INVALID_INPUT",
            EngineError::RenameSimilarityOutOfRange { .. } => "INVALID_INPUT",
            EngineError::InvalidChangesCursor { .. } => "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,
        }
    }

    /// 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`).
    pub fn details(&self) -> serde_json::Value {
        match self {
            EngineError::NotFound { id } => serde_json::json!({ "id": id }),
            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::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,
                        })
                    })
                    .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::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,
            } => {
                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();
                serde_json::json!({
                    "entity_type": entity_type,
                    "missing_count": missing_count,
                    "sections": sections_json,
                    "type_guidance": type_guidance,
                })
            }
            EngineError::PatchSectionEmpty { section } => serde_json::json!({ "section": section }),
            EngineError::PatchOldNotFound {
                section,
                current_content,
                truncated,
            } => {
                serde_json::json!({
                    "section": section,
                    "current_content": current_content,
                    "truncated": truncated,
                })
            }
            EngineError::RelationshipCycle {
                rel_type,
                from,
                to,
                existing_path,
                path_truncated,
            } => {
                let path_json: Vec<_> = existing_path.iter().map(|id| id.to_string()).collect();
                serde_json::json!({
                    "rel_type": rel_type,
                    "from": from.to_string(),
                    "to": to.to_string(),
                    "existing_path": path_json,
                    "path_truncated": path_truncated,
                })
            }
            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": [
                        "sections", "append_sections", "patch_sections",
                        "metadata", "metadata_unset", "declare_relations", "relations_unset",
                    ],
                })
            }
            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::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::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"] = 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<_, _>>())
            }
            _ => serde_json::Value::Object(serde_json::Map::new()),
        }
    }

    /// 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 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,
            } => {
                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 {
                    ""
                };
                format!(
                    "creating edge {rel_type} from '{from}' to '{to}' would close a cycle in the {rel_type} 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,
            } => {
                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("; ")));
                    }
                }
                out
            }
            EngineError::Validation(v) => v.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 _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}'")
    }
}

/// 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 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 if let Some(path) = install_hint {
        msg.push_str(&format!(
            "; an authoring package named {name:?} exists at {path:?} but is not installed — \
             run: memstead schema install {path}"
        ));
    } 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 EngineError::SchemaNotFound {
            mem,
            pin,
            sources,
            install_hint,
        } = self
        else {
            return self;
        };
        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,
        }
    }
}

/// 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.
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})")
    }
}

/// Errors surfaced by [`Engine::from_workspace_root`] (lean) and its
/// full 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 lean 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 migrate" },
                }),
                StoreError::Other(_) => serde_json::json!({}),
            },
            BootError::Instantiate(
                crate::workspace_store::InstantiateError::GitBranchRequiresMemRepoFeature { mem },
            ) => serde_json::json!({ "mem": mem }),
            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())
    }
}

#[cfg(test)]
mod plan05_subsystem_tests {
    use super::*;

    /// A title-case body wiki-link refusal carries the
    /// slug-form retry under `proposed_slug` (mirroring `INVALID_TITLE`),
    /// so an agent that wrote `[[Idempotency]]` finds `idempotency` under
    /// the key it already knows.
    #[test]
    fn invalid_wiki_link_details_carry_proposed_slug_for_title_case() {
        let err = EngineError::InvalidWikiLinkTarget {
            raw: "Idempotency".to_string(),
            suggested: Some("idempotency".to_string()),
            section: "purpose".to_string(),
            link_source: "body_link".to_string(),
            reason: "slugs must be lowercase".to_string(),
        };
        let d = err.details();
        assert_eq!(d["proposed_slug"], "idempotency");
        assert_eq!(d["suggested"], "idempotency");
    }

    /// `SCHEMA_NOT_FOUND` carries the fixed-order resolution
    /// diagnostics under `details.sources`: a right-name/wrong-version
    /// pin shows the built-in's available versions with
    /// `pinned_version_match = false`, and `remote` is the reserved
    /// `not_configured` slot. This is the agent-visible payload that
    /// tells the caller the name resolves but the version does not.
    #[test]
    fn schema_not_found_details_carry_fixed_order_source_diagnostics() {
        let requested: semver::Version = "99.0.0".parse().unwrap();
        let sources = SchemaSourceDiagnostic::for_failed_pin("default", &requested, &[]);
        let err = EngineError::SchemaNotFound {
            mem: "specs".to_string(),
            pin: "default@99.0.0".to_string(),
            sources,
            install_hint: None,
        };
        assert_eq!(err.code(), "SCHEMA_NOT_FOUND");
        let d = err.details();
        assert_eq!(d["mem"], "specs");
        assert_eq!(d["pin"], "default@99.0.0");
        let src = d["sources"].as_array().expect("sources is an array");
        let labels: Vec<&str> = src.iter().map(|s| s["source"].as_str().unwrap()).collect();
        assert_eq!(labels, ["local_storage", "builtin", "remote"]);
        // The `default` builtin exists at 1.0.0 — right name, wrong
        // version: builtin enumerates it but the pin does not match.
        let builtin = &src[1];
        assert!(
            builtin["versions_found"]
                .as_array()
                .unwrap()
                .iter()
                .any(|v| v == "1.0.0"),
            "builtin must enumerate default@1.0.0, got {builtin:?}",
        );
        assert_eq!(builtin["pinned_version_match"], false);
        // No local storage was consulted (empty `consulted` slice).
        assert_eq!(src[0]["versions_found"].as_array().unwrap().len(), 0);
        // Remote is the reserved, unenumerated slot.
        assert_eq!(src[2]["status"], "not_configured");
        assert!(
            src[2].get("versions_found").is_some(),
            "remote still ships an (empty) versions_found list",
        );
    }

    /// The MESSAGE (not just `details`) summarises the source trail,
    /// and a right-name/wrong-version failure is distinguishable from
    /// a never-installed one without opening `details`. The message
    /// names exactly the sources in `sources` — never one that was
    /// not searched — and the empty-sources internal miss keeps the
    /// bare legacy sentence.
    #[test]
    fn schema_not_found_message_summarises_trail_and_distinguishes_wrong_version() {
        // Wrong version: the builtin catalogue holds `default@1.0.0`,
        // the pin asks for 99.0.0.
        let requested: semver::Version = "99.0.0".parse().unwrap();
        let wrong_version = EngineError::SchemaNotFound {
            mem: "specs".to_string(),
            pin: "default@99.0.0".to_string(),
            sources: SchemaSourceDiagnostic::for_failed_pin("default", &requested, &[]),
            install_hint: None,
        };
        let msg = wrong_version.to_string();
        assert!(msg.contains("searched local_storage"), "got: {msg}");
        assert!(msg.contains("builtin (holds"), "got: {msg}");
        assert!(msg.contains("remote (not_configured)"), "got: {msg}");
        assert!(
            msg.contains("the pinned version is wrong"),
            "wrong-version case must be named in the message: {msg}"
        );
        assert!(
            msg.contains("memstead mem set-schema specs default@1.3.0"),
            "wrong-version case ends in the concrete repin command: {msg}"
        );

        // Never installed: no source holds any version of the name.
        let never: semver::Version = "1.0.0".parse().unwrap();
        let never_installed = EngineError::SchemaNotFound {
            mem: "specs".to_string(),
            pin: "no-such-schema@1.0.0".to_string(),
            sources: SchemaSourceDiagnostic::for_failed_pin("no-such-schema", &never, &[]),
            install_hint: None,
        };
        let msg2 = never_installed.to_string();
        assert!(
            msg2.contains("nothing for \"no-such-schema\""),
            "never-installed case names the empty sources: {msg2}"
        );
        assert!(
            !msg2.contains("the pinned version is wrong"),
            "never-installed must NOT claim a version mismatch: {msg2}"
        );
        assert!(
            msg2.contains("memstead schema install <package-dir>"),
            "never-installed (no probe) still names the install path: {msg2}"
        );
        assert_ne!(msg, msg2, "the two failures are distinguishable");

        // Internal lookup miss (empty sources): bare legacy sentence,
        // no trail is claimed.
        let internal = EngineError::SchemaNotFound {
            mem: "specs".to_string(),
            pin: "x@1.0.0".to_string(),
            sources: Vec::new(),
            install_hint: None,
        };
        assert_eq!(
            internal.to_string(),
            "mem specs: schema pin \"x@1.0.0\" did not resolve in any schema source",
        );
    }

    /// The install-hint probe attaches the authoring-package pointer
    /// exactly when a loadable package with the pin's name sits in the
    /// workspace root while NO source holds any version of the name —
    /// and stays silent for a version mismatch (installed at another
    /// version), for an absent package, and for a non-`SchemaNotFound`
    /// error.
    #[test]
    fn schema_install_probe_hints_only_for_uninstalled_authoring_package() {
        // Workspace root carrying the memstead-schema `examples/minimal`
        // package (name `recipe`) as an authoring folder.
        let tmp = tempfile::TempDir::new().unwrap();
        let src_pkg = std::path::Path::new(env!("CARGO_MANIFEST_DIR"))
            .join("../memstead-schema/examples/minimal");
        let dst = tmp.path().join("recipe");
        std::fs::create_dir_all(dst.join("types")).unwrap();
        std::fs::copy(src_pkg.join("schema.yaml"), dst.join("schema.yaml")).unwrap();
        for entry in std::fs::read_dir(src_pkg.join("types")).unwrap().flatten() {
            std::fs::copy(entry.path(), dst.join("types").join(entry.file_name())).unwrap();
        }

        let requested: semver::Version = "0.1.0".parse().unwrap();
        let not_found = || EngineError::SchemaNotFound {
            mem: "specs".to_string(),
            pin: "recipe@0.1.0".to_string(),
            sources: SchemaSourceDiagnostic::for_failed_pin("recipe", &requested, &[]),
            install_hint: None,
        };

        // Uninstalled + authored → hint attaches, message + details
        // point at `memstead schema install`.
        let hinted = not_found().with_schema_install_probe(Some(tmp.path()));
        let msg = hinted.to_string();
        assert!(
            msg.contains("memstead schema install"),
            "hint must name the install command: {msg}"
        );
        assert!(msg.contains("recipe"), "hint names the package: {msg}");
        let d = hinted.details();
        assert!(
            d["install_hint"]["command"]
                .as_str()
                .unwrap()
                .starts_with("memstead schema install"),
            "details carry the hint: {d}"
        );

        // No workspace root → no concrete package hint; the message
        // falls back to the generic install path.
        let no_root = not_found().with_schema_install_probe(None);
        let no_root_msg = no_root.to_string();
        assert!(
            no_root_msg.contains("memstead schema install <package-dir>"),
            "generic install path without a probe hit: {no_root_msg}"
        );
        assert!(
            !no_root_msg.contains(&tmp.path().display().to_string()),
            "no concrete package path without a probe hit: {no_root_msg}"
        );

        // No such authoring package → same generic fallback, no
        // concrete path.
        let other_tmp = tempfile::TempDir::new().unwrap();
        let absent = not_found().with_schema_install_probe(Some(other_tmp.path()));
        let absent_msg = absent.to_string();
        assert!(
            absent_msg.contains("memstead schema install <package-dir>"),
            "generic install path when no package exists: {absent_msg}"
        );
        assert!(
            !absent_msg.contains(&other_tmp.path().display().to_string()),
            "no concrete package path when no package exists: {absent_msg}"
        );

        // Version mismatch against an installed package (some source
        // holds versions of the name) → no hint even though the
        // authoring package exists.
        let mismatch_req: semver::Version = "99.0.0".parse().unwrap();
        let mismatch = EngineError::SchemaNotFound {
            mem: "specs".to_string(),
            pin: "default@99.0.0".to_string(),
            sources: SchemaSourceDiagnostic::for_failed_pin("default", &mismatch_req, &[]),
            install_hint: None,
        }
        .with_schema_install_probe(Some(tmp.path()));
        let mismatch_msg = mismatch.to_string();
        assert!(
            !mismatch_msg.contains("schema install"),
            "version mismatch must not hint install: {mismatch_msg}"
        );
        assert!(
            mismatch_msg.contains("memstead mem set-schema specs default@1.3.0"),
            "version mismatch hints version repair instead: {mismatch_msg}"
        );

        // Non-SchemaNotFound errors pass through unchanged.
        let other = EngineError::UnknownMem("specs".to_string())
            .with_schema_install_probe(Some(tmp.path()));
        assert_eq!(other.code(), "UNKNOWN_MEM");
    }

    /// The ambiguous-grammar case suggests a
    /// colon-form (`mem:slug`), which is NOT a bare slug — it must not
    /// be promoted to `proposed_slug`.
    #[test]
    fn invalid_wiki_link_colon_form_suggestion_is_not_a_proposed_slug() {
        let err = EngineError::InvalidWikiLinkTarget {
            raw: "team/sub--thing".to_string(),
            suggested: Some("team/sub:thing".to_string()),
            section: "purpose".to_string(),
            link_source: "body_link".to_string(),
            reason: "ambiguous".to_string(),
        };
        let d = err.details();
        assert!(
            d["proposed_slug"].is_null(),
            "colon-form must not be a proposed_slug: {d}"
        );
        assert_eq!(d["suggested"], "team/sub:thing");
    }

    /// A bad `--since` cursor is the typed `INVALID_CURSOR`
    /// code carrying the untruncated SHA in `details.since`.
    #[test]
    fn invalid_changes_cursor_code_and_details() {
        let sha = "deadbeefdeadbeefdeadbeefdeadbeefdeadbeef";
        let err = EngineError::InvalidChangesCursor {
            mem: "specs".to_string(),
            since: sha.to_string(),
        };
        assert_eq!(err.code(), "INVALID_CURSOR");
        let d = err.details();
        assert_eq!(d["mem"], "specs");
        assert_eq!(
            d["since"], sha,
            "the offending SHA must ride untruncated in details"
        );
    }
}

#[cfg(test)]
mod inline_list_tests {
    use super::*;

    #[test]
    fn empty_list_renders_empty_string() {
        let items: Vec<String> = Vec::new();
        assert_eq!(format_inline_list_overflow(&items, "x"), "");
    }

    #[test]
    fn list_at_cap_renders_all_no_overflow_suffix() {
        let items = vec!["a".to_string(), "b".to_string(), "c".to_string()];
        assert_eq!(format_inline_list_overflow(&items, "x"), "a, b, c");
    }

    #[test]
    fn list_under_cap_renders_all_no_overflow_suffix() {
        let items = vec!["a".to_string(), "b".to_string()];
        assert_eq!(format_inline_list_overflow(&items, "x"), "a, b");
    }

    #[test]
    fn list_over_cap_appends_count_and_field_name() {
        let items: Vec<String> = (0..23).map(|i| format!("id{i}")).collect();
        let rendered = format_inline_list_overflow(&items, "referrers");
        assert_eq!(rendered, "id0, id1, id2 +20 more — see details.referrers");
    }

    #[test]
    fn list_six_items_truncates_to_three_plus_three() {
        let items: Vec<String> = (0..6).map(|i| format!("t{i}")).collect();
        let rendered = format_inline_list_overflow(&items, "missing");
        assert_eq!(rendered, "t0, t1, t2 +3 more — see details.missing");
    }

    #[test]
    fn has_incoming_refs_display_inlines_first_three_referrer_ids() {
        let referrers: Vec<ReferrerInfo> = (0..23)
            .map(|i| ReferrerInfo {
                from_id: format!("specs--ref{i}"),
                rel_types: vec!["USES".to_string()],
                mem: "specs".to_string(),
            })
            .collect();
        let err = EngineError::HasIncomingRefs {
            id: "specs--hub".to_string(),
            referrers,
        };
        let s = err.to_string();
        // First three ids appear inline; the rest are summarised plus a
        // pointer to `details.referrers` on the structured channel.
        assert!(
            s.contains("specs--ref0, specs--ref1, specs--ref2"),
            "got: {s}"
        );
        assert!(s.contains("+20 more — see details.referrers"), "got: {s}");
        // Pre-fix the message only carried the count; check the count
        // still appears so callers parsing it for "N references" keep
        // working.
        assert!(s.contains("23 incoming reference"), "got: {s}");
    }

    #[test]
    fn wiki_link_without_relation_display_lists_all_when_under_cap() {
        let missing = vec![
            MissingWikiLink {
                section_key: "specifies".to_string(),
                target_id: "specs--a".to_string(),
            },
            MissingWikiLink {
                section_key: "specifies".to_string(),
                target_id: "specs--b".to_string(),
            },
            MissingWikiLink {
                section_key: "rationale".to_string(),
                target_id: "specs--c".to_string(),
            },
        ];
        let err = EngineError::WikiLinkWithoutRelation {
            from_id: "specs--src".to_string(),
            missing,
        };
        let s = err.to_string();
        assert!(s.contains("specifies→specs--a"), "got: {s}");
        assert!(s.contains("specifies→specs--b"), "got: {s}");
        assert!(s.contains("rationale→specs--c"), "got: {s}");
        assert!(!s.contains("more — see details"), "got: {s}");
    }

    #[test]
    fn wiki_link_without_relation_display_truncates_at_cap_with_pointer() {
        let missing: Vec<MissingWikiLink> = (0..6)
            .map(|i| MissingWikiLink {
                section_key: format!("s{i}"),
                target_id: format!("specs--t{i}"),
            })
            .collect();
        let err = EngineError::WikiLinkWithoutRelation {
            from_id: "specs--src".to_string(),
            missing,
        };
        let s = err.to_string();
        assert!(
            s.contains("s0→specs--t0, s1→specs--t1, s2→specs--t2"),
            "got: {s}"
        );
        assert!(s.contains("+3 more — see details.missing"), "got: {s}");
    }

    #[test]
    fn relation_has_body_links_display_inlines_section_keys() {
        let err = EngineError::RelationHasBodyLinks {
            from_id: "specs--src".to_string(),
            to_id: "specs--dst".to_string(),
            rel_type: "USES".to_string(),
            body_links: vec!["specifies".to_string(), "rationale".to_string()],
        };
        let s = err.to_string();
        assert!(s.contains("specifies, rationale"), "got: {s}");
        assert!(!s.contains("more — see details"), "got: {s}");
    }

    // --- prose_render -----------------------------------------------
    // The text
    // channel inlines full recovery payloads (no `+N more — see
    // details.X` pointer). Display stays terse for logs; prose_render
    // is the rich method MCP / CLI surfaces call for `content[0].text`.

    #[test]
    fn prose_render_has_incoming_refs_inlines_every_referrer() {
        let referrers = (0..7)
            .map(|i| ReferrerInfo {
                from_id: format!("specs--r{i}"),
                rel_types: vec!["DEPENDS_ON".to_string()],
                mem: "specs".to_string(),
            })
            .collect();
        let err = EngineError::HasIncomingRefs {
            id: "specs--target".to_string(),
            referrers,
        };
        let prose = err.prose_render();
        for i in 0..7 {
            assert!(
                prose.contains(&format!("specs--r{i}")),
                "every referrer must appear inline; missing r{i} in: {prose}"
            );
        }
        assert!(!prose.contains("see details"), "got: {prose}");
        // Display stays terse with the overflow suffix.
        let display = err.to_string();
        assert!(
            display.contains("+4 more — see details.referrers"),
            "got: {display}"
        );
    }

    #[test]
    fn prose_render_required_field_unset_inlines_field_description_and_rules() {
        // Update-path semantic: `on_create: false` → "cannot unset".
        let err = EngineError::RequiredFieldUnset {
            field: "verified_on".to_string(),
            entity_type: "requirement".to_string(),
            field_description: Some("ISO-8601 date the requirement was last validated".to_string()),
            enum_values: vec![],
            type_write_rules: vec!["bump verified_on on every status change".to_string()],
            on_create: false,
            missing: Vec::new(),
        };
        let prose = err.prose_render();
        assert!(
            prose.contains("ISO-8601 date"),
            "field_description missing: {prose}"
        );
        assert!(
            prose.contains("bump verified_on"),
            "type_write_rules missing: {prose}"
        );
        assert!(!prose.contains("see details"), "got: {prose}");
        assert!(
            prose.contains("cannot unset"),
            "update-path wording must say 'cannot unset': {prose}"
        );
    }

    /// Create
    /// path renders "not provided" instead of "cannot unset" — the
    /// pre-fix wording was misleading on a path where nothing was
    /// ever set in the first place.
    #[test]
    fn prose_render_required_field_unset_create_path_uses_not_provided_wording() {
        let err = EngineError::RequiredFieldUnset {
            field: "verified_on".to_string(),
            entity_type: "requirement".to_string(),
            field_description: Some("ISO-8601 date the requirement was last validated".to_string()),
            enum_values: vec![],
            type_write_rules: vec![],
            on_create: true,
            missing: Vec::new(),
        };
        let prose = err.prose_render();
        assert!(
            prose.contains("not provided"),
            "create-path wording must say 'not provided': {prose}"
        );
        assert!(
            !prose.contains("cannot unset"),
            "create-path wording must NOT say 'cannot unset': {prose}"
        );
        // Same Display dispatch — `to_string()` mirrors `prose_render`'s
        // create-path lead.
        let display = err.to_string();
        assert!(
            display.contains("not provided"),
            "Display must match: {display}"
        );
        assert!(
            !display.contains("cannot unset"),
            "Display must match: {display}"
        );
    }

    /// The
    /// create-path multi-field accumulator surfaces every required-
    /// no-default field unset in `details.missing[]`. Each entry
    /// carries `{field, description, enum_values, write_rules}` so
    /// the agent fixes the whole set in one retry. The singular
    /// `details.field` echoes `missing[0].field` for back-compat.
    #[test]
    fn details_required_field_unset_multi_field_envelope_shape() {
        use crate::runtime_validator::MissingRequiredField;
        let err = EngineError::RequiredFieldUnset {
            field: "decided_on".to_string(),
            entity_type: "decision".to_string(),
            field_description: Some("Date the decision was accepted. ISO YYYY-MM-DD.".to_string()),
            enum_values: vec![],
            type_write_rules: vec!["status transitions: proposed → accepted".to_string()],
            on_create: true,
            missing: vec![
                MissingRequiredField {
                    entity_type: "decision".to_string(),
                    key: "decided_on".to_string(),
                    description: "Date the decision was accepted. ISO YYYY-MM-DD.".to_string(),
                    enum_values: vec![],
                },
                MissingRequiredField {
                    entity_type: "decision".to_string(),
                    key: "deciders".to_string(),
                    description: "Who made the call. Comma-separated handles.".to_string(),
                    enum_values: vec![],
                },
            ],
        };
        let details = err.details();
        // Back-compat: singular `field` echoes the first-missing entry.
        assert_eq!(details["field"].as_str(), Some("decided_on"));
        // Multi-field accumulator surfaces every entry in
        // declaration order.
        let missing = details["missing"].as_array().expect("missing[] array");
        assert_eq!(missing.len(), 2);
        assert_eq!(missing[0]["field"].as_str(), Some("decided_on"));
        assert_eq!(missing[1]["field"].as_str(), Some("deciders"));
        // First entry's `field` agrees with the singular shape.
        assert_eq!(details["field"], missing[0]["field"]);
        // Per-entry `write_rules` echoes the type-level rules for
        // self-containment.
        assert_eq!(missing[0]["write_rules"], details["type_write_rules"]);
        // Prose mentions both field names so the agent reading the
        // text channel sees the whole set without crossing into the
        // structured channel.
        let prose = err.prose_render();
        assert!(prose.contains("decided_on"), "got: {prose}");
        assert!(prose.contains("deciders"), "got: {prose}");
    }

    /// The unset path's singular shape is
    /// preserved — `missing[]` is empty (the user targeted one field
    /// by definition); the singular fields above are authoritative.
    /// The typed code stays `REQUIRED_FIELD_UNSET`.
    #[test]
    fn details_required_field_unset_singular_shape_for_unset_path() {
        let err = EngineError::RequiredFieldUnset {
            field: "decided_on".to_string(),
            entity_type: "decision".to_string(),
            field_description: Some("".to_string()),
            enum_values: vec![],
            type_write_rules: vec![],
            on_create: false,
            missing: Vec::new(),
        };
        let details = err.details();
        assert_eq!(details["field"].as_str(), Some("decided_on"));
        let missing = details["missing"]
            .as_array()
            .expect("missing[] array present");
        assert!(missing.is_empty(), "unset-path missing[] must be empty");
        assert_eq!(err.code(), "REQUIRED_FIELD_UNSET");
    }

    #[test]
    fn prose_render_missing_required_section_enumerates_each_section_with_write_rules() {
        use crate::runtime_validator::MissingRequiredSection;
        let sections = vec![
            MissingRequiredSection {
                entity_type: "spec".to_string(),
                key: "purpose".to_string(),
                heading: "Purpose".to_string(),
                write_rules: vec!["one-sentence statement of intent".to_string()],
            },
            MissingRequiredSection {
                entity_type: "spec".to_string(),
                key: "scope".to_string(),
                heading: "Scope".to_string(),
                write_rules: vec!["what is in and out of scope".to_string()],
            },
        ];
        let mut type_guidance: std::collections::BTreeMap<String, Vec<String>> = Default::default();
        type_guidance.insert(
            "spec".to_string(),
            vec!["specs are immutable once stable".to_string()],
        );
        let err = EngineError::MissingRequiredSection {
            entity_type: "spec".to_string(),
            missing_count: 2,
            sections,
            type_guidance,
        };
        let prose = err.prose_render();
        assert!(prose.contains("purpose"), "got: {prose}");
        assert!(prose.contains("scope"), "got: {prose}");
        assert!(
            prose.contains("one-sentence statement of intent"),
            "got: {prose}"
        );
        assert!(
            prose.contains("specs are immutable once stable"),
            "got: {prose}"
        );
        assert!(!prose.contains("see details"), "got: {prose}");
    }

    #[test]
    fn prose_render_relationship_cycle_inlines_existing_path() {
        use crate::entity::EntityId;
        let path = vec![
            EntityId::canonical("specs--a"),
            EntityId::canonical("specs--b"),
            EntityId::canonical("specs--c"),
            EntityId::canonical("specs--a"),
        ];
        let err = EngineError::RelationshipCycle {
            rel_type: "PART_OF".to_string(),
            from: EntityId::canonical("specs--a"),
            to: EntityId::canonical("specs--c"),
            existing_path: path,
            path_truncated: false,
        };
        let prose = err.prose_render();
        assert!(
            prose.contains("specs--a → specs--b → specs--c → specs--a"),
            "got: {prose}"
        );
        assert!(!prose.contains("see details"), "got: {prose}");
    }

    #[test]
    fn prose_render_falls_back_to_display_for_trivial_variants() {
        // ReadOnlyMount has no list payload — Display already inlines
        // the recovery context.
        let err = EngineError::ReadOnlyMount("archive-2024".to_string());
        assert_eq!(err.prose_render(), err.to_string());
    }

    /// A slug collision names the occupying title on both channels —
    /// two distinct titles can derive one id, and the id alone does
    /// not tell the caller which one is already there.
    #[test]
    fn already_exists_names_the_occupying_title_on_both_channels() {
        let err = EngineError::AlreadyExists {
            id: "muehle--bösenberg-grundstücks-gmbh-co-kg".to_string(),
            existing_title: "Bösenberg Grundstücks GmbH Co KG".to_string(),
            existing_is_stub: false,
        };
        assert!(
            err.to_string()
                .contains("occupied by 'Bösenberg Grundstücks GmbH Co KG'"),
            "got: {err}"
        );
        let details = err.details();
        assert_eq!(
            details["existing_title"],
            "Bösenberg Grundstücks GmbH Co KG"
        );
        assert_eq!(details["existing_is_stub"], false);
        assert_eq!(details["id"], "muehle--bösenberg-grundstücks-gmbh-co-kg");
    }

    /// A stub occupant states it is a stub; a titleless stub must not
    /// render as an empty or missing title.
    #[test]
    fn already_exists_stub_occupant_never_renders_an_empty_title() {
        let titled = EngineError::AlreadyExists {
            id: "specs--x".to_string(),
            existing_title: "X".to_string(),
            existing_is_stub: true,
        };
        assert!(
            titled.to_string().contains("a stub titled 'X'"),
            "got: {titled}"
        );

        let untitled = EngineError::AlreadyExists {
            id: "specs--x".to_string(),
            existing_title: String::new(),
            existing_is_stub: true,
        };
        let msg = untitled.to_string();
        assert!(msg.contains("occupied by a stub"), "got: {msg}");
        assert!(!msg.contains("''"), "empty title must not render: {msg}");
    }
}