memstead-base 0.8.0

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

use std::collections::HashMap;
use std::sync::{Arc, OnceLock};

use memstead_schema::{
    FieldType, Filterable, ManualAuthoring, PerEdgeDescription, RelationshipMode, Schema,
    Serialization, TypeDefinition, all_types, type_by_name,
};
use serde::Serialize;

use crate::chunking::estimate_tokens;
use crate::graph::community::generate_auto_summary;
use crate::ops::Direction;
use crate::ops::{ExpansionInfo, Facets, ScoreBreakdown, SubsectionFacet, TermMatch};
use crate::store::Store;
use crate::{
    ContextResult, Edge, Entity, InEdge, ListResult, LouvainOutput, SearchHit, SearchResult,
};

// ---------------------------------------------------------------------------
// Entity rendering
// ---------------------------------------------------------------------------

/// Render a single entity as markdown with frontmatter metadata.
pub fn render_entity_markdown(entity: &Entity, sections_filter: Option<&[String]>) -> String {
    let body_text = render_entity_body(entity, sections_filter);

    // Frontmatter — _tokens reflects the rendered output, not the full entity.
    let mut lines = Vec::new();
    lines.push("---".to_string());
    lines.push(format!("_hash: {}", entity.content_hash));
    // Typed stub provenance — only emitted when the entity carries
    // a `stub_kind` (real entities are absent from this surface).
    // Agents reading a stub three calls after the mutation that
    // produced it recover the diagnostic context that the
    // mutation-time warning carried.
    if let Some(kind) = &entity.stub_kind {
        match kind {
            crate::entity::StubKind::ForwardReference => {
                lines.push("_stub_kind: forward_reference".to_string());
            }
            crate::entity::StubKind::LoadTime => {
                lines.push("_stub_kind: load_time".to_string());
            }
            crate::entity::StubKind::Residual {
                since_commit,
                readonly_referrers,
            } => {
                lines.push("_stub_kind: residual".to_string());
                if !since_commit.is_empty() {
                    lines.push(format!("_stub_since_commit: {since_commit}"));
                }
                if !readonly_referrers.is_empty() {
                    let refs: Vec<String> =
                        readonly_referrers.iter().map(|r| r.to_string()).collect();
                    lines.push(format!("_stub_readonly_referrers: [{}]", refs.join(", ")));
                }
            }
        }
    }
    let tokens = estimate_tokens(&body_text);
    lines.push(format!("_tokens: {tokens}"));

    // When sections are filtered and some were excluded, show full entity size
    // so agents know how much they're missing.
    let is_filtered = sections_filter.is_some_and(|f| {
        let all_keys: Vec<&String> = entity.sections.keys().collect();
        f.len() < all_keys.len() || !all_keys.iter().all(|k| f.iter().any(|fk| fk == *k))
    });
    if is_filtered {
        let full_body = render_entity_body(entity, None);
        let full_tokens = estimate_tokens(&full_body);
        lines.push(format!("_tokens_unfiltered_body: {full_tokens}"));
    }

    // Emit entity metadata
    for (key, value) in &entity.metadata {
        lines.push(format!("{key}: {value}"));
    }
    lines.push("---".to_string());
    lines.push(String::new());

    lines.push(body_text);
    lines.join("\n")
}

/// Token estimate for an entity's rendered body (title + sections +
/// relationships, filter applied) — the exact number `render_entity_markdown`
/// embeds as its frontmatter `_tokens`. Use this when building a structured
/// envelope so the envelope's `_tokens` and the markdown channel's frontmatter
/// `_tokens` describe the *same* thing for a given `_hash`: the rendered body,
/// not the full markdown document (which would additionally count frontmatter).
pub fn rendered_body_tokens(entity: &Entity, sections_filter: Option<&[String]>) -> usize {
    estimate_tokens(&render_entity_body(entity, sections_filter))
}

/// Build the body (title + sections + relationships) for an entity, optionally filtered.
///
/// Section iteration order follows `entity.sections` — an `IndexMap`, so
/// insertion order is the authoritative render order. The parser inserts keys
/// in the schema's declared order, which is what ships to clients. Do not
/// migrate `entity.sections` back to `HashMap`.
fn render_entity_body(entity: &Entity, sections_filter: Option<&[String]>) -> String {
    let mut body = Vec::new();

    body.push(format!("# {}", entity.title));
    body.push(String::new());

    // Look up the entity's TypeDefinition across every built-in schema
    // so non-default schemas (e.g. `ingest.inconsistency`) get their
    // declared headings rendered exactly as the on-disk markdown
    // emitted them. Falls back to key→heading derivation when no
    // built-in schema declares this type — preserves the prior shape
    // for custom workspace schemas not yet bridged through the
    // renderer.
    let type_def = lookup_builtin_type(&entity.entity_type);

    for (key, content) in &entity.sections {
        if let Some(filter) = sections_filter
            && !filter.iter().any(|f| f == key)
        {
            continue;
        }
        let heading = section_heading_for(type_def.as_deref(), key);
        body.push(format!("## {heading}"));
        body.push(String::new());
        body.push(content.trim().to_string());
        body.push(String::new());
    }

    if !entity.relationships.is_empty()
        && sections_filter.is_none_or(|f| f.iter().any(|s| s == "relationships"))
    {
        body.push("## Relationships".to_string());
        body.push(String::new());
        for rel in &entity.relationships {
            // Mirror the on-disk renderer (`entity::generator`):
            // canonical em-dash delimiter when the relation carries a
            // per-edge description, simple form otherwise.
            match rel
                .description
                .as_deref()
                .map(str::trim)
                .filter(|s| !s.is_empty())
            {
                Some(text) => body.push(format!(
                    "- **{}**: [[{}]] \u{2014} {text}",
                    rel.rel_type, rel.target
                )),
                None => body.push(format!("- **{}**: [[{}]]", rel.rel_type, rel.target)),
            }
        }
        body.push(String::new());
    }

    body.join("\n")
}

/// Render a `## Relations` section as markdown — typed edges grouped by
/// direction. Appended to `memstead_entity` output when `include_relations: true`.
/// A JSON-shaped version is available via `render_relations_json` for the
/// `memstead-cli relations --json` consumer.
pub fn render_relations_markdown(
    entity_id: &str,
    outgoing: &[Edge],
    incoming: &[InEdge],
) -> String {
    let mut lines = Vec::new();
    lines.push(String::new());
    lines.push("## Relations".to_string());
    lines.push(String::new());

    if outgoing.is_empty() && incoming.is_empty() {
        lines.push(format!("(no relations for {entity_id})"));
        lines.push(String::new());
        return lines.join("\n");
    }

    if !outgoing.is_empty() {
        lines.push("### Outgoing".to_string());
        for e in outgoing {
            lines.push(format!("- **{}** → [[{}]]", e.rel_type, e.target));
        }
        lines.push(String::new());
    }

    if !incoming.is_empty() {
        lines.push("### Incoming".to_string());
        for e in incoming {
            lines.push(format!("- [[{}]] → **{}** → (this)", e.from, e.rel_type));
        }
        lines.push(String::new());
    }

    lines.join("\n")
}

/// Render outgoing/incoming relations as a JSON envelope. Consumed by
/// `memstead-cli relations --json`; no MCP path uses it.
pub fn render_relations_json(
    entity_id: &str,
    outgoing: &[Edge],
    incoming: &[InEdge],
) -> serde_json::Value {
    let out: Vec<serde_json::Value> = outgoing
        .iter()
        .map(|e| {
            serde_json::json!({
                "type": e.rel_type,
                "target": e.target.to_string(),
                "source": format!("{:?}", e.source).to_lowercase(),
            })
        })
        .collect();

    let inc: Vec<serde_json::Value> = incoming
        .iter()
        .map(|e| {
            serde_json::json!({
                "type": e.rel_type,
                "from": e.from.to_string(),
                "source": format!("{:?}", e.source).to_lowercase(),
            })
        })
        .collect();

    serde_json::json!({
        "entity": entity_id,
        "outgoing": out,
        "incoming": inc,
    })
}

// ---------------------------------------------------------------------------
// Search / List rendering
// ---------------------------------------------------------------------------

/// Render search results as markdown.
pub fn render_search_markdown(result: &SearchResult, offset: usize) -> String {
    let mut lines = Vec::new();

    lines.push("---".to_string());
    lines.push(format!("_total: {}", result.total));
    lines.push(format!("_returned: {}", result.returned));
    lines.push(format!("_offset: {offset}"));
    lines.push(format!("_total_tokens: {}", result.total_tokens));
    lines.push("---".to_string());
    lines.push(String::new());

    if !result.warnings.is_empty() {
        // Render each search warning with its typed code as the lead — same
        // shape mutation-tool `## Warnings` blocks already use — so an
        // agent reading the markdown sees the code without decoding
        // the structured channel.
        lines.push("## Filter warnings".to_string());
        for w in &result.warnings {
            lines.push(format!("- **{}**: {}", w.code(), w.message()));
        }
        lines.push(String::new());
    }

    if let Some(facets) = &result.facets
        && let Some(block) = render_facets_block(facets)
    {
        lines.push(block);
    }

    for hit in &result.hits {
        lines.push(format!(
            "### {}{} (_score: {:.1}, _tokens: {})",
            hit.id, hit.title, hit.score, hit.tokens,
        ));
        lines.push(hit_summary_line(hit));
        if let Some(line) = render_matched_terms_line(hit.matched_terms.as_ref()) {
            lines.push(line);
        }
        if let Some(line) = render_score_breakdown_line(hit.score_breakdown.as_ref()) {
            lines.push(line);
        }
        if let Some(line) = render_heading_paths_line(hit.matched_terms.as_ref()) {
            lines.push(line);
        }
        if let Some(line) = render_expansion_line(hit.expansion.as_ref()) {
            lines.push(line);
        }
        if let Some(snippet) = &hit.snippet {
            lines.push(format!("> ...{snippet}..."));
        }
        lines.push(String::new());
    }

    lines.join("\n")
}

/// Render the `## Facets` block for a `SearchResult`. Returns `None` when
/// every facet bucket is empty — callers elide the section entirely in
/// that case. Buckets with mixed presence each ship independently.
///
/// Ordering: keys inside a bucket sort by count desc, then key asc so the
/// output is deterministic for tests. `by_subsection` uses its native
/// stored order (already sorted by count desc in `ops::search`).
fn render_facets_block(facets: &Facets) -> Option<String> {
    let blocks: Vec<(&str, String)> = [
        ("by_type", &facets.by_type),
        ("by_mem", &facets.by_mem),
        ("by_level", &facets.by_level),
        ("by_status", &facets.by_status),
        ("by_confidence", &facets.by_confidence),
        ("by_expansion", &facets.by_expansion),
    ]
    .into_iter()
    .filter_map(|(name, bucket)| format_facet_bucket(bucket).map(|s| (name, s)))
    .collect();

    if blocks.is_empty() && facets.by_subsection.is_empty() {
        return None;
    }

    let mut out = String::new();
    out.push_str("## Facets\n");
    for (name, body) in blocks {
        out.push_str(&format!("- **{name}:** {body}\n"));
    }
    if !facets.by_subsection.is_empty() {
        out.push_str("- **by_subsection:**\n");
        for entry in &facets.by_subsection {
            out.push_str(&format!("  - {}\n", format_subsection_facet(entry)));
        }
    }
    Some(out)
}

fn format_facet_bucket(bucket: &HashMap<String, usize>) -> Option<String> {
    if bucket.is_empty() {
        return None;
    }
    let mut entries: Vec<(&String, &usize)> = bucket.iter().collect();
    entries.sort_by(|a, b| b.1.cmp(a.1).then_with(|| a.0.cmp(b.0)));
    Some(
        entries
            .iter()
            .map(|(k, v)| format!("{k}={v}"))
            .collect::<Vec<_>>()
            .join(", "),
    )
}

fn format_subsection_facet(entry: &SubsectionFacet) -> String {
    let path = entry.path.join("");
    format!("`{path}`: {}", entry.count)
}

/// Render the `**Matched terms:**` line for one hit. `matched_terms`
/// groups `TermMatch`es per query term; output is one `term (field×N, ...)`
/// group per term, joined with `, `. Terms and fields both sort
/// alphabetically for deterministic output.
fn render_matched_terms_line(matched: Option<&HashMap<String, Vec<TermMatch>>>) -> Option<String> {
    let matched = matched?;
    if matched.is_empty() {
        return None;
    }
    let mut terms: Vec<(&String, &Vec<TermMatch>)> = matched.iter().collect();
    terms.sort_by(|a, b| a.0.cmp(b.0));
    let groups: Vec<String> = terms
        .iter()
        .map(|(term, tms)| {
            let mut field_counts: HashMap<&str, usize> = HashMap::new();
            for tm in tms.iter() {
                *field_counts.entry(tm.field.as_str()).or_insert(0) += 1;
            }
            let mut fields: Vec<(&&str, &usize)> = field_counts.iter().collect();
            fields.sort_by(|a, b| a.0.cmp(b.0));
            let inner: Vec<String> = fields.iter().map(|(f, n)| format!("{f}×{n}")).collect();
            format!("`{term}` ({})", inner.join(", "))
        })
        .collect();
    Some(format!("**Matched terms:** {}", groups.join(", ")))
}

/// Render the `**Score:**` line from a `ScoreBreakdown`. Fields render as
/// `bm25 X.X + title X.X + <field> X.X [+ expansion_decay ×X.X]`. Zero-
/// valued components still ship — the breakdown is informational, and the
/// composition "title 0.0" is itself a fact worth surfacing.
fn render_score_breakdown_line(breakdown: Option<&ScoreBreakdown>) -> Option<String> {
    let b = breakdown?;
    let mut parts: Vec<String> = Vec::new();
    parts.push(format!("bm25 {:.1}", b.bm25));
    parts.push(format!("title {:.1}", b.title_boost));
    let mut fields: Vec<(&String, &f32)> = b.field_weights.iter().collect();
    fields.sort_by(|a, b| a.0.cmp(b.0));
    for (k, v) in fields {
        parts.push(format!("{k} {v:.1}"));
    }
    if let Some(decay) = b.expansion_decay {
        parts.push(format!("expansion_decay ×{decay:.1}"));
    }
    Some(format!("**Score:** {}", parts.join(" + ")))
}

/// Render the `**Heading path:**` line for one hit. Collects distinct
/// non-empty `heading_path`s across the hit's `TermMatch`es. Single path
/// renders inline (`A › B`), multiple paths render as `A › B; C › D`.
fn render_heading_paths_line(matched: Option<&HashMap<String, Vec<TermMatch>>>) -> Option<String> {
    let matched = matched?;
    let mut paths: Vec<Vec<String>> = Vec::new();
    let mut term_keys: Vec<&String> = matched.keys().collect();
    term_keys.sort();
    for term in term_keys {
        for tm in &matched[term] {
            if let Some(path) = &tm.heading_path
                && !path.is_empty()
                && !paths.iter().any(|p| p == path)
            {
                paths.push(path.clone());
            }
        }
    }
    if paths.is_empty() {
        return None;
    }
    let formatted: Vec<String> = paths.iter().map(|p| p.join("")).collect();
    Some(format!("**Heading path:** {}", formatted.join("; ")))
}

/// Render the `**Expansion:**` line for one hit — `from <id> via <edge>
/// [out|in] (depth N)`. The direction rides wherever the label does,
/// so a `both` walk stays interpretable per hit.
fn render_expansion_line(expansion: Option<&ExpansionInfo>) -> Option<String> {
    let e = expansion?;
    let dir = match e.via_direction {
        crate::graph::query::TraversalDirection::Out => "out",
        crate::graph::query::TraversalDirection::In => "in",
        // A concrete reaching edge always has one direction; `Both`
        // cannot occur here by construction.
        crate::graph::query::TraversalDirection::Both => "both",
    };
    Some(format!(
        "**Expansion:** from `{}` via `{}` [{dir}] (depth {})",
        e.of, e.via_edge, e.depth,
    ))
}

/// Render list results as markdown.
pub fn render_list_markdown(result: &ListResult) -> String {
    let mut lines = Vec::new();

    lines.push("---".to_string());
    lines.push(format!("_total: {}", result.total));
    lines.push(format!("_returned: {}", result.returned));
    lines.push(format!("_offset: {}", result.offset));
    lines.push(format!("_total_tokens: {}", result.total_tokens));
    lines.push("---".to_string());
    lines.push(String::new());

    if !result.warnings.is_empty() {
        lines.push("## Filter warnings".to_string());
        for w in &result.warnings {
            lines.push(format!("- **{}**: {}", w.code(), w.message()));
        }
        lines.push(String::new());
    }

    for hit in &result.hits {
        let meta = hit
            .sections
            .get("level")
            .map(|l| format!("{l}, "))
            .unwrap_or_default();
        lines.push(format!(
            "### {}{} ({meta}_tokens: {})",
            hit.id, hit.title, hit.tokens,
        ));
        lines.push(hit_summary_line(hit));
        lines.push(String::new());
    }

    lines.join("\n")
}

// ---------------------------------------------------------------------------
// Context / Overview rendering
// ---------------------------------------------------------------------------

/// Render a `## Community Context` section — cluster id + neighbor list —
/// appended to `memstead_entity` output when `include_context: true`. No
/// frontmatter; the entity body owns that.
pub fn render_community_context_section(result: &ContextResult, cluster_id: &str) -> String {
    let mut lines = Vec::new();
    lines.push(String::new());
    lines.push("## Community Context".to_string());
    lines.push(String::new());
    lines.push(format!("**Cluster {cluster_id}**"));
    lines.push(String::new());

    if !result.neighbors.is_empty() {
        lines.push("### Neighbors".to_string());
        for n in &result.neighbors {
            let dir = match n.direction {
                Direction::Outgoing => "",
                Direction::Incoming => "",
            };
            lines.push(format!(
                "- {}{}— **{}** ({})",
                result.entity_id, dir, n.id, n.relationship,
            ));
        }
        lines.push(String::new());
    }

    lines.join("\n")
}

/// Render context (community cluster) as markdown.
pub fn render_context_markdown(result: &ContextResult, cluster_id: &str) -> String {
    let mut lines = Vec::new();

    lines.push("---".to_string());
    lines.push(format!("_cluster_id: {cluster_id}"));
    lines.push("---".to_string());
    lines.push(String::new());
    lines.push(format!("## Cluster {cluster_id}"));
    lines.push(String::new());

    // Neighbors grouped by direction
    lines.push("### Neighbors".to_string());
    for n in &result.neighbors {
        let dir = match n.direction {
            Direction::Outgoing => "",
            Direction::Incoming => "",
        };
        lines.push(format!(
            "- {}{}— **{}** ({})",
            result.entity_id, dir, n.id, n.relationship,
        ));
    }
    lines.push(String::new());

    lines.join("\n")
}

/// Render overview (all clusters) as markdown. `store` provides entity titles
/// for the on-the-fly auto-summary (title-join) — there is no stored summary.
pub fn render_overview_markdown(output: &LouvainOutput, store: &Store) -> String {
    let mut lines = Vec::new();

    let entity_count: usize = output.clusters.values().map(|c| c.entities.len()).sum();

    lines.push("---".to_string());
    lines.push(format!("_cluster_count: {}", output.count));
    lines.push(format!("_entity_count: {entity_count}"));
    // Use compact formatting to match JS: "0" instead of "0.0000"
    let mod_str = if output.modularity == 0.0 {
        "0".to_string()
    } else {
        format!("{:.4}", output.modularity)
    };
    lines.push(format!("_modularity: {mod_str}"));
    lines.push("---".to_string());
    lines.push(String::new());

    // Sort clusters by ID for deterministic output
    let mut cluster_ids: Vec<&String> = output.clusters.keys().collect();
    cluster_ids.sort();

    for cluster_id in cluster_ids {
        let info = &output.clusters[cluster_id];
        let summary = generate_auto_summary(store, &info.entities);

        lines.push(format!(
            "## Cluster {cluster_id} ({} entities)",
            info.entities.len(),
        ));
        if !summary.is_empty() {
            lines.push(summary);
        }
        for entity_id in &info.entities {
            lines.push(format!("- {entity_id}"));
        }
        lines.push(String::new());
    }

    lines.join("\n")
}

// ---------------------------------------------------------------------------
// JSON envelopes for search / list — consumed by `memstead-cli` only
// ---------------------------------------------------------------------------
//
// These wrap the core `SearchResult` / `ListResult` with precomputed
// `summary_heading` / `summary_value` per hit — the same values the
// markdown renderer emits — so the CLI's `--json` output doesn't
// reimplement schema lead-section lookup. The MCP side carries no JSON
// sidecar; these envelopes remain on the `memstead-cli search --json` /
// `memstead-cli list --json` path.
//
// Snake-case field names are intentional: they match on-disk YAML and the
// core `SearchHit` struct. Do not add `rename_all = "camelCase"`.

/// Envelope wrapping a `SearchHit` with precomputed summary fields.
#[derive(Serialize)]
pub struct SearchHitEnvelope<'a> {
    #[serde(flatten)]
    pub hit: &'a SearchHit,
    pub summary_heading: String,
    pub summary_value: String,
}

/// Envelope for a full `SearchResult`:
/// `_-prefixed` engine-emitted counters at the top level, `facets`
/// as a structured object (not a markdown blob), and the full per-hit
/// shape (score, score_breakdown, matched_terms, expansion) inherited
/// verbatim from `SearchHit` so the structured envelope is the
/// branching surface — agents reading `structured_content` don't have
/// to parse the text channel's rendered prose to recover scores or
/// score components. CLI `--json` and MCP `structured_content` share
/// this shape.
#[derive(Serialize)]
pub struct SearchResultEnvelope<'a> {
    #[serde(rename = "_total")]
    pub total: usize,
    #[serde(rename = "_returned")]
    pub returned: usize,
    #[serde(rename = "_offset")]
    pub offset: usize,
    /// Sum of estimated tokens across all matching entities (pre-pagination).
    /// Mirrors `ListResultEnvelope.total_tokens` so the field has consistent
    /// meaning across both surfaces — migration cost for agents is zero.
    #[serde(rename = "_total_tokens")]
    pub total_tokens: usize,
    pub hits: Vec<SearchHitEnvelope<'a>>,
    /// Faceted counts over the unpaginated hit set. Skipped on the
    /// wire when the engine produced no facets (rare; the unified
    /// engine always populates an empty `Facets::default()` for
    /// shape stability).
    #[serde(skip_serializing_if = "Option::is_none")]
    pub facets: Option<&'a Facets>,
    #[serde(skip_serializing_if = "Vec::is_empty")]
    pub warnings: &'a Vec<crate::ops::WarningHint>,
}

/// Envelope for a full `ListResult`. The engine-meta counters carry the
/// same `_`-prefixed wire keys as [`SearchResultEnvelope`] (and as both
/// surfaces' markdown form) so an agent moving between `memstead list --json`
/// and `memstead search --json` parses one envelope-meta convention. The
/// `_` prefix reads as "engine-meta, not entity content".
#[derive(Serialize)]
pub struct ListResultEnvelope<'a> {
    #[serde(rename = "_total")]
    pub total: usize,
    #[serde(rename = "_returned")]
    pub returned: usize,
    #[serde(rename = "_offset")]
    pub offset: usize,
    #[serde(rename = "_total_tokens")]
    pub total_tokens: usize,
    pub hits: Vec<SearchHitEnvelope<'a>>,
    #[serde(skip_serializing_if = "Vec::is_empty")]
    pub warnings: &'a Vec<crate::ops::WarningHint>,
}

/// Build the structured `memstead_entity` envelope. Identity fields
/// (`_hash`, `id`, `mem`, `type`, `title`, `_stub_kind`) come from the
/// parsed `Entity` and live at the top level. Every schema-declared frontmatter
/// key surfaces under a nested `metadata: {...}` map — its single home.
/// Read a metadata
/// value as `envelope.metadata.<key>`; generic consumers iterate the map
/// without per-type branching. The prior shape additionally hoisted
/// `level`/`stability`/`created_date`/`last_modified` to the top level,
/// serialising those fields twice; that hoist is gone. The read-only
/// identity triple (`mem`/`id`/`type`) is excluded from the nested map
/// — it appears only top-level — and underscore-prefixed internal keys
/// (`_hash`, `_tokens*`, `_mem_schema`, `_stub_*`) live in dedicated
/// top-level slots and never appear inside the nested map. `sections` and
/// `relationships` round-trip the engine's internal IndexMap / Vec
/// shapes verbatim. `_tokens` is computed from the rendered body
/// (filter and opt-in inserts applied) so agents can pre-size before
/// a follow-up `token_budget`-bounded read. `_mem_schema` rides
/// when the workspace pinned a schema for the mem.
///
/// Per-section filtering applies — when `sections_filter` is
/// `Some`, the structured `sections` map carries only the requested
/// keys (matching the markdown projection). The unfiltered-base
/// token cost surfaces as `_tokens_unfiltered_body` so agents can
/// predict the cost of dropping the filter. The name avoids implying a
/// monotonic relationship (`_tokens_unfiltered_body ≥ _tokens`) that the
/// opt-in (`include_relations` / `include_context`) path can invert:
/// opt-in inserts contribute to `_tokens` but not to this baseline. Stub
/// entities ship every key with empty `sections` / `relationships`
/// arrays.
///
/// The structured envelope is the contract for `memstead_entity`:
/// agents read `_hash`, sections, and relations from typed fields
/// rather than string-scraping the markdown frontmatter.
pub fn build_entity_envelope(
    entity: &Entity,
    rendered_body_tokens: usize,
    full_tokens: Option<usize>,
    sections_filter: Option<&[String]>,
    schema_anchor: Option<&str>,
    outgoing_edges: &[crate::store::Edge],
) -> serde_json::Value {
    let mut envelope = serde_json::Map::new();
    envelope.insert(
        "_hash".to_string(),
        serde_json::Value::String(entity.content_hash.clone()),
    );
    envelope.insert(
        "id".to_string(),
        serde_json::Value::String(entity.id.to_string()),
    );
    envelope.insert(
        "mem".to_string(),
        serde_json::Value::String(entity.mem.clone()),
    );
    envelope.insert(
        "type".to_string(),
        serde_json::Value::String(entity.entity_type.clone()),
    );
    // The `# H1` display title. Structural identity like `id`/`mem`/
    // `type`, so it lives top-level next to them; before this slot the
    // structured envelope had no title at all and consumers had to
    // parse the rendered markdown's H1 to recover it.
    envelope.insert(
        "title".to_string(),
        serde_json::Value::String(entity.title.clone()),
    );

    // Metadata has exactly one home on the envelope — the nested
    // `metadata` map. Scalars like `level`/`stability`/`created_date`/
    // `last_modified` are NOT hoisted to the top level; agents read
    // `envelope.metadata.<key>`. The nested map is authoritative because
    // it carries every schema-declared frontmatter key (including
    // type-specific fields a top-level hoist never covered).
    //
    // Identity keys stay top-level and are excluded here so they too
    // appear exactly once: `_hash`, `id`, `mem`, `type` are the
    // entity's structural identity (inserted above), not free-form
    // metadata. `mem`/`id`/`type` is the engine's read-only key triple
    // (`READ_ONLY_METADATA_KEYS`); `_`-prefixed internal keys live in
    // dedicated top-level slots (`_tokens*`, `_mem_schema`, `_stub_*`).
    // Stub entities surface an empty `metadata: {}` so consumers don't
    // branch on its presence.
    let mut metadata = serde_json::Map::new();
    for (key, value) in &entity.metadata {
        if key.starts_with('_')
            || crate::runtime_validator::READ_ONLY_METADATA_KEYS.contains(&key.as_str())
        {
            continue;
        }
        metadata.insert(
            key.clone(),
            serde_json::Value::String(value.to_frontmatter_string()),
        );
    }
    envelope.insert("metadata".to_string(), serde_json::Value::Object(metadata));

    envelope.insert(
        "_tokens".to_string(),
        serde_json::Value::Number(serde_json::Number::from(rendered_body_tokens)),
    );
    if let Some(t) = full_tokens {
        // This measures the unfiltered base body cost without
        // `include_relations` / `include_context` opt-in inserts.
        // `_tokens` may exceed `_tokens_unfiltered_body` when opt-ins
        // are active (the opt-in inserts contribute to `_tokens` but not
        // to this baseline) — the field name avoids implying a monotonic
        // relationship the opt-in path can invert.
        envelope.insert(
            "_tokens_unfiltered_body".to_string(),
            serde_json::Value::Number(serde_json::Number::from(t)),
        );
    }
    if let Some(s) = schema_anchor {
        envelope.insert(
            "_mem_schema".to_string(),
            serde_json::Value::String(s.to_string()),
        );
    }

    if let Some(kind) = &entity.stub_kind {
        envelope.insert(
            "_stub_kind".to_string(),
            serde_json::to_value(kind).unwrap_or(serde_json::Value::Null),
        );
    }

    let mut sections = serde_json::Map::new();
    for (key, content) in &entity.sections {
        if let Some(filter) = sections_filter
            && !filter.iter().any(|f| f == key)
        {
            continue;
        }
        sections.insert(key.clone(), serde_json::Value::String(content.clone()));
    }
    envelope.insert("sections".to_string(), serde_json::Value::Object(sections));

    // Resolve each relationship's `source` label against the store's
    // outgoing-edge index. A hardcoded `"explicit"` would disagree
    // with the stub-adoption
    // response's `incoming[].source` for alias-synthesised
    // REFERENCES edges (and was actively misleading because
    // REFERENCES carries `manual_authoring: forbidden` — no edge of
    // that rel-type can be authored explicitly). The store's
    // `EdgeSource` is the single source of truth; the markdown
    // round-trip (which doesn't encode source) is no longer
    // consulted for this field.
    let resolve_source = |rel: &crate::entity::Relationship| -> &'static str {
        outgoing_edges
            .iter()
            .find(|e| e.rel_type == rel.rel_type && e.target == rel.target)
            .map(|e| match e.source {
                crate::store::EdgeSource::BodyLink => "body_link",
                crate::store::EdgeSource::Hierarchy => "hierarchy",
                crate::store::EdgeSource::Explicit => "explicit",
            })
            .unwrap_or("explicit")
    };
    let relationships = entity
        .relationships
        .iter()
        .map(|rel| {
            let mut obj = serde_json::Map::new();
            obj.insert(
                "rel_type".to_string(),
                serde_json::Value::String(rel.rel_type.clone()),
            );
            obj.insert(
                "target".to_string(),
                serde_json::Value::String(rel.target.to_string()),
            );
            obj.insert(
                "source".to_string(),
                serde_json::Value::String(resolve_source(rel).to_string()),
            );
            if let Some(desc) = rel
                .description
                .as_deref()
                .map(str::trim)
                .filter(|s| !s.is_empty())
            {
                obj.insert(
                    "description".to_string(),
                    serde_json::Value::String(desc.to_string()),
                );
            }
            serde_json::Value::Object(obj)
        })
        .collect();
    envelope.insert(
        "relationships".to_string(),
        serde_json::Value::Array(relationships),
    );

    serde_json::Value::Object(envelope)
}

/// Build a `SearchResultEnvelope` borrowing from `result`.
pub fn build_search_envelope<'a>(
    result: &'a SearchResult,
    offset: usize,
) -> SearchResultEnvelope<'a> {
    SearchResultEnvelope {
        total: result.total,
        returned: result.returned,
        offset,
        total_tokens: result.total_tokens,
        hits: result.hits.iter().map(build_hit_envelope).collect(),
        facets: result.facets.as_ref(),
        warnings: &result.warnings,
    }
}

/// Build a `ListResultEnvelope` borrowing from `result`.
pub fn build_list_envelope(result: &ListResult) -> ListResultEnvelope<'_> {
    ListResultEnvelope {
        total: result.total,
        returned: result.returned,
        offset: result.offset,
        total_tokens: result.total_tokens,
        hits: result.hits.iter().map(build_hit_envelope).collect(),
        warnings: &result.warnings,
    }
}

fn build_hit_envelope(hit: &SearchHit) -> SearchHitEnvelope<'_> {
    let (heading, value) = hit_summary_pair(hit);
    SearchHitEnvelope {
        hit,
        summary_heading: heading,
        summary_value: value,
    }
}

// ---------------------------------------------------------------------------
// Helpers
// ---------------------------------------------------------------------------

/// Build the one-line summary for a search/list hit.
///
/// Resolves the hit's schema and uses its lead section (first required, or
/// first section if none are required) as the label. Never panics — unknown
/// schemas or schemas with no sections fall back to `**Summary**: —`.
fn hit_summary_line(hit: &SearchHit) -> String {
    let (heading, value) = hit_summary_pair(hit);
    format!("**{heading}**: {value}")
}

/// Resolve `(heading, value)` for a hit's summary line — the single source of
/// truth for lead-section lookup. Used by both markdown rendering and the
/// structured-content envelope.
///
/// Prefers the engine-precomputed [`SearchHit::summary`] (resolved against the
/// hit's own mem schema at search time). Falls back to the global
/// `type_by_name` lookup only for hits built outside the search op (FFI/bridge
/// and test fixtures) — that fallback sees only the `default` schema, which is
/// why the engine resolves the pair where the per-mem schema is in hand.
fn hit_summary_pair(hit: &SearchHit) -> (String, String) {
    if let Some(summary) = &hit.summary {
        return (summary.heading.clone(), summary.value.clone());
    }
    summary_pair(type_by_name(&hit.entity_type).as_deref(), &hit.sections)
}

/// Resolve `(heading, value)` given a schema and the hit's section map.
fn summary_pair(
    schema: Option<&TypeDefinition>,
    sections: &HashMap<String, String>,
) -> (String, String) {
    match schema {
        Some(schema) => lead_section_pair(schema, |k| sections.get(k).map(String::as_str)),
        None => ("Summary".to_string(), "".to_string()),
    }
}

/// The lead-section `(heading, value)` for a hit given its resolved schema:
/// the first required section (or the first section when none are required),
/// with its value pulled from `sections`. Returns `("Summary", "—")` when the
/// type declares no sections, and an honest `"—"` value when the lead section
/// is absent/empty in this hit. The single source of truth shared by the
/// render-time fallback ([`summary_pair`]) and the search op, which calls it
/// with each hit's correctly-resolved per-mem schema.
pub(crate) fn lead_section_pair<'a>(
    schema: &TypeDefinition,
    get_section: impl Fn(&str) -> Option<&'a str>,
) -> (String, String) {
    let Some(section) = schema
        .required_sections()
        .next()
        .or(schema.sections.first())
    else {
        return ("Summary".to_string(), "".to_string());
    };
    let value = get_section(section.key.as_str()).unwrap_or("");
    (section.heading.clone(), value.to_string())
}

/// Convert a section key to a display heading via the simple
/// derivation: first char uppercased, underscores → spaces. Used as
/// a fallback when no schema-declared heading is available.
fn section_key_to_heading(key: &str) -> String {
    let mut chars = key.chars();
    match chars.next() {
        None => String::new(),
        Some(c) => {
            let first: String = c.to_uppercase().collect();
            let rest: String = chars.map(|c| if c == '_' { ' ' } else { c }).collect();
            format!("{first}{rest}")
        }
    }
}

/// Resolve the heading for `key` from the type's declared sections;
/// fall back to the key-derivation when the type is unknown or the
/// key is not declared (e.g. the `relationships` virtual surface, or
/// catch-all extra keys). The schema-declared heading is the on-disk
/// truth — the renderer must echo it so rendered text matches the
/// markdown file content.
fn section_heading_for(type_def: Option<&TypeDefinition>, key: &str) -> String {
    type_def
        .and_then(|t| t.sections.iter().find(|s| s.key == key))
        .map(|s| s.heading.clone())
        .unwrap_or_else(|| section_key_to_heading(key))
}

/// Search every built-in schema for `name`, returning the first match.
/// Caches the loaded schema list via `OnceLock` so subsequent renders
/// pay only the HashMap lookup cost.
///
/// Distinct from `memstead_schema::type_by_name`, which is limited to the
/// `default` schema — that helper exists for legacy short-name lookups
/// and is left unchanged here. Custom workspace schemas (not embedded
/// in the binary) still fall through to the key-derivation path.
fn lookup_builtin_type(name: &str) -> Option<Arc<TypeDefinition>> {
    static CACHE: OnceLock<Vec<Arc<Schema>>> = OnceLock::new();
    let schemas =
        CACHE.get_or_init(|| memstead_schema::builtins::load_builtin_schemas().unwrap_or_default());
    for s in schemas {
        if let Some(t) = s.get_type(name) {
            return Some(t);
        }
    }
    None
}

// ---------------------------------------------------------------------------
// Schema introspection rendering
// ---------------------------------------------------------------------------

/// Render the full schema catalog as markdown — built-in default types.
pub fn render_type_catalog_markdown() -> String {
    render_type_catalog_lines(all_types())
}

/// Render the type catalog for an arbitrary loaded [`Schema`].
/// Same shape as [`render_type_catalog_markdown`]; iterates the
/// schema's own types in name order so multi-mem workspaces can
/// describe the schema pinned by the writable mem, not the engine's
/// hard-coded built-in.
pub fn render_type_catalog_markdown_for(schema: &Schema) -> String {
    let mut types: Vec<Arc<TypeDefinition>> = schema.types.values().cloned().collect();
    types.sort_by(|a, b| a.name.as_str().cmp(b.name.as_str()));
    render_type_catalog_lines(types)
}

fn render_type_catalog_lines(types: Vec<Arc<TypeDefinition>>) -> String {
    let mut lines = vec![
        "# Available types".to_string(),
        String::new(),
        "Run `memstead type <name>` to see its metadata fields, sections, relationship types, and writing guidance — over MCP, `memstead_schema` takes the *schema* name and returns every type at once."
            .to_string(),
        String::new(),
    ];
    for schema in types {
        let required_sections = schema.required_sections().count();
        let total_sections = schema.sections.len();
        let metadata_count = schema.metadata_fields.len();
        lines.push(format!(
            "- **{}** — {} sections ({} required), {} metadata fields, staleness {}d",
            schema.name.as_str(),
            total_sections,
            required_sections,
            metadata_count,
            schema.staleness_threshold_days,
        ));
    }
    lines.push(String::new());
    lines.join("\n")
}

/// Render a single type's definition as agent-friendly markdown.
pub fn render_type_info_markdown(schema: &TypeDefinition) -> String {
    let mut lines = Vec::new();
    lines.push(format!("# Type: {}", schema.name.as_str()));
    lines.push(String::new());
    lines.push(format!(
        "Staleness threshold: {} days. Hierarchy: `{}`.",
        schema.staleness_threshold_days, schema.hierarchy_relationship,
    ));
    lines.push(String::new());

    // Metadata fields
    lines.push("## Metadata fields".to_string());
    for field in &schema.metadata_fields {
        lines.push(format!("- {}", describe_metadata_field(field)));
    }
    lines.push(String::new());

    // Sections
    lines.push("## Sections".to_string());
    for section in &schema.sections {
        let req = if section.required {
            "required"
        } else {
            "optional"
        };
        let catch_all = if section.catch_all { ", catch-all" } else { "" };
        lines.push(format!(
            "- **{}** ({req}{catch_all}, search_weight: {:.1})",
            section.key, section.search_weight,
        ));
        for rule in &section.write_rules {
            lines.push(format!("  - Write rule: {rule}"));
        }
    }
    lines.push(String::new());

    // Relationship types
    lines.push("## Relationship types (with edge weights)".to_string());
    for (rel_type, weight) in &schema.edge_weights {
        if rel_type == "_default" {
            continue;
        }
        let mut flags: Vec<&str> = Vec::new();
        if rel_type == &schema.hierarchy_relationship {
            flags.push("hierarchy");
        }
        if schema
            .no_self_loop_relationships
            .iter()
            .any(|r| r == rel_type)
        {
            flags.push("no-self-loop");
        }
        let flag_str = if flags.is_empty() {
            String::new()
        } else {
            format!(" ({})", flags.join(", "))
        };
        lines.push(format!("- **{rel_type}**: {weight}{flag_str}"));
    }
    // Default weight
    if let Some((_, default_weight)) = schema.edge_weights.iter().find(|(n, _)| *n == "_default") {
        lines.push(format!(
            "- _default_ (any other relationship type): {default_weight}"
        ));
    }
    lines.push(String::new());

    // Writing guidance (schema-level)
    if !schema.write_rules.is_empty() {
        lines.push("## Writing guidance".to_string());
        for rule in &schema.write_rules {
            lines.push(format!("- {rule}"));
        }
        lines.push(String::new());
    }

    // System context
    let system_msg = schema.system_message_str();
    if !system_msg.is_empty() {
        lines.push("## System context".to_string());
        lines.push(system_msg.to_string());
        lines.push(String::new());
    }

    // Canonical exemplar (agent-trust plan 09) — the engine-validated
    // few-shot entity, rendered in the mem markdown shape. The CLI's
    // full-depth type view matches `memstead_schema verbosity: full`.
    if let Some(ex) = &schema.exemplar {
        lines.push("## Exemplar (engine-validated)".to_string());
        lines.push(String::new());
        lines.push(format!("Title: {}", ex.title));
        if !ex.metadata.is_empty() {
            lines.push("Metadata:".to_string());
            for (k, v) in &ex.metadata {
                lines.push(format!("- {k}: {v}"));
            }
        }
        for (key, body) in &ex.sections {
            let heading = schema
                .section(key)
                .map(|s| s.heading.clone())
                .unwrap_or_else(|| key.clone());
            lines.push(format!("### {heading}"));
            lines.push(body.clone());
        }
        if !ex.relations.is_empty() {
            lines.push("Relations (placeholder targets):".to_string());
            for r in &ex.relations {
                match &r.description {
                    Some(d) => lines.push(format!("- {}{}{d}", r.rel_type, r.to)),
                    None => lines.push(format!("- {}{}", r.rel_type, r.to)),
                }
            }
        }
        lines.push(String::new());
    }

    lines.join("\n")
}

/// Render a [`PerEdgeDescription`] to its wire literal — bit-identical to
/// what the schema YAML accepts so consumers can echo the value back
/// without case fiddling. `forbidden` (the default) is emitted explicitly
/// rather than omitted so a schema without an explicit declaration still
/// surfaces the resolved posture on the wire.
pub fn per_edge_description_str(p: PerEdgeDescription) -> &'static str {
    match p {
        PerEdgeDescription::Forbidden => "forbidden",
        PerEdgeDescription::Optional => "optional",
        PerEdgeDescription::Required => "required",
    }
}

/// Stable wire string for the `manual_authoring` posture.
pub fn manual_authoring_str(p: ManualAuthoring) -> &'static str {
    match p {
        ManualAuthoring::Allow => "allow",
        ManualAuthoring::Warn => "warn",
        ManualAuthoring::Forbidden => "forbidden",
    }
}

/// Verbosity selector for [`build_schema_payload`].
///
/// `Full` is the complete payload — every description, `when_to_use`,
/// write-rule, and writing-guidance string. `Lite` drops that long-form
/// prose and returns a structural skeleton: entity-type names with their
/// section keys and metadata-field shapes, relationship names with their
/// allowed endpoints. The skeleton keeps every *flag* an agent needs to
/// author a legal write — the alias-model pointer, required-section and
/// required-field markers, endpoint constraints, the manual-authoring
/// posture, the `acyclic` flag, and the per-edge-description posture — so
/// a lite caller can plan a write without round-tripping to full and
/// without walking into a write-time refusal. Full and lite emit the two
/// heavy arrays under *distinct keys* (`types` / `relationships` vs.
/// `types_summary` / `relationships_summary`), so a consumer decodes by
/// key presence rather than by branching on the request shape.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
pub enum SchemaVerbosity {
    #[default]
    Full,
    Lite,
}

impl SchemaVerbosity {
    /// Parse the wire token (`"full"` / `"lite"`). Returns `None` for an
    /// unrecognized token so the calling surface can raise a typed error
    /// naming the bad value rather than silently defaulting. An absent
    /// parameter maps to `Full` at the call site, not here.
    pub fn from_wire(s: &str) -> Option<Self> {
        match s {
            "full" => Some(Self::Full),
            "lite" => Some(Self::Lite),
            _ => None,
        }
    }

    /// The wire token for this verbosity.
    pub fn as_wire(self) -> &'static str {
        match self {
            Self::Full => "full",
            Self::Lite => "lite",
        }
    }
}

/// Trust origin of a schema (or the mem that pins it), decided at
/// adopt/write time and reported — never re-derived — on the read path.
///
/// `FirstParty` is an engine built-in or a schema authored/explicitly
/// trusted in this workspace. Its prose-instruction fields
/// (`system_context`, `write_rules`, `writing_guidance`, `when_to_use`,
/// prose `description`, `default_writing_guidance`) guide *authoring* in
/// this workspace and are served in full.
///
/// `ThirdParty` is a schema that arrived from outside this workspace
/// (registry-installed or adopted from a foreign folder/clone) and has
/// not been explicitly trusted. Memstead's value proposition pulls a
/// mem's schema directly into a consuming agent's context, where the
/// schema's free-text fields are framed *as instructions* ("System
/// context", "Writing guidance"). A third-party schema is therefore
/// served structural-only: [`build_schema_payload`] forces the
/// [`SchemaVerbosity::Lite`] skeleton regardless of the requested
/// verbosity, omitting every prose-instruction field. This is lossless
/// for the legitimate use case — the omitted fields only guide writing,
/// and a write never targets a foreign mem.
///
/// The class is unforgeable by a publisher: it is decided by *how* the
/// schema entered the workspace, not by any content the schema carries.
/// An unknown/ambiguous origin classifies `ThirdParty` — the safe
/// default (a stranger's prose is never served as first-party
/// instructions on the strength of a missing label).
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
pub enum OriginClass {
    /// Engine built-in, or authored/explicitly trusted in this workspace.
    FirstParty,
    /// Arrived from outside this workspace and not explicitly trusted.
    /// The safe default for an unlabelled/ambiguous origin.
    #[default]
    ThirdParty,
}

impl OriginClass {
    /// The wire token for this origin (`"first-party"` / `"third-party"`),
    /// emitted on every schema read so a consuming host can quarantine
    /// non-first-party content.
    pub fn as_wire(self) -> &'static str {
        match self {
            Self::FirstParty => "first-party",
            Self::ThirdParty => "third-party",
        }
    }

    /// Whether this origin must have its schema served structural-only
    /// (prose-instruction fields omitted) on the read path.
    pub fn is_third_party(self) -> bool {
        matches!(self, Self::ThirdParty)
    }
}

/// Build the transport-neutral, rmcp-free JSON payload for a schema read
/// (`memstead_schema`). Shared by the MCP server, the HTTP surface, and
/// the filesystem-mem MCP flavour so every surface emits identical
/// schema-read bytes from one source. `used_by` lists the writable mems
/// whose pinned schema resolves to this one; `verbosity` toggles the full
/// payload versus the lightweight skeleton (see [`SchemaVerbosity`]).
///
/// `origin` ([`OriginClass`]) is reported on the wire as `origin` and
/// governs de-framing: a [`OriginClass::ThirdParty`] schema is served
/// structural-only — the requested `verbosity` is overridden to
/// [`SchemaVerbosity::Lite`] so none of its prose-instruction fields
/// (`system_context`, `write_rules`, `writing_guidance`, `when_to_use`,
/// prose `description`, `default_writing_guidance`) reach a consuming
/// agent as instructions. A `full`-verbosity request on a third-party
/// schema therefore still omits them — the override is one-directional.
/// Append a section's format declaration (plan 08) to its rendered
/// object — only the declared keys, so undeclared sections keep their
/// exact pre-plan shape. `format_severity` renders whenever a
/// `content` declaration exists (the default `block` is a legality
/// fact, not noise).
fn append_section_format(
    obj: &mut serde_json::Map<String, serde_json::Value>,
    s: &memstead_schema::SectionDef,
) {
    if let Some(content) = &s.content {
        obj.insert("content".into(), serde_json::json!(content));
        obj.insert(
            "format_severity".into(),
            serde_json::json!(s.format_severity),
        );
    }
    if let Some(pattern) = &s.item_pattern {
        obj.insert("item_pattern".into(), serde_json::json!(pattern));
    }
    if let Some(table) = &s.table {
        obj.insert("table".into(), serde_json::json!(table));
    }
    if let Some(example) = &s.example {
        obj.insert("example".into(), serde_json::json!(example));
    }
}

pub fn build_schema_payload(
    schema: &Arc<Schema>,
    used_by: Vec<String>,
    verbosity: SchemaVerbosity,
    origin: OriginClass,
) -> serde_json::Value {
    let manifest = &schema.manifest;
    // De-frame third-party schemas: their prose-instruction fields only
    // guide authoring (which never targets a foreign mem), so omitting
    // them is lossless — and serving them would place a stranger's
    // free-text in the consuming agent's instruction context. The Lite
    // skeleton keeps every structural flag an agent needs to understand
    // and query the mem. The override is one-directional: a `full`
    // request cannot re-admit the prose for a third-party schema.
    let verbosity = if origin.is_third_party() {
        SchemaVerbosity::Lite
    } else {
        verbosity
    };

    // `_default` is the schema's internal weight-fallback knob — it
    // sets the edge weight every `_default`-less rel-type inherits and
    // is *not* a usable rel-type on `memstead_relate` (the relate path
    // rejects it with `INVALID_REL_TYPE`). Surfacing it in the agent-
    // facing vocabulary cost one round-trip per
    // session as agents tried it and learned the asymmetry by trial,
    // so it is suppressed here: the schema response advertises only
    // the rel-types `memstead_relate` actually accepts. Schemas that
    // declare `_default` for weight purposes are unaffected — the
    // engine still consults it for `edge_weight` fallback.
    let relationships: Vec<serde_json::Value> = manifest
        .relationships
        .definitions
        .iter()
        .filter(|d| d.name != "_default")
        .map(|d| {
            // Surface the `acyclic` flag so agents can predict cycle-check
            // refusal from introspection without trial-and-error.
            // Combined with each type's `no_self_loop_relationships`
            // list (below), the schema response fully describes the
            // self-loop / long-cycle gates.
            //
            // Surface the `manual_authoring` posture so agents see at
            // introspection time which rel-types refuse explicit
            // `memstead_relate` (forbidden), warn softly (warn), or
            // admit explicit authoring (allow, default).
            //
            // Surface the source/target type pinning declared on the
            // schema's `RelationshipDefinition` so agents can pre-filter
            // rel-types for their `(from_type, to_type)` pair from
            // introspection instead of trial-and-error against
            // `INVALID_REL_SHAPE`. Field names mirror the
            // `INVALID_REL_SHAPE` `details.allowed_source_types` /
            // `details.allowed_target_types` payload so the agent
            // learns the contract once. Empty arrays = "any type
            // admitted" (no pinning).
            let mut o = serde_json::json!({
                "name": d.name,
                "description": d.description,
                "when_to_use": d.when_to_use,
                "default_weight": d.default_weight,
                "acyclic": d.acyclic,
                "per_edge_description": per_edge_description_str(d.per_edge_description),
                "manual_authoring": manual_authoring_str(d.manual_authoring),
                "allowed_sources": d.source_types,
                "allowed_targets": d.target_types,
            });
            // Derivation declaration (agent-trust plan 12) — a
            // behaviour-bearing flag (baseline recording, the
            // stale_derivations axis, duplicate-add re-baseline), so
            // it must be visible at introspection time. Emitted only
            // when true so undeclared schemas keep their bytes.
            if d.derivation {
                o["derivation"] = serde_json::json!(true);
            }
            o
        })
        .collect();

    // Outbound cross-mem vocabulary, one entry per target schema.
    // Same shape as the YAML — `{ to_schema, definitions: [...] }` —
    // so consumers can decode the section symmetrically with the
    // intra-mem `relationships` array. `_default` filtering mirrors
    // the intra-mem block; the rest of the per-definition shape is
    // identical so a single decoder handles both.
    let cross_mem_relationships: Vec<serde_json::Value> = manifest
        .cross_mem_relationships
        .iter()
        .map(|entry| {
            let definitions: Vec<serde_json::Value> = entry
                .definitions
                .iter()
                .filter(|d| d.name != "_default")
                .map(|d| {
                    serde_json::json!({
                        "name": d.name,
                        "description": d.description,
                        "when_to_use": d.when_to_use,
                        "default_weight": d.default_weight,
                        "source_types": d.source_types,
                        "target_types": d.target_types,
                        "per_edge_description": per_edge_description_str(d.per_edge_description),
                    })
                })
                .collect();
            serde_json::json!({
                "to_schema": entry.to_schema,
                "definitions": definitions,
            })
        })
        .collect();

    // Iterate type names in manifest-declared order so the output is
    // deterministic and matches the schema author's intent.
    let types_full: Vec<serde_json::Value> = manifest
        .types
        .iter()
        .filter_map(|name| schema.types.get(name.as_str()).map(|td| (name, td)))
        .map(|(_, td)| {
            let sections: Vec<serde_json::Value> = td
                .sections
                .iter()
                .map(|s| {
                    let mut obj = serde_json::json!({
                        "key": s.key,
                        "heading": s.heading,
                        "required": s.required,
                        "write_rules": s.write_rules,
                    });
                    // Section-format declarations (plan 08) — a
                    // legality condition, so it must never be
                    // invisible in the schema response (rendered at
                    // BOTH verbosity levels via the lite projection
                    // below).
                    append_section_format(obj.as_object_mut().unwrap(), s);
                    obj
                })
                .collect();

            let fields: Vec<serde_json::Value> = td
                .metadata_fields
                .iter()
                .map(|f| {
                    let mut obj = serde_json::json!({
                        "name": f.key,
                        "description": f.description,
                        "required": f.is_required(),
                    });
                    if let Some(enum_values) = &f.enum_values {
                        obj.as_object_mut()
                            .unwrap()
                            .insert("enum".into(), serde_json::json!(enum_values));
                    }
                    // Surface schema-declared `default_value` so agents
                    // see what the create path fills in when a required
                    // field is omitted. Without this, the engine appears
                    // to silently default — `priority: mid` on a
                    // `coverage_gap` would land with no schema-side
                    // explanation of where the value came from.
                    if let Some(default) = &f.default_value {
                        obj.as_object_mut()
                            .unwrap()
                            .insert("default".into(), serde_json::json!(default));
                    }
                    // Surface the `filterable` posture so an agent constructs
                    // valid `filters` / `range_filters` from the schema body
                    // in one shot. Always present: `"equality"` accepts
                    // `filters`, `"range"` accepts `range_filters`, `null`
                    // means not filterable.
                    obj.as_object_mut().unwrap().insert(
                        "filterable".into(),
                        match f.filterable.as_wire_str() {
                            Some(s) => serde_json::json!(s),
                            None => serde_json::Value::Null,
                        },
                    );
                    obj
                })
                .collect();

            // Expose the per-type `no_self_loop_relationships` list so agents
            // can predict self-loop refusal. The engine refuses
            // `memstead_relate type=R from=X(type=T) to=X` whenever R
            // appears here, independent of R's `acyclic` flag.
            //
            // `required_outgoing` is the only declared legality condition
            // on an entity's outgoing edges: each block lists the
            // relationship-name alternatives and the cardinality bound,
            // in declaration order. Always present — a type with no
            // blocks emits an empty list, because an absent key would
            // read as "unknown" and send agents back to the authoring
            // YAML. Cardinality is rendered exactly as declared
            // (`at_least_one` — an open upper bound stays open, never
            // normalised into a number).
            let required_outgoing: Vec<serde_json::Value> = td
                .required_outgoing
                .iter()
                .map(|block| {
                    serde_json::json!({
                        "relationships": block.relationships,
                        "cardinality": block.cardinality.to_string(),
                        "severity": block.severity,
                    })
                })
                .collect();

            // Declared `constraints` — like `required_outgoing`, a
            // legality/health condition that must never be invisible
            // in the schema response (a hidden legality condition is
            // a defect class of its own). Always present, empty list
            // for a type declaring none; each entry restates the
            // declaration with its `severity` (`warn` = health
            // finding, `block` = write-time refusal), in declaration
            // order, at BOTH verbosity levels.
            let constraints: Vec<serde_json::Value> = td
                .constraints
                .iter()
                .map(|c| match c {
                    memstead_schema::ConstraintDef::RequiresWhen {
                        field,
                        when_field,
                        when_value,
                        severity,
                    } => serde_json::json!({
                        "kind": "requires_when",
                        "field": field,
                        "when_field": when_field,
                        "when_value": when_value,
                        "severity": severity,
                    }),
                    memstead_schema::ConstraintDef::Unique { fields, severity } => {
                        serde_json::json!({
                            "kind": "unique",
                            "fields": fields,
                            "severity": severity,
                        })
                    }
                    memstead_schema::ConstraintDef::EnumFromNeighbour {
                        field,
                        rel_type,
                        section,
                        severity,
                    } => serde_json::json!({
                        "kind": "enum_from_neighbour",
                        "field": field,
                        "rel_type": rel_type,
                        "section": section,
                        "severity": severity,
                    }),
                    memstead_schema::ConstraintDef::StatusPropagation {
                        field,
                        value,
                        rel_type,
                        direction,
                        severity,
                    } => serde_json::json!({
                        "kind": "status_propagation",
                        "field": field,
                        "value": value,
                        "rel_type": rel_type,
                        "direction": direction,
                        "severity": severity,
                    }),
                })
                .collect();
            let mut obj = serde_json::json!({
                "name": td.name,
                "description": td.description,
                "when_to_use": td.when_to_use,
                "sections": sections,
                "fields": fields,
                "writing_guidance": td.write_rules,
                "system_context": td.system_message_str(),
                "staleness_threshold_days": td.staleness_threshold_days,
                "no_self_loop_relationships": td.no_self_loop_relationships,
                "required_outgoing": required_outgoing,
                "constraints": constraints,
            });
            // Leaf declaration — a legality-relevant fact an agent
            // planning writes must see; emitted only when true so
            // undeclared schemas keep their payload bytes unchanged.
            if td.leaf {
                obj["leaf"] = serde_json::json!(true);
            }
            // The type's canonical exemplar (agent-trust plan 09) —
            // engine-validated at install/seal, so what it teaches is
            // exactly what the validator accepts. Rides FULL mode only
            // (this array); the lite projection below drops it by
            // allowlist, so the per-session skeleton stays unchanged.
            // Relation targets are placeholder slugs by contract.
            if let Some(ex) = &td.exemplar {
                let relations: Vec<serde_json::Value> = ex
                    .relations
                    .iter()
                    .map(|r| {
                        let mut o = serde_json::json!({
                            "to": r.to,
                            "type": r.rel_type,
                        });
                        if let Some(d) = &r.description {
                            o["description"] = serde_json::json!(d);
                        }
                        o
                    })
                    .collect();
                obj["exemplar"] = serde_json::json!({
                    "title": ex.title,
                    "metadata": ex.metadata,
                    "sections": ex.sections,
                    "relations": relations,
                });
            }
            obj
        })
        .collect();

    let mode = match manifest.relationships.mode {
        RelationshipMode::Strict => "strict",
        RelationshipMode::Open => "open",
    };

    let full = verbosity == SchemaVerbosity::Full;

    // Scalar fields present in BOTH modes. `ref` names the schema even
    // in the lite skeleton; `relationship_mode`, `community`, and
    // `used_by` are bounded and cheap.
    let mut payload = serde_json::json!({
        "ref": format!("{}@{}", manifest.name, schema.version),
        "relationship_mode": mode,
        "community": {
            "resolution": manifest.community.resolution,
            "seed": manifest.community.seed,
        },
        "used_by": used_by,
        // Machine-readable trust origin, present in both modes. A
        // consuming host reads this to decide whether to treat the
        // schema as workspace instructions (`first-party`) or quarantine
        // it as untrusted (`third-party`). Additive — a client that
        // ignores it still decodes the rest of the payload unchanged.
        "origin": origin.as_wire(),
    });
    let obj = payload.as_object_mut().unwrap();

    // Schema-level prose — FULL mode only. An agent that asked for the
    // lite skeleton is orienting on structure; the human-readable
    // `description` / `when_to_use` is exactly the weight the lite cut
    // exists to drop. The schema `ref` still identifies the schema.
    if full {
        obj.insert(
            "description".into(),
            serde_json::Value::String(manifest.description.clone()),
        );
        obj.insert(
            "when_to_use".into(),
            serde_json::Value::String(manifest.when_to_use.clone()),
        );
        // Schema-level `system_message`, wire-named `system_context` to
        // match the per-type key. Without this the manifest's voice/
        // posture prose is unreachable from the agent surface entirely
        // (its only other consumer is the `memstead type` CLI markdown).
        // Omitted when undeclared so existing schemas render unchanged.
        if let Some(msg) = &manifest.system_message {
            obj.insert(
                "system_context".into(),
                serde_json::Value::String(msg.clone()),
            );
        }
    }

    // One-line effect note for the per-type `no_self_loop_relationships`
    // arrays — present in BOTH modes, right where the field is read.
    // The retired `propagating_relationships` name misled outside
    // schema authors into declaring impact propagation; the renamed
    // key states the single functional effect. Top-level (not
    // per-type) so the note costs one key, not one per type.
    obj.insert(
        "no_self_loop_relationships_effect".into(),
        serde_json::Value::String(
            "Per-type `no_self_loop_relationships` governs exactly one behaviour: \
             memstead_relate refuses a self-loop (from == to) on a rel-type the \
             source type lists here. It does not propagate impact, imply an \
             evidence obligation, or have any other effect (the name says it \
             all). To declare real impact propagation, use the \
             `status_propagation` constraint (`constraints:` on the type), which \
             taints dependents of a terminal status value via a named rel-type \
             and direction and surfaces them as health findings."
                .to_string(),
        ),
    );

    // Schema-level `alias_target_rel_type` pointer — names the rel-type
    // that body wiki-links `[[target]]` auto-emit through the
    // alias-synthesis pass. Present in BOTH modes: it governs whether an
    // unbacked wiki-link bakes an edge or refuses with
    // `WIKILINK_WITHOUT_RELATION`, so dropping it from lite would leave a
    // caller one round-trip from a write-time refusal. Schemas omitting
    // the field render with the key absent so existing agents don't see
    // a noisy `null`.
    if let Some(target) = &manifest.alias_target_rel_type {
        obj.insert(
            "alias_target_rel_type".into(),
            serde_json::Value::String(target.clone()),
        );
    }

    // Surface `default_writing_guidance` at the top level so plugin-side
    // resolvers can concatenate the schema-generic prose with per-mem
    // additions without parsing schema YAML themselves. FULL mode only —
    // it is guidance prose. Field-by-field omission — a schema with
    // neither `avoid` nor `goal` declared emits no key at all (both
    // `Option<String>` inside an `Option<DefaultWritingGuidance>`).
    if full && let Some(dwg) = &manifest.default_writing_guidance {
        let mut block = serde_json::Map::new();
        if let Some(avoid) = &dwg.avoid {
            block.insert("avoid".into(), serde_json::Value::String(avoid.clone()));
        }
        if let Some(goal) = &dwg.goal {
            block.insert("goal".into(), serde_json::Value::String(goal.clone()));
        }
        if !block.is_empty() {
            obj.insert(
                "default_writing_guidance".into(),
                serde_json::Value::Object(block),
            );
        }
    }

    if full {
        obj.insert(
            "relationships".into(),
            serde_json::Value::Array(relationships),
        );
        // Only surface the cross-mem block when the schema declares
        // outbound entries — keeps the response minimal for schemas
        // that don't speak cross-mem vocabulary.
        if !cross_mem_relationships.is_empty() {
            obj.insert(
                "cross_mem_relationships".into(),
                serde_json::Value::Array(cross_mem_relationships),
            );
        }
        obj.insert("types".into(), serde_json::Value::Array(types_full));
    } else {
        // Lite relationship form: name + endpoint constraints
        // (`allowed_sources`/`allowed_targets`) + manual-authoring
        // posture + `acyclic` + per-edge-description posture — every flag
        // that governs a relate-path refusal (`INVALID_REL_SHAPE`,
        // `RELATION_MANUAL_AUTHORING_FORBIDDEN`, cycle check,
        // `MISSING_REQUIRED_DESCRIPTION`) — with the description /
        // when_to_use / weight prose dropped. The ~42 rel-types carry the
        // bulk of the bytes, so this is the load-bearing half of the cut.
        // Projected from the rich array so each field value has one source.
        let relationships_summary: Vec<serde_json::Value> = relationships
            .iter()
            .map(|r| {
                let mut o = serde_json::json!({
                    "name": r["name"],
                    "allowed_sources": r["allowed_sources"],
                    "allowed_targets": r["allowed_targets"],
                    "manual_authoring": r["manual_authoring"],
                    "acyclic": r["acyclic"],
                    "per_edge_description": r["per_edge_description"],
                });
                if r.get("derivation") == Some(&serde_json::json!(true)) {
                    o["derivation"] = serde_json::json!(true);
                }
                o
            })
            .collect();
        obj.insert(
            "relationships_summary".into(),
            serde_json::Value::Array(relationships_summary),
        );

        // Lite cross-mem form mirrors the intra-mem lite shape:
        // name + endpoint pinning, prose dropped. Same emit-when-non-empty
        // rule as full mode.
        if !cross_mem_relationships.is_empty() {
            let cross_summary: Vec<serde_json::Value> = cross_mem_relationships
                .iter()
                .map(|e| {
                    let definitions: Vec<serde_json::Value> = e["definitions"]
                        .as_array()
                        .map(|defs| {
                            defs.iter()
                                .map(|d| {
                                    serde_json::json!({
                                        "name": d["name"],
                                        "source_types": d["source_types"],
                                        "target_types": d["target_types"],
                                    })
                                })
                                .collect()
                        })
                        .unwrap_or_default();
                    serde_json::json!({
                        "to_schema": e["to_schema"],
                        "definitions": definitions,
                    })
                })
                .collect();
            obj.insert(
                "cross_mem_relationships_summary".into(),
                serde_json::Value::Array(cross_summary),
            );
        }

        // Lite entity-type form: name + section keys (each with its
        // `required` marker) + metadata-field shapes (name, required,
        // `enum`, `default`) + `no_self_loop_relationships` +
        // `required_outgoing` — the structural minimum to author a
        // legal write — with the type/section prose (descriptions,
        // write_rules, writing_guidance, system_context) dropped.
        // `no_self_loop_relationships` rides along because it governs
        // the self-loop relate refusal (relate R X→X when type T lists
        // R), one of the refusals the lite view must let an
        // agent avoid. `required_outgoing` rides along because it is
        // the only declared legality condition on outgoing edges —
        // dropping it would make "enough to plan a legal write" false.
        // Projected from the rich array.
        let types_summary: Vec<serde_json::Value> = types_full
            .iter()
            .map(|t| {
                let sections: Vec<serde_json::Value> = t["sections"]
                    .as_array()
                    .map(|secs| {
                        secs.iter()
                            .map(|s| {
                                let mut o = serde_json::Map::new();
                                o.insert("key".into(), s["key"].clone());
                                o.insert("required".into(), s["required"].clone());
                                // The format declaration is a
                                // legality condition — the lite
                                // skeleton carries it in full.
                                for k in [
                                    "content",
                                    "item_pattern",
                                    "table",
                                    "example",
                                    "format_severity",
                                ] {
                                    if let Some(v) = s.get(k) {
                                        o.insert(k.into(), v.clone());
                                    }
                                }
                                serde_json::Value::Object(o)
                            })
                            .collect()
                    })
                    .unwrap_or_default();
                let fields: Vec<serde_json::Value> = t["fields"]
                    .as_array()
                    .map(|fs| {
                        fs.iter()
                            .map(|f| {
                                let mut o = serde_json::Map::new();
                                o.insert("name".into(), f["name"].clone());
                                o.insert("required".into(), f["required"].clone());
                                if let Some(e) = f.get("enum") {
                                    o.insert("enum".into(), e.clone());
                                }
                                if let Some(d) = f.get("default") {
                                    o.insert("default".into(), d.clone());
                                }
                                serde_json::Value::Object(o)
                            })
                            .collect()
                    })
                    .unwrap_or_default();
                let mut o = serde_json::json!({
                    "name": t["name"],
                    "sections": sections,
                    "fields": fields,
                    "no_self_loop_relationships": t["no_self_loop_relationships"],
                    "required_outgoing": t["required_outgoing"],
                    "constraints": t["constraints"],
                });
                // Leaf declaration rides the lite skeleton too — it is
                // a legality-relevant per-type fact.
                if t.get("leaf") == Some(&serde_json::json!(true)) {
                    o["leaf"] = serde_json::json!(true);
                }
                o
            })
            .collect();
        obj.insert(
            "types_summary".into(),
            serde_json::Value::Array(types_summary),
        );
    }

    payload
}

/// Format a metadata field definition as a single bullet line.
fn describe_metadata_field(field: &memstead_schema::MetadataFieldDef) -> String {
    let type_str = match field.field_type {
        FieldType::String => "String",
        FieldType::Number => "Number",
        FieldType::Date => "Date",
        FieldType::Boolean => "Boolean",
    };

    let mut flags: Vec<&str> = Vec::new();
    if !field.is_required() {
        flags.push("optional");
    } else {
        flags.push("required");
    }
    if field.init_timestamp {
        flags.push("auto-init");
    }
    if field.auto_timestamp {
        flags.push("auto-update");
    }
    match field.serialization {
        Serialization::CsvArray => flags.push("csv array"),
        Serialization::OmitWhenFalsy => flags.push("omit when falsy"),
        Serialization::Default => {}
    }

    let mut extras: Vec<String> = Vec::new();
    if let Some(values) = &field.enum_values {
        extras.push(format!("enum: {}", values.join(", ")));
    }
    if let Some(default) = &field.default_value {
        extras.push(format!("default: {default}"));
    }
    let filterable_str = match field.filterable {
        Filterable::None => None,
        Filterable::Equality => Some("filterable: equality"),
        Filterable::Range => Some("filterable: range"),
    };
    if let Some(f) = filterable_str {
        extras.push(f.to_string());
    }

    let extras_str = if extras.is_empty() {
        String::new()
    } else {
        format!("{}", extras.join(""))
    };

    format!(
        "**{key}**: {type_str} ({flags}){extras_str}",
        key = field.key,
        flags = flags.join(", "),
    )
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::{Entity, EntityId, ListResult, SearchResult};
    use indexmap::IndexMap;
    use std::collections::HashMap;

    fn make_hit(id: &str, title: &str, entity_type: &str, sections: &[(&str, &str)]) -> SearchHit {
        SearchHit {
            id: EntityId(id.to_string()),
            last_modified: None,
            title: title.to_string(),
            mem: id.split("--").next().unwrap_or("").to_string(),
            entity_type: entity_type.to_string(),
            stub: false,
            score: 1.0,
            tokens: 10,
            snippet: None,
            sections: sections
                .iter()
                .map(|(k, v)| (k.to_string(), v.to_string()))
                .collect(),
            score_breakdown: None,
            matched_terms: None,
            expansion: None,
            // Test fixtures exercise the render-time fallback (default-schema
            // lookup); the engine-precomputed path is set in the search op.
            summary: None,
        }
    }

    fn search_result(hits: Vec<SearchHit>) -> SearchResult {
        let returned = hits.len();
        let total_tokens = hits.iter().map(|h| h.tokens).sum();
        SearchResult {
            total: returned,
            returned,
            offset: 0,
            total_tokens,
            hits,
            facets: None,
            warnings: vec![],
        }
    }

    fn list_result(hits: Vec<SearchHit>) -> ListResult {
        let returned = hits.len();
        ListResult {
            total: returned,
            returned,
            offset: 0,
            total_tokens: hits.iter().map(|h| h.tokens).sum(),
            hits,
            warnings: vec![],
        }
    }

    fn test_entity() -> Entity {
        Entity {
            id: EntityId("specs--test-entity".to_string()),
            title: "Test Entity".to_string(),
            entity_type: "spec".to_string(),
            mem: "specs".to_string(),
            file_path: "test-entity.md".to_string(),
            metadata: IndexMap::new(),
            sections: IndexMap::from([
                ("identity".to_string(), "A test entity for unit tests.".to_string()),
                ("purpose".to_string(), "Validates render logic.".to_string()),
                ("specifies".to_string(), "Long section content that adds significant token weight to the full entity estimate.".to_string()),
            ]),
            relationships: vec![],
            content_hash: "abc123".to_string(),
            stub: false,
            stub_kind: None,
            heading_spans: std::collections::HashMap::new(),
            raw_section_headings: Vec::new(),
        }
    }

    #[test]
    fn section_key_to_heading_basic() {
        assert_eq!(section_key_to_heading("identity"), "Identity");
        assert_eq!(section_key_to_heading("current_state"), "Current state");
    }

    #[test]
    fn render_uses_schema_declared_heading_for_non_trivial_casing() {
        // The `ingest.inconsistency` schema declares `claim_a` with
        // heading "Claim A" — the simple key-derivation would produce
        // "Claim a", which would disagree with the on-disk markdown
        // emitted by the generator. The renderer must echo the
        // schema's declared heading verbatim.
        let mut sections: IndexMap<String, String> = IndexMap::new();
        sections.insert("claim_a".to_string(), "Body A.".to_string());
        sections.insert("claim_b".to_string(), "Body B.".to_string());

        let entity = Entity {
            id: EntityId("ingest--example".to_string()),
            title: "Example".to_string(),
            entity_type: "inconsistency".to_string(),
            mem: "ingest".to_string(),
            file_path: "example.md".to_string(),
            metadata: IndexMap::new(),
            sections,
            relationships: vec![],
            content_hash: "h".to_string(),
            stub: false,
            stub_kind: None,
            heading_spans: std::collections::HashMap::new(),
            raw_section_headings: Vec::new(),
        };

        let md = render_entity_markdown(&entity, None);
        assert!(
            md.contains("## Claim A"),
            "expected schema-declared `## Claim A` heading; got:\n{md}"
        );
        assert!(
            md.contains("## Claim B"),
            "expected schema-declared `## Claim B` heading; got:\n{md}"
        );
        // The naive derivation would have produced lower-case `a`/`b`.
        assert!(
            !md.contains("## Claim a"),
            "renderer must not fall back to key-derivation when the \
             schema declares a heading; got:\n{md}"
        );
    }

    #[test]
    fn render_falls_back_to_key_derivation_for_unknown_types() {
        // When the entity_type is not in any built-in schema (custom
        // workspace schemas, legacy entities), the renderer falls back
        // to the simple key→heading derivation.
        let mut sections: IndexMap<String, String> = IndexMap::new();
        sections.insert("identity".to_string(), "body".to_string());

        let entity = Entity {
            id: EntityId("custom--example".to_string()),
            title: "Example".to_string(),
            entity_type: "not-a-builtin-type".to_string(),
            mem: "custom".to_string(),
            file_path: "example.md".to_string(),
            metadata: IndexMap::new(),
            sections,
            relationships: vec![],
            content_hash: "h".to_string(),
            stub: false,
            stub_kind: None,
            heading_spans: std::collections::HashMap::new(),
            raw_section_headings: Vec::new(),
        };

        let md = render_entity_markdown(&entity, None);
        assert!(
            md.contains("## Identity"),
            "fallback derivation must produce `## Identity`; got:\n{md}"
        );
    }

    // Regression lock for deterministic section order. The invariant:
    // render_entity_body walks `entity.sections` in IndexMap insertion order,
    // so whatever order the parser/caller inserts is what ships. The parser
    // inserts in schema-declared order; this test deliberately inserts in
    // REVERSE schema order to prove the renderer honors insertion order
    // (not the schema's declared order directly).
    #[test]
    fn render_entity_sections_follow_indexmap_insertion_order() {
        let mut sections: IndexMap<String, String> = IndexMap::new();
        sections.insert("specifies".to_string(), "S content.".to_string());
        sections.insert("purpose".to_string(), "P content.".to_string());
        sections.insert("identity".to_string(), "I content.".to_string());

        let entity = Entity {
            id: EntityId("specs--order-test".to_string()),
            title: "Order Test".to_string(),
            entity_type: "spec".to_string(),
            mem: "specs".to_string(),
            file_path: "order-test.md".to_string(),
            metadata: IndexMap::new(),
            sections,
            relationships: vec![],
            content_hash: "abc123".to_string(),
            stub: false,
            stub_kind: None,
            heading_spans: std::collections::HashMap::new(),
            raw_section_headings: Vec::new(),
        };

        let md = render_entity_markdown(&entity, None);
        let specifies_pos = md.find("## Specifies").expect("## Specifies must appear");
        let purpose_pos = md.find("## Purpose").expect("## Purpose must appear");
        let identity_pos = md.find("## Identity").expect("## Identity must appear");

        assert!(
            specifies_pos < purpose_pos,
            "Specifies (inserted first) must render before Purpose; got:\n{md}"
        );
        assert!(
            purpose_pos < identity_pos,
            "Purpose (inserted second) must render before Identity; got:\n{md}"
        );
    }

    /// `_tokens_unfiltered_body` rides only when a section filter
    /// narrows the rendered output; it carries the unfiltered-base
    /// cost so agents can predict the cost of dropping the filter. The
    /// name avoids a monotonic-relationship implication
    /// that the opt-in path could invert.
    #[test]
    fn tokens_reflect_filtered_output() {
        let entity = test_entity();

        // Full render — no filter
        let full = render_entity_markdown(&entity, None);
        assert!(full.contains("_tokens:"), "should have _tokens");
        assert!(
            !full.contains("_tokens_unfiltered_body:"),
            "should NOT have _tokens_unfiltered_body when unfiltered"
        );
        assert!(
            !full.contains("_tokens_full:"),
            "old _tokens_full name must not survive — rename is one-way"
        );

        // Filtered render — request only "identity"
        let filtered = render_entity_markdown(&entity, Some(&["identity".to_string()]));
        assert!(filtered.contains("_tokens:"), "should have _tokens");
        assert!(
            filtered.contains("_tokens_unfiltered_body:"),
            "should have _tokens_unfiltered_body when filtered"
        );
        assert!(
            !filtered.contains("_tokens_full:"),
            "old _tokens_full name must not survive — rename is one-way"
        );

        // Extract token values
        let full_tokens: usize = full
            .lines()
            .find(|l| l.starts_with("_tokens:"))
            .unwrap()
            .trim_start_matches("_tokens: ")
            .parse()
            .unwrap();
        let filtered_tokens: usize = filtered
            .lines()
            .find(|l| l.starts_with("_tokens:"))
            .unwrap()
            .trim_start_matches("_tokens: ")
            .parse()
            .unwrap();
        let tokens_unfiltered_body: usize = filtered
            .lines()
            .find(|l| l.starts_with("_tokens_unfiltered_body:"))
            .unwrap()
            .trim_start_matches("_tokens_unfiltered_body: ")
            .parse()
            .unwrap();

        assert!(
            filtered_tokens < full_tokens,
            "filtered _tokens ({filtered_tokens}) should be less than full _tokens ({full_tokens})"
        );
        assert!(
            tokens_unfiltered_body >= full_tokens,
            "_tokens_unfiltered_body ({tokens_unfiltered_body}) should be >= full render _tokens ({full_tokens})"
        );
    }

    // -----------------------------------------------------------------------
    // Summary line — search rendering
    // -----------------------------------------------------------------------

    #[test]
    fn render_search_uses_first_required_section_for_spec() {
        let hit = make_hit(
            "specs--demo",
            "Demo Spec",
            "spec",
            &[
                ("identity", "A demo spec."),
                ("purpose", "Verifies rendering."),
            ],
        );
        let out = render_search_markdown(&search_result(vec![hit]), 0);
        assert!(
            out.contains("**Identity**: A demo spec."),
            "expected Identity line for spec hit, got:\n{out}"
        );
    }

    #[test]
    fn render_search_uses_first_required_section_for_memo() {
        let hit = make_hit(
            "memos--d1",
            "Memo One",
            "memo",
            &[("claim", "Some claim."), ("context", "Some context.")],
        );
        let out = render_search_markdown(&search_result(vec![hit]), 0);
        assert!(
            out.contains("**Claim**: Some claim."),
            "expected Claim line for memo hit, got:\n{out}"
        );
        assert!(
            !out.contains("**Identity**"),
            "memo hit must not render Identity label"
        );
        assert!(
            !out.contains("**Purpose**"),
            "memo hit must not render Purpose label"
        );
    }

    #[test]
    fn render_search_uses_first_required_section_for_concept() {
        let hit = make_hit(
            "concepts--thing",
            "Thing",
            "concept",
            &[("definition", "A thing."), ("explanation", "Details.")],
        );
        let out = render_search_markdown(&search_result(vec![hit]), 0);
        assert!(
            out.contains("**Definition**: A thing."),
            "expected Definition line for concept hit, got:\n{out}"
        );
    }

    #[test]
    fn render_search_missing_summary_section_shows_dash() {
        // Memo hit with no "claim" section — renderer falls back to em-dash.
        let hit = make_hit("memos--empty", "Empty Memo", "memo", &[]);
        let out = render_search_markdown(&search_result(vec![hit]), 0);
        assert!(
            out.contains("**Claim**: —"),
            "expected Claim dash fallback, got:\n{out}"
        );
    }

    #[test]
    fn render_search_mixes_schemas_in_one_result() {
        let spec_hit = make_hit(
            "specs--s1",
            "Spec One",
            "spec",
            &[("identity", "Spec body.")],
        );
        let memo_hit = make_hit("memos--m1", "Memo One", "memo", &[("claim", "Memo claim.")]);
        let out = render_search_markdown(&search_result(vec![spec_hit, memo_hit]), 0);
        assert!(
            out.contains("**Identity**: Spec body."),
            "spec hit should still render Identity, got:\n{out}"
        );
        assert!(
            out.contains("**Claim**: Memo claim."),
            "memo hit should render Claim in the same output, got:\n{out}"
        );
    }

    #[test]
    fn render_search_unknown_schema_shows_summary_dash() {
        let hit = make_hit("bogus--x", "Bogus", "bogus", &[]);
        let out = render_search_markdown(&search_result(vec![hit]), 0);
        assert!(
            out.contains("**Summary**: —"),
            "unknown schema should render Summary dash, got:\n{out}"
        );
    }

    #[test]
    fn summary_pair_falls_back_when_schema_has_no_required_sections() {
        use memstead_schema::{SectionDef, TypeDefinition};

        let schema = TypeDefinition {
            name: "spec".to_string(),
            description: "test".to_string(),
            when_to_use: "test".to_string(),
            boundaries: vec![],
            exemplar: None,
            legacy_examples: None,
            system_message: None,
            sections: vec![SectionDef {
                key: "note".to_string(),
                heading: "Note".to_string(),
                required: false,
                search_weight: 1.0,
                catch_all: false,
                write_rules: vec![],
                description: None,
                content: None,
                item_pattern: None,
                table: None,
                example: None,
                format_severity: memstead_schema::ConstraintSeverity::Block,
                compiled_content: None,
                format_problems: Vec::new(),
            }],
            metadata_fields: vec![],
            title_weight: 1.0,
            text_fields: vec![],
            hierarchy_relationship: "PART_OF".to_string(),
            edge_weight_overrides: indexmap::IndexMap::new(),
            edge_weights: indexmap::IndexMap::new(),
            no_self_loop_relationships: vec![],
            legacy_propagating_relationships: None,
            due: None,
            leaf: false,
            updatable_fields: vec![],
            health_required_fields: vec![],
            staleness_threshold_days: 90,
            write_rules: vec![],
            required_outgoing: vec![],
            constraints: vec![],
            declared_metadata_keys: vec![],
        };

        let mut sections = HashMap::new();
        sections.insert("note".to_string(), "a note".to_string());
        assert_eq!(
            summary_pair(Some(&schema), &sections),
            ("Note".to_string(), "a note".to_string()),
        );

        assert_eq!(
            summary_pair(Some(&schema), &HashMap::new()),
            ("Note".to_string(), "".to_string()),
        );
    }

    // -----------------------------------------------------------------------
    // Summary line — list rendering (symmetric)
    // -----------------------------------------------------------------------

    #[test]
    fn render_list_uses_first_required_section_for_spec() {
        let hit = make_hit(
            "specs--demo",
            "Demo Spec",
            "spec",
            &[
                ("identity", "A demo spec."),
                ("purpose", "Verifies rendering."),
            ],
        );
        let out = render_list_markdown(&list_result(vec![hit]));
        assert!(
            out.contains("**Identity**: A demo spec."),
            "expected Identity line for spec hit, got:\n{out}"
        );
    }

    #[test]
    fn render_list_uses_first_required_section_for_memo() {
        let hit = make_hit("memos--d1", "Memo One", "memo", &[("claim", "Some claim.")]);
        let out = render_list_markdown(&list_result(vec![hit]));
        assert!(
            out.contains("**Claim**: Some claim."),
            "expected Claim line for memo hit, got:\n{out}"
        );
        assert!(
            !out.contains("**Identity**"),
            "memo hit must not render Identity label in list output"
        );
    }

    #[test]
    fn render_list_uses_first_required_section_for_concept() {
        let hit = make_hit(
            "concepts--thing",
            "Thing",
            "concept",
            &[("definition", "A thing.")],
        );
        let out = render_list_markdown(&list_result(vec![hit]));
        assert!(
            out.contains("**Definition**: A thing."),
            "expected Definition line for concept hit, got:\n{out}"
        );
    }

    #[test]
    fn render_list_missing_summary_section_shows_dash() {
        let hit = make_hit("memos--empty", "Empty Memo", "memo", &[]);
        let out = render_list_markdown(&list_result(vec![hit]));
        assert!(
            out.contains("**Claim**: —"),
            "expected Claim dash fallback in list output, got:\n{out}"
        );
    }

    #[test]
    fn render_list_mixes_schemas_in_one_result() {
        let spec_hit = make_hit(
            "specs--s1",
            "Spec One",
            "spec",
            &[("identity", "Spec body.")],
        );
        let memo_hit = make_hit("memos--m1", "Memo One", "memo", &[("claim", "Memo claim.")]);
        let out = render_list_markdown(&list_result(vec![spec_hit, memo_hit]));
        assert!(
            out.contains("**Identity**: Spec body."),
            "spec hit should still render Identity in list output, got:\n{out}"
        );
        assert!(
            out.contains("**Claim**: Memo claim."),
            "memo hit should render Claim in list output, got:\n{out}"
        );
    }

    #[test]
    fn render_list_unknown_schema_shows_summary_dash() {
        let hit = make_hit("bogus--x", "Bogus", "bogus", &[]);
        let out = render_list_markdown(&list_result(vec![hit]));
        assert!(
            out.contains("**Summary**: —"),
            "unknown schema should render Summary dash in list output, got:\n{out}"
        );
    }

    // -----------------------------------------------------------------------
    // summary_pair — structured-content source of truth
    // -----------------------------------------------------------------------

    #[test]
    fn summary_pair_for_spec_returns_identity() {
        let schema = type_by_name("spec");
        let mut sections = HashMap::new();
        sections.insert("identity".to_string(), "A demo spec.".to_string());
        assert_eq!(
            summary_pair(schema.as_deref(), &sections),
            ("Identity".to_string(), "A demo spec.".to_string()),
        );
    }

    #[test]
    fn summary_pair_for_memo_returns_claim() {
        let schema = type_by_name("memo");
        let mut sections = HashMap::new();
        sections.insert("claim".to_string(), "Memos matter.".to_string());
        assert_eq!(
            summary_pair(schema.as_deref(), &sections),
            ("Claim".to_string(), "Memos matter.".to_string()),
        );
    }

    #[test]
    fn summary_pair_missing_section_returns_dash() {
        let schema = type_by_name("memo");
        assert_eq!(
            summary_pair(schema.as_deref(), &HashMap::new()),
            ("Claim".to_string(), "".to_string()),
        );
    }

    #[test]
    fn summary_pair_unknown_schema_returns_summary_dash() {
        assert_eq!(
            summary_pair(None, &HashMap::new()),
            ("Summary".to_string(), "".to_string()),
        );
    }

    // -----------------------------------------------------------------------
    // Envelope serialization — structured-content sidecar
    // -----------------------------------------------------------------------

    #[test]
    fn envelope_serializes_summary_fields() {
        let hit = make_hit(
            "memos--d1",
            "Memo One",
            "memo",
            &[("claim", "Memos matter.")],
        );
        let result = search_result(vec![hit]);
        let envelope = build_search_envelope(&result, 0);
        let value = serde_json::to_value(&envelope).expect("envelope must serialize");

        // The top-level counters use the `_-prefixed` engine-emitted
        // shape so the wire signals "engine-authored metadata, not
        // user data".
        assert_eq!(value["_total"], 1);
        assert_eq!(value["_returned"], 1);
        assert_eq!(value["_offset"], 0);
        // Warnings field is omitted when empty (skip_serializing_if).
        assert!(
            value.get("warnings").is_none(),
            "empty warnings must be elided, got: {value}"
        );

        let hit0 = &value["hits"][0];
        assert_eq!(hit0["summary_heading"], "Claim");
        assert_eq!(hit0["summary_value"], "Memos matter.");
        // Flattened SearchHit fields present.
        assert_eq!(hit0["id"], "memos--d1");
        assert_eq!(hit0["title"], "Memo One");
        assert_eq!(hit0["entity_type"], "memo");
        assert_eq!(hit0["mem"], "memos");
        assert_eq!(hit0["stub"], false);
        assert_eq!(hit0["tokens"], 10);
        assert!(hit0["sections"].is_object());
    }

    #[test]
    fn envelope_roundtrips_through_structured_content() {
        // Mixed-schema result: one spec hit, one memo hit. Both summary pairs
        // must match what summary_pair produces for each schema.
        let spec_hit = make_hit(
            "specs--s1",
            "Spec One",
            "spec",
            &[("identity", "Spec body.")],
        );
        let memo_hit = make_hit("memos--m1", "Memo One", "memo", &[("claim", "Memo claim.")]);
        let result = search_result(vec![spec_hit, memo_hit]);
        let envelope = build_search_envelope(&result, 0);
        let value = serde_json::to_value(&envelope).expect("envelope must serialize");

        let hits = value["hits"].as_array().expect("hits must be array");
        assert_eq!(hits.len(), 2);
        assert_eq!(hits[0]["summary_heading"], "Identity");
        assert_eq!(hits[0]["summary_value"], "Spec body.");
        assert_eq!(hits[1]["summary_heading"], "Claim");
        assert_eq!(hits[1]["summary_value"], "Memo claim.");
    }

    #[test]
    fn list_envelope_includes_total_tokens() {
        let hit = make_hit(
            "concepts--c1",
            "Thing",
            "concept",
            &[("definition", "A thing.")],
        );
        let result = list_result(vec![hit]);
        let envelope = build_list_envelope(&result);
        let value = serde_json::to_value(&envelope).expect("envelope must serialize");

        // `_`-prefixed engine-meta keys, matching the search envelope.
        assert_eq!(value["_total"], 1);
        assert_eq!(value["_total_tokens"], 10);
        assert!(value.get("total").is_none(), "unprefixed keys retired");
        assert_eq!(value["hits"][0]["summary_heading"], "Definition");
        assert_eq!(value["hits"][0]["summary_value"], "A thing.");
    }

    #[test]
    fn envelope_emits_warnings_when_present() {
        let mut result = search_result(vec![]);
        // Search warnings ship as typed `WarningHint` entries (same
        // `{code, details, message}` envelope every other tool uses).
        result.warnings = vec![crate::ops::WarningHint::FieldNotFilterable {
            field: "foo".to_string(),
        }];
        let envelope = build_search_envelope(&result, 0);
        let value = serde_json::to_value(&envelope).expect("envelope must serialize");
        assert_eq!(value["warnings"][0]["code"], "FIELD_NOT_FILTERABLE");
        assert_eq!(value["warnings"][0]["details"]["field"], "foo");
        assert!(
            value["warnings"][0]["message"]
                .as_str()
                .is_some_and(|m| m.contains("not filterable"))
        );
    }

    // -----------------------------------------------------------------------
    // Per-hit and per-result fields that must appear in the Markdown body.
    // -----------------------------------------------------------------------

    fn tm(field: &str, snippet: &str, heading_path: Option<&[&str]>) -> TermMatch {
        TermMatch {
            field: field.to_string(),
            snippet: snippet.to_string(),
            heading_path: heading_path.map(|p| p.iter().map(|s| s.to_string()).collect()),
        }
    }

    fn sample_facets() -> Facets {
        use crate::ops::SubsectionFacet;
        Facets {
            by_type: HashMap::from([
                ("spec".to_string(), 7),
                ("memo".to_string(), 3),
                ("decision".to_string(), 2),
            ]),
            by_mem: HashMap::from([("specs".to_string(), 10), ("memos".to_string(), 2)]),
            by_level: HashMap::from([("high".to_string(), 4)]),
            by_status: HashMap::from([("active".to_string(), 6)]),
            by_confidence: HashMap::from([("medium".to_string(), 3)]),
            by_subsection: vec![
                SubsectionFacet {
                    path: vec!["specifies".to_string(), "Response Shapes".to_string()],
                    count: 4,
                },
                SubsectionFacet {
                    path: vec!["purpose".to_string(), "Rationale".to_string()],
                    count: 2,
                },
            ],
            by_expansion: HashMap::from([("primary".to_string(), 8), ("expanded".to_string(), 4)]),
        }
    }

    #[test]
    fn render_search_emits_matched_terms_line() {
        let mut hit = make_hit(
            "specs--e1",
            "Entity One",
            "spec",
            &[("identity", "Body text.")],
        );
        hit.matched_terms = Some(HashMap::from([
            (
                "entity".to_string(),
                vec![
                    tm("title", "...entity...", None),
                    tm("purpose", "...entity...", None),
                    tm("purpose", "...entity two...", None),
                ],
            ),
            ("one".to_string(), vec![tm("title", "...one...", None)]),
        ]));
        let out = render_search_markdown(&search_result(vec![hit]), 0);
        assert!(
            out.contains("**Matched terms:**"),
            "missing Matched terms line; got:\n{out}"
        );
        assert!(
            out.contains("`entity` (purpose×2, title×1)"),
            "entity term grouping wrong; got:\n{out}"
        );
        assert!(
            out.contains("`one` (title×1)"),
            "one term grouping wrong; got:\n{out}"
        );
    }

    #[test]
    fn render_search_emits_score_breakdown_line() {
        let mut hit = make_hit("specs--e1", "Entity", "spec", &[("identity", "b")]);
        hit.score_breakdown = Some(ScoreBreakdown {
            bm25: 2.5,
            title_boost: 2.0,
            field_weights: HashMap::from([("body".to_string(), 0.8), ("purpose".to_string(), 0.3)]),
            expansion_decay: Some(0.5),
        });
        let out = render_search_markdown(&search_result(vec![hit]), 0);
        assert!(
            out.contains(
                "**Score:** bm25 2.5 + title 2.0 + body 0.8 + purpose 0.3 + expansion_decay ×0.5"
            ),
            "score breakdown line wrong; got:\n{out}"
        );
    }

    #[test]
    fn render_search_omits_expansion_decay_when_none() {
        let mut hit = make_hit("specs--e1", "Entity", "spec", &[("identity", "b")]);
        hit.score_breakdown = Some(ScoreBreakdown {
            bm25: 1.5,
            title_boost: 1.0,
            field_weights: HashMap::new(),
            expansion_decay: None,
        });
        let out = render_search_markdown(&search_result(vec![hit]), 0);
        assert!(
            out.contains("**Score:** bm25 1.5 + title 1.0"),
            "base score wrong; got:\n{out}"
        );
        assert!(
            !out.contains("expansion_decay"),
            "expansion_decay must be absent when None; got:\n{out}"
        );
    }

    #[test]
    fn render_search_emits_heading_path_line() {
        let mut hit = make_hit("specs--e1", "Entity", "spec", &[("identity", "b")]);
        hit.matched_terms = Some(HashMap::from([(
            "x".to_string(),
            vec![
                tm("purpose", "...x...", Some(&["Purpose", "Rationale"])),
                tm("purpose", "...x...", Some(&["Purpose", "Rationale"])), // duplicate, dedupe
                tm("specifies", "...x...", Some(&["Specifies", "Responses"])),
            ],
        )]));
        let out = render_search_markdown(&search_result(vec![hit]), 0);
        assert!(
            out.contains("**Heading path:** Purpose › Rationale; Specifies › Responses"),
            "heading path line wrong; got:\n{out}"
        );
    }

    #[test]
    fn render_search_emits_expansion_line() {
        let mut hit = make_hit("specs--e2", "Entity Two", "spec", &[("identity", "b")]);
        hit.expansion = Some(ExpansionInfo {
            of: EntityId("specs--seed".to_string()),
            via_edge: "refines".to_string(),
            via_direction: crate::graph::query::TraversalDirection::Out,
            depth: 1,
        });
        let out = render_search_markdown(&search_result(vec![hit]), 0);
        assert!(
            out.contains("**Expansion:** from `specs--seed` via `refines` [out] (depth 1)"),
            "expansion line reports the traversal direction beside the label; got:\n{out}"
        );
    }

    #[test]
    fn render_search_emits_facets_block() {
        let mut result = search_result(vec![]);
        result.facets = Some(sample_facets());
        let out = render_search_markdown(&result, 0);
        assert!(
            out.contains("## Facets"),
            "facets header missing; got:\n{out}"
        );
        assert!(
            out.contains("- **by_type:** spec=7, memo=3, decision=2"),
            "by_type bucket wrong; got:\n{out}"
        );
        assert!(
            out.contains("- **by_mem:** specs=10, memos=2"),
            "by_mem bucket wrong; got:\n{out}"
        );
        assert!(
            out.contains("- **by_level:** high=4"),
            "by_level bucket wrong; got:\n{out}"
        );
        assert!(
            out.contains("- **by_status:** active=6"),
            "by_status bucket wrong; got:\n{out}"
        );
        assert!(
            out.contains("- **by_confidence:** medium=3"),
            "by_confidence bucket wrong; got:\n{out}"
        );
        assert!(
            out.contains("- **by_expansion:** primary=8, expanded=4"),
            "by_expansion bucket wrong; got:\n{out}"
        );
        assert!(
            out.contains("- **by_subsection:**"),
            "by_subsection header missing; got:\n{out}"
        );
        assert!(
            out.contains("`specifies › Response Shapes`: 4"),
            "subsection facet wrong; got:\n{out}"
        );
    }

    #[test]
    fn render_search_omits_facets_block_when_all_empty() {
        let mut result = search_result(vec![]);
        result.facets = Some(Facets::default());
        let out = render_search_markdown(&result, 0);
        assert!(
            !out.contains("## Facets"),
            "empty facets must not emit header; got:\n{out}"
        );
    }

    /// Every field the search-tool description promises must be rendered
    /// in Markdown. This test exercises all of them in one result and
    /// asserts they all appear.
    #[test]
    fn search_markdown_covers_every_sidecar_field() {
        let mut hit = make_hit(
            "specs--e1",
            "Entity One",
            "spec",
            &[("identity", "Body text.")],
        );
        hit.matched_terms = Some(HashMap::from([(
            "entity".to_string(),
            vec![tm("title", "...entity...", Some(&["Purpose", "Rationale"]))],
        )]));
        hit.score_breakdown = Some(ScoreBreakdown {
            bm25: 1.5,
            title_boost: 1.0,
            field_weights: HashMap::from([("body".to_string(), 0.4)]),
            expansion_decay: Some(0.5),
        });
        hit.expansion = Some(ExpansionInfo {
            of: EntityId("specs--seed".to_string()),
            via_edge: "refines".to_string(),
            via_direction: crate::graph::query::TraversalDirection::Out,
            depth: 2,
        });

        let mut result = search_result(vec![hit]);
        result.facets = Some(sample_facets());

        let out = render_search_markdown(&result, 0);
        for marker in [
            "## Facets",
            "- **by_type:**",
            "- **by_mem:**",
            "- **by_level:**",
            "- **by_status:**",
            "- **by_confidence:**",
            "- **by_expansion:**",
            "- **by_subsection:**",
            "**Matched terms:**",
            "**Score:**",
            "**Heading path:**",
            "**Expansion:**",
        ] {
            assert!(
                out.contains(marker),
                "lockstep marker `{marker}` missing from search markdown; \
                 update render_search_markdown when adding sidecar fields. got:\n{out}"
            );
        }
    }

    /// The envelope's `relationships[].source` field reads the store's
    /// `EdgeSource` discriminator rather than a hardcoded `"explicit"`,
    /// which would disagree with the stub-adoption
    /// response for alias-synthesised edges (and would be
    /// misleading because REFERENCES carries `manual_authoring:
    /// forbidden`).
    #[test]
    fn build_entity_envelope_source_field_reads_edge_source() {
        let mut entity = test_entity();
        let body_link_target = EntityId("specs--body-link-target".to_string());
        let explicit_target = EntityId("specs--explicit-target".to_string());
        entity.relationships = vec![
            crate::entity::Relationship::new("REFERENCES".to_string(), body_link_target.clone()),
            crate::entity::Relationship::new("USES".to_string(), explicit_target.clone()),
        ];

        let edges = vec![
            crate::store::Edge {
                rel_type: "REFERENCES".to_string(),
                target: body_link_target.clone(),
                source: crate::store::EdgeSource::BodyLink,
            },
            crate::store::Edge {
                rel_type: "USES".to_string(),
                target: explicit_target.clone(),
                source: crate::store::EdgeSource::Explicit,
            },
        ];

        let env = build_entity_envelope(&entity, 0, None, None, None, &edges);
        let relationships = env["relationships"].as_array().expect("array");
        let refs = relationships
            .iter()
            .find(|r| r["rel_type"] == "REFERENCES")
            .expect("REFERENCES present");
        assert_eq!(
            refs["source"], "body_link",
            "alias-synthesised edge must label body_link"
        );
        let uses = relationships
            .iter()
            .find(|r| r["rel_type"] == "USES")
            .expect("USES present");
        assert_eq!(
            uses["source"], "explicit",
            "explicit-authored edge must label explicit"
        );
    }

    /// A relationship whose store edge is missing
    /// (transitional drift, store-rebuild lag) falls back to
    /// `"explicit"` so the envelope doesn't crash. The fallback is
    /// the conservative label — agents already branch on it.
    #[test]
    fn build_entity_envelope_source_field_falls_back_to_explicit_when_edge_missing() {
        let mut entity = test_entity();
        let target = EntityId("specs--unmapped".to_string());
        entity.relationships = vec![crate::entity::Relationship::new("USES".to_string(), target)];
        let edges: Vec<crate::store::Edge> = Vec::new();
        let env = build_entity_envelope(&entity, 0, None, None, None, &edges);
        let relationships = env["relationships"].as_array().expect("array");
        assert_eq!(relationships[0]["source"], "explicit");
    }

    /// Every schema-declared frontmatter key surfaces under the nested
    /// `metadata` map — its single home. The four
    /// formerly-hoisted scalars are not at the top level; the
    /// read-only identity triple (mem/id/type) and underscore-prefixed
    /// internal keys are excluded from the nested map.
    #[test]
    fn build_entity_envelope_nested_metadata_carries_every_schema_field() {
        use crate::entity::MetadataValue;
        let mut entity = test_entity();
        entity.entity_type = "contract".to_string();
        // Pre-fix the envelope dropped every non-promoted key.
        entity.metadata = IndexMap::from([
            ("level".to_string(), MetadataValue::String("M0".to_string())),
            (
                "stability".to_string(),
                MetadataValue::String("stable".to_string()),
            ),
            (
                "created_date".to_string(),
                MetadataValue::String("2026-01-01".to_string()),
            ),
            (
                "last_modified".to_string(),
                MetadataValue::String("2026-05-19".to_string()),
            ),
            (
                "protocol".to_string(),
                MetadataValue::String("https".to_string()),
            ),
            (
                "version".to_string(),
                MetadataValue::String("0.1.0".to_string()),
            ),
            (
                "deprecation_status".to_string(),
                MetadataValue::String("none".to_string()),
            ),
        ]);

        let env = build_entity_envelope(&entity, 0, None, None, None, &[]);

        // Metadata scalars are NOT hoisted to the top level — the
        // nested map is their single home.
        assert!(
            env.get("level").is_none(),
            "level must not be hoisted top-level"
        );
        assert!(
            env.get("stability").is_none(),
            "stability must not be hoisted"
        );
        assert!(
            env.get("created_date").is_none(),
            "created_date must not be hoisted"
        );
        assert!(
            env.get("last_modified").is_none(),
            "last_modified must not be hoisted"
        );
        // `type` stays top-level as identity.
        assert_eq!(env["type"], "contract");

        // Nested map carries every non-internal, non-identity frontmatter key.
        let metadata = env["metadata"].as_object().expect("metadata map");
        assert_eq!(metadata["level"], "M0");
        assert_eq!(metadata["stability"], "stable");
        assert_eq!(metadata["created_date"], "2026-01-01");
        assert_eq!(metadata["last_modified"], "2026-05-19");
        assert_eq!(metadata["protocol"], "https");
        assert_eq!(metadata["version"], "0.1.0");
        assert_eq!(metadata["deprecation_status"], "none");

        // Internal underscore-prefixed keys and the read-only identity
        // triple (mem/id/type) do NOT appear inside the nested map.
        for k in metadata.keys() {
            assert!(
                !k.starts_with('_'),
                "metadata map must not carry underscore-prefixed key `{k}`"
            );
            assert!(
                !["mem", "id", "type"].contains(&k.as_str()),
                "metadata map must not carry identity key `{k}` (it lives top-level)"
            );
        }
    }

    /// Stub envelopes carry an
    /// empty `metadata: {}` map so consumers don't branch on the
    /// map's presence.
    #[test]
    fn build_entity_envelope_stub_carries_empty_metadata_map() {
        let mut entity = test_entity();
        entity.stub = true;
        entity.stub_kind = Some(crate::entity::StubKind::ForwardReference);
        entity.metadata = IndexMap::new();
        let env = build_entity_envelope(&entity, 0, None, None, None, &[]);
        let metadata = env["metadata"]
            .as_object()
            .expect("metadata key present even on stubs");
        assert!(metadata.is_empty(), "stub metadata map must be empty");
    }

    /// A user-defined schema names a
    /// metadata field colliding with structured envelope slots
    /// (`sections`, `relationships`). The colliding name surfaces
    /// under `metadata.sections` / `metadata.relationships` without
    /// disturbing the top-level structured arrays — the nested map
    /// decouples user namespace from engine namespace.
    #[test]
    fn build_entity_envelope_user_field_collisions_isolated_to_nested_map() {
        use crate::entity::MetadataValue;
        let mut entity = test_entity();
        entity.metadata = IndexMap::from([
            (
                "sections".to_string(),
                MetadataValue::String("user-supplied-shadow".to_string()),
            ),
            (
                "relationships".to_string(),
                MetadataValue::String("also-shadowed".to_string()),
            ),
        ]);
        let env = build_entity_envelope(&entity, 0, None, None, None, &[]);
        // Top-level structured slots stay structured.
        assert!(
            env["sections"].is_object(),
            "top-level sections stays a map"
        );
        assert!(
            env["relationships"].is_array(),
            "top-level relationships stays an array"
        );
        // User-supplied collisions land inside the nested map.
        let metadata = env["metadata"].as_object().expect("metadata map");
        assert_eq!(metadata["sections"], "user-supplied-shadow");
        assert_eq!(metadata["relationships"], "also-shadowed");
    }

    /// `_tokens_unfiltered_body` on the structured envelope rides only
    /// when `full_tokens` is supplied (a section filter was active);
    /// the legacy `_tokens_full` name is not present as an alias.
    #[test]
    fn build_entity_envelope_unfiltered_body_token_field_name() {
        let entity = test_entity();
        // Filter-active path — field present under new name.
        let env_filtered = build_entity_envelope(&entity, 10, Some(42), None, None, &[]);
        assert_eq!(env_filtered["_tokens_unfiltered_body"], 42);
        assert!(
            env_filtered.get("_tokens_full").is_none(),
            "_tokens_full must not survive — rename is one-way"
        );
        // No-filter path — field absent under both names.
        let env_unfiltered = build_entity_envelope(&entity, 10, None, None, None, &[]);
        assert!(env_unfiltered.get("_tokens_unfiltered_body").is_none());
        assert!(env_unfiltered.get("_tokens_full").is_none());
    }

    // ------------------------------------------------------------------
    // Schema verbosity (lite vs. full) — Plan 01.
    // ------------------------------------------------------------------

    /// Load the embedded `software` schema (~42 rel-types, 9 entity
    /// types, `alias_target_rel_type: REFERENCES`) — the heaviest builtin,
    /// so the lite cut has something to bite into.
    fn software_schema() -> Arc<Schema> {
        memstead_schema::builtins::load_builtin_schemas()
            .expect("builtins load")
            .into_iter()
            .find(|s| s.manifest.name == "software")
            .expect("software schema is a builtin")
    }

    #[test]
    fn schema_verbosity_wire_round_trips() {
        assert_eq!(
            SchemaVerbosity::from_wire("full"),
            Some(SchemaVerbosity::Full)
        );
        assert_eq!(
            SchemaVerbosity::from_wire("lite"),
            Some(SchemaVerbosity::Lite)
        );
        assert_eq!(SchemaVerbosity::from_wire("brief"), None);
        assert_eq!(SchemaVerbosity::from_wire(""), None);
        assert_eq!(SchemaVerbosity::Full.as_wire(), "full");
        assert_eq!(SchemaVerbosity::Lite.as_wire(), "lite");
        assert_eq!(SchemaVerbosity::default(), SchemaVerbosity::Full);
    }

    /// Exemplar serving (agent-trust plan 09): `verbosity: full`
    /// carries each type's exemplar (title, metadata, sections,
    /// relations with placeholder targets); the lite skeleton is
    /// BYTE-unchanged between the same schema with and without an
    /// exemplar — the per-session lite fetch never grows.
    #[test]
    fn exemplar_serves_at_full_and_lite_stays_byte_unchanged() {
        let manifest = r#"name: servefix
version: 1.0.0
description: serving fixture
when_to_use: tests
types:
  - sample
relationships:
  mode: strict
  definitions:
    - name: PART_OF
      description: hier
      default_weight: 3.0
    - name: _default
      description: fallback
      default_weight: 1.0
community:
  resolution: 1.0
  seed: 42
"#;
        let base_type = r#"name: sample
description: t
when_to_use: tests
sections:
  - key: body
    heading: Body
    required: true
    search_weight: 10.0
    catch_all: true
    write_rules: []
metadata_fields:
  - key: status
    description: state
    field_type: string
    enum_values: [draft, final]
    optional: true
title_weight: 100.0
text_fields:
  - body
hierarchy_relationship: PART_OF
no_self_loop_relationships: []
updatable_fields:
  - title
  - body
health_required_fields:
  - body
staleness_threshold_days: 90
write_rules: []
"#;
        let with_exemplar = format!(
            "{base_type}exemplar:\n  title: A Conforming Sample\n  metadata:\n    status: draft\n  sections:\n    body: \"One canonical body paragraph.\"\n  relations:\n    - to: parent-placeholder\n      type: PART_OF\n"
        );

        let plain = Arc::new(
            memstead_schema::loader::load_schema_from_memory(
                manifest,
                &[("sample".to_string(), base_type.to_string())],
            )
            .expect("fixture loads"),
        );
        let exemplary = Arc::new(
            memstead_schema::loader::load_schema_from_memory(
                manifest,
                &[("sample".to_string(), with_exemplar)],
            )
            .expect("fixture loads"),
        );

        // FULL serves the exemplar with the type.
        let full = build_schema_payload(
            &exemplary,
            vec![],
            SchemaVerbosity::Full,
            OriginClass::FirstParty,
        );
        let ex = &full["types"][0]["exemplar"];
        assert_eq!(ex["title"], "A Conforming Sample", "{full}");
        assert_eq!(ex["metadata"]["status"], "draft");
        assert_eq!(ex["sections"]["body"], "One canonical body paragraph.");
        assert_eq!(ex["relations"][0]["to"], "parent-placeholder");
        assert_eq!(ex["relations"][0]["type"], "PART_OF");

        // FULL without an exemplar: no key (absent, not null).
        let full_plain = build_schema_payload(
            &plain,
            vec![],
            SchemaVerbosity::Full,
            OriginClass::FirstParty,
        );
        assert!(full_plain["types"][0].get("exemplar").is_none());

        // LITE is byte-identical with and without the exemplar — the
        // skeleton every session fetches does not grow.
        let lite_with = build_schema_payload(
            &exemplary,
            vec![],
            SchemaVerbosity::Lite,
            OriginClass::FirstParty,
        );
        let lite_without = build_schema_payload(
            &plain,
            vec![],
            SchemaVerbosity::Lite,
            OriginClass::FirstParty,
        );
        assert_eq!(
            serde_json::to_string(&lite_with).unwrap(),
            serde_json::to_string(&lite_without).unwrap(),
            "lite must not change when an exemplar exists"
        );
        assert!(
            !serde_json::to_string(&lite_with)
                .unwrap()
                .contains("exemplar"),
            "lite must not mention exemplars at all"
        );
    }

    /// A first-party schema labels its origin and serves its full prose
    /// under `full`. The origin field is additive and present in both
    /// verbosities so a consuming host can always read it.
    #[test]
    fn first_party_origin_is_labelled_and_keeps_prose() {
        let schema = software_schema();
        let full = build_schema_payload(
            &schema,
            vec!["v".into()],
            SchemaVerbosity::Full,
            OriginClass::FirstParty,
        );
        assert_eq!(full["origin"], "first-party");
        // First-party full keeps the prose-instruction fields.
        assert!(full["description"].is_string());
        let t = &full["types"].as_array().unwrap()[0];
        assert!(t.get("system_context").is_some());
        assert!(t.get("writing_guidance").is_some());

        // The origin label rides the lite skeleton too.
        let lite = build_schema_payload(
            &schema,
            vec!["v".into()],
            SchemaVerbosity::Lite,
            OriginClass::FirstParty,
        );
        assert_eq!(lite["origin"], "first-party");
    }

    /// Declared constraints and `required_outgoing` severities are
    /// visible at BOTH verbosity levels — no legality condition may
    /// exist that the schema response omits. Complement: a type
    /// declaring none renders `constraints: []`, never an absent key.
    #[test]
    fn constraints_and_severity_render_at_both_verbosities() {
        let manifest = r#"name: constrained
version: 1.0.0
description: constraint render fixture
when_to_use: render tests
types:
  - sample
relationships:
  mode: strict
  definitions:
    - name: PART_OF
      description: hier
      default_weight: 3.0
    - name: _default
      description: fallback
      default_weight: 1.0
community:
  resolution: 1.0
  seed: 42
"#;
        let type_yaml = r#"name: sample
description: t
when_to_use: tests
sections:
  - key: body
    heading: Body
    required: true
    search_weight: 10.0
    catch_all: true
    write_rules: []
metadata_fields:
  - key: status
    description: state
    field_type: string
    enum_values: [open, checked]
    optional: true
  - key: checked_by
    description: who
    field_type: string
    optional: true
title_weight: 100.0
text_fields:
  - body
hierarchy_relationship: PART_OF
no_self_loop_relationships: []
updatable_fields:
  - title
  - body
health_required_fields:
  - body
staleness_threshold_days: 90
required_outgoing:
  - relationships: [PART_OF]
    cardinality: at_least_one
    severity: block
constraints:
  - kind: requires_when
    field: checked_by
    when_field: status
    when_value: checked
  - kind: unique
    fields: [status, checked_by]
  - kind: enum_from_neighbour
    field: status
    rel_type: PART_OF
    section: body
  - kind: status_propagation
    field: status
    value: checked
    rel_type: PART_OF
    direction: incoming
write_rules: []
"#;
        let schema = Arc::new(
            memstead_schema::loader::load_schema_from_memory(
                manifest,
                &[("sample".to_string(), type_yaml.to_string())],
            )
            .expect("fixture loads"),
        );

        // All five constraint forms (requires_when, unique,
        // enum_from_neighbour, status_propagation here; form 4 is the
        // required_outgoing severity) must be visible with their
        // severity at both verbosity levels.
        let expected_constraints = serde_json::json!([
            {
                "kind": "requires_when",
                "field": "checked_by",
                "when_field": "status",
                "when_value": "checked",
                "severity": "warn",
            },
            {
                "kind": "unique",
                "fields": ["status", "checked_by"],
                "severity": "block",
            },
            {
                "kind": "enum_from_neighbour",
                "field": "status",
                "rel_type": "PART_OF",
                "section": "body",
                "severity": "warn",
            },
            {
                "kind": "status_propagation",
                "field": "status",
                "value": "checked",
                "rel_type": "PART_OF",
                "direction": "incoming",
                "severity": "warn",
            },
        ]);

        let full = build_schema_payload(
            &schema,
            vec![],
            SchemaVerbosity::Full,
            OriginClass::FirstParty,
        );
        let t = &full["types"].as_array().unwrap()[0];
        assert_eq!(t["constraints"], expected_constraints);
        assert_eq!(t["required_outgoing"][0]["severity"], "block");

        let lite = build_schema_payload(
            &schema,
            vec![],
            SchemaVerbosity::Lite,
            OriginClass::FirstParty,
        );
        let ts = &lite["types_summary"].as_array().unwrap()[0];
        assert_eq!(ts["constraints"], expected_constraints);
        assert_eq!(ts["required_outgoing"][0]["severity"], "block");

        // Section-format declarations render at BOTH verbosity
        // levels (plan 08 shares plan 07's no-hidden-legality rule).
        let fmt_manifest = r#"name: formatted
version: 1.0.0
description: format render fixture
when_to_use: render tests
types:
  - plan
relationships:
  mode: strict
  definitions:
    - name: PART_OF
      description: hier
      default_weight: 1.0
    - name: _default
      description: fallback
      default_weight: 1.0
community:
  resolution: 1.0
  seed: 42
"#;
        let fmt_type = r#"name: plan
description: t
when_to_use: tests
sections:
  - key: body
    heading: Body
    required: true
    search_weight: 10.0
    catch_all: true
    write_rules: []
  - key: meilensteine
    heading: Meilensteine
    required: false
    search_weight: 5.0
    catch_all: false
    write_rules: []
    content: "(heading(3) list(bullet))+"
    item_pattern: '\*\*(?<name>[^*]+)\*\*'
    example: |
      ### Phase 1
      - **Kickoff**
    format_severity: warn
  - key: tabelle
    heading: Tabelle
    required: false
    search_weight: 5.0
    catch_all: false
    write_rules: []
    content: "table"
    table:
      columns: [Name, Datum]
      column_patterns:
        Datum: '\d{4}-\d{2}-\d{2}'
  - key: belege
    heading: Belege
    required: false
    search_weight: 5.0
    catch_all: false
    write_rules: []
    content: "paragraph+"
    item_pattern: '(?<quelle>\S[^|]*?) \| (?<aussage>.+)'
metadata_fields: []
title_weight: 100.0
text_fields:
  - body
hierarchy_relationship: PART_OF
no_self_loop_relationships: []
updatable_fields:
  - title
  - body
health_required_fields:
  - body
staleness_threshold_days: 90
write_rules: []
"#;
        let fmt_schema = Arc::new(
            memstead_schema::loader::load_schema_from_memory(
                fmt_manifest,
                &[("plan".to_string(), fmt_type.to_string())],
            )
            .expect("format fixture loads"),
        );
        for verbosity in [SchemaVerbosity::Full, SchemaVerbosity::Lite] {
            let payload =
                build_schema_payload(&fmt_schema, vec![], verbosity, OriginClass::FirstParty);
            let sections_key = match verbosity {
                SchemaVerbosity::Full => &payload["types"][0]["sections"],
                SchemaVerbosity::Lite => &payload["types_summary"][0]["sections"],
            };
            let secs = sections_key.as_array().unwrap();
            let meilensteine = secs
                .iter()
                .find(|s| s["key"] == "meilensteine")
                .expect("declared section present");
            assert_eq!(
                meilensteine["content"], "(heading(3) list(bullet))+",
                "{verbosity:?} carries content"
            );
            assert!(
                meilensteine["item_pattern"]
                    .as_str()
                    .unwrap()
                    .contains("name")
            );
            assert!(
                meilensteine["example"]
                    .as_str()
                    .unwrap()
                    .contains("Kickoff")
            );
            assert_eq!(meilensteine["format_severity"], "warn");
            let tabelle = secs.iter().find(|s| s["key"] == "tabelle").unwrap();
            assert_eq!(tabelle["format_severity"], "block", "default renders");
            assert_eq!(tabelle["table"]["columns"][0], "Name");
            assert!(
                tabelle["table"]["column_patterns"]["Datum"]
                    .as_str()
                    .is_some()
            );
            let belege = secs.iter().find(|s| s["key"] == "belege").unwrap();
            assert_eq!(belege["content"], "paragraph+");
            assert!(belege["item_pattern"].as_str().unwrap().contains("quelle"));
            let body = secs.iter().find(|s| s["key"] == "body").unwrap();
            assert!(
                body.get("content").is_none() && body.get("format_severity").is_none(),
                "undeclared section keeps its pre-plan shape"
            );
        }

        // Complement: a constraint-free builtin renders the
        // always-present empty list at both levels.
        let plain_full = build_schema_payload(
            &software_schema(),
            vec![],
            SchemaVerbosity::Full,
            OriginClass::FirstParty,
        );
        let pt = &plain_full["types"].as_array().unwrap()[0];
        assert_eq!(pt["constraints"], serde_json::json!([]));
        let plain_lite = build_schema_payload(
            &software_schema(),
            vec![],
            SchemaVerbosity::Lite,
            OriginClass::FirstParty,
        );
        let pts = &plain_lite["types_summary"].as_array().unwrap()[0];
        assert_eq!(pts["constraints"], serde_json::json!([]));
    }

    /// A third-party schema is de-framed: a `full`-verbosity request is
    /// overridden to the structural-only skeleton, so NONE of the
    /// prose-instruction fields (`system_context`, `writing_guidance`,
    /// section `write_rules`, schema `description` / `when_to_use`,
    /// `default_writing_guidance`, rel `description` / `when_to_use`)
    /// reach a consuming agent — even though `full` was asked for. The
    /// structural skeleton (type/section/field/rel shape) survives so the
    /// mem stays understandable and queryable. This is the refusal
    /// complement: a `full` request cannot re-admit the prose.
    #[test]
    fn third_party_origin_forces_structural_only_even_under_full() {
        let schema = software_schema();
        let full_requested = build_schema_payload(
            &schema,
            vec!["v".into()],
            SchemaVerbosity::Full,
            OriginClass::ThirdParty,
        );

        // Origin label.
        assert_eq!(full_requested["origin"], "third-party");

        // Prose-bearing rich arrays are GONE despite the full request;
        // the structural-only summaries are present instead.
        assert!(
            full_requested.get("types").is_none(),
            "third-party omits the rich `types` array even under full"
        );
        assert!(
            full_requested.get("relationships").is_none(),
            "third-party omits the rich `relationships` array even under full"
        );
        assert!(
            full_requested["types_summary"].is_array(),
            "third-party serves the structural `types_summary` skeleton"
        );
        assert!(
            full_requested["relationships_summary"].is_array(),
            "third-party serves the structural `relationships_summary` skeleton"
        );

        // Schema-level prose-instruction fields dropped.
        assert!(
            full_requested.get("description").is_none(),
            "third-party drops schema description prose"
        );
        assert!(
            full_requested.get("when_to_use").is_none(),
            "third-party drops schema when_to_use prose"
        );
        assert!(
            full_requested.get("default_writing_guidance").is_none(),
            "third-party drops default_writing_guidance prose"
        );

        // Per-type prose-instruction fields dropped.
        for t in full_requested["types_summary"].as_array().unwrap() {
            assert!(
                t.get("system_context").is_none(),
                "third-party drops system_context"
            );
            assert!(
                t.get("writing_guidance").is_none(),
                "third-party drops writing_guidance"
            );
            assert!(
                t.get("description").is_none(),
                "third-party drops type description"
            );
            for s in t["sections"].as_array().unwrap() {
                assert!(
                    s.get("write_rules").is_none(),
                    "third-party drops section write_rules"
                );
            }
        }
        // Per-rel prose dropped.
        for r in full_requested["relationships_summary"].as_array().unwrap() {
            assert!(
                r.get("description").is_none(),
                "third-party drops rel description"
            );
            assert!(
                r.get("when_to_use").is_none(),
                "third-party drops rel when_to_use"
            );
        }

        // A third-party schema served under `full` is byte-identical to
        // the same schema served under `lite` (modulo the origin label,
        // which is identical here) — the override fully collapses to Lite.
        let lite_requested = build_schema_payload(
            &schema,
            vec!["v".into()],
            SchemaVerbosity::Lite,
            OriginClass::ThirdParty,
        );
        assert_eq!(
            full_requested, lite_requested,
            "third-party full must collapse to the lite skeleton"
        );
    }

    #[test]
    fn full_payload_carries_the_rich_arrays_and_prose() {
        let schema = software_schema();
        let full = build_schema_payload(
            &schema,
            vec!["v".into()],
            SchemaVerbosity::Full,
            OriginClass::FirstParty,
        );

        // Full keeps today's contract: rich arrays + schema-level prose.
        assert!(full["types"].is_array(), "full has `types`");
        assert!(full["relationships"].is_array(), "full has `relationships`");
        assert!(
            full.get("types_summary").is_none(),
            "full omits `types_summary`"
        );
        assert!(
            full.get("relationships_summary").is_none(),
            "full omits `relationships_summary`"
        );
        assert!(
            full["description"].is_string(),
            "full keeps schema description"
        );
        assert!(
            full["when_to_use"].is_string(),
            "full keeps schema when_to_use"
        );
        assert_eq!(full["alias_target_rel_type"], "REFERENCES");

        // A full type entry keeps the prose the lite cut drops.
        let t = &full["types"].as_array().unwrap()[0];
        assert!(t["description"].is_string());
        assert!(t.get("writing_guidance").is_some());
        assert!(t.get("system_context").is_some());
        // A full rel entry keeps its prose.
        let r = &full["relationships"].as_array().unwrap()[0];
        assert!(r["description"].is_string());
        assert!(r.get("when_to_use").is_some());
        assert!(r.get("default_weight").is_some());
    }

    /// The declared `required_outgoing` blocks appear per type — with
    /// their relationship lists and cardinality, in declaration order —
    /// at BOTH verbosity levels, and a type declaring none reports an
    /// empty list (never a missing key). The `project` built-in is the
    /// live fixture: `evidence` declares one block, `decision` (among
    /// others) declares none. The `no_self_loop_relationships_effect`
    /// note ships at both levels and claims nothing beyond the
    /// self-loop refusal.
    #[test]
    fn required_outgoing_reported_with_cardinality_at_both_levels() {
        let reg = memstead_schema::SchemaRegistry::builtin();
        let project = reg
            .get("project", &semver::Version::new(0, 2, 0))
            .expect("project is a built-in");

        for verbosity in [SchemaVerbosity::Full, SchemaVerbosity::Lite] {
            let payload =
                build_schema_payload(&project, vec![], verbosity, OriginClass::FirstParty);
            let types_key = if verbosity == SchemaVerbosity::Full {
                "types"
            } else {
                "types_summary"
            };
            let types = payload[types_key].as_array().expect("types array");

            let mut saw_evidence = false;
            let mut saw_memo = false;
            for t in types {
                let ro = t
                    .get("required_outgoing")
                    .unwrap_or_else(|| panic!("type {} omits required_outgoing", t["name"]))
                    .as_array()
                    .expect("required_outgoing is an array for every type");
                if t["name"] == "evidence" {
                    saw_evidence = true;
                    assert_eq!(ro.len(), 1, "evidence declares one block");
                    assert_eq!(
                        ro[0]["relationships"],
                        serde_json::json!(["STRENGTHENS", "WEAKENS", "VALIDATES", "CONTRADICTS"]),
                        "relationship alternatives in declaration order"
                    );
                    assert_eq!(
                        ro[0]["cardinality"], "at_least_one",
                        "cardinality rendered as declared — the open upper bound \
                         stays open, never a finite number"
                    );
                } else if t["name"] == "memo" {
                    // A type declaring no blocks reports the empty
                    // list, not a missing key.
                    saw_memo = true;
                    assert!(ro.is_empty(), "memo declares no blocks → empty list");
                }
            }
            assert!(saw_evidence, "project schema carries the evidence type");
            assert!(saw_memo, "project schema carries the memo type");

            // The effect note for no_self_loop_relationships ships at both
            // levels and states the single real effect.
            let note = payload["no_self_loop_relationships_effect"]
                .as_str()
                .expect("effect note present at both verbosity levels");
            assert!(note.contains("self-loop"), "names the actual effect");
            assert!(
                !note.contains("propagates impact") || note.contains("does not propagate"),
                "claims no propagation behaviour beyond the self-loop refusal"
            );
            assert!(
                note.contains("status_propagation"),
                "deprecation pointer names the real propagation declaration"
            );
        }
    }

    #[test]
    fn lite_payload_is_the_structural_skeleton_without_prose() {
        let schema = software_schema();
        let lite = build_schema_payload(
            &schema,
            vec!["v".into()],
            SchemaVerbosity::Lite,
            OriginClass::FirstParty,
        );

        // Heavy arrays under the distinct lite keys; rich keys absent.
        let types = lite["types_summary"]
            .as_array()
            .expect("lite has `types_summary`");
        let rels = lite["relationships_summary"]
            .as_array()
            .expect("lite has `relationships_summary`");
        assert!(lite.get("types").is_none(), "lite omits rich `types`");
        assert!(
            lite.get("relationships").is_none(),
            "lite omits rich `relationships`"
        );

        // Alias pointer + endpoint constraints survive the cut — every
        // flag an agent needs to author a legal write.
        assert_eq!(lite["alias_target_rel_type"], "REFERENCES");

        // Schema-level prose dropped.
        assert!(
            lite.get("description").is_none(),
            "lite drops schema description"
        );
        assert!(
            lite.get("when_to_use").is_none(),
            "lite drops schema when_to_use"
        );
        assert!(
            lite.get("default_writing_guidance").is_none(),
            "lite drops default_writing_guidance"
        );

        // Every entity-type name carries its section keys (with `required`)
        // and field shapes — and NO type/section prose.
        for t in types {
            assert!(t["name"].is_string());
            let sections = t["sections"].as_array().expect("lite type has sections");
            for s in sections {
                assert!(s["key"].is_string(), "section carries its key");
                assert!(s["required"].is_boolean(), "section carries required flag");
                assert!(
                    s.get("write_rules").is_none(),
                    "lite section drops write_rules prose"
                );
                assert!(s.get("heading").is_none(), "lite section drops heading");
            }
            assert!(
                t.get("description").is_none(),
                "lite type drops description"
            );
            assert!(
                t.get("writing_guidance").is_none(),
                "lite type drops writing_guidance"
            );
            assert!(
                t.get("system_context").is_none(),
                "lite type drops system_context"
            );
            // `no_self_loop_relationships` rides along — it governs the
            // self-loop relate refusal, a write-time refusal lite must let
            // an agent avoid.
            assert!(
                t.get("no_self_loop_relationships").is_some(),
                "lite type keeps no_self_loop_relationships"
            );
            // `required_outgoing` rides along — the only declared
            // legality condition on outgoing edges. Always an array,
            // never an absent key (absence would read as "unknown").
            assert!(
                t.get("required_outgoing").is_some_and(|v| v.is_array()),
                "lite type keeps required_outgoing as an array"
            );
            // Field shapes present (name + required), prose absent.
            if let Some(fields) = t["fields"].as_array() {
                for f in fields {
                    assert!(f["name"].is_string());
                    assert!(f["required"].is_boolean());
                    assert!(
                        f.get("description").is_none(),
                        "lite field drops description"
                    );
                }
            }
        }

        // Every relationship name carries its allowed endpoints and the
        // refusal-governing flags — and NO description/when_to_use prose.
        for r in rels {
            assert!(r["name"].is_string());
            assert!(
                r.get("allowed_sources").is_some(),
                "lite rel has allowed_sources"
            );
            assert!(
                r.get("allowed_targets").is_some(),
                "lite rel has allowed_targets"
            );
            assert!(
                r.get("manual_authoring").is_some(),
                "lite rel keeps manual_authoring"
            );
            assert!(r.get("acyclic").is_some(), "lite rel keeps acyclic");
            assert!(
                r.get("per_edge_description").is_some(),
                "lite rel keeps per_edge_description"
            );
            assert!(r.get("description").is_none(), "lite rel drops description");
            assert!(r.get("when_to_use").is_none(), "lite rel drops when_to_use");
            assert!(
                r.get("default_weight").is_none(),
                "lite rel drops default_weight"
            );
        }
    }

    #[test]
    fn lite_is_measurably_smaller_than_full() {
        let schema = software_schema();
        let full = build_schema_payload(
            &schema,
            vec!["v".into()],
            SchemaVerbosity::Full,
            OriginClass::FirstParty,
        );
        let lite = build_schema_payload(
            &schema,
            vec!["v".into()],
            SchemaVerbosity::Lite,
            OriginClass::FirstParty,
        );
        let full_len = serde_json::to_string(&full).unwrap().len();
        let lite_len = serde_json::to_string(&lite).unwrap().len();
        assert!(
            lite_len * 2 < full_len,
            "lite ({lite_len} B) must be well under half of full ({full_len} B)"
        );
    }

    #[test]
    fn lite_full_carry_the_same_type_and_rel_names() {
        // The cut drops prose, never an entity type or a rel-type — an
        // agent orienting on lite sees the full vocabulary.
        let schema = software_schema();
        let full = build_schema_payload(
            &schema,
            vec!["v".into()],
            SchemaVerbosity::Full,
            OriginClass::FirstParty,
        );
        let lite = build_schema_payload(
            &schema,
            vec!["v".into()],
            SchemaVerbosity::Lite,
            OriginClass::FirstParty,
        );

        let names = |arr: &serde_json::Value| -> Vec<String> {
            arr.as_array()
                .unwrap()
                .iter()
                .map(|v| v["name"].as_str().unwrap().to_string())
                .collect()
        };
        assert_eq!(names(&full["types"]), names(&lite["types_summary"]));
        assert_eq!(
            names(&full["relationships"]),
            names(&lite["relationships_summary"])
        );
    }
}