memstead-base 0.7.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
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135
3136
3137
3138
3139
3140
3141
3142
3143
3144
3145
3146
3147
3148
3149
3150
3151
3152
3153
3154
3155
3156
3157
3158
3159
3160
3161
3162
3163
3164
3165
3166
3167
3168
3169
3170
3171
3172
3173
3174
3175
3176
3177
3178
3179
3180
3181
3182
3183
3184
3185
3186
3187
3188
3189
3190
3191
3192
3193
3194
3195
3196
3197
3198
3199
3200
3201
3202
3203
3204
3205
3206
3207
3208
3209
3210
3211
3212
3213
3214
3215
3216
3217
3218
3219
3220
3221
3222
3223
3224
3225
3226
3227
3228
3229
3230
3231
3232
3233
3234
3235
3236
3237
3238
3239
3240
3241
3242
3243
3244
3245
3246
3247
3248
3249
3250
3251
3252
3253
3254
3255
3256
3257
3258
3259
3260
3261
3262
3263
3264
3265
3266
3267
3268
3269
3270
3271
3272
3273
3274
3275
3276
3277
3278
3279
3280
3281
3282
3283
3284
3285
3286
3287
3288
3289
3290
3291
3292
3293
3294
3295
3296
3297
3298
3299
3300
3301
3302
3303
3304
3305
3306
3307
3308
3309
3310
3311
3312
3313
3314
3315
3316
3317
3318
3319
3320
3321
3322
3323
3324
3325
3326
3327
3328
3329
3330
3331
3332
3333
3334
3335
3336
3337
3338
3339
3340
3341
3342
3343
3344
3345
3346
3347
3348
3349
3350
3351
3352
3353
3354
3355
3356
3357
3358
3359
3360
3361
3362
3363
3364
3365
3366
3367
3368
3369
3370
3371
3372
3373
3374
3375
3376
3377
3378
3379
3380
3381
3382
3383
3384
3385
3386
3387
3388
3389
3390
3391
3392
3393
3394
3395
3396
3397
3398
3399
3400
3401
3402
3403
3404
3405
3406
3407
3408
3409
3410
3411
3412
3413
3414
3415
3416
3417
3418
3419
3420
3421
3422
3423
3424
3425
3426
3427
3428
3429
3430
3431
3432
3433
3434
3435
3436
3437
3438
3439
3440
3441
3442
3443
3444
3445
3446
3447
3448
3449
3450
3451
3452
3453
3454
3455
3456
3457
3458
3459
3460
3461
3462
3463
3464
3465
3466
3467
3468
3469
3470
3471
3472
3473
3474
3475
3476
3477
3478
3479
3480
3481
3482
3483
3484
3485
3486
3487
3488
3489
3490
3491
3492
3493
3494
3495
3496
3497
3498
3499
3500
3501
3502
3503
3504
3505
3506
3507
3508
3509
3510
3511
3512
3513
3514
3515
3516
3517
3518
3519
3520
3521
3522
3523
3524
3525
3526
3527
3528
3529
3530
3531
3532
3533
3534
3535
3536
3537
3538
3539
3540
3541
3542
3543
3544
3545
3546
3547
3548
3549
3550
3551
3552
3553
3554
3555
3556
3557
3558
3559
3560
3561
3562
3563
3564
3565
3566
3567
3568
3569
3570
3571
3572
3573
3574
3575
3576
3577
3578
3579
3580
3581
3582
3583
3584
3585
3586
3587
3588
3589
3590
3591
3592
3593
3594
3595
3596
3597
3598
3599
3600
3601
3602
3603
3604
3605
3606
3607
3608
3609
3610
3611
3612
3613
3614
3615
3616
3617
3618
3619
3620
3621
3622
3623
3624
3625
3626
3627
3628
3629
3630
3631
3632
3633
3634
3635
3636
3637
3638
3639
3640
3641
3642
3643
3644
3645
3646
3647
3648
3649
3650
3651
3652
3653
3654
3655
3656
3657
3658
3659
3660
3661
3662
3663
3664
3665
3666
3667
3668
3669
3670
3671
3672
3673
//! Operation request/response types and the gix-free read paths
//! (`health`, `search`).
//!
//! Per-entity delta envelopes for `memstead_changes_since` live in
//! [`changes`] — backend-neutral so both the git-branch tree-diff
//! and any future folder-backend JSONL-walk produce the same shape.
//! Wire types for the agent-notes payload live in [`agent_notes`] —
//! pure data shapes, no gix. The producer functions
//! (`agent_notes_since`, `read_memstead_ref`) stay in
//! `memstead-git-branch::ops::agent_notes` because they read from a
//! gitdir.
//! The git-touching operation submodules (`crud`, `export`) still
//! live in `memstead-git-branch` and are re-exported into
//! `memstead_git_branch::ops` for downstream callers.

pub mod agent_notes;
pub mod branch_reset;
pub mod changes;
pub mod commit_envelope;
pub mod diff;
pub mod export;
pub mod health;
pub mod integrity;
#[cfg(not(target_arch = "wasm32"))]
pub mod search;
pub mod transport;

pub use agent_notes::{AgentNotesReport, CommitNote};
pub use branch_reset::{BranchResetOutcome, StrandedCrossMemRef};
pub use changes::{
    BackendChanges, ChangeEnvelope, ChangesReport, EMPTY_TREE_SHA, MemChangedNotice,
    NoticeByChange, NoticeChanges, RENAME_SIMILARITY_DEFAULT, RENAME_SIMILARITY_MAX,
    RENAME_SIMILARITY_MIN, folder_changes_since,
};
pub use commit_envelope::{CommitEnvelope, EntityChange};
pub use diff::{Diff, DiffConfig, EntityDiff, IncomingRipple};
pub use export::{MemExportBytes, MemExportError};
pub use transport::{FetchOutcome, PullOutcome, PushOutcome, RemoteAddOutcome, UpdatedRef};

use crate::entity::EntityId;
use indexmap::IndexMap;
use schemars::JsonSchema;
use serde::{Deserialize, Serialize, Serializer, ser::SerializeStruct};
use std::collections::HashMap;
use std::fmt;

/// Allowed `include` keys for `memstead_overview` — single source of
/// truth shared across the lean MCP server, full MCP server, and the
/// lean CLI's `overview` command. Mirrors `HEALTH_INCLUDE_KEYS` for
/// the `health` surface. The CLI `--include` flag validates against
/// this list and surfaces `UNKNOWN_INCLUDE_KEY` warnings, matching the
/// MCP tool's behaviour.
pub const OVERVIEW_INCLUDE_KEYS: &[&str] = &[
    "community_members",
    "community_bridges",
    "mem_distribution",
    "dangling_links",
];

// The unknown-filter warning prose lives in the `Display` impl of the
// typed `WarningHint::UnknownFilterKey` / `WarningHint::UnknownRangeFilterField`
// variants below. These helpers are shared with that Display impl. They
// are pure string formatting with no search/tantivy dependency, so they
// live here (not in the wasm-gated `search` module) and stay available
// on `wasm32`.

/// Render the type-list clause as quoted items only — `"'X'"` for one
/// declarer, `"'X', 'Y'"` for many — without a leading "type" /
/// "types" word. Caller composes the leading word via
/// [`type_word_for`] so prose contexts like `"of types ..."` don't
/// produce the duplicate-word output `"of types types '...'"`.
pub(crate) fn format_types_clause(types: &[String]) -> String {
    types
        .iter()
        .map(|t| format!("'{t}'"))
        .collect::<Vec<_>>()
        .join(", ")
}

/// Leading word to pair with [`format_types_clause`]: `"type"` for a
/// single declarer, `"types"` for many. Empty slice maps to `"types"`
/// (callers should not invoke this for an empty list; the typed-
/// warning sites guard the `is_empty` case already).
pub(crate) fn type_word_for(types: &[String]) -> &'static str {
    if types.len() == 1 { "type" } else { "types" }
}

// ---------------------------------------------------------------------------
// CRUD types
// ---------------------------------------------------------------------------

/// Arguments for creating an entity.
#[derive(Debug, Clone)]
pub struct CreateArgs {
    pub title: String,
    pub mem: String,
    pub entity_type: String,
    /// Section contents keyed by section key: `{ "<section-key>": "..." }`.
    /// Valid keys depend on the schema (see `TypeDefinition::sections`).
    pub sections: IndexMap<String, String>,
    /// Metadata overrides: `{ "<field-key>": "value" }`.
    pub metadata: IndexMap<String, String>,
    /// Relationships to create: `[{ to: EntityId, type: "USES" }]`.
    pub relations: Vec<RelateArg>,
    /// When true, validate and compute the result but do not write to
    /// disk, mutate the store, create edges, or commit. Response carries
    /// the prospective `id`, `file_path`, `content_hash`, and any
    /// `warnings` — `commit_sha` is empty.
    pub dry_run: bool,
}

/// Arguments for updating an entity.
#[derive(Debug, Clone)]
pub struct UpdateArgs {
    pub id: EntityId,
    /// Expected content hash (optimistic locking). Required.
    pub expected_hash: String,
    /// Section fields to set: `{ "<section-key>": "new content" }`.
    pub sections: IndexMap<String, String>,
    /// Section fields to append to: `{ "<section-key>": "extra content" }`.
    pub append_sections: IndexMap<String, String>,
    /// Section fields to patch: `{ "<section-key>": PatchArg { old, new } }`.
    pub patch_sections: IndexMap<String, PatchArg>,
    /// Metadata fields to set: `{ "<field-key>": "value" }`.
    pub metadata: IndexMap<String, String>,
    /// Metadata keys to remove from the entity. Silent no-op on absent
    /// keys. Errors on read-only fields (mem, id, type) and on
    /// schema-required fields for the entity's type.
    pub metadata_unset: Vec<String>,
    /// Dry-run mode — return proposed changes without persisting.
    pub dry_run: bool,
}

/// Arguments for a patch (substring replacement).
#[derive(Debug, Clone)]
pub struct PatchArg {
    pub old: String,
    pub new: String,
    /// When `true`, replace every occurrence of `old` in the target
    /// section. Default `false` replaces only the first occurrence.
    pub all: bool,
}

/// Section-level mutations applied by a single `memstead_update` call.
/// Each vec lists the section keys that landed in that mutation mode.
/// Empty inner vecs are serde-omitted so the wire stays quiet; the
/// struct itself always serialises so the outer `modified_sections` key
/// is a stable shape regardless of what the call actually touched.
#[derive(Debug, Clone, Default, Serialize)]
pub struct ModifiedSections {
    /// Section keys whose body was replaced wholesale (`sections` input).
    #[serde(default, skip_serializing_if = "Vec::is_empty")]
    pub replaced: Vec<String>,
    /// Section keys whose body received an append (`append_sections`).
    #[serde(default, skip_serializing_if = "Vec::is_empty")]
    pub appended: Vec<String>,
    /// Section keys whose body was patched via find-and-replace
    /// (`patch_sections`).
    #[serde(default, skip_serializing_if = "Vec::is_empty")]
    pub patched: Vec<String>,
}

/// Metadata-level mutations applied by a single `memstead_update` call.
/// Same empty-vec-omit convention as `ModifiedSections`; auto-timestamp
/// metadata fields written by the engine are NOT surfaced here (they are
/// engine-driven, not user-driven — the caller has nothing to react to).
#[derive(Debug, Clone, Default, Serialize)]
pub struct ModifiedMetadata {
    /// Metadata keys whose value was set or replaced.
    #[serde(default, skip_serializing_if = "Vec::is_empty")]
    pub set: Vec<String>,
    /// Metadata keys that were removed from the frontmatter.
    #[serde(default, skip_serializing_if = "Vec::is_empty")]
    pub unset: Vec<String>,
}

/// Result of an update operation.
#[derive(Debug, Clone, Serialize)]
pub struct UpdateResult {
    pub id: EntityId,
    pub title: String,
    /// Section-level mutations grouped by mode. Replaces the former flat
    /// `modified_fields: Vec<String>` (which leaked mode as a string
    /// prefix and collided on bare keys with `modified_metadata`).
    pub modified_sections: ModifiedSections,
    /// Metadata-level mutations grouped by direction (set vs unset).
    pub modified_metadata: ModifiedMetadata,
    pub modified_date: String,
    /// On a real (non-dry-run) update: the new on-disk content hash after
    /// the write. On a dry-run: the **current** on-disk hash (unchanged) —
    /// the value an agent passes back as `expected_hash` on the follow-up
    /// real call. Pair with `prospective_hash` to predict the post-write
    /// hash without a second read. Wire key `_hash`.
    #[serde(rename = "_hash")]
    pub content_hash: String,
    /// Dry-run only: the hash the entity *would* have after the proposed
    /// write. `None` on real (non-dry-run) updates. Lets agents preview a
    /// change and then call the real update with `expected_hash =
    /// content_hash` (pinning the disk state) while still knowing what the
    /// post-write hash will look like. Additive optional field — stable
    /// shape for callers that ignore it.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub prospective_hash: Option<String>,
    /// Per-mem commit SHA produced by this mutation. Agents remember it
    /// and feed it to `memstead_changes_since` to pick up incremental updates.
    /// Empty for dry runs (no commit happens).
    #[serde(default)]
    pub commit_sha: String,
    /// Typed non-fatal issues — same shape as `CreateResult::warnings`.
    /// Pre-Bug-4 this was `Vec<String>` and unused; now carries
    /// `WarningHint` so e.g. `INLINE_WIKI_LINK_AUTO_STUBBED` from update
    /// flows out via the same `{code, message, details}` envelope agents
    /// already branch on for create-time warnings.
    #[serde(default, skip_serializing_if = "Vec::is_empty")]
    pub warnings: Vec<WarningHint>,
}

/// Typed non-fatal issue surfaced from engine operations. Serialises as the
/// uniform `{ code, message, details }` envelope so a generic warning handler
/// (log sink, UI, alerting) can read `code` + `message` without branching on
/// variant. `Display` renders the agent-facing text, reachable via
/// [`WarningHint::message`]; per-variant structured fields land under
/// `details`, their shape keyed by `code`.
///
/// Shared across `CreateResult`, `RelateResult`, and `HealthSummary`. New
/// variants are additive; they widen the enum rather than fork a per-site
/// type so wire-level warning consumers keep a single discriminated union
/// to branch on. The wire shape matches what [`envelope`] produces for the
/// MCP error channel, so one decoder handles both surfaces.
#[derive(Debug, Clone)]
pub enum WarningHint {
    /// A required section was empty or missing at create time. Carries
    /// the type and section keys plus the section's own `write_rules`
    /// so the agent can self-correct with a follow-up `memstead_update`.
    /// Type-level `write_rules` no longer ride per warning — they
    /// ship once at the mutation-response top level on
    /// `type_guidance` keyed by `entity_type` (F9). Decoders look up
    /// the guidance via `entity_type` against the top-level map.
    MissingRequiredSection {
        entity_type: String,
        key: String,
        heading: String,
        write_rules: Vec<String>,
    },
    /// A required metadata field was not supplied at create time and the
    /// schema does not auto-fill the value (no `default_value`, no
    /// `init_timestamp`, no `auto_timestamp`). The entity still lands —
    /// the generator may write an empty / today's-date placeholder into
    /// the frontmatter — but the warning surfaces the gap so the agent
    /// follows up via `memstead_update` rather than leaving the entity in a
    /// stuck state. Payload mirrors [`Self::MissingRequiredSection`] in
    /// shape so a single decoder handles both. Wire-equivalent shape
    /// with `EngineError::RequiredFieldUnset`'s `details` payload, since
    /// the recovery path is the same (read the description / allowed
    /// enum values from the envelope rather than re-fetching the
    /// schema).
    MissingRequiredField {
        entity_type: String,
        key: String,
        description: String,
        enum_values: Vec<String>,
    },
    /// An undeclared relationship was admitted because the mem's schema
    /// is in open mode. The caller can still suggest the name be added to
    /// the schema vocabulary.
    UndeclaredRelationshipOpen { rel_type: String, message: String },
    /// `memstead_relate` was asked to add an edge that already exists. The
    /// op is a successful no-op — the warning surfaces what would otherwise
    /// be silent so an agent relying on `renames` / side-effects can notice
    /// the call didn't change the graph.
    DuplicateRelationship {
        rel_type: String,
        from: EntityId,
        to: EntityId,
    },
    /// `memstead_relate` with `remove: true` was asked to drop an edge that
    /// wasn't present. Successful no-op, surfaced so an agent operating on
    /// a stale mental model sees the mismatch.
    NoSuchRelationship {
        rel_type: String,
        from: EntityId,
        to: EntityId,
    },
    /// An `include` key passed to `memstead_health` was outside the accepted
    /// set. The key is ignored; the allowed list is echoed back verbatim so
    /// an agent with a typo can correct on the next call without opening a
    /// schema doc.
    UnknownIncludeKey { key: String, allowed: Vec<String> },
    /// A paged/bounded parameter exceeded its cap. The cap is authoritative
    /// so the op still ran, but the warning surfaces what the caller
    /// requested vs. what was served.
    LimitClamped { requested: usize, actual: usize },
    /// `memstead_rename` was asked to change the title but normalisation
    /// (lowercase, diacritic-folding, punctuation-strip, hyphen-collapse)
    /// mapped the requested title to the existing slug — so the id is
    /// unchanged and nothing is written to disk. Surfaced so autonomous
    /// skills don't mistake the silent short-circuit for a successful
    /// cosmetic rewrite.
    TitleNormalizedToSlugNoop {
        requested_title: String,
        current_slug: String,
    },
    /// The title grammar admits any single-line text, but the slug
    /// alphabet stays narrow — this create/rename derived an id that
    /// dropped one or more title characters (`&`, `.`, `§`, …). The
    /// entity lands with the verbatim title; the warning keeps the
    /// title↔id divergence visible without being fatal, naming each
    /// distinct dropped character and the derived slug.
    TitleCharsDroppedFromSlug {
        title: String,
        dropped_chars: Vec<char>,
        slug: String,
    },
    /// `memstead_update` produced a post-mutation entity whose regenerated
    /// markdown is bytes-identical to the on-disk content — no field,
    /// section, metadata value, relation, or auto-timestamp actually
    /// changed. The op is a successful no-op: no disk write, no
    /// commit, `content_hash` unchanged. Surfaced so autonomous skills
    /// branching on `commit_sha != ""` see an explicit signal, and
    /// `expected_hash`-based polling stays stable across the no-op.
    /// Mirrors `TitleNormalizedToSlugNoop` for the rename surface.
    UpdateNoop { id: EntityId },
    /// `memstead_search` was called with both `stub=true` and `entity_type`
    /// set. Stubs carry no `entity_type` (they are ID-only placeholders),
    /// so the combined filter excludes every stub — the call is an empty
    /// set by construction. Surfaced so an agent doesn't interpret the
    /// empty result as "no stubs of this type exist" when in fact no
    /// stub can ever satisfy the filter. Drop `entity_type` to list stubs.
    StubFilterExcludesAll { entity_type: String },
    /// `memstead_search(filters: {<key>: ...})` named a filter key that the
    /// queried type does not declare. The wire `code()` discriminates
    /// the two outcomes, so a consumer branches on `code` alone:
    /// - `declared_on_other_types` **empty** → no reachable schema
    ///   declares the key → `UNKNOWN_FILTER_KEY`; the filter is truly
    ///   ignored and the result set equals the same search without it.
    /// - `declared_on_other_types` **non-empty** → the key is declared
    ///   on other type(s) and the filter was applied with strict
    ///   type-narrowing (result restricted to the declaring type(s), or
    ///   emptied when the call scoped to a non-declaring type) →
    ///   `FILTER_TYPE_SCOPED`.
    ///
    /// `declared_on_other_types` stays on the wire as enrichment, not as
    /// the disambiguator.
    UnknownFilterKey {
        key: String,
        /// `entity_type` the search call scoped to (`None` for an
        /// unscoped call).
        scoped_type: Option<String>,
        /// Types where the filter IS declared, sorted alphabetically.
        /// Empty when no reachable schema declares the key at all.
        declared_on_other_types: Vec<String>,
    },
    /// `memstead_search(filters: {<field>: ...})` named a field that the
    /// schema declares but with `filterable: none` — the filter is
    /// ignored, the hit set is unconstrained by it.
    FieldNotFilterable { field: String },
    /// `memstead_search(filters: {<csv-field>: "a,b"})` passed a comma-bearing
    /// value to a csv-array field. csv fields match a *single* member, so
    /// the whole rendered value (e.g. the `tags: dedup,retry` an entity
    /// displays) can never equal any one member — the filter matches
    /// nothing. Surfaced so an agent that copied the rendered value gets a
    /// recoverable signal (split into repeated single-member filters)
    /// rather than an empty result indistinguishable from a true
    /// no-match. The filter still applies as written (matches nothing);
    /// this only adds the advisory.
    FilterValueMultiMember { key: String, value: String },
    /// `memstead_search(filters: {<field>: <value>})` passed a value the
    /// schema field constrains with an `enum_values` allow-list, but the
    /// value (or, for a csv-array field, one of its comma members) is not a
    /// member. The filter still applies as written and matches nothing for
    /// that value, so an empty result is otherwise indistinguishable from a
    /// true no-match — this surfaces the typo plus the allowed values so an
    /// agent corrects without opening the schema. Reuses the
    /// `INVALID_ENUM_VALUE` code from the mutation surface.
    FilterValueNotInEnum {
        key: String,
        value: String,
        allowed: Vec<String>,
    },
    /// `memstead_search(related_to: <id>)` reached a neighbourhood larger
    /// than the cap. The results were ranked by proximity (nearer first)
    /// and bounded to the nearest `kept` of `total` reachable entities so a
    /// hub can't flood the caller. Surfaced so the agent knows the
    /// neighbourhood was truncated — narrow with `depth`/filters for more.
    NeighbourhoodCapped { kept: usize, total: usize },
    /// `memstead_search` trimmed the returned page to fit the token budget.
    /// The highest-ranked `kept` hits that fit under `budget` are returned;
    /// the rest of the page is dropped so the response stays under the MCP
    /// transport cap. `_total` still reflects the full match count — page the
    /// remainder with `offset`, narrow the query, or raise `token_budget`.
    SearchResultsTruncated { kept: usize, budget: usize },
    /// `memstead_search(range_filters: {<key>: ...})` named a key that
    /// doesn't follow the `min_<field>` / `max_<field>` / `<field>_before`
    /// / `<field>_after` grammar. The key is ignored.
    RangeFilterKeyMalformed { key: String },
    /// `memstead_search(range_filters: {<key>: ...})` named a range-filter
    /// key whose underlying field the queried type does not declare.
    /// Same shape and same one-code-per-outcome split as
    /// [`Self::UnknownFilterKey`]: `code()` is `UNKNOWN_RANGE_FILTER_FIELD`
    /// when `declared_on_other_types` is empty (truly ignored, result =
    /// unfiltered) and `RANGE_FILTER_TYPE_SCOPED` when non-empty (applied
    /// with strict type-narrowing). Includes the literal `key` (the
    /// prefixed/suffixed form the caller sent) alongside the bare `field`.
    UnknownRangeFilterField {
        field: String,
        /// The literal filter key the caller sent, e.g. `min_count`.
        key: String,
        scoped_type: Option<String>,
        declared_on_other_types: Vec<String>,
    },
    /// `memstead_search(range_filters: {<field>: ...})` named a field that
    /// the schema declares but with a filterability other than `range`.
    /// The range filter is ignored.
    FieldNotRangeFilterable { field: String },
    /// `memstead_search` could not query a target mem's search index —
    /// either the mem has no index yet (`reason: "missing_index"`)
    /// or a tantivy execution failure surfaced (`reason:
    /// "query_failed"` plus the error string).
    SearchMemIndexUnavailable {
        mem: String,
        /// Discriminator: `"missing_index"` or `"query_failed"`.
        reason: &'static str,
        /// The underlying error string when `reason == "query_failed"`;
        /// `None` for `"missing_index"`.
        error: Option<String>,
    },
    // There is deliberately no `RenameSimilarityClamped` variant:
    // out-of-range `rename_similarity` hard-refuses
    // (`EngineError::RenameSimilarityOutOfRange` → typed
    // `INVALID_INPUT`) rather than clamping, so the warning channel has
    // no story to tell and the typed-warning vocabulary tracks the live
    // wire shape.
    /// `memstead_create` (or `memstead_rename`) received a `title` with leading
    /// or trailing whitespace. The engine silently strips the surround
    /// before slug derivation and storage; the warning records what the
    /// caller sent vs. what landed so the audit trail can spot the
    /// drift. Internal whitespace (between words) is preserved
    /// untouched. Fully-whitespace titles are still refused at the
    /// validator boundary (those collapse to empty).
    TitleTrimmed { original: String, trimmed: String },
    /// An inline wiki-link resolved to an ID of the form
    /// `<current-mem>--<other-known-mem-suffix>--<slug>`. This is
    /// almost always drift from a mem-rename — the author wrote
    /// `[[plugin--slug]]` expecting `plugin` to be the mem prefix, but
    /// the current mem is `test-mem-plugin`, so the literal
    /// resolution nests the prefix. Detection only — the load path still
    /// creates the stub (no silent rewrite). Fix via `memstead_update
    /// patch_sections` to either the bare slug or the fully-qualified ID.
    /// Emitted at load / reload / attach time and carried through
    /// `HealthSummary.warnings`; mutation paths never emit this warning
    /// to avoid noise on every edit.
    SuspiciousNestedPrefix {
        from: EntityId,
        resolved_id: EntityId,
        /// Stripped-and-resolved candidate via the two-pass resolver
        /// (cross-mem lookup first, bare-slug fallback second). `None`
        /// when no real entity was found — the author must disambiguate.
        candidate_target: Option<EntityId>,
        section: String,
    },
    /// Inline `[[wiki-link]]` syntax in entity section bodies parsed to
    /// targets that did not yet resolve, so the engine auto-created stub
    /// entities for them. A common authoring hazard: an agent illustrating
    /// link syntax in prose (`[[example:slug]]`) inadvertently creates
    /// ghost stubs and a REFERENCES edge from the prose entity to each.
    /// Surfaced so the agent reviews the list and either replaces the
    /// inline literal with a fenced/quoted form or removes the entity if
    /// the stub was not intended. Carries the source entity id (`from`)
    /// and every newly-stubbed `target` id created by THIS call.
    InlineWikiLinkAutoStubbed {
        from: EntityId,
        stubs: Vec<EntityId>,
    },
    /// A body wiki-link resolved to the entity's own id, so the
    /// alias-synthesis pass dropped the would-be self-referential edge
    /// (F11) — a self-edge carries no navigational value and would render
    /// as both an Outgoing and an Incoming neighbour of itself. The
    /// create/update still succeeds (the author may have written their
    /// own slug); this warns so the dropped link is observable, matching
    /// the alias pass's other side-effect warnings (`AUTO_STUB_CREATED` /
    /// `INLINE_WIKI_LINK_AUTO_STUBBED`).
    SelfLinkIgnored { id: EntityId },
    /// `memstead_relate` to a cross-mem target whose mem is not (yet)
    /// mounted in the workspace. The cross-mem link policy permits
    /// the edge, so the engine auto-stubs the target as a forward
    /// reference — but with the target mem entirely absent from
    /// `writable_mems()`, the stub has no `_mem_schema` resolution
    /// and any later read sees an indeterminate-schema entity. The
    /// warning makes the missing-mem state visible so an operator
    /// can distinguish a typo (intended `B` but typed `b`) from a
    /// deliberate forward reference that expects the mem to be
    /// created later. (F4)
    CrossMemTargetMemUncreated {
        from_mem: String,
        to_mem: String,
        target_id: EntityId,
    },
    /// A mutation landed without a `note` field while the workspace
    /// config's `[mutations].require_notes = true` — provenance is
    /// best-effort, so the engine completes the commit but flags the
    /// absence so autonomous skills can audit their coverage. The
    /// mutation still writes to disk and produces a commit; this warning
    /// exists purely to surface the missed opportunity for a human- /
    /// agent-readable body line. `tool` carries the MCP tool name
    /// (`memstead_create`, `memstead_update`, …) so consumers can attribute the
    /// gap without re-deriving it from the response context.
    NoteMissing { tool: String },
    /// A create supplied a value for an auto-managed metadata field
    /// (`init_timestamp` like `created_date`, or `auto_timestamp` like
    /// `last_modified`); the engine owns those values, so the supplied
    /// one was discarded and the engine value stamped instead. The
    /// entity still lands — this warning closes the silent-drop gap so
    /// the agent learns its input had no effect without a follow-up
    /// read. `field` names the discarded key; `supplied` echoes the
    /// rejected value. (The `memstead_update` path refuses the same keys
    /// outright with `READ_ONLY_FIELD`; create's posture is
    /// stamp-and-proceed, so it warns rather than refusing.)
    IgnoredReadonlyField { field: String, supplied: String },
    /// The workspace is embedded inside another git repository
    /// (`outer_repo_root`) whose `.gitignore` does not list
    /// `mem-repo/`. Without that ignore line, the outer repo would
    /// either swallow `mem-repo-git` as a nested untracked tree or
    /// (worse) record it as a submodule via gitlink — both shapes
    /// silently corrupt the mem-repo identity.
    ///
    /// Surfaced from `memstead_health` so the agent / operator can fix
    /// the outer repo's `.gitignore` (or pass `--no-gitignore` at
    /// `memstead mem-repo init`/`migrate-from-disk` time and accept the
    /// risk explicitly).
    OuterRepoNotIgnoringMemRepo {
        outer_repo_root: String,
        workspace_root: String,
    },
    /// One or more `required_outgoing` blocks on the entity's type are
    /// not yet satisfied by its post-application outgoing edges. Tier-2
    /// — the create/update lands; the warning surfaces every unsatisfied
    /// block in a single payload so the agent can emit one batched
    /// `memstead_relate` follow-up.
    MissingRequiredOutgoing {
        entity_type: String,
        entity_id: EntityId,
        /// Each entry mirrors one unsatisfied `RequiredOutgoing` block:
        /// the alternative relationship names plus the rendered
        /// cardinality literal (`"at_least_one"`).
        missing: Vec<MissingRequiredOutgoingBlock>,
    },
    /// The written entity violates warn-tier declared `constraints`
    /// of its type (e.g. `requires_when`: a field required under the
    /// current value of another field is unset). Block-tier violations
    /// refuse instead ([`EngineError::ConstraintUnsatisfied`]) — the
    /// warning only ever carries `severity: warn` entries.
    ConstraintUnsatisfied {
        entity_type: String,
        entity_id: EntityId,
        violations: Vec<crate::ops::health::UnsatisfiedConstraint>,
    },
    /// A markdown file declared the same `## <Heading>` twice or more for a
    /// schema-declared section key. The parser keeps the first occurrence's
    /// body and drops the rest — the duplicate headers and their bodies are
    /// removed from the storage value, so the next read-modify-write cycle
    /// emits a single heading. Surfaced so the operator (or the next ingest
    /// cycle) sees that content was discarded; common cause is an agent
    /// appending a section instead of replacing it.
    ///
    /// Emitted at load / reload / attach time only; mutation paths do not
    /// re-parse the just-written file.
    DuplicateSectionHeading {
        entity_id: EntityId,
        section_key: String,
        heading: String,
        occurrences: usize,
    },
    /// The engine detected that a sibling writer (another `Engine`
    /// instance, an out-of-band `git pull`, etc.) advanced the on-disk
    /// HEAD of `mem` past the engine's cached `last_known_head`, so
    /// the engine reloaded that mem's slice of the in-memory store
    /// before serving the current call. The response carries fresh
    /// content; the warning explains why state shifted under the
    /// caller. Agents that need the per-entity diff call
    /// `memstead_changes_since` with the supplied `old_head`.
    MemReloaded {
        mem: String,
        old_head: String,
        new_head: String,
        entities_loaded: usize,
    },
    /// `memstead_relate` add path landed on a not-yet-real target id and
    /// the engine materialised a stub at that id (in-memory upsert; the
    /// file lands when a follow-up `memstead_create` promotes the stub).
    /// Pre-fix surfaced through a top-level `stub_warning: Option<String>`
    /// field on the relate response — agents iterating `warnings[]` to
    /// surface non-fatal findings silently skipped the auto-stub case.
    /// Carries the materialised stub id so the agent can pin a
    /// follow-up `memstead_create` (or `memstead_relate remove=true` to drop
    /// the edge before authoring). `pending` marks the dry-run path:
    /// the rehearsal validated the add and REPORTS the would-be stub
    /// without writing it — the code stays `AUTO_STUB_CREATED`
    /// (response-shape stability), only the message branches, so a
    /// rehearsed response never claims a performed effect.
    AutoStubCreated { stub_id: EntityId, pending: bool },
    /// A duplicate-add `memstead_relate` on a derivation-declared
    /// rel-type refreshed the edge's baseline (agent-trust plan 12) —
    /// the agent's explicit "I have reviewed the target's change; the
    /// derivation still holds". Sidecar-only: `_hash` unchanged, the
    /// edge unchanged; the response carries this warning so the
    /// refresh is stated rather than a bare no-op.
    DerivationBaselineRefreshed {
        from: EntityId,
        rel_type: String,
        to: EntityId,
    },
    /// A relation parsed from an entity's `## Relationships` section
    /// at load time failed validation against the source mem's
    /// schema (or wiki-link grammar). The entity itself loads
    /// normally; the offending relation is dropped from the
    /// in-memory store. `reason` discriminates:
    /// - `unknown_rel_type` — the rel-type is not declared in the
    ///   source mem's schema and the schema is in `strict` mode.
    /// - `shape` — the `(source_type, target_type)` pair is not
    ///   allowed by the rel-type's `source_types` / `target_types`.
    /// - `cycle` — adding this relation would close a cycle in an
    ///   acyclic-declared subgraph (emitted by the post-load
    ///   second-pass cycle check; not yet implemented).
    ///
    /// Hand-edits, external tooling, and the macOS app's editor
    /// surface can inject relations that bypass `memstead_relate`; the
    /// parse-path validation catches those. Mutation-path writes
    /// pre-validated by the engine never trip this warning.
    ///
    /// `origin` discriminates the source mount's capability:
    /// `"writable"` (the operator can fix the source markdown via
    /// `memstead_update` / `memstead_relate` and re-run) or `"readonly"`
    /// (the source mem is mounted read-only — purely diagnostic,
    /// the operator either uninstalls the archive or accepts the
    /// dropped relation).
    ///
    /// `recovery` carries an abstract-action payload sufficient to
    /// reverse the drop without consulting another response. `Some`
    /// when `origin == "writable"` — the engine can rewrite the
    /// source markdown via the mutation surface, so a consumer (an
    /// agent walking `memstead_health`, a bulk-fix orchestrator, the
    /// macOS app's drift panel) maps `kind` to the concrete call on
    /// whichever MCP / CLI / UniFFI surface it uses. `None` when
    /// `origin == "readonly"` — the source markdown is not reachable
    /// via the engine, so no abstract action exists; the warning's
    /// message names the operator-level path (uninstall the archive
    /// or accept the drop).
    ParsedRelationInvalid {
        entity_id: EntityId,
        rel_type: String,
        target: EntityId,
        reason: String,
        origin: String,
        recovery: Option<ParsedRelationRecovery>,
    },
    /// `memstead_delete` (or `memstead_rename`, when implemented) on a
    /// Write-Mem entity that had **no** Write-Mem referrers but
    /// **does** have ReadOnly-mount referrers. The on-disk file is
    /// removed and committed; the in-memory entity is demoted to a
    /// stub at the same id so the surviving incoming edges from the
    /// ReadOnly mount(s) keep a valid target. The agent sees
    /// `memstead_entity <id>` returning a stub immediately and not
    /// stale data after a server reload — fresh boot from disk
    /// reconstructs the same stub via the parser's auto-stub-on-
    /// unresolved-link path. `referrers` carries the surviving
    /// ReadOnly source ids so the agent can either accept the stub
    /// or uninstall the archive.
    ResidualStubForReadOnlyReferrers {
        id: EntityId,
        referrers: Vec<EntityId>,
    },
    /// `memstead_mem_delete` was called with `delete_files: true` but
    /// at least one part of the symmetric cleanup did not complete.
    /// The mem is already unregistered from the router; this
    /// warning surfaces what survived so an agent reading
    /// `files_deleted: false` doesn't trigger redundant cleanup or
    /// blame the wrong layer. `reason` discriminates:
    /// - `rmdir_failed` — folder-backed mem directory survived
    ///   `remove_dir_all` (filesystem permission, busy handle, …).
    ///   `path` names the directory; `error` carries the OS-level
    ///   diagnostic.
    /// - `backend_prune_failed` — git-branch backend rejected the
    ///   ref-edit transaction that prunes
    ///   `refs/heads/<branch_leaf>` + `__MEMSTEAD:mems/.../config.json`
    ///   (gitdir IO, concurrent writer racing the ref). `path` is
    ///   `None`; `error` carries the wrapped backend message.
    ///
    /// One emission per failed step — both can land in the same
    /// response when a folder mount somehow has both an rmdir
    /// failure and a backend cleanup failure (rare; the folder
    /// backend's `delete_artifacts` is a no-op default).
    MemFilesNotDeleted {
        mem: String,
        reason: String,
        path: Option<String>,
        error: Option<String>,
    },
    /// `memstead mem init` detected a pre-existing branch + config
    /// blob carrying the `unregistered_at` tombstone marker that
    /// `memstead mem unregister` writes — the operator's deliberate
    /// "preserve for re-attach" signal. The create path adopted the
    /// residual entities, cleared the tombstone, and registered the
    /// branch as a writable mount. Audit visibility for the
    /// reattach so an agent reading the warnings sees what shape
    /// the new mount took. `unregistered_at` carries the ISO-8601
    /// timestamp the tombstone recorded so the operator can correlate
    /// the reattach with a prior unregister event.
    MemReattachedAfterUnregister {
        mem: String,
        unregistered_at: String,
    },
    /// One-time boot migration: legacy `readMems` entries found in a
    /// writable mem's config were converted into workspace-level
    /// read-only mounts and the legacy key was removed from the
    /// config. `mems` lists the migrated read-mem names,
    /// `from_host_mems` the writable mems whose configs carried them.
    /// A second boot is silent — the source key is gone.
    ReadMemsMigratedToMounts {
        mems: Vec<String>,
        from_host_mems: Vec<String>,
    },
    /// Boot-honesty skew: the mem's engine-owned mutation stamp
    /// (`MemConfig.mutation_stamp`, written after mutations) records a
    /// different engine version than the running binary. Informative,
    /// never fatal — the next mutation under this binary re-stamps.
    /// Absence of a stamp (a pre-stamp mem) never fires this; only a
    /// present, disagreeing stamp does. Surfaces on boot output and
    /// `memstead health` without an include gate.
    EngineVersionSkew {
        mem: String,
        /// Engine version the last mutation was performed under.
        stamped_engine: String,
        /// Engine version of the running binary.
        running_engine: String,
        /// Resolved schema the last mutation validated against.
        stamped_schema: String,
    },
    /// Generation-behind hint: the mem's pinned schema resolved from
    /// the BUILT-IN catalogue and the catalogue registers at least
    /// one strictly-higher version of the same name (real semver
    /// ordering). Warn-tier, ungated, never blocking — retention
    /// seals every shipped version, so the pin keeps working; the
    /// hint names the newest available generation and the migration
    /// verb. Locally-installed (workspace-storage) pins are silent:
    /// the engine only knows generations for built-ins. Surfaces on
    /// boot output and `memstead health` without an include gate,
    /// like the skew hint above.
    SchemaGenerationsBehind {
        mem: String,
        /// The pinned ref (`name@version`).
        pinned: String,
        /// The newest built-in version registered under the same name.
        newest: String,
    },
    /// The mem was created on storage with no version control (a
    /// folder mount). Provenance means something WEAKER there than the
    /// headline "every mutation a reasoned commit": mutations ARE
    /// recorded — each lands in the folder backend's changelog ledger
    /// (`.memstead/changelog.jsonl`) with its provenance note — but
    /// there are no commits, the `commit_sha` every mutation returns
    /// is a synthetic placeholder, and the content is not durable
    /// until the surrounding repository commits it. Emitted once, at
    /// creation, to whoever is actually acting; never a refusal —
    /// folder mems are a supported storage class.
    FolderMemProvenance { mem: String },
    /// Authoring-drift health axis: a pinned schema's sealed copy
    /// carries an install-provenance stamp, and the authoring path it
    /// names is GONE from the working tree. Distinct from
    /// [`WarningHint::SchemaAuthoringSourceDiverged`] — a missing
    /// package and a diverged one need different actions. Only
    /// stamped schemas are checked: on git-branch workspaces the
    /// authoring folder is typically absent for unstamped seals, so a
    /// naive existence check would warn on healthy workspaces.
    SchemaAuthoringSourceMissing {
        schema_ref: String,
        stamped_path: String,
        mems: Vec<String>,
    },
    /// Authoring-drift health axis: the stamped authoring path exists
    /// but its package no longer parses EQUIVALENT to the sealed copy
    /// the engine runs on (parsed-schema comparison, never raw bytes —
    /// editor-header comment lines and serialisation reordering do not
    /// trip it). `detail` says how: a load failure's message, or the
    /// parsed-difference marker.
    SchemaAuthoringSourceDiverged {
        schema_ref: String,
        stamped_path: String,
        mems: Vec<String>,
        detail: String,
    },
    /// A `## Relationships` row was followed by trailing content that
    /// did not match the canonical em-dash delimiter (` — `, U+2014
    /// framed by spaces) — ASCII `--`, ASCII `-`, en-dash U+2013, or
    /// minus U+2212. The relation parses with `description: None`;
    /// the trailing content is NOT preserved on the in-memory
    /// `Relationship`, so the next render of this entity normalises
    /// the row to the simple form `- **TYPE**: [[X]]`. The warning is
    /// the operator's signal that content was dropped — restore the
    /// description with an explicit em-dash if it should round-trip.
    /// Emitted at parse time (load / reload / attach); mutation paths
    /// never trip it because they go through the typed `description`
    /// parameter rather than markdown text.
    AmbiguousDescriptionDelimiter {
        from: EntityId,
        rel_type: String,
        target: EntityId,
        /// Literal trailing content captured between `]]` and end of
        /// line — surfaced verbatim so the operator can paste the
        /// intended text back in with a canonical delimiter.
        trailing: String,
    },
    /// Parse-time variant of [`crate::EngineError::MissingRequiredDescription`].
    /// A hand-edited `## Relationships` row used a rel-type whose
    /// schema declares `per_edge_description: required` without a
    /// trailing description. The relation still loads (the engine
    /// does not block the file from booting), but the warning
    /// surfaces the gap so the operator follows up with `memstead_update`
    /// / `memstead_relate` to author the missing description.
    ParseMissingRequiredDescription {
        from: EntityId,
        rel_type: String,
        target: EntityId,
    },
    /// Parse-time variant of [`crate::EngineError::DescriptionNotPermitted`].
    /// A hand-edited `## Relationships` row used a rel-type whose
    /// schema declares `per_edge_description: forbidden` together
    /// with a trailing em-dash description. The relation still loads
    /// (the engine does not block the file from booting); the
    /// description is dropped from the in-memory `Relationship` and
    /// the next render normalises the row to the simple form. The
    /// warning surfaces the violation so the operator either removes
    /// the text from disk or asks the schema author to widen the
    /// rel-type's posture.
    ParseDescriptionNotPermitted {
        from: EntityId,
        rel_type: String,
        target: EntityId,
    },
    /// A mem's `Mount.schema` expectation (the pin recorded in the
    /// workspace `mounts.json`) disagreed with the authoritative pin in
    /// the mem's own per-mem config. Boot resolves the effective
    /// schema from the mem config (authoritative — a copied/cloned
    /// mem is self-resolvable); this warning surfaces the discrepancy
    /// so neither value is silently dropped. Recovery: align the
    /// `mounts.json` entry to the mem's config, or correct the config.
    SchemaPinMismatch {
        /// Mem whose mount expectation and config pin disagree.
        mem: String,
        /// Authoritative pin from the mem's per-mem config.
        config_pin: String,
        /// Expectation pin recorded on the workspace mount.
        mount_pin: String,
    },
    /// A mutation wrote a section whose emitted heading differs from a
    /// heading already present in the file that derives to the same
    /// section key. The write still commits — refusing would strand
    /// entities written before the round-trip gate existed — but the
    /// divergence is surfaced so the caller sees the file's heading
    /// text shifting under it (the regenerated file carries the
    /// schema's declared heading; the previous text is replaced).
    SectionHeadingDivergence {
        entity_id: EntityId,
        section_key: String,
        /// Heading the mutation is writing (the schema's declared one).
        writing_heading: String,
        /// Different heading the file carried for the same key.
        existing_heading: String,
    },
    /// A mem's resolved (already-installed) schema declares one or
    /// more sections whose heading does not derive back to its key —
    /// the condition new installs are refused for
    /// (`check_section_heading_roundtrip`). Sealed schemas keep
    /// loading by contract (refusing at boot would brick the
    /// workspace), so the violation surfaces here instead: every write
    /// against such a section forks its content into a second heading
    /// or the catch-all. Recovery: fix the schema's heading/key pairs
    /// and reinstall.
    SchemaHeadingRoundtripViolation {
        /// Mem whose pinned schema violates the rule.
        mem: String,
        /// The pinned `<name>@<version>`.
        schema_ref: String,
        /// Every offending `(type, key, heading, derived_key)` tuple.
        violations: Vec<SchemaHeadingViolation>,
    },
}

/// Wire-shape entry inside `SchemaHeadingRoundtripViolation.violations`
/// — one section whose declared heading does not derive back to its
/// declared key. Mirrors `memstead_schema::HeadingKeyViolation`, kept
/// as a local struct so the warning's JSON shape is owned here.
#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
pub struct SchemaHeadingViolation {
    pub type_name: String,
    pub key: String,
    pub heading: String,
    pub derived_key: String,
}

impl From<&memstead_schema::HeadingKeyViolation> for SchemaHeadingViolation {
    fn from(v: &memstead_schema::HeadingKeyViolation) -> Self {
        Self {
            type_name: v.type_name.clone(),
            key: v.key.clone(),
            heading: v.heading.clone(),
            derived_key: v.derived_key.clone(),
        }
    }
}

/// Wire-shape entry inside `MissingRequiredOutgoing.missing`. Lists the
/// relationship-name alternatives and the rendered cardinality literal
/// for one unsatisfied `RequiredOutgoing` block. Custom struct so the
/// JSON output is `{ "relationships": [...], "cardinality": "at_least_one" }`
/// — identical to the schema YAML shape, so an agent can copy the
/// envelope's `details.missing` entry directly into a `memstead_relate`
/// plan without renaming fields.
#[derive(Debug, Clone, Serialize)]
pub struct MissingRequiredOutgoingBlock {
    pub relationships: Vec<String>,
    pub cardinality: String,
    /// The block's declared severity. Serialized only for `block` —
    /// warn is the default the vocabulary has always had, and existing
    /// consumers keep their byte-identical `{ relationships,
    /// cardinality }` shape.
    #[serde(skip_serializing_if = "severity_is_warn")]
    pub severity: memstead_schema::ConstraintSeverity,
}

fn severity_is_warn(s: &memstead_schema::ConstraintSeverity) -> bool {
    *s == memstead_schema::ConstraintSeverity::Warn
}

/// Abstract recovery action attached to a `PARSED_RELATION_INVALID`
/// warning when the source mem is writable. The shape is tool-
/// agnostic: it names *what* to do, not *which tool* to call. A
/// consumer (agent, bulk-fix orchestrator, app surface) maps `kind`
/// to the concrete call on whichever MCP / CLI / UniFFI path it
/// uses; the warning's payload itself does not drift when the
/// mutation surface evolves.
///
/// `kind` is the discriminator. Additive — new variants may land as
/// the recovery taxonomy grows. Current values:
///
/// - `"remove_explicit_relation"` — drop the relation from the
///   source entity's `## Relationships` section. Agents map this to
///   `memstead_relate { from: source_id, to: target_id, type: rel_type,
///   remove: true }`. The CLI maps it to the equivalent
///   `memstead relate --remove` invocation. The bulk-fix consumer reads
///   `source_id`, `target_id`, `rel_type` straight from the payload.
///
/// The mirrored `source_id` / `target_id` / `rel_type` fields are
/// redundant with the warning's `entity_id` / `target` / `rel_type`
/// — duplication is intentional. A consumer that branches on
/// `recovery` and forwards the payload downstream does not need to
/// stitch the warning's top-level fields back in.
#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
pub struct ParsedRelationRecovery {
    pub kind: String,
    pub source_id: EntityId,
    pub target_id: EntityId,
    pub rel_type: String,
}

impl ParsedRelationRecovery {
    /// Stable discriminator for the "drop the relation from the
    /// source markdown" recovery — the only abstract action this
    /// warning emits today.
    pub const KIND_REMOVE_EXPLICIT_RELATION: &'static str = "remove_explicit_relation";

    /// Constructor for the standard `remove_explicit_relation`
    /// recovery — the only shape produced by the parser today.
    /// Emission sites use this so the discriminator string lives in
    /// one place.
    pub fn remove_explicit_relation(
        source_id: EntityId,
        target_id: EntityId,
        rel_type: String,
    ) -> Self {
        Self {
            kind: Self::KIND_REMOVE_EXPLICIT_RELATION.to_string(),
            source_id,
            target_id,
            rel_type,
        }
    }
}

/// Per-entry result of an `apply_parse_recovery` call. One entry per
/// `PARSED_RELATION_INVALID` warning the engine observed at the call
/// site: the bulk-fix dispatches the writable-origin recoveries and
/// reports the read-only-origin warnings as skipped. Wire-equivalent
/// across MCP, CLI, and UniFFI surfaces; the renderer chooses the
/// shape it prefers.
///
/// `outcome` is the stable discriminator. Current values:
/// - `"removed"` — the source entity was re-rendered; the parse-time-
///   dropped row no longer appears in the on-disk markdown. `reason`
///   is `None`.
/// - `"skipped"` — the engine intentionally did not attempt the
///   recovery. `reason` carries a stable code: `"readonly_mount"`
///   (source mem is read-only and not engine-writable).
/// - `"failed"` — the engine attempted the recovery and the underlying
///   mutation surfaced a typed error. `reason` carries the engine's
///   `UPPER_SNAKE_CASE` error code (`HASH_MISMATCH`,
///   `WIKILINK_WITHOUT_RELATION`, etc.). The original entity-side
///   drift survives and will surface again on the next reload.
#[derive(Debug, Clone, Serialize)]
pub struct ParseRecoveryEntry {
    pub entity_id: EntityId,
    pub rel_type: String,
    pub target: EntityId,
    pub outcome: String,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub reason: Option<String>,
}

impl ParseRecoveryEntry {
    pub const OUTCOME_REMOVED: &'static str = "removed";
    pub const OUTCOME_SKIPPED: &'static str = "skipped";
    pub const OUTCOME_FAILED: &'static str = "failed";

    /// Stable reason value for read-only-origin warnings the bulk-fix
    /// cannot act on — the source markdown is not engine-writable.
    pub const REASON_READONLY_MOUNT: &'static str = "readonly_mount";
}

/// Outcome of `Engine::apply_parse_recovery`. Carries one
/// `ParseRecoveryEntry` per parse-time-dropped relation observed at
/// the call site plus the last successful commit sha for callers that
/// want to poll `memstead_changes_since` for the per-entity diff. An empty
/// `entries` list means the workspace was already clean.
///
/// Idempotency: re-running on a workspace where the writable drops
/// were already cleaned produces an empty `entries` list (no work,
/// no commits, no errors).
#[derive(Debug, Clone, Default, Serialize)]
pub struct ParseRecoveryReport {
    #[serde(default, skip_serializing_if = "Vec::is_empty")]
    pub entries: Vec<ParseRecoveryEntry>,
    /// Last successful commit sha across all per-source re-renders
    /// the bulk-fix performed. Empty when no recovery wrote to disk
    /// (workspace already clean, only read-only warnings, or every
    /// writable attempt failed).
    #[serde(default, skip_serializing_if = "String::is_empty")]
    pub commit_sha: String,
}

impl fmt::Display for WarningHint {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            WarningHint::SchemaPinMismatch {
                mem,
                config_pin,
                mount_pin,
            } => write!(
                f,
                "mem '{mem}': the workspace mount expects schema '{mount_pin}' but the \
                 mem's own config pins '{config_pin}' — the config pin is authoritative and \
                 was used; align the mounts.json entry or the mem config to clear this"
            ),
            WarningHint::SectionHeadingDivergence {
                entity_id,
                section_key,
                writing_heading,
                existing_heading,
            } => write!(
                f,
                "entity '{entity_id}': section '{section_key}' is being written under \
                 heading '{writing_heading}' but the file carried '{existing_heading}' for \
                 the same section — the write commits and the regenerated file uses \
                 '{writing_heading}'; the previous heading text is replaced"
            ),
            WarningHint::SchemaHeadingRoundtripViolation {
                mem,
                schema_ref,
                violations,
            } => {
                let list = violations
                    .iter()
                    .map(|v| {
                        format!(
                            "type '{}' section '{}' heading '{}' (derives to '{}')",
                            v.type_name, v.key, v.heading, v.derived_key
                        )
                    })
                    .collect::<Vec<_>>()
                    .join("; ");
                write!(
                    f,
                    "mem '{mem}': pinned schema '{schema_ref}' declares section heading(s) \
                     that cannot round-trip to their key(s): {list}. The mem keeps loading, \
                     but writes to these sections fork content into a second heading or the \
                     catch-all. Fix the schema's heading/key pairs and reinstall — new \
                     installs of such a schema are refused"
                )
            }
            WarningHint::MissingRequiredSection {
                key,
                heading,
                write_rules,
                ..
            } => {
                write!(
                    f,
                    "required section '{key}' (heading \"{heading}\") is empty — \
                     entity will show as unhealthy"
                )?;
                if !write_rules.is_empty() {
                    write!(f, ". Writing guidance:")?;
                    for rule in write_rules {
                        write!(f, "\n  - {rule}")?;
                    }
                }
                Ok(())
            }
            WarningHint::MissingRequiredField {
                key,
                entity_type,
                description,
                enum_values,
            } => {
                write!(
                    f,
                    "required metadata field '{key}' on type '{entity_type}' was not \
                     supplied — entity landed with a placeholder. {description}"
                )?;
                if !enum_values.is_empty() {
                    write!(f, " Allowed values: [{}].", enum_values.join(", "))?;
                }
                Ok(())
            }
            WarningHint::UndeclaredRelationshipOpen { message, .. } => f.write_str(message),
            WarningHint::DuplicateRelationship { rel_type, from, to } => write!(
                f,
                "relationship {rel_type} from {from} to {to} already exists — no-op"
            ),
            WarningHint::NoSuchRelationship { rel_type, from, to } => write!(
                f,
                "relationship {rel_type} from {from} to {to} does not exist — no-op"
            ),
            WarningHint::UnknownIncludeKey { key, allowed } => write!(
                f,
                "unknown include key '{key}' ignored. Allowed: [{}]",
                allowed.join(", ")
            ),
            WarningHint::LimitClamped { requested, actual } => write!(
                f,
                "limit clamped from {requested} to {actual} (max for memstead_health)"
            ),
            WarningHint::TitleNormalizedToSlugNoop {
                requested_title,
                current_slug,
            } => write!(
                f,
                "requested title '{requested_title}' normalises to the existing slug \
                 '{current_slug}' — no change written to disk"
            ),
            WarningHint::TitleCharsDroppedFromSlug {
                title,
                dropped_chars,
                slug,
            } => write!(
                f,
                "title '{title}' keeps its characters as display text, but the derived \
                 slug '{slug}' drops {dropped_chars:?} — link this entity by its slug"
            ),
            WarningHint::UpdateNoop { id } => write!(
                f,
                "update on {id} produced bytes-identical content — no \
                 disk write, no commit, content_hash unchanged"
            ),
            WarningHint::StubFilterExcludesAll { entity_type } => write!(
                f,
                "stub=true combined with entity_type='{entity_type}' excludes every \
                 stub — stubs carry no entity_type. Drop entity_type to list stubs."
            ),
            WarningHint::UnknownFilterKey {
                key,
                scoped_type,
                declared_on_other_types,
            } => {
                let on_other = !declared_on_other_types.is_empty();
                let scoped_matches_other = matches!(
                    scoped_type.as_deref(),
                    Some(t) if declared_on_other_types.iter().any(|o| o == t)
                );
                if let Some(t) = scoped_type.as_deref() {
                    if on_other && !scoped_matches_other {
                        let word = type_word_for(declared_on_other_types);
                        let items = format_types_clause(declared_on_other_types);
                        return write!(
                            f,
                            "filter '{key}' applied with strict type-exclusion semantics — exists on {word} {items} but the query scoped to type '{t}', where it is not declared. All entities of type '{t}' will be excluded; scope to a declaring type to apply the filter."
                        );
                    }
                    return write!(
                        f,
                        "unknown filter key '{key}' for type '{t}' — filter ignored"
                    );
                }
                if on_other {
                    let word = type_word_for(declared_on_other_types);
                    let items = format_types_clause(declared_on_other_types);
                    return write!(
                        f,
                        "filter '{key}' applied with strict type-exclusion semantics — only entities of {word} {items} will match. Scope explicitly via entity_type=… to suppress this warning."
                    );
                }
                write!(
                    f,
                    "unknown filter key '{key}' — no reachable schema declares it — filter ignored"
                )
            }
            WarningHint::FieldNotFilterable { field } => {
                write!(f, "field '{field}' is not filterable — filter ignored")
            }
            WarningHint::FilterValueMultiMember { key, value } => write!(
                f,
                "filter '{key}={value}' targets a csv-array field but the value contains a comma — \
                 csv fields match a single member, so the full value matches nothing. Filter on one \
                 member at a time (e.g. `{key}={first}`)",
                first = value.split(',').next().map(str::trim).unwrap_or("").trim(),
            ),
            WarningHint::FilterValueNotInEnum {
                key,
                value,
                allowed,
            } => write!(
                f,
                "filter '{key}={value}' is not an allowed value for '{key}' — allowed: [{}]. \
                 The filter applies as written and matches nothing.",
                allowed.join(", ")
            ),
            WarningHint::NeighbourhoodCapped { kept, total } => write!(
                f,
                "related_to neighbourhood has {total} entities; ranked by proximity and bounded to \
                 the nearest {kept}. Narrow with `depth` or filters to see fewer, more specific hits."
            ),
            WarningHint::SearchResultsTruncated { kept, budget } => write!(
                f,
                "results trimmed to the highest-ranked {kept} hits to fit the {budget}-token budget. \
                 `_total` is the full match count — page the rest with `offset`, narrow the query, \
                 or raise `token_budget`."
            ),
            WarningHint::RangeFilterKeyMalformed { key } => write!(
                f,
                "range filter key '{key}' must start with 'min_'/'max_' or end with '_before'/'_after' — filter ignored"
            ),
            WarningHint::UnknownRangeFilterField {
                field,
                key,
                scoped_type,
                declared_on_other_types,
            } => {
                let on_other = !declared_on_other_types.is_empty();
                let scoped_matches_other = matches!(
                    scoped_type.as_deref(),
                    Some(t) if declared_on_other_types.iter().any(|o| o == t)
                );
                if let Some(t) = scoped_type.as_deref() {
                    if on_other && !scoped_matches_other {
                        let word = type_word_for(declared_on_other_types);
                        let items = format_types_clause(declared_on_other_types);
                        return write!(
                            f,
                            "range filter field '{field}' (from key '{key}') applied with strict type-exclusion semantics — exists on {word} {items} but the query scoped to type '{t}', where it is not declared. All entities of type '{t}' will be excluded; scope to a declaring type to apply the filter."
                        );
                    }
                    return write!(
                        f,
                        "unknown range filter field '{field}' (from key '{key}') for type '{t}' — filter ignored"
                    );
                }
                if on_other {
                    let word = type_word_for(declared_on_other_types);
                    let items = format_types_clause(declared_on_other_types);
                    return write!(
                        f,
                        "range filter field '{field}' (from key '{key}') applied with strict type-exclusion semantics — only entities of {word} {items} will match. Scope explicitly via entity_type=… to suppress this warning."
                    );
                }
                write!(
                    f,
                    "unknown range filter field '{field}' (from key '{key}') — no reachable schema declares it — filter ignored"
                )
            }
            WarningHint::FieldNotRangeFilterable { field } => write!(
                f,
                "field '{field}' is not range-filterable — filter ignored"
            ),
            WarningHint::SearchMemIndexUnavailable { mem, reason, error } => {
                match (*reason, error.as_deref()) {
                    ("missing_index", _) => {
                        write!(f, "mem '{mem}' has no search index — query returns no hits")
                    }
                    ("query_failed", Some(e)) => {
                        write!(f, "search index for mem '{mem}' errored: {e}")
                    }
                    _ => write!(f, "search index for mem '{mem}' is unavailable ({reason})"),
                }
            }
            WarningHint::TitleTrimmed { original, trimmed } => write!(
                f,
                "title trimmed of surrounding whitespace: {original:?}{trimmed:?}"
            ),
            WarningHint::SuspiciousNestedPrefix {
                from,
                resolved_id,
                candidate_target,
                section,
            } => {
                write!(
                    f,
                    "wiki-link in {from}#{section} resolves to nested prefix \
                     {resolved_id} — almost certainly mem-rename drift"
                )?;
                if let Some(cand) = candidate_target {
                    write!(f, "; did you mean {cand}?")?;
                }
                Ok(())
            }
            WarningHint::InlineWikiLinkAutoStubbed { from, stubs } => {
                write!(
                    f,
                    "{from} contained {n} inline wiki-link(s) that auto-created stub \
                     entities — review whether the stubs were intended; if not, \
                     remove the inline syntax or wrap the example in a fenced/quoted \
                     form. Auto-stubbed targets:",
                    n = stubs.len(),
                )?;
                for s in stubs {
                    write!(f, "\n  - {s}")?;
                }
                Ok(())
            }
            WarningHint::SelfLinkIgnored { id } => write!(
                f,
                "{id} contains a body wiki-link to its own id — the self-referential edge \
                 was dropped (a self-link carries no navigational value). The entity was \
                 created/updated normally; remove the `[[{slug}]]` link if it was a mistake",
                slug = id.name(),
            ),
            WarningHint::CrossMemTargetMemUncreated {
                from_mem,
                to_mem,
                target_id,
            } => write!(
                f,
                "cross-mem relate from '{from_mem}' to '{target_id}': \
                 target mem '{to_mem}' is not mounted in the workspace — \
                 the auto-stub has no schema resolution until the mem is created. \
                 If '{to_mem}' is a typo, fix the relate; if forward-reference \
                 is intended, create the mem to promote the stub."
            ),
            WarningHint::NoteMissing { tool } => write!(
                f,
                "{tool} called without a `note` while \
                 `[mutations].require_notes = true` — commit landed, \
                 body carries no provenance line"
            ),
            WarningHint::IgnoredReadonlyField { field, supplied } => write!(
                f,
                "'{field}' is auto-managed by the engine — the supplied \
                 value '{supplied}' was discarded and the engine value \
                 stamped instead"
            ),
            WarningHint::OuterRepoNotIgnoringMemRepo {
                outer_repo_root,
                workspace_root,
            } => write!(
                f,
                "workspace at '{workspace_root}' is embedded inside the git \
                 repository at '{outer_repo_root}' but the outer .gitignore \
                 does not list 'mem-repo/'. Add 'mem-repo/' (or the \
                 workspace-relative equivalent) to the outer repo's \
                 .gitignore to keep mem-repo-git out of the outer index."
            ),
            WarningHint::MissingRequiredOutgoing {
                entity_type,
                entity_id,
                missing,
            } => {
                write!(
                    f,
                    "{entity_id} ({entity_type}) is missing required outgoing edges — \
                     schema declares {n} `required_outgoing` block(s) still unsatisfied:",
                    n = missing.len(),
                )?;
                for block in missing {
                    write!(
                        f,
                        "\n  - [{}] cardinality={}",
                        block.relationships.join(", "),
                        block.cardinality,
                    )?;
                }
                Ok(())
            }
            WarningHint::ConstraintUnsatisfied {
                entity_type,
                entity_id,
                violations,
            } => {
                write!(
                    f,
                    "{entity_id} ({entity_type}) violates {n} declared constraint(s):",
                    n = violations.len(),
                )?;
                for v in violations {
                    write!(f, "\n  - {}", v.describe())?;
                }
                Ok(())
            }
            WarningHint::DuplicateSectionHeading {
                entity_id,
                section_key,
                heading,
                occurrences,
            } => write!(
                f,
                "{entity_id} declared `## {heading}` {occurrences} times — \
                 section '{section_key}' kept the first occurrence's body \
                 and dropped the rest. The next read-modify-write will \
                 collapse the markdown to one heading."
            ),
            WarningHint::MemReloaded {
                mem,
                old_head,
                new_head,
                entities_loaded,
            } => write!(
                f,
                "mem '{mem}' was reloaded — on-disk HEAD advanced from \
                 {old_head} to {new_head} (a sibling writer or out-of-band \
                 commit landed since the engine last read the mem). \
                 {entities_loaded} entities reloaded; response carries \
                 fresh content. Re-derive any conclusions that depended on \
                 the prior content of this mem before continuing. Call \
                 `memstead_changes_since since={old_head}` for the per-entity \
                 diff."
            ),
            WarningHint::AutoStubCreated { stub_id, pending } => {
                if *pending {
                    write!(
                        f,
                        "target '{stub_id}' does not exist — a stub would be \
                         auto-created by the real call. Promote it via \
                         memstead_create first, or let the real call create \
                         the stub (adoption preserves the incoming edge)."
                    )
                } else {
                    write!(
                        f,
                        "target '{stub_id}' did not exist — stub auto-created. \
                         Promote it via memstead_create when authoring the real \
                         entity (stub adoption preserves the incoming edge)."
                    )
                }
            }
            WarningHint::DerivationBaselineRefreshed { from, rel_type, to } => write!(
                f,
                "derivation baseline refreshed: '{from}' -[{rel_type}]-> '{to}' — the edge \
                 already existed; its baseline now records the target's current content \
                 hash (reviewed, still holds). Nothing else changed."
            ),
            WarningHint::ParsedRelationInvalid {
                entity_id,
                rel_type,
                target,
                reason,
                origin,
                recovery: _,
            } => {
                let recovery_msg = if origin == "readonly" {
                    "Source mem is mounted read-only; the engine cannot \
                     rewrite the markdown. Either remove the mount \
                     (`memstead uninstall <mem>`) or accept the dropped \
                     relation."
                } else {
                    "Fix the source markdown (via memstead_update / \
                     memstead_relate — `details.recovery` carries the abstract \
                     action) or adjust the schema."
                };
                write!(
                    f,
                    "parsed relation {rel_type} from {entity_id} to \
                     {target} was dropped — reason: {reason}, origin: \
                     {origin}. The entity loaded but the relation does \
                     not appear in the in-memory graph. {recovery_msg}"
                )
            }
            WarningHint::ResidualStubForReadOnlyReferrers { id, referrers } => write!(
                f,
                "{id} was deleted from disk but {n} read-only-mount \
                 referrer(s) still target it; the in-memory entity is \
                 demoted to a stub at the same id so the surviving \
                 incoming edges keep a valid target. Surviving referrers: \
                 [{}]. Either accept the stub or remove the source mount \
                 (`memstead uninstall <mem>`) — read-only content cannot \
                 be rewritten by the engine.",
                referrers
                    .iter()
                    .map(|r| r.to_string())
                    .collect::<Vec<_>>()
                    .join(", "),
                n = referrers.len(),
            ),
            WarningHint::AmbiguousDescriptionDelimiter {
                from,
                rel_type,
                target,
                trailing,
            } => write!(
                f,
                "{from}{target} ({rel_type}): trailing content {trailing:?} \
                 after `]]` did not match the canonical em-dash delimiter ` — ` \
                 (U+2014); content dropped, the relation parses with no \
                 description. Restore with `memstead_relate {from} {rel_type} \
                 {target} --description \"<text>\"` (or hand-edit using \
                 ` — `) if the text was intentional."
            ),
            WarningHint::ParseMissingRequiredDescription {
                from,
                rel_type,
                target,
            } => write!(
                f,
                "{from}{target} ({rel_type}): rel-type declares \
                 `per_edge_description: required` but the row has no \
                 trailing em-dash description. Add one via `memstead_relate \
                 {from} {rel_type} {target} --description \"<text>\"` (or \
                 hand-edit the markdown using ` — `)."
            ),
            WarningHint::ParseDescriptionNotPermitted {
                from,
                rel_type,
                target,
            } => write!(
                f,
                "{from}{target} ({rel_type}): rel-type declares \
                 `per_edge_description: forbidden` but the markdown row \
                 carries a trailing description. The description is \
                 dropped from the in-memory graph and the next render \
                 normalises the row to the simple form. Drop the trailing \
                 text from the source markdown if it should not round-trip."
            ),
            WarningHint::MemReattachedAfterUnregister {
                mem,
                unregistered_at,
            } => write!(
                f,
                "mem '{mem}' was reattached to pre-existing storage \
                 that carried an `unregistered_at: {unregistered_at}` \
                 tombstone marker. The entities from the prior session \
                 were adopted; the tombstone has been cleared. If this \
                 reattach was unexpected, run `memstead mem delete \
                 {mem}` to destroy the storage and start fresh."
            ),
            WarningHint::ReadMemsMigratedToMounts {
                mems,
                from_host_mems,
            } => write!(
                f,
                "legacy `readMems` registrations were migrated to \
                 workspace-level read-only mounts: [{}] (previously \
                 attached to writable mem(s) [{}]). The legacy key was \
                 removed from the config; this migration runs once. \
                 Remove a migrated read-mem with `memstead uninstall \
                 <name>`.",
                mems.join(", "),
                from_host_mems.join(", "),
            ),
            WarningHint::EngineVersionSkew {
                mem,
                stamped_engine,
                running_engine,
                stamped_schema,
            } => write!(
                f,
                "mem '{mem}': the last mutation was performed by engine \
                 v{stamped_engine} (against schema {stamped_schema}); \
                 this binary is engine v{running_engine}. Informative \
                 only — the next mutation re-stamps. If behaviour \
                 differs from the last session, the binary changed \
                 between them.",
            ),
            WarningHint::SchemaGenerationsBehind {
                mem,
                pinned,
                newest,
            } => write!(
                f,
                "mem '{mem}' pins built-in schema {pinned}, but the \
                 catalogue registers newer generations up to {newest}. \
                 The pin keeps working (retained versions stay sealed); \
                 migrate via `memstead mem set-schema` when ready.",
            ),
            WarningHint::FolderMemProvenance { mem } => write!(
                f,
                "mem '{mem}' was created on folder storage with no \
                 version control. Provenance here is the changelog \
                 ledger (`.memstead/changelog.jsonl`), which records \
                 every mutation with its note — but there are no \
                 commits: the `commit_sha` mutations return is a \
                 synthetic placeholder, and the content is not durable \
                 until the surrounding repository commits it."
            ),
            WarningHint::SchemaAuthoringSourceMissing {
                schema_ref,
                stamped_path,
                mems,
            } => write!(
                f,
                "schema '{schema_ref}' (pinned by {}) was installed from \
                 '{stamped_path}', and that authoring package is no longer \
                 there. The engine keeps running on its sealed copy — \
                 nothing is broken — but the source the seal came from is \
                 gone: restore or move back the package, or re-install \
                 from its new location to re-stamp.",
                mems.join(", ")
            ),
            WarningHint::SchemaAuthoringSourceDiverged {
                schema_ref,
                stamped_path,
                mems,
                detail,
            } => write!(
                f,
                "schema '{schema_ref}' (pinned by {}) no longer matches \
                 its authoring package at '{stamped_path}': {detail}. The \
                 engine keeps running on its sealed copy; if the authoring \
                 change is intended, bump the version and `memstead schema \
                 install` it.",
                mems.join(", ")
            ),
            WarningHint::MemFilesNotDeleted {
                mem,
                reason,
                path,
                error,
            } => match (reason.as_str(), path.as_deref(), error.as_deref()) {
                ("rmdir_failed", Some(p), Some(e)) => write!(
                    f,
                    "mem '{mem}' was unregistered but rmdir of \
                         {p:?} failed: {e}. Files remain on disk; agent \
                         may follow up with manual cleanup."
                ),
                ("rmdir_failed", Some(p), None) => write!(
                    f,
                    "mem '{mem}' was unregistered but rmdir of \
                         {p:?} failed. Files remain on disk."
                ),
                ("backend_prune_failed", _, Some(e)) => write!(
                    f,
                    "mem '{mem}' was unregistered but backend \
                         artifact cleanup failed: {e}. The mem-repo \
                         branch and/or `__MEMSTEAD:mems/.../config.json` \
                         entry may survive; rerun delete with the same \
                         arguments or have an operator inspect."
                ),
                ("backend_prune_failed", _, None) => write!(
                    f,
                    "mem '{mem}' was unregistered but backend \
                         artifact cleanup failed. The mem-repo branch \
                         and/or `__MEMSTEAD` config entry may survive."
                ),
                _ => write!(
                    f,
                    "mem '{mem}' was unregistered but \
                         `delete_files: true` did not run to completion \
                         (reason: {reason})."
                ),
            },
        }
    }
}

impl WarningHint {
    /// Stable UPPER_SNAKE_CASE identifier. Wire-level contract — never rename
    /// an existing value; new variants add new codes. Agents branch on this,
    /// not on [`WarningHint::message`].
    pub fn code(&self) -> &'static str {
        match self {
            Self::InlineWikiLinkAutoStubbed { .. } => "INLINE_WIKI_LINK_AUTO_STUBBED",
            Self::CrossMemTargetMemUncreated { .. } => "CROSS_MEM_TARGET_MEM_UNCREATED",
            Self::MissingRequiredSection { .. } => "MISSING_REQUIRED_SECTION",
            Self::MissingRequiredField { .. } => "MISSING_REQUIRED_FIELD",
            Self::UndeclaredRelationshipOpen { .. } => "UNDECLARED_RELATIONSHIP_OPEN",
            Self::DuplicateRelationship { .. } => "DUPLICATE_RELATIONSHIP",
            Self::NoSuchRelationship { .. } => "NO_SUCH_RELATIONSHIP",
            Self::UnknownIncludeKey { .. } => "UNKNOWN_INCLUDE_KEY",
            Self::LimitClamped { .. } => "LIMIT_CLAMPED",
            Self::TitleNormalizedToSlugNoop { .. } => "TITLE_NORMALIZED_TO_SLUG_NOOP",
            Self::TitleCharsDroppedFromSlug { .. } => "TITLE_CHARS_DROPPED_FROM_SLUG",
            Self::UpdateNoop { .. } => "UPDATE_NOOP",
            Self::StubFilterExcludesAll { .. } => "STUB_FILTER_EXCLUDES_ALL",
            // One code per outcome:
            // a key declared on some OTHER reachable type was applied
            // with strict type-narrowing (the filter took effect — it
            // restricts the result to the declaring type(s)), so it
            // carries a distinct code from a key no schema declares
            // (which is truly ignored). A consumer branches on `code`
            // alone to learn whether its filter took effect, without
            // inspecting `declared_on_other_types`.
            Self::UnknownFilterKey {
                declared_on_other_types,
                ..
            } => {
                if declared_on_other_types.is_empty() {
                    "UNKNOWN_FILTER_KEY"
                } else {
                    "FILTER_TYPE_SCOPED"
                }
            }
            Self::FieldNotFilterable { .. } => "FIELD_NOT_FILTERABLE",
            Self::FilterValueMultiMember { .. } => "FILTER_VALUE_MULTI_MEMBER",
            Self::FilterValueNotInEnum { .. } => "INVALID_ENUM_VALUE",
            Self::NeighbourhoodCapped { .. } => "NEIGHBOURHOOD_CAPPED",
            Self::SearchResultsTruncated { .. } => "SEARCH_RESULTS_TRUNCATED",
            Self::RangeFilterKeyMalformed { .. } => "RANGE_FILTER_KEY_MALFORMED",
            Self::UnknownRangeFilterField {
                declared_on_other_types,
                ..
            } => {
                if declared_on_other_types.is_empty() {
                    "UNKNOWN_RANGE_FILTER_FIELD"
                } else {
                    "RANGE_FILTER_TYPE_SCOPED"
                }
            }
            Self::FieldNotRangeFilterable { .. } => "FIELD_NOT_RANGE_FILTERABLE",
            Self::SearchMemIndexUnavailable { .. } => "SEARCH_MEM_INDEX_UNAVAILABLE",
            Self::TitleTrimmed { .. } => "TITLE_TRIMMED",
            Self::SuspiciousNestedPrefix { .. } => "SUSPICIOUS_NESTED_PREFIX",
            Self::NoteMissing { .. } => "NOTE_MISSING",
            Self::IgnoredReadonlyField { .. } => "IGNORED_READONLY_FIELD",
            Self::OuterRepoNotIgnoringMemRepo { .. } => "OUTER_REPO_NOT_IGNORING_MEM_REPO",
            Self::MissingRequiredOutgoing { .. } => "MISSING_REQUIRED_OUTGOING",
            Self::ConstraintUnsatisfied { .. } => "CONSTRAINT_UNSATISFIED",
            Self::DuplicateSectionHeading { .. } => "DUPLICATE_SECTION_HEADING",
            Self::MemReloaded { .. } => "MEM_RELOADED",
            Self::SchemaPinMismatch { .. } => "SCHEMA_PIN_MISMATCH",
            Self::EngineVersionSkew { .. } => "ENGINE_VERSION_SKEW",
            Self::SchemaGenerationsBehind { .. } => "SCHEMA_GENERATIONS_BEHIND",
            Self::SchemaHeadingRoundtripViolation { .. } => "SCHEMA_HEADING_ROUNDTRIP_VIOLATION",
            Self::SectionHeadingDivergence { .. } => "SECTION_HEADING_DIVERGENCE",
            Self::AutoStubCreated { .. } => "AUTO_STUB_CREATED",
            Self::DerivationBaselineRefreshed { .. } => "DERIVATION_BASELINE_REFRESHED",
            Self::SelfLinkIgnored { .. } => "SELF_LINK_IGNORED",
            Self::ParsedRelationInvalid { .. } => "PARSED_RELATION_INVALID",
            Self::ResidualStubForReadOnlyReferrers { .. } => "RESIDUAL_STUB_FOR_READONLY_REFERRERS",
            Self::MemFilesNotDeleted { .. } => "MEM_FILES_NOT_DELETED",
            Self::MemReattachedAfterUnregister { .. } => "MEM_REATTACHED_AFTER_UNREGISTER",
            Self::ReadMemsMigratedToMounts { .. } => "READ_MEMS_MIGRATED_TO_MOUNTS",
            Self::FolderMemProvenance { .. } => "FOLDER_MEM_PROVENANCE",
            Self::SchemaAuthoringSourceMissing { .. } => "SCHEMA_AUTHORING_SOURCE_MISSING",
            Self::SchemaAuthoringSourceDiverged { .. } => "SCHEMA_AUTHORING_SOURCE_DIVERGED",
            Self::AmbiguousDescriptionDelimiter { .. } => "AMBIGUOUS_DESCRIPTION_DELIMITER",
            Self::ParseMissingRequiredDescription { .. } => "MISSING_REQUIRED_DESCRIPTION",
            Self::ParseDescriptionNotPermitted { .. } => "DESCRIPTION_NOT_PERMITTED",
        }
    }

    /// Human-readable message — delegates to `Display`. May change across
    /// releases; use [`WarningHint::code`] for branching.
    pub fn message(&self) -> String {
        self.to_string()
    }

    /// Mem that "owns" the warning when one can be attributed.
    /// Workspace-/request-scoped variants return `None` — `memstead_health`'s
    /// mem filter keeps those visible regardless of scope, while
    /// mem-attributable variants drop out when the filter doesn't
    /// match. The contract mirrors the data fields the same filter
    /// gates (counts, distributions, detail lists are source-mem
    /// scoped; rosters stay global).
    pub fn source_mem(&self) -> Option<&str> {
        match self {
            Self::SuspiciousNestedPrefix { from, .. } => Some(from.mem()),
            Self::DuplicateSectionHeading { entity_id, .. } => Some(entity_id.mem()),
            Self::SchemaPinMismatch { mem, .. } => Some(mem.as_str()),
            Self::SchemaHeadingRoundtripViolation { mem, .. } => Some(mem.as_str()),
            Self::SectionHeadingDivergence { entity_id, .. } => Some(entity_id.mem()),
            Self::MemReloaded { mem, .. } => Some(mem.as_str()),
            Self::MemFilesNotDeleted { mem, .. } => Some(mem.as_str()),
            Self::MemReattachedAfterUnregister { mem, .. } => Some(mem.as_str()),
            Self::ReadMemsMigratedToMounts { .. } => None,
            Self::EngineVersionSkew { mem, .. } => Some(mem.as_str()),
            Self::SchemaGenerationsBehind { mem, .. } => Some(mem.as_str()),
            Self::FolderMemProvenance { mem } => Some(mem.as_str()),
            Self::MissingRequiredOutgoing { entity_id, .. } => Some(entity_id.mem()),
            Self::ConstraintUnsatisfied { entity_id, .. } => Some(entity_id.mem()),
            Self::DuplicateRelationship { from, .. } => Some(from.mem()),
            Self::NoSuchRelationship { from, .. } => Some(from.mem()),
            Self::InlineWikiLinkAutoStubbed { from, .. } => Some(from.mem()),
            Self::SelfLinkIgnored { id } => Some(id.mem()),
            Self::CrossMemTargetMemUncreated { from_mem, .. } => Some(from_mem.as_str()),
            Self::AutoStubCreated { stub_id, .. } => Some(stub_id.mem()),
            Self::DerivationBaselineRefreshed { from, .. } => Some(from.mem()),
            Self::UpdateNoop { id } => Some(id.mem()),
            Self::ParsedRelationInvalid { entity_id, .. } => Some(entity_id.mem()),
            Self::ResidualStubForReadOnlyReferrers { id, .. } => Some(id.mem()),
            Self::AmbiguousDescriptionDelimiter { from, .. } => Some(from.mem()),
            Self::ParseMissingRequiredDescription { from, .. } => Some(from.mem()),
            Self::ParseDescriptionNotPermitted { from, .. } => Some(from.mem()),
            // Search-mem-index unavailability is attributable to the
            // failing mem; the filter-key warnings are request-
            // derived (the agent's filter payload) and fall through
            // to `None` below to stay visible to the caller.
            Self::SearchMemIndexUnavailable { mem, .. } => Some(mem.as_str()),
            // Workspace- or request-scoped — no mem to attribute.
            // OuterRepoNotIgnoringMemRepo concerns the embedding repo,
            // not a specific mem; an agent should see it under any
            // filter. UnknownIncludeKey / LimitClamped / NoteMissing /
            // TitleNormalizedToSlugNoop / StubFilterExcludesAll /
            // UndeclaredRelationshipOpen / MissingRequiredSection /
            // MissingRequiredField are request-derived (mutation
            // payload or schema-level), so the mem is the
            // request's mem — `None` here keeps them visible to
            // the caller that triggered them.
            _ => None,
        }
    }

    /// One representative of every `WarningHint` variant — the single
    /// source of truth consumed by stability tests (`envelope_*`,
    /// `code_values_are_upper_snake_case`) and by the MCP description
    /// drift-guard (`every_warning_code_appears_in_a_description`).
    /// Adding a new variant without extending this list fails those tests;
    /// that's the forcing function.
    pub fn all_samples() -> Vec<WarningHint> {
        vec![
            WarningHint::EngineVersionSkew {
                mem: "m".into(),
                stamped_engine: "0.3.0".into(),
                running_engine: "0.4.0".into(),
                stamped_schema: "default@1.0.0".into(),
            },
            WarningHint::SchemaGenerationsBehind {
                mem: "m".into(),
                pinned: "default@1.0.0".into(),
                newest: "1.2.0".into(),
            },
            WarningHint::MissingRequiredSection {
                entity_type: "t".into(),
                key: "k".into(),
                heading: "H".into(),
                write_rules: vec![],
            },
            WarningHint::MissingRequiredField {
                entity_type: "decision".into(),
                key: "decided_on".into(),
                description: "Date the decision was accepted.".into(),
                enum_values: vec![],
            },
            WarningHint::UndeclaredRelationshipOpen {
                rel_type: "X".into(),
                message: "m".into(),
            },
            WarningHint::DuplicateRelationship {
                rel_type: "X".into(),
                from: EntityId("a".into()),
                to: EntityId("b".into()),
            },
            WarningHint::NoSuchRelationship {
                rel_type: "X".into(),
                from: EntityId("a".into()),
                to: EntityId("b".into()),
            },
            WarningHint::UnknownIncludeKey {
                key: "x".into(),
                allowed: vec![],
            },
            WarningHint::LimitClamped {
                requested: 1,
                actual: 1,
            },
            WarningHint::SearchResultsTruncated {
                kept: 12,
                budget: 12_000,
            },
            WarningHint::TitleNormalizedToSlugNoop {
                requested_title: "Hello World!".into(),
                current_slug: "hello-world".into(),
            },
            WarningHint::TitleCharsDroppedFromSlug {
                title: "Acme Inc. & Co".into(),
                dropped_chars: vec!['.', '&'],
                slug: "acme-inc-co".into(),
            },
            WarningHint::UpdateNoop {
                id: EntityId("specs--example".into()),
            },
            WarningHint::StubFilterExcludesAll {
                entity_type: "spec".into(),
            },
            // Non-empty `declared_on_other_types` → code FILTER_TYPE_SCOPED.
            WarningHint::UnknownFilterKey {
                key: "nonexistent_field".into(),
                scoped_type: Some("spec".into()),
                declared_on_other_types: vec!["decision".into()],
            },
            // Empty `declared_on_other_types` → code UNKNOWN_FILTER_KEY.
            WarningHint::UnknownFilterKey {
                key: "stauts".into(),
                scoped_type: None,
                declared_on_other_types: vec![],
            },
            WarningHint::FieldNotFilterable {
                field: "title".into(),
            },
            WarningHint::RangeFilterKeyMalformed {
                key: "weird_key".into(),
            },
            // Empty `declared_on_other_types` → code UNKNOWN_RANGE_FILTER_FIELD.
            WarningHint::UnknownRangeFilterField {
                field: "count".into(),
                key: "min_count".into(),
                scoped_type: None,
                declared_on_other_types: vec![],
            },
            // Non-empty → code RANGE_FILTER_TYPE_SCOPED.
            WarningHint::UnknownRangeFilterField {
                field: "priority".into(),
                key: "min_priority".into(),
                scoped_type: Some("spec".into()),
                declared_on_other_types: vec!["decision".into()],
            },
            WarningHint::FieldNotRangeFilterable {
                field: "tags".into(),
            },
            WarningHint::SearchMemIndexUnavailable {
                mem: "specs".into(),
                reason: "missing_index",
                error: None,
            },
            WarningHint::SuspiciousNestedPrefix {
                from: EntityId("test-mem-plugin--audit-skill".into()),
                resolved_id: EntityId("test-mem-plugin--plugin--memstead-mcp-tool-surface".into()),
                candidate_target: Some(EntityId(
                    "test-mem-plugin--memstead-mcp-tool-surface".into(),
                )),
                section: "constraints".into(),
            },
            WarningHint::InlineWikiLinkAutoStubbed {
                from: EntityId("specs--demo".into()),
                stubs: vec![EntityId("specs--example-target".into())],
            },
            WarningHint::CrossMemTargetMemUncreated {
                from_mem: "specs".into(),
                to_mem: "memos".into(),
                target_id: EntityId("memos--example".into()),
            },
            WarningHint::NoteMissing {
                tool: "memstead_update".into(),
            },
            WarningHint::OuterRepoNotIgnoringMemRepo {
                outer_repo_root: "/repos/demo".into(),
                workspace_root: "/repos/demo/memstead".into(),
            },
            WarningHint::MissingRequiredOutgoing {
                entity_type: "decision".into(),
                entity_id: EntityId("planning--decision-x".into()),
                missing: vec![
                    MissingRequiredOutgoingBlock {
                        relationships: vec!["CHOSEN".into()],
                        cardinality: "at_least_one".into(),
                        severity: memstead_schema::ConstraintSeverity::Warn,
                    },
                    MissingRequiredOutgoingBlock {
                        relationships: vec!["REJECTED".into()],
                        cardinality: "at_least_one".into(),
                        severity: memstead_schema::ConstraintSeverity::Warn,
                    },
                ],
            },
            WarningHint::DuplicateSectionHeading {
                entity_id: EntityId("plugin--hooks-subsystem".into()),
                section_key: "realization".into(),
                heading: "Realization".into(),
                occurrences: 3,
            },
            WarningHint::MemReloaded {
                mem: "test-mem-plugin".into(),
                old_head: "abc123".into(),
                new_head: "def456".into(),
                entities_loaded: 42,
            },
            WarningHint::AutoStubCreated {
                stub_id: EntityId("specs--future-target".into()),
                pending: false,
            },
            WarningHint::ParsedRelationInvalid {
                entity_id: EntityId("specs--example-source".into()),
                rel_type: "EXECUTES".into(),
                target: EntityId("specs--example-target".into()),
                reason: "shape".into(),
                origin: "writable".into(),
                recovery: Some(ParsedRelationRecovery::remove_explicit_relation(
                    EntityId("specs--example-source".into()),
                    EntityId("specs--example-target".into()),
                    "EXECUTES".into(),
                )),
            },
            WarningHint::ResidualStubForReadOnlyReferrers {
                id: EntityId("specs--archived-target".into()),
                referrers: vec![EntityId("archive--archived-source".into())],
            },
            WarningHint::MemFilesNotDeleted {
                mem: "plan-example".into(),
                reason: "backend_prune_failed".into(),
                path: None,
                error: Some("ref-edit transaction rejected".into()),
            },
            WarningHint::MemReattachedAfterUnregister {
                mem: "plan-example".into(),
                unregistered_at: "2026-05-17T08:43:29Z".into(),
            },
            WarningHint::FolderMemProvenance {
                mem: "plan-example".into(),
            },
            WarningHint::SchemaAuthoringSourceMissing {
                schema_ref: "authored@0.1.0".into(),
                stamped_path: "/workspace/authored".into(),
                mems: vec!["specs".into()],
            },
            WarningHint::SchemaAuthoringSourceDiverged {
                schema_ref: "authored@0.1.0".into(),
                stamped_path: "/workspace/authored".into(),
                mems: vec!["specs".into()],
                detail: "the parsed authoring package differs from the sealed copy".into(),
            },
            WarningHint::AmbiguousDescriptionDelimiter {
                from: EntityId("specs--example-source".into()),
                rel_type: "OTHER".into(),
                target: EntityId("specs--example-target".into()),
                trailing: " -- legacy delimiter".into(),
            },
            WarningHint::ParseMissingRequiredDescription {
                from: EntityId("specs--example-source".into()),
                rel_type: "OTHER".into(),
                target: EntityId("specs--example-target".into()),
            },
            WarningHint::ParseDescriptionNotPermitted {
                from: EntityId("specs--example-source".into()),
                rel_type: "IMPLEMENTS".into(),
                target: EntityId("specs--example-target".into()),
            },
        ]
    }

    fn details_payload(&self) -> serde_json::Value {
        match self {
            Self::MissingRequiredSection {
                entity_type,
                key,
                heading,
                write_rules,
            } => serde_json::json!({
                "entity_type": entity_type,
                "key": key,
                "heading": heading,
                "write_rules": write_rules,
            }),
            Self::MissingRequiredField {
                entity_type,
                key,
                description,
                enum_values,
            } => serde_json::json!({
                "entity_type": entity_type,
                "key": key,
                "field_description": description,
                "enum_values": enum_values,
            }),
            Self::UndeclaredRelationshipOpen { rel_type, .. } => {
                serde_json::json!({ "rel_type": rel_type })
            }
            Self::DuplicateRelationship { rel_type, from, to } => {
                serde_json::json!({ "rel_type": rel_type, "from": from, "to": to })
            }
            Self::NoSuchRelationship { rel_type, from, to } => {
                serde_json::json!({ "rel_type": rel_type, "from": from, "to": to })
            }
            Self::UnknownIncludeKey { key, allowed } => {
                serde_json::json!({ "key": key, "allowed": allowed })
            }
            Self::LimitClamped { requested, actual } => {
                serde_json::json!({ "requested": requested, "actual": actual })
            }
            Self::TitleNormalizedToSlugNoop {
                requested_title,
                current_slug,
            } => serde_json::json!({
                "requested_title": requested_title,
                "current_slug": current_slug,
            }),
            Self::TitleCharsDroppedFromSlug {
                title,
                dropped_chars,
                slug,
            } => serde_json::json!({
                "title": title,
                "dropped_chars": dropped_chars,
                "slug": slug,
            }),
            Self::UpdateNoop { id } => serde_json::json!({ "id": id }),
            Self::StubFilterExcludesAll { entity_type } => {
                serde_json::json!({ "entity_type": entity_type })
            }
            Self::UnknownFilterKey {
                key,
                scoped_type,
                declared_on_other_types,
            } => serde_json::json!({
                "key": key,
                "scoped_type": scoped_type,
                "declared_on_other_types": declared_on_other_types,
            }),
            Self::FieldNotFilterable { field } => serde_json::json!({ "field": field }),
            Self::FilterValueMultiMember { key, value } => {
                serde_json::json!({ "key": key, "value": value })
            }
            Self::FilterValueNotInEnum {
                key,
                value,
                allowed,
            } => {
                serde_json::json!({ "key": key, "value": value, "allowed": allowed })
            }
            Self::NeighbourhoodCapped { kept, total } => {
                serde_json::json!({ "kept": kept, "total": total })
            }
            Self::SearchResultsTruncated { kept, budget } => {
                serde_json::json!({ "kept": kept, "budget": budget })
            }
            Self::RangeFilterKeyMalformed { key } => serde_json::json!({ "key": key }),
            Self::UnknownRangeFilterField {
                field,
                key,
                scoped_type,
                declared_on_other_types,
            } => serde_json::json!({
                "field": field,
                "key": key,
                "scoped_type": scoped_type,
                "declared_on_other_types": declared_on_other_types,
            }),
            Self::FieldNotRangeFilterable { field } => serde_json::json!({ "field": field }),
            Self::SearchMemIndexUnavailable { mem, reason, error } => serde_json::json!({
                "mem": mem,
                "reason": reason,
                "error": error,
            }),
            Self::TitleTrimmed { original, trimmed } => serde_json::json!({
                "original": original,
                "trimmed": trimmed,
            }),
            Self::SuspiciousNestedPrefix {
                from,
                resolved_id,
                candidate_target,
                section,
            } => serde_json::json!({
                "from": from,
                "resolved_id": resolved_id,
                "candidate_target": candidate_target,
                "section": section,
            }),
            Self::InlineWikiLinkAutoStubbed { from, stubs } => serde_json::json!({
                "from": from,
                "stubs": stubs,
            }),
            Self::SelfLinkIgnored { id } => serde_json::json!({ "id": id }),
            Self::CrossMemTargetMemUncreated {
                from_mem,
                to_mem,
                target_id,
            } => serde_json::json!({
                "from_mem": from_mem,
                "to_mem": to_mem,
                "target_id": target_id,
            }),
            Self::NoteMissing { tool } => serde_json::json!({ "tool": tool }),
            Self::IgnoredReadonlyField { field, supplied } => {
                serde_json::json!({ "field": field, "supplied": supplied })
            }
            Self::OuterRepoNotIgnoringMemRepo {
                outer_repo_root,
                workspace_root,
            } => serde_json::json!({
                "outer_repo_root": outer_repo_root,
                "workspace_root": workspace_root,
            }),
            Self::MissingRequiredOutgoing {
                entity_type,
                entity_id,
                missing,
            } => serde_json::json!({
                "entity_type": entity_type,
                "entity_id": entity_id,
                "missing": missing,
            }),
            Self::ConstraintUnsatisfied {
                entity_type,
                entity_id,
                violations,
            } => serde_json::json!({
                "entity_type": entity_type,
                "entity_id": entity_id,
                "violations": violations,
            }),
            Self::DuplicateSectionHeading {
                entity_id,
                section_key,
                heading,
                occurrences,
            } => serde_json::json!({
                "entity_id": entity_id,
                "section_key": section_key,
                "heading": heading,
                "occurrences": occurrences,
            }),
            Self::MemReloaded {
                mem,
                old_head,
                new_head,
                entities_loaded,
            } => serde_json::json!({
                "mem": mem,
                "old_head": old_head,
                "new_head": new_head,
                "entities_loaded": entities_loaded,
            }),
            Self::AutoStubCreated { stub_id, .. } => serde_json::json!({ "stub_id": stub_id }),
            Self::DerivationBaselineRefreshed { from, rel_type, to } => serde_json::json!({
                "from": from,
                "rel_type": rel_type,
                "to": to,
            }),
            Self::ParsedRelationInvalid {
                entity_id,
                rel_type,
                target,
                reason,
                origin,
                recovery,
            } => {
                serde_json::json!({
                    "entity_id": entity_id,
                    "rel_type": rel_type,
                    "target": target,
                    "reason": reason,
                    "origin": origin,
                    "recovery": recovery,
                })
            }
            Self::ResidualStubForReadOnlyReferrers { id, referrers } => serde_json::json!({
                "id": id,
                "referrers": referrers,
            }),
            Self::MemFilesNotDeleted {
                mem,
                reason,
                path,
                error,
            } => serde_json::json!({
                "mem": mem,
                "reason": reason,
                "path": path,
                "error": error,
            }),
            Self::MemReattachedAfterUnregister {
                mem,
                unregistered_at,
            } => serde_json::json!({
                "mem": mem,
                "unregistered_at": unregistered_at,
            }),
            Self::EngineVersionSkew {
                mem,
                stamped_engine,
                running_engine,
                stamped_schema,
            } => {
                serde_json::json!({
                    "mem": mem,
                    "stamped_engine": stamped_engine,
                    "running_engine": running_engine,
                    "stamped_schema": stamped_schema,
                })
            }
            Self::SchemaGenerationsBehind {
                mem,
                pinned,
                newest,
            } => serde_json::json!({
                "mem": mem,
                "pinned": pinned,
                "newest": newest,
            }),
            Self::ReadMemsMigratedToMounts {
                mems,
                from_host_mems,
            } => serde_json::json!({
                "mems": mems,
                "from_host_mems": from_host_mems,
            }),
            Self::FolderMemProvenance { mem } => serde_json::json!({
                "mem": mem,
                "ledger": ".memstead/changelog.jsonl",
                "commit_sha": "synthetic placeholder (no version control)",
                "durability": "content persists only when the surrounding repository commits it",
            }),
            Self::SchemaAuthoringSourceMissing {
                schema_ref,
                stamped_path,
                mems,
            } => serde_json::json!({
                "schema_ref": schema_ref,
                "stamped_path": stamped_path,
                "mems": mems,
            }),
            Self::SchemaAuthoringSourceDiverged {
                schema_ref,
                stamped_path,
                mems,
                detail,
            } => serde_json::json!({
                "schema_ref": schema_ref,
                "stamped_path": stamped_path,
                "mems": mems,
                "detail": detail,
            }),
            Self::AmbiguousDescriptionDelimiter {
                from,
                rel_type,
                target,
                trailing,
            } => serde_json::json!({
                "from": from,
                "rel_type": rel_type,
                "target": target,
                "trailing": trailing,
            }),
            Self::ParseMissingRequiredDescription {
                from,
                rel_type,
                target,
            } => {
                serde_json::json!({ "from": from, "rel_type": rel_type, "target": target })
            }
            Self::ParseDescriptionNotPermitted {
                from,
                rel_type,
                target,
            } => {
                serde_json::json!({ "from": from, "rel_type": rel_type, "target": target })
            }
            Self::SchemaPinMismatch {
                mem,
                config_pin,
                mount_pin,
            } => {
                serde_json::json!({
                    "mem": mem,
                    "config_pin": config_pin,
                    "mount_pin": mount_pin,
                })
            }
            Self::SchemaHeadingRoundtripViolation {
                mem,
                schema_ref,
                violations,
            } => {
                serde_json::json!({
                    "mem": mem,
                    "schema_ref": schema_ref,
                    "violations": violations,
                })
            }
            Self::SectionHeadingDivergence {
                entity_id,
                section_key,
                writing_heading,
                existing_heading,
            } => {
                serde_json::json!({
                    "entity_id": entity_id,
                    "section_key": section_key,
                    "writing_heading": writing_heading,
                    "existing_heading": existing_heading,
                })
            }
        }
    }
}

impl Serialize for WarningHint {
    fn serialize<S: Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
        // Direct struct emission — avoids the intermediate `Value` allocation
        // `envelope(...).serialize(serializer)` would incur. Wire shape is
        // bit-identical to `envelope(...)`'s output; DRY lives at the
        // constructor level via the shared `envelope` helper used by the MCP
        // error path (`engine_err_with_suggestions`).
        let details = self.details_payload();
        let mut state = serializer.serialize_struct("WarningHint", 3)?;
        state.serialize_field("code", self.code())?;
        state.serialize_field("message", &self.message())?;
        state.serialize_field("details", &details)?;
        state.end()
    }
}

/// Build the uniform `{ code, message, details }` envelope used on both the
/// warning wire (`WarningHint`'s custom `Serialize`) and the MCP error wire
/// (`tool_error_with_payload` payloads in `engine_err_with_suggestions`).
/// Agents and other decoders branch on `code` (UPPER_SNAKE_CASE, stable)
/// and parse `details` by `code` when they need structured fields.
pub fn envelope(
    code: &str,
    message: impl Into<String>,
    details: serde_json::Value,
) -> serde_json::Value {
    serde_json::json!({
        "code": code,
        "message": message.into(),
        "details": details,
    })
}

/// Result of a create operation.
#[derive(Debug, Clone, Serialize)]
pub struct CreateResult {
    pub id: EntityId,
    pub title: String,
    pub mem: String,
    pub file_path: String,
    pub created_date: String,
    /// Post-write content hash under the real path; the **prospective**
    /// hash under `dry_run` — bit-identical to what a real call with the
    /// same inputs would produce. Wire key `_hash`.
    #[serde(rename = "_hash")]
    pub content_hash: String,
    /// Per-mem commit SHA — see `UpdateResult::commit_sha`. Empty under
    /// `dry_run`.
    #[serde(default)]
    pub commit_sha: String,
    /// Typed non-fatal issues — missing required sections (with writing
    /// guidance) and open-mode relationship admissions.
    #[serde(default, skip_serializing_if = "Vec::is_empty")]
    pub warnings: Vec<WarningHint>,
    /// Type-level `write_rules` keyed by `entity_type` — the
    /// MISSING_REQUIRED_SECTION / MISSING_REQUIRED_FIELD warnings on
    /// `warnings[]` reference this top-level map via their
    /// `entity_type` field rather than each carrying the (identical,
    /// type-axis) array (F9). Stable empty shape (`{}`) ships when no
    /// such warnings fire — consumers don't branch on field presence.
    #[serde(default)]
    pub type_guidance: std::collections::BTreeMap<String, Vec<String>>,
    /// Number of incoming edges adopted from a pre-existing stub at this
    /// id (real path) or that would be adopted (dry_run). `None` means
    /// no pre-existing stub / no incoming refs — field is serde-omitted.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub incoming_count: Option<usize>,
    /// Incoming edges present at this id at create time. Real path:
    /// edges preserved during stub adoption. Dry_run: edges that would
    /// be adopted if committed. Sorted by (rel_type, from) for
    /// determinism. Empty vec is serde-omitted.
    #[serde(default, skip_serializing_if = "Vec::is_empty")]
    pub incoming: Vec<IncomingRef>,
}

/// Serialisable projection of `store::InEdge` for `CreateResult.incoming`.
/// `source` is the lowercase `EdgeSource` variant:
/// `"explicit" | "hierarchy" | "body_link"`.
#[derive(Debug, Clone, Serialize)]
pub struct IncomingRef {
    pub from: EntityId,
    pub rel_type: String,
    pub source: String,
}

/// Project `&[store::InEdge]` into a sorted `Vec<IncomingRef>`. Ordering
/// by (rel_type, from) ascending — deterministic output despite the
/// underlying HashMap iteration order.
pub fn project_incoming(edges: &[crate::store::InEdge]) -> Vec<IncomingRef> {
    let mut out: Vec<IncomingRef> = edges
        .iter()
        .map(|e| IncomingRef {
            from: e.from.clone(),
            rel_type: e.rel_type.clone(),
            source: match e.source {
                crate::store::EdgeSource::Explicit => "explicit",
                crate::store::EdgeSource::Hierarchy => "hierarchy",
                crate::store::EdgeSource::BodyLink => "body_link",
            }
            .to_string(),
        })
        .collect();
    out.sort_by(|a, b| a.rel_type.cmp(&b.rel_type).then(a.from.0.cmp(&b.from.0)));
    out
}

/// Result of a delete operation.
#[derive(Debug, Clone, Serialize)]
pub struct DeleteResult {
    pub id: EntityId,
    pub relations_removed: usize,
    /// Per-mem commit SHA — see `UpdateResult::commit_sha`.
    #[serde(default)]
    pub commit_sha: String,
    /// Stub entities that became orphaned by this delete (their last
    /// incoming edge disappeared with this entity) and were garbage-
    /// collected. Empty vec is serde-omitted.
    #[serde(default, skip_serializing_if = "Vec::is_empty")]
    pub orphan_stubs_removed: Vec<EntityId>,
}

/// Result of a rename operation.
#[derive(Debug, Clone, Serialize)]
pub struct RenameResult {
    pub old_id: EntityId,
    pub new_id: EntityId,
    pub old_path: String,
    pub new_path: String,
    /// Content hash of the renamed entity after the write. Sources by branch:
    ///   - Real rename (slug change): post-write hash from the re-parsed
    ///     entity, including the `modified_date` bump applied by
    ///     `rename_entity` and any wiki-link rewrites in referrers.
    ///   - Slug-noop short-circuit: the unchanged on-disk hash (no write
    ///     happened).
    ///
    /// Pass this as `expected_hash` on the next hash-protected op
    /// (`memstead_update`, `memstead_rename`, `memstead_delete`) on the entity — no
    /// `memstead_entity` re-read required. Mirrors `RelateResult._hash`.
    /// Wire key `_hash`.
    #[serde(default, rename = "_hash", skip_serializing_if = "String::is_empty")]
    pub content_hash: String,
    /// Per-mem commit SHA — see `UpdateResult::commit_sha`. Empty on the
    /// no-op same-title rename (no file change, no commit).
    #[serde(default)]
    pub commit_sha: String,
    /// Typed non-fatal issues. The slug-noop short-circuit
    /// (`TitleNormalizedToSlugNoop`) surfaces here when a requested title
    /// normalises to the existing slug — the op stays a silent no-op on
    /// disk, but the warning tells autonomous skills not to trust
    /// `old_id == new_id` as "cosmetic rewrite landed".
    #[serde(default, skip_serializing_if = "Vec::is_empty")]
    pub warnings: Vec<WarningHint>,
}

/// Arguments for a relate/unrelate operation.
#[derive(Debug, Clone)]
pub struct RelateArg {
    pub to: EntityId,
    pub rel_type: String,
    /// Optional per-edge description text. Validated against the
    /// rel-type's `per_edge_description` posture at call time —
    /// `forbidden` rejects `Some`; `required` rejects `None`.
    /// Empty / whitespace-only strings normalise to `None` before
    /// validation.
    pub description: Option<String>,
}

/// One repair-shaped relation removal on `memstead_update` —
/// `relations_unset: [{ rel_type, target }]`. Symmetric with
/// `metadata_unset`: an absent `(rel_type, target)` pair is a silent
/// no-op. Only accepted when the target entity currently fails the
/// conformance check (`REPAIR_NOT_NEEDED` otherwise) — the everyday
/// detach path stays `memstead_relate(remove)`.
#[derive(Debug, Clone, serde::Deserialize)]
pub struct RelationUnsetArg {
    pub rel_type: String,
    pub target: EntityId,
}

/// Result of a relate operation.
#[derive(Debug, Clone, Serialize)]
pub struct RelateResult {
    pub from: EntityId,
    pub to: EntityId,
    pub rel_type: String,
    pub source: String,
    /// Content hash of the source entity after the relate. On successful
    /// add/remove, reflects the re-rendered file (Relationships section
    /// updated); on duplicate-add and remove-nonexistent no-ops, reflects
    /// the unchanged file. Pass this as `expected_hash` on the next
    /// hash-protected op (`memstead_update`, `memstead_rename`, `memstead_delete`) on
    /// the source — no `memstead_entity` re-read required. Wire key `_hash`.
    #[serde(default, rename = "_hash", skip_serializing_if = "String::is_empty")]
    pub content_hash: String,
    /// Per-mem commit SHA — see `UpdateResult::commit_sha`.
    #[serde(default)]
    pub commit_sha: String,
    /// Typed non-fatal issues — open-mode schema admissions, duplicate-add
    /// no-ops (`DuplicateRelationship`), remove-nonexistent no-ops
    /// (`NoSuchRelationship`). Previously silent edge cases now surface here.
    #[serde(default, skip_serializing_if = "Vec::is_empty")]
    pub warnings: Vec<WarningHint>,
    /// True if the op wrote to disk (real add or real remove). False on
    /// duplicate-add and remove-nonexistent-edge. Internal signal — the
    /// wrapper gates reindex + vcs_commit on this; the MCP wire relies on
    /// `commit_sha.is_empty()` as the external no-op indicator.
    #[serde(skip)]
    pub disk_changed: bool,
    /// Stub entities that became orphaned by an edge removal (their last
    /// incoming edge was this one) and were garbage-collected. Only
    /// populated on `remove: true` calls where the edge actually existed;
    /// empty on add paths and no-op removes. Empty vec is serde-omitted.
    #[serde(default, skip_serializing_if = "Vec::is_empty")]
    pub orphan_stubs_removed: Vec<EntityId>,
}

fn is_zero(n: &usize) -> bool {
    *n == 0
}

/// Result of an **atomic** batch update — all-or-nothing.
///
/// A batch either applies in full as a single commit (`applied: true`)
/// or, if any item fails (validation, hash mismatch, missing entity),
/// applies *nothing* and refuses (`applied: false`) with the offending
/// item named. There is no partial-application middle state: a refused
/// batch leaves the on-disk mem and the in-memory store byte-identical
/// to the pre-call state.
#[derive(Debug, Clone, Serialize)]
pub struct BatchResult {
    /// `true` when every item applied (one commit); `false` when the
    /// batch was refused (a single item failed → nothing committed).
    pub applied: bool,
    /// One entry per submitted item, in submission order. On an applied
    /// batch every entry's `action` is `"updated"` (a real write) or
    /// `"noop"` (content unchanged). On a refused batch the failing
    /// item's `action` is `"error"` with a populated `error` envelope,
    /// and every other item's `action` is `"not_applied"`.
    pub results: Vec<BatchEntry>,
    /// Count of applied items when `applied`; `0` when refused.
    pub succeeded: usize,
    /// Number of FAILING entries whose error envelopes were suppressed
    /// beyond the reporting cap (bounded reporting for very large
    /// failing batches — the entries still carry `action: "error"`,
    /// only the detailed envelope is omitted). `0` when every failure
    /// is fully reported.
    #[serde(default, skip_serializing_if = "is_zero")]
    pub errors_suppressed: usize,
    /// Count of failed items when refused (≥1); `0` when applied.
    pub failed: usize,
    /// Ids of stub entities GC'd because a removed edge in this batch
    /// was their last incoming reference — the batch sibling of the
    /// single relate response's `orphan_stubs_removed`. Empty (and
    /// serde-omitted) for batch-create / batch-update and for batches
    /// that removed nothing.
    #[serde(default, skip_serializing_if = "Vec::is_empty")]
    pub orphan_stubs_removed: Vec<EntityId>,
    /// The single batch commit SHA when the batch applied and produced
    /// at least one write — an honest `memstead_changes_since` cursor /
    /// revert handle for the whole batch. Empty when the batch was
    /// refused, when it was empty, or when every item was a no-op (no
    /// commit happens). For a batch spanning multiple mems this names
    /// the last mem committed; single-mem batches (the common case)
    /// name their one commit.
    #[serde(default)]
    pub commit_sha: String,
}

#[derive(Debug, Clone, Serialize)]
pub struct BatchEntry {
    pub id: EntityId,
    pub action: String,
    /// Structured error envelope when this entry failed. Mirrors the
    /// `{code, message, details}` shape single-update errors carry on
    /// the wire so a mixed-success batch is structurally uniform —
    /// consumers branch on `code` rather than prose-parsing a string.
    /// Empty (`None`) for successful entries.
    pub error: Option<BatchError>,
}

/// Per-item error envelope on a batch result. The shape matches the
/// MCP wire envelope for single-entry failures: `code` is the stable
/// `UPPER_SNAKE_CASE` token from [`crate::EngineError::code()`];
/// `details` carries the variant-specific recovery payload (e.g.
/// declared list, allowed enum values, hash-mismatch current) when
/// available, or an empty object for variants without a structured
/// payload.
#[derive(Debug, Clone, Serialize)]
pub struct BatchError {
    pub code: String,
    pub message: String,
    pub details: serde_json::Value,
}

// ---------------------------------------------------------------------------
// Search types
// ---------------------------------------------------------------------------

/// Flat query shape for full-text search. Four optional fields, all
/// combined with implicit AND across fields.
///
/// Within `any`: at least one term must match (OR semantics). Entities
/// matching more terms rank higher automatically — no explicit `and`.
/// Within `not`: none of the listed terms may appear. `phrase` requires
/// exact adjacency (case- and diacritic-folded). `field` narrows the match
/// region for all three to a single indexed field; `None` = match anywhere
/// indexed.
///
/// Empty/unset everywhere ⇒ no text predicate; `search` behaves as a
/// metadata-only filter (subsumes the former `list` semantics).
///
/// No stemming, wildcards, or regex — the caller expands morphology and
/// synonyms by enumerating variants in `any`.
#[derive(Debug, Clone, Default, Serialize, Deserialize, JsonSchema)]
pub struct Query {
    /// Terms where at least one must match (OR semantics).
    #[serde(default, skip_serializing_if = "Vec::is_empty")]
    pub any: Vec<String>,
    /// Terms that must not match (exclusion).
    #[serde(default, skip_serializing_if = "Vec::is_empty")]
    pub not: Vec<String>,
    /// Exact phrase that must appear (case- and diacritic-folded).
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub phrase: Option<String>,
    /// Restrict `any` / `not` / `phrase` to a single field (title or section
    /// key). `None` = match anywhere indexed.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub field: Option<String>,
}

impl Query {
    /// True if no text predicate is set — caller falls back to the
    /// metadata-only filter path.
    pub fn is_empty(&self) -> bool {
        self.any.is_empty() && self.not.is_empty() && self.phrase.is_none()
    }
}

/// Scope filters for search and list operations.
#[derive(Debug, Clone, Default)]
pub struct SearchScope {
    /// Structured flat query. All text matching flows through this field;
    /// see [`Query`] for semantics. `None` (or an empty query) makes
    /// `search` behave as a metadata-only filter.
    pub query: Option<Query>,
    pub mem: Option<String>,
    pub entity_type: Option<String>,
    pub limit: Option<usize>,
    pub offset: Option<usize>,
    /// Equality filters on metadata fields: `{ "level": "M0" }`.
    pub filters: HashMap<String, String>,
    /// Range filters: `{ "min_coverage": "0.5", "max_coverage": "1.0" }`.
    pub range_filters: HashMap<String, String>,
    /// Only entities with this edge type (incoming or outgoing).
    pub edge_type: Option<String>,
    /// Only entities reachable from this entity within `depth` hops.
    pub related_to: Option<EntityId>,
    pub depth: Option<usize>,
    /// Relationship types to follow from primary hits to pull in graph-proximal
    /// neighbours.
    pub expand_via: Option<Vec<String>>,
    /// Maximum hops to traverse via `expand_via` (default: 1 when `expand_via`
    /// is set).
    pub expand_depth: Option<usize>,
    /// Traversal direction for `related_to` AND `expand_via`, applied at
    /// EVERY hop (depth > 1 is a pure transitive closure in the chosen
    /// direction, never a mixed walk). Defaults to `both` — the
    /// historical undirected behaviour, so a query omitting the
    /// selector returns exactly what it always returned.
    pub direction: crate::graph::query::TraversalDirection,
    /// Filter by stub status. `None` = no filter (returns both stubs and real
    /// entities); `Some(true)` = only stubs; `Some(false)` = only real entities.
    pub stub: Option<bool>,
    /// Token budget bounding the returned hit payload (search path only).
    /// `None` uses the engine default. A page whose hits exceed the budget is
    /// greedily trimmed (at least one hit always returns) with a
    /// `SEARCH_RESULTS_TRUNCATED` warning; `total` still reflects the full
    /// match count so the agent can page with `offset`.
    pub token_budget: Option<usize>,
}

/// Per-hit score components surfaced so agents can understand ranking.
///
/// Note: this is illustrative feedback, not a numerically authoritative
/// decomposition — tantivy's `Explanation` for `BoostQuery` over
/// `BooleanQuery` does not always sum cleanly. Agents should treat these
/// as proportions, not exact sums.
#[derive(Debug, Clone, Serialize, JsonSchema)]
pub struct ScoreBreakdown {
    pub bm25: f32,
    pub title_boost: f32,
    pub field_weights: HashMap<String, f32>,
    /// `Some(f32)` on expanded hits only, carrying the depth-based decay
    /// factor (`0.5.powi(depth)`). `None` on primary hits.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub expansion_decay: Option<f32>,
}

/// One snippet-level match recorded per (term, field). `heading_path` is
/// `Some` when the match falls under an H3–H6 sub-heading; elements are
/// ordered outermost → innermost.
#[derive(Debug, Clone, Serialize, JsonSchema)]
pub struct TermMatch {
    pub field: String,
    pub snippet: String,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub heading_path: Option<Vec<String>>,
}

/// Metadata attached to hits reached via graph expansion. The
/// primary hit that seeded the expansion is identified by `of`; `via_edge`
/// is the exact `rel_type` string; `depth` counts hops from the seed.
#[derive(Debug, Clone, Serialize, JsonSchema)]
pub struct ExpansionInfo {
    pub of: EntityId,
    pub via_edge: String,
    pub depth: usize,
    /// The direction the first-reaching edge was traversed in (`out` =
    /// away from the seed, `in` = at the seed) — keeps a `both` result
    /// interpretable. Additive: clients that ignore it decode unchanged.
    pub via_direction: crate::graph::query::TraversalDirection,
}

/// One sub-section-level facet entry. `path` is ordered outermost →
/// innermost, prefixed with the H2 section key (e.g. `["specifies",
/// "Response Shapes", "Markdown Output"]`). Structured vector (not a
/// delimiter-joined string) so headings containing punctuation don't break
/// the key.
#[derive(Debug, Clone, Serialize, JsonSchema)]
pub struct SubsectionFacet {
    pub path: Vec<String>,
    pub count: usize,
}

/// Fixed set of facet dimensions computed over the unpaginated hit set.
/// Tier 1 freezes the dimensions; extend later only if empirical use
/// demands it. Zero-count entries are excluded to keep the payload small.
#[derive(Debug, Clone, Default, Serialize, JsonSchema)]
pub struct Facets {
    pub by_type: HashMap<String, usize>,
    pub by_mem: HashMap<String, usize>,
    pub by_level: HashMap<String, usize>,
    pub by_status: HashMap<String, usize>,
    pub by_confidence: HashMap<String, usize>,
    pub by_subsection: Vec<SubsectionFacet>,
    /// `"primary"` / `"expanded"` — counts of primary vs. graph-expanded
    /// hits. Always present; `expanded` is `0` when no expansion ran.
    pub by_expansion: HashMap<String, usize>,
}

/// A search result hit.
#[derive(Debug, Clone, Serialize)]
pub struct SearchHit {
    pub id: EntityId,
    pub title: String,
    pub mem: String,
    pub entity_type: String,
    pub stub: bool,
    pub score: f32,
    pub tokens: usize,
    /// The entity's `last_modified` stamp (RFC-3339 date) — list/roster
    /// consumers (the app's Liste, agents asking "what moved lately")
    /// sort on it without per-entity reads. `None` for stubs and hits
    /// built outside the engine ops.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub last_modified: Option<String>,
    pub snippet: Option<String>,
    /// Lead/key section bodies for the hit. The `search` op leaves this
    /// **empty** — search finds entities, `memstead_entity` reads their
    /// bodies; carrying every required section per hit overflowed the MCP
    /// transport cap. The `list` op still populates it (its human-facing
    /// roster consumers read the lead section as a one-line summary).
    /// Empty maps are omitted from the serialized envelope.
    #[serde(default, skip_serializing_if = "HashMap::is_empty")]
    pub sections: HashMap<String, String>,
    /// Score component breakdown — populated when the call supplied a
    /// text predicate; `None` on the metadata-only path.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub score_breakdown: Option<ScoreBreakdown>,
    /// Per-term match details keyed by query term — populated when the
    /// call supplied a text predicate; `None` on the metadata-only path.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub matched_terms: Option<HashMap<String, Vec<TermMatch>>>,
    /// Expansion metadata — populated on hits reached via graph
    /// expansion; `None` on primary hits.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub expansion: Option<ExpansionInfo>,
    /// Lead-section summary resolved against the hit's *own* mem schema
    /// at search time (see [`SummaryPair`]). The renderer cannot resolve
    /// it correctly on its own — the global `type_by_name` only sees the
    /// `default` schema, so a `software`-schema hit (`requirement` →
    /// `Statement`, `actor` → `Role`) would miss its anchor section and
    /// render `—`. `#[serde(skip)]` keeps `SearchHit`'s wire shape
    /// unchanged; the value surfaces on the envelope's `summary_heading` /
    /// `summary_value`. `None` only on hits built outside the engine
    /// search op (FFI/bridge and test fixtures), where the renderer falls
    /// back to the default-schema lookup.
    #[serde(skip)]
    pub summary: Option<SummaryPair>,
}

/// Lead-section `(heading, value)` for a search/list hit, resolved
/// against the hit's own mem schema at search time. Carried in-memory
/// from the search op to the renderers; see [`SearchHit::summary`].
#[derive(Debug, Clone)]
pub struct SummaryPair {
    pub heading: String,
    pub value: String,
}

/// Search result with metadata.
#[derive(Debug, Clone, Serialize)]
pub struct SearchResult {
    pub total: usize,
    pub returned: usize,
    pub offset: usize,
    /// Sum of estimated tokens across all matching entities (pre-pagination).
    /// Lets agents judge read cost before paging.
    pub total_tokens: usize,
    pub hits: Vec<SearchHit>,
    /// Faceted counts over the unpaginated hit set. Stable closed
    /// struct; zero-count entries are excluded.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub facets: Option<Facets>,
    /// Non-fatal issues surfaced to the caller. Structured
    /// `WarningHint` shape (`{code, details, message}`) — same wire
    /// envelope every other tool's warnings already use. Agents
    /// branch on `code`; the message field carries the existing
    /// remediation prose.
    #[serde(default, skip_serializing_if = "Vec::is_empty")]
    pub warnings: Vec<WarningHint>,
}

/// List result with token totals.
#[derive(Debug, Clone, Serialize)]
pub struct ListResult {
    pub total: usize,
    pub returned: usize,
    pub offset: usize,
    pub total_tokens: usize,
    pub hits: Vec<SearchHit>,
    /// Non-fatal issues surfaced to the caller — same structured
    /// shape as `SearchResult.warnings`.
    #[serde(default, skip_serializing_if = "Vec::is_empty")]
    pub warnings: Vec<WarningHint>,
}

// ---------------------------------------------------------------------------
// Health types
// ---------------------------------------------------------------------------

/// Health check result for one entity.
#[derive(Debug, Clone, Serialize)]
pub struct HealthReport {
    pub id: EntityId,
    pub title: String,
    pub score: f32,
    pub issues: Vec<HealthIssue>,
}

/// Machine-readable condition discriminator for a [`HealthIssue`] —
/// the enumeration lives here, with the issue type, and is never
/// re-derived per projection. A projection that lists issues carries
/// the code; the code is NEVER only a message-string prefix (a
/// projection that drops messages would silently collapse distinct
/// conditions — the exact misdirection `SECTION_HEADING_MISMATCH`
/// exists to prevent).
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize)]
#[serde(rename_all = "SCREAMING_SNAKE_CASE")]
pub enum HealthIssueCode {
    /// The required section/field is genuinely absent or empty.
    Missing,
    /// The section's content is present in the file but sits under a
    /// heading that does not derive back to the section key — NOT
    /// missing; fix the schema's heading/key pair.
    SectionHeadingMismatch,
    /// The entity carries a relationship whose rel-type the mem's
    /// schema does not declare.
    UndeclaredRelationship,
    /// An existing edge violates the rel-type's declared
    /// `source_types` / `target_types` shape.
    InvalidRelShape,
}

impl HealthIssueCode {
    /// Stable wire string — matches the serde `SCREAMING_SNAKE_CASE`
    /// serialization, exposed for text renderers.
    pub fn as_wire(&self) -> &'static str {
        match self {
            HealthIssueCode::Missing => "MISSING",
            HealthIssueCode::SectionHeadingMismatch => "SECTION_HEADING_MISMATCH",
            HealthIssueCode::UndeclaredRelationship => "UNDECLARED_RELATIONSHIP",
            HealthIssueCode::InvalidRelShape => "INVALID_REL_SHAPE",
        }
    }
}

#[derive(Debug, Clone, Serialize)]
pub struct HealthIssue {
    pub field: String,
    /// Which condition this issue reports — see [`HealthIssueCode`].
    pub code: HealthIssueCode,
    pub message: String,
}

/// One quarantine-roster entry on [`HealthSummary`]: the mem, the
/// typed reason code, and the full reason message (repair command
/// included — plan-01 material).
#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)]
pub struct QuarantinedMemReport {
    pub mem: String,
    pub reason_code: String,
    pub reason_message: String,
}

/// Aggregated health report for the whole graph.
#[derive(Debug, Clone, Serialize)]
pub struct HealthSummary {
    pub stale_entities: Vec<StaleEntity>,
    pub missing_fields: Vec<HealthReport>,
    pub orphan_count: usize,
    pub stub_count: usize,
    /// Typed non-fatal issues visible to every caller of `Engine::health()`.
    /// Populated in two layers: `Engine.load_warnings` contributes drift
    /// warnings surfaced during mem load / reload / attach
    /// (`SuspiciousNestedPrefix`, future load-time checks); the MCP
    /// handler additionally appends request-scoped warnings (unknown
    /// `include` keys, clamped `limit`) on top of whatever the engine
    /// merged. Empty on the happy path.
    #[serde(default, skip_serializing_if = "Vec::is_empty")]
    pub warnings: Vec<WarningHint>,
    /// Quarantine roster: mems that failed their mem-level boot step
    /// and serve nothing until repaired + reloaded. Always present in
    /// `Engine::health()` output when non-empty — a boot-honesty fact,
    /// never behind an include gate. Empty (and omitted from the wire)
    /// on a healthy workspace, keeping default output byte-unchanged.
    #[serde(default, skip_serializing_if = "Vec::is_empty")]
    pub quarantined: Vec<QuarantinedMemReport>,
    /// Workspace-level boot diagnosis from a diagnostic-shell engine
    /// (`{code, message}`): why the real workspace could not boot at
    /// all. Absent on every ordinarily booted engine.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub boot_diagnosis: Option<serde_json::Value>,
    /// Real-entity count per leaf-declared type (`<schema_ref>:<type>`
    /// keys) — the population the orphan axis exempts because those
    /// types are terminal by construction (agent-trust plan 06).
    /// Visible, never vanished. Empty (and omitted from the wire) for
    /// schemas that declare nothing, keeping default output
    /// byte-unchanged.
    #[serde(default, skip_serializing_if = "std::collections::BTreeMap::is_empty")]
    pub leaf_entities_by_type: std::collections::BTreeMap<String, usize>,
    /// Inline wiki-links in entity section bodies that resolve to stub
    /// targets (no on-disk markdown file). Populated only when the caller
    /// opts in via `include=["dangling_links"]`; `None` otherwise, so
    /// absence-of-key means "not requested" and presence-of-empty-array
    /// means "requested, zero findings". Scan is handler-driven (same
    /// pattern as `warnings` above), so non-MCP callers of
    /// `Engine::health()` always see `None` unless they invoke
    /// [`health::collect_dangling_links`] directly.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub dangling_links: Option<Vec<DanglingLink>>,
    /// Integrity findings (`{ id, axis, code, detail }`) over the
    /// conformance axis — and, under `include=["integrity"]`, the
    /// consistency axis too. Populated only when the caller opts in
    /// via `include=["conformance"]` / `include=["integrity"]`;
    /// `None` otherwise (same handler-driven pattern as
    /// `dangling_links`: absence means "not requested", an empty
    /// array means "requested, fully integral").
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub findings: Option<Vec<integrity::IntegrityFinding>>,
    /// Tag distribution (count per distinct tag, case-sensitive) over non-stub
    /// entities. Populated only when the caller opts in via `include=["tags"]`.
    /// Case-variant drift is surfaced via the sibling field [`tag_distribution_folded`].
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub tag_distribution: Option<Vec<TagDistribution>>,
    /// Case-drift audit sidecar: entries where two or more casings of the same
    /// canonical tag (lowercase) both appear in authored tags. Only entries with
    /// `variants.len() > 1` are returned — the default read of `tag_distribution`
    /// stays untouched. Populated alongside `tag_distribution`.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub tag_distribution_folded: Option<Vec<FoldedTag>>,
    /// Count of non-stub entities whose `tags` metadata is missing, empty,
    /// or resolves to zero effective tags after splitting on `,` and trimming.
    /// Populated alongside `tag_distribution` when `include=["tags"]`.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub untagged_entities: Option<UntaggedStats>,
}

#[derive(Debug, Clone, Serialize)]
pub struct StaleEntity {
    pub id: EntityId,
    pub title: String,
    pub days_since_modified: u64,
}

/// One entry in the tag distribution surface: an authored tag string, the
/// number of non-stub entities carrying it, and the per-entity-type breakdown
/// of those hits. Comparison is case-sensitive — `decision` and `Decision`
/// count as distinct entries here (see `tag_distribution_folded` for the
/// drift-aware sidecar).
#[derive(Debug, Clone, Serialize)]
pub struct TagDistribution {
    pub tag: String,
    pub count: usize,
    pub by_entity_type: HashMap<String, usize>,
}

/// Case-drift audit entry. Surfaces when two or more casings of the same
/// canonical (lowercased) tag appear in the authored graph — the agent-hostile
/// bug where `decision` and `Decision` look like two healthy low-count tags
/// in the case-sensitive primary surface.
#[derive(Debug, Clone, Serialize)]
pub struct FoldedTag {
    /// Lowercase form — the canonical key.
    pub canonical: String,
    /// Sum of counts across every casing variant.
    pub total: usize,
    /// Authored casings (as-written), each with its individual count.
    /// Sorted by `count` descending; ties broken by `tag` ascending.
    pub variants: Vec<TagVariant>,
}

#[derive(Debug, Clone, Serialize)]
pub struct TagVariant {
    pub tag: String,
    pub count: usize,
}

/// Aggregate count of non-stub entities with zero effective tags, broken
/// down by `entity_type`. "Untagged" collapses three states: missing `tags`
/// metadata, empty string value, and comma-only value (e.g. `","`).
#[derive(Debug, Clone, Serialize)]
pub struct UntaggedStats {
    pub total: usize,
    pub by_entity_type: HashMap<String, usize>,
}

/// One dangling wiki-link finding surfaced by
/// `memstead_health include=["dangling_links"]`. A link is dangling when its
/// resolved target is a stub (i.e. the markdown file does not exist on disk).
/// This is the post-delete / renamed-without-rewrite / typo signal.
#[derive(Debug, Clone, Serialize)]
pub struct DanglingLink {
    pub from: EntityId,
    /// Canonical ID the wiki-link resolves to. Stub-typed in the store.
    pub target_id: EntityId,
    /// Resolved mem-relative path segment of the target ID (e.g. `gone`
    /// for `specs--gone`). This is the normalised form the engine records —
    /// not the literal `[[…]]` characters as authored. Widening `WikiLink`
    /// to preserve the authored form is a future-work item if agents need
    /// grep-to-source precision.
    pub target_path: String,
    /// Section key in which the link appears (e.g. `"purpose"`). `None`
    /// only if the link appears outside any typed section — unusual but
    /// possible in free-form prose before the first heading.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub section: Option<String>,
}

// ---------------------------------------------------------------------------
// Export types
// ---------------------------------------------------------------------------

/// Export result.
///
/// Workspace-wide `export_markdown` returns this struct with
/// `skipped_mounts` populated for every mount whose active backend
/// doesn't support
/// markdown regeneration in place (git-branch, archive). Per-mem
/// export against an incompatible backend short-circuits with
/// `EngineError::MarkdownExportUnsupportedBackend` instead.
#[derive(Debug, Clone, Serialize)]
pub struct ExportResult {
    pub written: usize,
    pub unchanged: usize,
    /// Mounts that the workspace-wide export declined to write
    /// because their backend doesn't support markdown regeneration.
    /// Empty on the happy path (every mount is folder-backed).
    #[serde(default, skip_serializing_if = "Vec::is_empty")]
    pub skipped_mounts: Vec<SkippedMount>,
}

/// One mount declined by `export_markdown` because the active
/// backend doesn't support in-place markdown regeneration.
///
/// `reason` is a stable token (today: `"backend_does_not_support_markdown_export"`);
/// `active_backend` matches [`crate::workspace::MountStorage::backend_id`].
#[derive(Debug, Clone, Serialize)]
pub struct SkippedMount {
    pub mem: String,
    pub active_backend: String,
    pub reason: String,
}

/// Result of a `.mem` mem-archive export.
#[derive(Debug, Clone, Serialize)]
pub struct MemExportResult {
    pub archive_path: String,
    pub name: String,
    pub version: String,
    pub entity_count: usize,
    pub size_bytes: u64,
    /// Cross-mem edges in the exported slice whose target won't travel
    /// inside this single-mem archive — `install` will reject the
    /// archive for each one. Surfaced at export time
    /// (`DANGLING_CROSS_MEM_EDGE_IN_EXPORT`) so the operator sees the
    /// install-time failure before sharing. Empty for a self-contained
    /// export.
    #[serde(default, skip_serializing_if = "Vec::is_empty")]
    pub dangling_cross_mem_edges: Vec<crate::validator::DanglingCrossMemEdge>,
}

/// Result of `Engine::set_mem_version`. Carries the (mem,
/// old_version, new_version) triple so callers (CLI, MCP) can surface
/// the change without an extra read.
#[derive(Debug, Clone, Serialize)]
pub struct SetMemVersionOutcome {
    pub mem: String,
    /// Previous version. `None` when the mem config carried no
    /// version field before this call (pre-gate / externally-imported
    /// config, or the residual `MEM_CONFIG_INCOMPLETE` path).
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub old_version: Option<semver::Version>,
    pub new_version: semver::Version,
    /// Concurrent-drift warnings detected at the pre-write probe —
    /// e.g. `MemReloaded` when a sibling engine committed between
    /// this engine's last snapshot and the set-version write. Empty
    /// on the happy path. F1.
    #[serde(default, skip_serializing_if = "Vec::is_empty")]
    pub warnings: Vec<WarningHint>,
}

/// Result of `Engine::set_mem_title`. Same shape discipline as
/// [`SetMemDescriptionOutcome`].
#[derive(Debug, Clone, Serialize)]
pub struct SetMemTitleOutcome {
    pub mem: String,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub old_title: Option<String>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub new_title: Option<String>,
    #[serde(default, skip_serializing_if = "Vec::is_empty")]
    pub warnings: Vec<WarningHint>,
}

/// Result of `Engine::set_mem_subject`. The block sets/clears as a
/// unit; old/new carry the whole block.
#[derive(Debug, Clone, Serialize)]
pub struct SetMemSubjectOutcome {
    pub mem: String,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub old_subject: Option<memstead_schema::MemSubject>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub new_subject: Option<memstead_schema::MemSubject>,
    #[serde(default, skip_serializing_if = "Vec::is_empty")]
    pub warnings: Vec<WarningHint>,
}

/// Result of `Engine::set_mem_description`. Carries the (mem,
/// old_description, new_description) triple so callers can surface
/// the change without an extra read.
#[derive(Debug, Clone, Serialize)]
pub struct SetMemDescriptionOutcome {
    pub mem: String,
    /// Previous description. `None` when the mem config carried no
    /// description before this call (the common case — mem creation
    /// seeds none).
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub old_description: Option<String>,
    /// The description now persisted; `None` when the call cleared it.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub new_description: Option<String>,
    /// Concurrent-drift warnings detected at the pre-write probe.
    /// Empty on the happy path.
    #[serde(default, skip_serializing_if = "Vec::is_empty")]
    pub warnings: Vec<WarningHint>,
}

/// Result of `Engine::set_mem_sync_state`. Carries the (mem, key,
/// previous-token) triple so callers (CLI, MCP) can surface the change
/// without an extra read. The token values are opaque to the engine —
/// see `MemConfig::sync_state`.
#[derive(Debug, Clone, Serialize)]
pub struct SetMemSyncStateOutcome {
    pub mem: String,
    /// The sync-state key that was set or cleared (opaque; the ingest
    /// layer keys per `(ingest, facet)`).
    pub key: String,
    /// Previous token under `key`, `None` when the key was unset before
    /// this call. Lets callers report set-vs-overwrite without a read.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub previous: Option<String>,
    /// True when an empty token cleared an existing key. `false` for a
    /// set/overwrite and for a clear of an already-absent key (a no-op).
    pub removed: bool,
    /// Concurrent-drift warnings detected at the pre-write probe — e.g.
    /// `MemReloaded` when a sibling engine committed between this
    /// engine's last snapshot and the write. Empty on the happy path.
    #[serde(default, skip_serializing_if = "Vec::is_empty")]
    pub warnings: Vec<WarningHint>,
}

// ---------------------------------------------------------------------------
// Context types
// ---------------------------------------------------------------------------

/// Context around an entity — neighbors, community, related entities.
#[derive(Debug, Clone, Serialize)]
pub struct ContextResult {
    pub entity_id: EntityId,
    pub community: Option<String>,
    pub neighbors: Vec<NeighborInfo>,
}

#[derive(Debug, Clone, Serialize)]
pub struct NeighborInfo {
    pub id: EntityId,
    pub title: String,
    pub relationship: String,
    pub direction: Direction,
}

#[derive(Debug, Clone, Serialize)]
pub enum Direction {
    Outgoing,
    Incoming,
}

// ---------------------------------------------------------------------------
// Status
// ---------------------------------------------------------------------------

/// Graph status — node / edge counts and schema distribution. Renamed from
/// the former `Stats` when the `stats` command became `status` (bundle plan
/// `03-projection-promotion`, D11); the fields are unchanged so every caller's
/// payload stays byte-compatible.
#[derive(Debug, Clone, Serialize)]
pub struct Status {
    pub entity_count: usize,
    pub edge_count: usize,
    pub edge_types: HashMap<String, usize>,
    pub community_count: usize,
    pub mem_count: usize,
    pub types_in_use: Vec<String>,
}

// ---------------------------------------------------------------------------
// Reload result
// ---------------------------------------------------------------------------

#[derive(Debug, Clone, Serialize)]
pub struct ReloadResult {
    pub added: Vec<EntityId>,
    pub changed: Vec<EntityId>,
    pub removed: Vec<EntityId>,
}

/// Per-mem reload outcome — produced by [`Engine::reload_one_mem`]
/// and surfaced verbatim in the `memstead_reload` MCP tool's response when
/// an explicit operator-triggered reload runs against a single mem.
/// Auto-reloads on the read path consume this internally and emit a
/// [`WarningHint::MemReloaded`] (which carries `mem`, `old_head`,
/// `new_head`, `entities_loaded` — the diff list is intentionally
/// omitted from the lean warning payload; agents that need it call
/// `memstead_changes_since` themselves with the supplied `old_head`).
///
/// `head_before` / `head_after` are hex-rendered SHAs (or
/// `EMPTY_TREE_SHA` for the no-baseline case) so the wire shape
/// matches what `memstead_changes_since` already accepts as `since`.
/// `changed_entity_ids` is the list of non-stub IDs whose
/// `content_hash` differs between the pre- and post-reload store
/// snapshots, plus every newly-added or newly-removed id — same
/// semantic as `ReloadResult { added, changed, removed }` flattened
/// into a single set so callers don't have to merge three lists.
#[derive(Debug, Clone, Serialize)]
pub struct ReloadReport {
    pub mem: String,
    pub head_before: String,
    pub head_after: String,
    pub entities_loaded: usize,
    pub changed_entity_ids: Vec<EntityId>,
}

/// What `Engine::full_refresh` changed — and, just as deliberately,
/// what it SKIPPED. The refresh is additive-only: removals never take
/// effect warm, and this report is how the caller learns whether its
/// next call will succeed instead of guessing.
#[derive(Debug, Clone, Default, Serialize)]
pub struct FullRefreshReport {
    /// Schema versions (`name@version`) newly resolvable.
    pub schemas_added: Vec<String>,
    /// In-memory schema versions absent from the re-scanned sources —
    /// the removal was skipped; they stay resolvable until restart.
    pub schema_removals_skipped: Vec<String>,
    /// Mems newly mounted (cold-loaded like any boot-time mount).
    pub mems_mounted: Vec<String>,
    /// Mounted writable mems absent from the re-scanned manifest —
    /// the removal was skipped; they stay live until restart.
    pub mem_removals_skipped: Vec<String>,
    /// Per-item failures: a source or mount that failed to refresh.
    /// Failed items never surface as newly available; the others
    /// proceed.
    pub failures: Vec<RefreshFailure>,
    /// Wall-clock cost of the refresh (the bounded-cost report).
    pub elapsed_ms: u64,
}

/// One failed refresh item — `item` is `schema-source:<which>`,
/// `mount:<mem>`, `mount-manifest`, or `workspace`.
#[derive(Debug, Clone, Serialize)]
pub struct RefreshFailure {
    pub item: String,
    pub error: String,
}

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

    // Locks the wire shape of `Query` across every combination of
    // set/unset fields. Agents compose queries on the fly; a drift here
    // silently changes the MCP tool's JSON contract.
    #[test]
    fn query_json_roundtrip_every_combination() {
        let cases: Vec<Query> = vec![
            Query::default(),
            Query {
                any: vec!["auth".into()],
                ..Default::default()
            },
            Query {
                not: vec!["mock".into()],
                ..Default::default()
            },
            Query {
                phrase: Some("client side agent".into()),
                ..Default::default()
            },
            Query {
                field: Some("identity".into()),
                ..Default::default()
            },
            Query {
                any: vec!["a".into(), "b".into()],
                not: vec!["x".into()],
                phrase: Some("ex act".into()),
                field: Some("purpose".into()),
            },
        ];
        for q in &cases {
            let json = serde_json::to_string(q).expect("serialize");
            let back: Query = serde_json::from_str(&json).expect("deserialize");
            assert_eq!(q.any, back.any, "any field round-trip: {json}");
            assert_eq!(q.not, back.not, "not field round-trip: {json}");
            assert_eq!(q.phrase, back.phrase, "phrase field round-trip: {json}");
            assert_eq!(q.field, back.field, "field field round-trip: {json}");
            assert_eq!(q.is_empty(), back.is_empty());
        }
    }

    // Empty fields stay out of the wire shape — agents see a lean object.
    #[test]
    fn query_default_serializes_as_empty_object() {
        let q = Query::default();
        let json = serde_json::to_string(&q).unwrap();
        assert_eq!(json, "{}", "default query must serialize as `{{}}`");
    }

    // Null / missing keys all round-trip to the same default via serde.
    #[test]
    fn query_accepts_missing_and_null_fields() {
        let with_missing: Query = serde_json::from_str("{}").unwrap();
        let with_nulls: Query =
            serde_json::from_str(r#"{"any":[],"not":[],"phrase":null,"field":null}"#).unwrap();
        assert!(with_missing.is_empty());
        assert!(with_nulls.is_empty());
    }

    // Schema is generated via schemars so MCP agents see the full
    // structured contract. Cheap smoke test — locks that the four known
    // fields appear and nothing regresses to an action-discriminator.
    #[test]
    fn query_json_schema_exposes_four_fields() {
        let schema = schemars::schema_for!(Query);
        let rendered = serde_json::to_string(&schema).unwrap();
        for field in ["any", "not", "phrase", "field"] {
            assert!(
                rendered.contains(&format!("\"{field}\"")),
                "schema must mention `{field}`: {rendered}"
            );
        }
    }

    // ------------------------------------------------------------------
    // WarningHint wire-envelope snapshots. Each variant locks `code`
    // (stable UPPER_SNAKE_CASE), a message substring (phrasing may
    // drift — we assert a durable anchor), and the `details` key-set.
    // Arrays are asserted shape-only because their content depends on
    // the active schema / allowed-include list.
    // ------------------------------------------------------------------

    fn to_envelope(w: &WarningHint) -> serde_json::Value {
        serde_json::to_value(w).expect("WarningHint serializes")
    }

    #[test]
    fn warning_hint_missing_required_section_envelope() {
        // F9: type-level write_rules moved out of per-warning details
        // to the mutation response's top-level `type_guidance` map.
        // The warning now carries only section-axis fields.
        let w = WarningHint::MissingRequiredSection {
            entity_type: "spec".into(),
            key: "purpose".into(),
            heading: "Purpose".into(),
            write_rules: vec!["one sentence".into(), "state the why".into()],
        };
        let json = to_envelope(&w);
        assert_eq!(json["code"], "MISSING_REQUIRED_SECTION");
        assert!(
            json["message"]
                .as_str()
                .unwrap()
                .contains("required section")
        );
        assert_eq!(json["details"]["entity_type"], "spec");
        assert_eq!(json["details"]["key"], "purpose");
        assert_eq!(json["details"]["heading"], "Purpose");
        assert!(json["details"]["write_rules"].is_array());
        // type_write_rules no longer rides on the per-warning envelope.
        assert!(json["details"].get("type_write_rules").is_none());
    }

    #[test]
    fn warning_hint_undeclared_relationship_open_envelope() {
        let w = WarningHint::UndeclaredRelationshipOpen {
            rel_type: "USES".into(),
            message: "USES admitted in open mode".into(),
        };
        let json = to_envelope(&w);
        assert_eq!(json["code"], "UNDECLARED_RELATIONSHIP_OPEN");
        // Display delegates to the stored message — substring anchor is safe.
        assert!(json["message"].as_str().unwrap().contains("open mode"));
        assert_eq!(json["details"]["rel_type"], "USES");
        // Consistency rule: details must not duplicate the envelope message.
        assert!(json["details"].get("message").is_none());
        // Only rel_type belongs under details for this variant.
        assert_eq!(json["details"].as_object().unwrap().len(), 1);
    }

    #[test]
    fn warning_hint_duplicate_relationship_envelope() {
        let w = WarningHint::DuplicateRelationship {
            rel_type: "USES".into(),
            from: EntityId("specs--a".into()),
            to: EntityId("specs--b".into()),
        };
        let json = to_envelope(&w);
        assert_eq!(json["code"], "DUPLICATE_RELATIONSHIP");
        assert!(json["message"].as_str().unwrap().contains("already exists"));
        assert_eq!(json["details"]["rel_type"], "USES");
        assert_eq!(json["details"]["from"], "specs--a");
        assert_eq!(json["details"]["to"], "specs--b");
    }

    #[test]
    fn warning_hint_no_such_relationship_envelope() {
        let w = WarningHint::NoSuchRelationship {
            rel_type: "USES".into(),
            from: EntityId("specs--a".into()),
            to: EntityId("specs--b".into()),
        };
        let json = to_envelope(&w);
        assert_eq!(json["code"], "NO_SUCH_RELATIONSHIP");
        assert!(json["message"].as_str().unwrap().contains("does not exist"));
        assert_eq!(json["details"]["rel_type"], "USES");
        assert_eq!(json["details"]["from"], "specs--a");
        assert_eq!(json["details"]["to"], "specs--b");
    }

    #[test]
    fn warning_hint_unknown_include_key_envelope() {
        let w = WarningHint::UnknownIncludeKey {
            key: "bogus".into(),
            allowed: vec!["orphans".into(), "stubs".into()],
        };
        let json = to_envelope(&w);
        assert_eq!(json["code"], "UNKNOWN_INCLUDE_KEY");
        assert!(json["message"].as_str().unwrap().contains("bogus"));
        assert_eq!(json["details"]["key"], "bogus");
        assert!(json["details"]["allowed"].is_array());
    }

    #[test]
    fn warning_hint_limit_clamped_envelope() {
        let w = WarningHint::LimitClamped {
            requested: 1000,
            actual: 100,
        };
        let json = to_envelope(&w);
        assert_eq!(json["code"], "LIMIT_CLAMPED");
        assert!(json["message"].as_str().unwrap().contains("clamped"));
        assert_eq!(json["details"]["requested"].as_u64(), Some(1000));
        assert_eq!(json["details"]["actual"].as_u64(), Some(100));
    }

    #[test]
    fn warning_hint_title_normalized_to_slug_noop_envelope() {
        let w = WarningHint::TitleNormalizedToSlugNoop {
            requested_title: "Hello World!".into(),
            current_slug: "hello-world".into(),
        };
        let json = to_envelope(&w);
        assert_eq!(json["code"], "TITLE_NORMALIZED_TO_SLUG_NOOP");
        assert!(
            json["message"]
                .as_str()
                .unwrap()
                .contains("no change written to disk")
        );
        assert_eq!(json["details"]["requested_title"], "Hello World!");
        assert_eq!(json["details"]["current_slug"], "hello-world");
    }

    // Top-level envelope shape lock — every WarningHint emits exactly
    // three keys and nothing else. Protects against accidental field
    // additions at the envelope level.
    #[test]
    fn warning_hint_envelope_has_exactly_three_top_level_keys() {
        for w in &WarningHint::all_samples() {
            let json = to_envelope(w);
            let obj = json.as_object().expect("envelope is an object");
            assert_eq!(
                obj.len(),
                3,
                "{} must emit exactly 3 top-level keys; got {:?}",
                w.code(),
                obj.keys().collect::<Vec<_>>()
            );
            assert!(obj.contains_key("code"));
            assert!(obj.contains_key("message"));
            assert!(obj.contains_key("details"));
        }
    }

    // Stability lock — `code()` values are a public wire contract. Every
    // variant must expose an UPPER_SNAKE_CASE identifier. Catches
    // accidental rename / case drift in a single test.
    #[test]
    fn warning_hint_code_values_are_upper_snake_case() {
        let re = regex::Regex::new(r"^[A-Z][A-Z0-9_]*$").unwrap();
        for w in &WarningHint::all_samples() {
            let code = w.code();
            assert!(
                re.is_match(code),
                "code() violates UPPER_SNAKE_CASE: {code}"
            );
        }
    }

    // Envelope helper emits the same shape as WarningHint::serialize — one
    // constructor, two callers (warnings + MCP error path).
    #[test]
    fn envelope_shape_is_code_message_details() {
        let v = envelope("FOO_BAR", "hello", serde_json::json!({ "x": 1 }));
        assert_eq!(v["code"], "FOO_BAR");
        assert_eq!(v["message"], "hello");
        assert_eq!(v["details"]["x"], 1);
        assert_eq!(
            v.as_object().unwrap().len(),
            3,
            "envelope has exactly 3 top-level keys"
        );
    }
}