mati 0.1.0

Engineering knowledge that survives turnover
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
//! MCP tool implementations (M-07, M-11).
//!
//! Public MCP surface:
//! - `mem_get`       — direct key lookup
//! - `mem_query`     — BM25 text search or graph traversal
//! - `mem_bootstrap` — session context assembly within a token budget
//! - `mem_set`       — knowledge record writes

use std::collections::HashSet;
use std::path::PathBuf;

use rmcp::handler::server::tool::ToolRouter;
use rmcp::handler::server::wrapper::Parameters;
use rmcp::tool_router;
use serde_json::json;

use crate::graph::edges::EdgeKind;
use crate::graph::Graph;
use crate::store::record::{
    Category, ContextPacket, FileRecord, GotchaRecord, Priority, QualityTier, Record,
    RecordLifecycle, StaleReviewPayload, StalenessTier,
};

use super::protocol::{
    self as proto, Command, DecisionUpsertInput, DevNoteUpsertInput, GotchaConfirmInput,
    GotchaDraftInput, GotchaTombstoneInput,
};
use super::server::{proxy_daemon_result, proxy_daemon_v2, ProxyDaemonResult};
use super::types::{MemBootstrapParams, MemGetParams, MemQueryParams, MemSetParams};

/// Vector B — appended to every mem_bootstrap result (64 tokens, budget 77).
pub(crate) const VECTOR_B: &str =
    "\n\n[mati] Before reading any file: call mem_get(\"file:<path>\").\n\
    confidence>=0.6 + confirmed=true \u{2192} use record, skip file read.\n\
    confidence<0.3 \u{2192} read file, consider mem_set to improve.\n\
    \"add gotcha\" \u{2192} mem_set(Gotcha) then mati gotcha confirm <key>.";

/// Token budget for mem_bootstrap output (ARCHITECTURE.md §6).
const TOKEN_BUDGET: usize = 2_000;

/// Reserved tokens for Vector B suffix.
const VECTOR_B_TOKENS: usize = 77;

/// Estimate token count as text.len() / 4 (consistent with analysis/mod.rs).
fn estimate_tokens(text: &str) -> usize {
    text.len() / 4
}

/// Priority weight for sorting gotchas: confidence × priority_weight.
fn priority_weight(priority: &Priority) -> f32 {
    match priority {
        Priority::Low => 0.25,
        Priority::Normal => 0.50,
        Priority::High => 0.75,
        Priority::Critical => 1.00,
    }
}

/// Strip a Record to its agent-facing shape. Removes internal metadata
/// (device_id, clocks, gap_analysis_score, computed_at, sha, counters)
/// that agents never use. Cuts ~40% of response size.
pub(crate) fn record_to_agent_json(record: &Record) -> serde_json::Value {
    let mut obj = serde_json::Map::new();
    obj.insert("key".into(), serde_json::json!(record.key));
    obj.insert("value".into(), serde_json::json!(record.value));
    obj.insert("category".into(), serde_json::json!(record.category));
    obj.insert("priority".into(), serde_json::json!(record.priority));
    if !record.tags.is_empty() {
        obj.insert("tags".into(), serde_json::json!(record.tags));
    }
    obj.insert(
        "confidence".into(),
        serde_json::json!(record.confidence.value),
    );
    obj.insert(
        "confirmation_count".into(),
        serde_json::json!(record.confidence.confirmation_count),
    );
    obj.insert("quality".into(), serde_json::json!(record.quality.value));
    obj.insert(
        "quality_tier".into(),
        serde_json::json!(record.quality.tier),
    );
    if !record.quality.signals.is_empty() {
        obj.insert(
            "quality_signals".into(),
            serde_json::json!(record.quality.signals),
        );
    }
    obj.insert("source".into(), serde_json::json!(record.source));
    obj.insert(
        "staleness_tier".into(),
        serde_json::json!(record.staleness.tier),
    );
    if let Some(ref url) = record.ref_url {
        obj.insert("ref_url".into(), serde_json::json!(url));
    }
    if let Some(ref payload) = record.payload {
        obj.insert("payload".into(), strip_payload(payload, &record.category));
    }
    serde_json::Value::Object(obj)
}

/// Strip internal-only fields from the payload based on record category.
fn strip_payload(payload: &serde_json::Value, category: &Category) -> serde_json::Value {
    let Some(obj) = payload.as_object() else {
        return payload.clone();
    };

    // Fields to remove per category
    let internal_fields: &[&str] = match category {
        Category::File => &[
            "token_cost_estimate",
            "last_modified_session",
            "content_hash",
        ],
        Category::Gotcha => &["discovered_session"],
        _ => &[],
    };

    if internal_fields.is_empty() {
        return payload.clone();
    }

    let mut stripped = obj.clone();
    for field in internal_fields {
        stripped.remove(*field);
    }

    // Remove empty arrays from file payloads to save space
    if matches!(category, Category::File) {
        stripped.retain(|_, v| !matches!(v, serde_json::Value::Array(a) if a.is_empty()));
    }

    serde_json::Value::Object(stripped)
}

/// The MCP server struct. After γ-C4, `mati serve` is always a thin
/// MCP-stdio ↔ UDS proxy that forwards every tool call to a separate
/// daemon process (spawned by `mati daemon start` or auto-spawned via
/// `daemon_lifecycle::ensure_daemon`). The daemon owns the store; this
/// struct only carries the path to the daemon root so we know where to
/// open the Unix socket.
#[derive(Clone)]
pub struct MatiServer {
    root: PathBuf,
    pub(crate) tool_router: ToolRouter<Self>,
}

impl MatiServer {
    /// Construct a socket-backed proxy rooted at `~/.mati/<slug>/`.
    pub fn with_socket_root(root: PathBuf) -> Self {
        Self {
            root,
            tool_router: Self::tool_router(),
        }
    }

    fn socket_error(op: &str, result: ProxyDaemonResult) -> String {
        let message = match result {
            ProxyDaemonResult::NotRunning => format!("{op}: daemon not running"),
            ProxyDaemonResult::StaleSocket => format!("{op}: daemon socket stale"),
            ProxyDaemonResult::Unresponsive => format!("{op}: daemon unresponsive"),
            ProxyDaemonResult::Ok(v) => format!("{op}: malformed daemon response: {v}"),
        };
        json!({ "error": message }).to_string()
    }

    async fn socket_call(&self, op: &str, args: serde_json::Value) -> String {
        match proxy_daemon_result(&self.root, op, args).await {
            ProxyDaemonResult::Ok(v) => Self::format_envelope(op, v),
            other => Self::socket_error(op, other),
        }
    }

    /// Send a typed v2 [`Command`] over the daemon socket and format the
    /// response the same way [`Self::socket_call`] does.
    ///
    /// Use this for mutating commands (gotcha_upsert/confirm/tombstone,
    /// decision_upsert, dev_note_upsert) which have no entry in the legacy
    /// v1→v2 mapper and would panic the rmcp task if routed through
    /// [`Self::socket_call`].
    async fn socket_call_typed(&self, cmd: Command) -> String {
        let op = cmd.kind();
        match proxy_daemon_v2(&self.root, cmd).await {
            ProxyDaemonResult::Ok(v) => Self::format_envelope(op, v),
            other => Self::socket_error(op, other),
        }
    }

    /// Render a daemon envelope `{ok,data}` / `{ok:false,error}` into the
    /// JSON string the rmcp `String` return type expects.
    fn format_envelope(op: &str, v: serde_json::Value) -> String {
        if v.get("ok") != Some(&serde_json::Value::Bool(true)) {
            let err = v
                .get("error")
                .and_then(|e| e.as_str())
                .unwrap_or("daemon request failed");
            // Surface the structured error code if present so callers can
            // distinguish validation failures from store errors.
            let code = v.get("code").and_then(|c| c.as_str()).unwrap_or("");
            if code.is_empty() {
                return json!({ "error": err, "op": op }).to_string();
            }
            return json!({ "error": err, "op": op, "code": code }).to_string();
        }
        match v.get("data") {
            Some(serde_json::Value::String(s)) => s.clone(),
            Some(other) => other.to_string(),
            None => json!({ "error": "daemon response missing data" }).to_string(),
        }
    }
}

#[tool_router]
impl MatiServer {
    /// Retrieve a single record by its namespaced key.
    ///
    /// Returns the JSON-serialised record, or "null" if not found.
    ///
    /// Note: `read_only_hint = true` is set because mem_get does not modify
    /// knowledge content. However, it does write consultation receipts
    /// (session:consulted:*) synchronously — these are critical for hook
    /// enforcement (deny → mem_get → allow cycle) — and defers access_count
    /// and analytics writes to a background task.
    #[rmcp::tool(
        name = "mem_get",
        description = "Look up one mati knowledge record by key. Before reading a file directly, call this with \"file:<path>\" and use the record instead when it is confirmed and high-confidence.",
        annotations(read_only_hint = true)
    )]
    pub(crate) async fn mem_get(&self, Parameters(params): Parameters<MemGetParams>) -> String {
        self.socket_call("mem_get", json!({ "key": params.key }))
            .await
    }

    /// Search the knowledge store using BM25 text search or graph traversal.
    ///
    /// Modes: "text" (default) for full-text BM25, "graph" for 1-hop traversal.
    /// Text mode returns a JSON array. Graph mode returns a grouped JSON object.
    #[rmcp::tool(
        name = "mem_query",
        description = "Search the mati knowledge store. Use mode \"text\" for BM25 full-text search, mode \"tag\" to filter by tag, or mode \"graph\" for a 1-hop traversal from a seed key.",
        annotations(read_only_hint = true)
    )]
    pub(crate) async fn mem_query(&self, Parameters(params): Parameters<MemQueryParams>) -> String {
        self.socket_call(
            "mem_query",
            json!({ "query": params.query, "mode": params.mode, "limit": params.limit }),
        )
        .await
    }

    /// Assemble a context packet for the current session.
    ///
    /// Gathers stage, gotchas, file records, and decisions within a 2,000-token budget.
    /// Returns a markdown injection string for Claude.
    #[rmcp::tool(
        name = "mem_bootstrap",
        description = "Assemble a compact context packet for the current coding session from relevant gotchas, file records, and decisions. Call this at session start.",
        annotations(read_only_hint = true)
    )]
    pub(crate) async fn mem_bootstrap(
        &self,
        Parameters(params): Parameters<MemBootstrapParams>,
    ) -> String {
        self.socket_call(
            "mem_bootstrap",
            json!({ "context_files": params.context_files }),
        )
        .await
    }

    /// Write an enriched knowledge record to the mati store.
    ///
    /// Used during `/mati-enrich` sessions. Source is always `ClaudeEnrich`.
    /// Gotcha records land with `confirmed=false` — developer runs `mati review`
    /// to confirm and activate hook enforcement.
    #[rmcp::tool(
        name = "mem_set",
        description = "Write, confirm, or delete a knowledge record. Actions: \"write\" (default) creates/updates a record, \"confirm\" activates a gotcha for hook enforcement, \"delete\" tombstones a gotcha.",
        annotations(
            read_only_hint = false,
            destructive_hint = true,
            idempotent_hint = false
        )
    )]
    pub(crate) async fn mem_set(&self, Parameters(params): Parameters<MemSetParams>) -> String {
        // Route mem_set through typed Commands via proxy_daemon_v2. The
        // legacy v1 mapper has no arms for gotcha_upsert / gotcha_confirm /
        // gotcha_tombstone / decision_upsert / dev_note_upsert / the bogus
        // literal "mem_set" — every prior call panicked the rmcp task and
        // surfaced as `Transport closed` to the client.
        match build_mem_set_command(&params) {
            Ok(cmd) => self.socket_call_typed(cmd).await,
            Err(error) => json!({ "error": error }).to_string(),
        }
    }
}

/// Map a `MemSetParams` request to a typed v2 [`Command`] for daemon dispatch.
///
/// Returns `Err(String)` when the request cannot be expressed as a typed
/// Command — the caller renders this into a JSON error envelope rather
/// than panicking the MCP transport.
///
/// # Routing rules
///
/// - `action = "confirm"` / `"delete"` → key MUST start with `gotcha:`.
///   This mirrors the Direct path's `mem_set_confirm` / `mem_set_delete`
///   guards (tools.rs:~1058).
/// - `action = "write"` (default) routes by key prefix:
///   - `gotcha:*`   → [`Command::GotchaUpsert`]
///   - `decision:*` → [`Command::DecisionUpsert`]
///   - `dev_note:*` → [`Command::DevNoteUpsert`]
///   - other        → error (file: writes have no public typed Command —
///     file records are managed by the static-analysis pipeline +
///     `file_enrich` / `file_reparse`, not direct mem_set).
fn build_mem_set_command(params: &MemSetParams) -> Result<Command, String> {
    match params.action.as_str() {
        "confirm" => {
            if !params.key.starts_with("gotcha:") {
                return Err("confirm action only applies to gotcha: keys".into());
            }
            Ok(Command::GotchaConfirm(GotchaConfirmInput {
                key: params.key.clone(),
            }))
        }
        "delete" => {
            if !params.key.starts_with("gotcha:") {
                return Err("delete action only applies to gotcha: keys".into());
            }
            Ok(Command::GotchaTombstone(GotchaTombstoneInput {
                key: params.key.clone(),
            }))
        }
        "write" | "" => build_mem_set_write_command(params),
        other => Err(format!(
            "unknown action: {other}. Valid: write, confirm, delete"
        )),
    }
}

fn build_mem_set_write_command(params: &MemSetParams) -> Result<Command, String> {
    // Some MCP clients (Codex) send the payload as a JSON-encoded string;
    // mirror the Direct-path normalization (tools.rs ~860).
    let payload = match &params.payload {
        serde_json::Value::String(s) => {
            serde_json::from_str::<serde_json::Value>(s).unwrap_or_else(|_| params.payload.clone())
        }
        other => other.clone(),
    };

    let priority = parse_protocol_priority(&params.priority);

    if let Some(stripped) = params.key.strip_prefix("gotcha:") {
        if stripped.is_empty() {
            return Err("gotcha key must not be just the prefix".into());
        }
        let rule = field_string(&payload, "rule")
            .ok_or_else(|| "gotcha payload requires non-empty 'rule'".to_string())?;
        let reason = field_string(&payload, "reason")
            .ok_or_else(|| "gotcha payload requires non-empty 'reason'".to_string())?;
        let severity = parse_protocol_severity(payload.get("severity").and_then(|v| v.as_str()));
        let affected_files = field_string_list(&payload, "affected_files");
        let ref_url = payload
            .get("ref_url")
            .and_then(|v| v.as_str())
            .map(|s| s.to_string());

        return Ok(Command::GotchaUpsert(GotchaDraftInput {
            key: params.key.clone(),
            rule,
            reason,
            severity,
            affected_files,
            ref_url,
            tags: params.tags.clone(),
            priority,
            source: None,
        }));
    }

    if let Some(slug) = params.key.strip_prefix("decision:") {
        if slug.is_empty() {
            return Err("decision key must not be just the prefix".into());
        }
        let summary = field_string(&payload, "summary")
            .ok_or_else(|| "decision payload requires non-empty 'summary'".to_string())?;
        let rationale = field_string(&payload, "rationale")
            .ok_or_else(|| "decision payload requires non-empty 'rationale'".to_string())?;
        return Ok(Command::DecisionUpsert(DecisionUpsertInput {
            slug: slug.to_string(),
            value: params.value.clone(),
            summary,
            rationale,
            tags: params.tags.clone(),
            priority,
        }));
    }

    if let Some(stripped) = params.key.strip_prefix("dev_note:") {
        if stripped.is_empty() {
            return Err("dev_note key must not be just the prefix".into());
        }
        if params.value.is_empty() {
            return Err("dev_note requires non-empty value".into());
        }
        return Ok(Command::DevNoteUpsert(DevNoteUpsertInput {
            key: Some(params.key.clone()),
            text: params.value.clone(),
            tags: params.tags.clone(),
            priority,
        }));
    }

    Err("mem_set write requires key with gotcha:/decision:/dev_note: prefix".into())
}

fn field_string(payload: &serde_json::Value, field: &str) -> Option<String> {
    payload
        .get(field)
        .and_then(|v| v.as_str())
        .map(|s| s.to_string())
        .filter(|s| !s.is_empty())
}

fn field_string_list(payload: &serde_json::Value, field: &str) -> Vec<String> {
    payload
        .get(field)
        .and_then(|v| v.as_array())
        .map(|arr| {
            arr.iter()
                .filter_map(|v| v.as_str().map(|s| s.to_string()))
                .collect()
        })
        .unwrap_or_default()
}

fn parse_protocol_priority(s: &str) -> proto::Priority {
    match s {
        "Critical" | "critical" => proto::Priority::Critical,
        "High" | "high" => proto::Priority::High,
        "Low" | "low" => proto::Priority::Low,
        _ => proto::Priority::Normal,
    }
}

fn parse_protocol_severity(s: Option<&str>) -> proto::Severity {
    match s.map(|s| s.to_ascii_lowercase()).as_deref() {
        Some("critical") => proto::Severity::Critical,
        Some("high") => proto::Severity::High,
        Some("low") => proto::Severity::Low,
        _ => proto::Severity::Normal,
    }
}

// ── mem_set action helpers ──────────────────────────────────────────────────
//
// γ-C1.85: the `mem_set_confirm` / `try_confirm_once` / `finalize_confirm` /
// `mem_set_delete` helpers that lived here are now free functions inside
// `super::handlers` (apply_mem_set_*). `MatiServer::mem_set` delegates to
// `handlers::handle_mem_set` so v1 (rmcp wrapper) and v2 (Socket → typed
// Commands) cannot diverge. The bodies are byte-for-byte identical to the
// originals — only the `&self` parameter was dropped.

/// Returns true if a gotcha record is eligible for injection into a context packet.
///
/// Two classes of gotchas surface in bootstrap:
///
/// 1. **Developer-confirmed gotchas** (`payload.confirmed = true`) — these are
///    intentional captures and always inject when quality is acceptable.
/// 2. **Auto-derived Layer 0 stubs with intrinsic signal value** —
///    `gotcha:cochange:*`, `gotcha:revert:*`, `gotcha:ownership:*` records
///    are minted by `mati init` from git history. They are NOT
///    developer-confirmed (so they never trigger hook enforcement / file-read
///    DENY), but their content is high-signal information the agent should
///    see in bootstrap. Pre-fix these were marked `confirmed=true` at init
///    which violated the "confirmed ⇒ developer-authoritative ⇒ confidence
///    ≥ 0.80" schema invariant. Now we keep them `confirmed=false` and
///    explicitly allowlist them here so bootstrap still surfaces them.
fn is_injectable_gotcha(r: &Record) -> bool {
    if !matches!(r.lifecycle, RecordLifecycle::Active) {
        return false;
    }
    if r.staleness.tier == StalenessTier::Tombstone {
        return false;
    }
    if r.quality.value < 0.4 {
        return false;
    }
    if let Some(gotcha) = r.payload_as::<GotchaRecord>() {
        if gotcha.confirmed {
            return true;
        }
    }
    // Auto-derived Layer 0 stubs: include advisory signals even unconfirmed.
    r.key.starts_with("gotcha:cochange:")
        || r.key.starts_with("gotcha:revert:")
        || r.key.starts_with("gotcha:ownership:")
}

/// Resolve the existing record for a mem_set write path.
///
/// Returns `Ok(Option<Record>)` on success, or an error JSON string
/// if the store read failed — callers must abort the write.
/// Extracted for testability: the `Err` branch was previously untestable
/// because it required a real store failure.
pub(crate) fn resolve_existing_for_write(
    store_result: anyhow::Result<Option<Record>>,
) -> Result<Option<Record>, String> {
    match store_result {
        Ok(record) => Ok(record),
        Err(e) => Err(serde_json::json!({
            "error": format!("store read failed \u{2014} refusing to write: {e}")
        })
        .to_string()),
    }
}

/// Assemble a [`ContextPacket`] from the store and graph.
///
/// Steps:
/// 1. Fetch `stage:current`
/// 2. Collect confirmed gotchas (deferred until after step 3):
///    - For non-empty `context_files`: fetch only linked gotchas by key
///    - For empty `context_files` (global bootstrap): scan all `gotcha:*`
/// 3. For each context_file: get FileRecord, traverse HasGotcha (1-hop),
///    traverse Imports→HasGotcha (2-hop), traverse AffectedBy for decisions
/// 4. Dedup + sort gotchas by confidence × priority_weight
/// 5. Quality filter: exclude Suppressed, caveat Poor
/// 6. Build markdown injection string within 2,000-token budget
/// 7. Append Vector B suffix
pub async fn assemble_context_packet(
    store: &crate::store::Store,
    graph: &Graph,
    context_files: &[String],
) -> anyhow::Result<ContextPacket> {
    // 1. Stage
    let stage = store.get("stage:current").await?;

    // 2. Gotcha collection — deferred until after context-file traversal
    //    so we can optimize non-empty context_files to fetch only linked gotchas.

    // 3. Context-file traversal
    let mut file_records = Vec::new();
    let mut context_gotcha_keys = HashSet::new();
    let mut decision_keys = HashSet::new();
    // Collect nudge candidates during this pass to avoid N+1 re-lookups later.
    let mut unconfirmed_candidates = Vec::new();
    // M-13-B: collect stale warnings
    let mut stale_warnings: Vec<String> = Vec::new();
    let mut seen_stale_keys: HashSet<String> = HashSet::new();

    for file_path in context_files {
        let file_key = if file_path.starts_with("file:") {
            file_path.clone()
        } else {
            format!("file:{file_path}")
        };

        // Get file record first to check lifecycle/staleness before traversal
        if let Ok(Some(record)) = store.get(&file_key).await {
            // M-13-B: exclude tombstone files from traversal entirely
            if record.staleness.tier == StalenessTier::Tombstone
                || !matches!(record.lifecycle, RecordLifecycle::Active)
            {
                continue;
            }

            // M-13-B: stale/liability file records generate warnings
            match record.staleness.tier {
                StalenessTier::Stale => {
                    let path = file_key.strip_prefix("file:").unwrap_or(&file_key);
                    if seen_stale_keys.insert(file_key.clone()) {
                        stale_warnings.push(format!(
                            "`{path}` record is stale (staleness {:.2}) — verify before trusting",
                            record.staleness.value
                        ));
                    }
                }
                StalenessTier::Liability => {
                    let path = file_key.strip_prefix("file:").unwrap_or(&file_key);
                    if seen_stale_keys.insert(file_key.clone()) {
                        stale_warnings.push(format!(
                            "`{path}` record is a liability (staleness {:.2}) — do not trust, read the file",
                            record.staleness.value
                        ));
                    }
                }
                _ => {}
            }

            if let Some(fr) = record.payload_as::<FileRecord>() {
                // Supplement graph traversal with the record-level gotcha_keys list.
                // FileRecord.gotcha_keys is the authoritative persistent source; the
                // in-memory graph edges are a cache that can lag after CLI gotcha writes
                // (apply_gotcha_write persists to disk but historically skipped the
                // in-memory graph update). Including these keys here ensures bootstrap
                // surfaces confirmed gotchas even when graph edges are stale or missing.
                for key in &fr.gotcha_keys {
                    context_gotcha_keys.insert(key.clone());
                }
                // Nudge detection: hot file (access_count >= 3) with no gotchas
                let is_nudge_candidate = record.access_count >= 3 && fr.gotcha_keys.is_empty();
                file_records.push(fr);
                if is_nudge_candidate {
                    unconfirmed_candidates.push(file_key.clone());
                }
            }
        }

        // 1-hop: direct gotchas
        for key in graph.neighbors(&file_key, &EdgeKind::HasGotcha) {
            context_gotcha_keys.insert(key);
        }

        // 2-hop: imports → their gotchas
        for imported in graph.neighbors(&file_key, &EdgeKind::Imports) {
            for key in graph.neighbors(&imported, &EdgeKind::HasGotcha) {
                context_gotcha_keys.insert(key);
            }
        }

        // Decisions via AffectedBy
        for key in graph.neighbors(&file_key, &EdgeKind::AffectedBy) {
            decision_keys.insert(key);
        }
    }

    // 2. (deferred) Collect confirmed gotchas — scope depends on context_files.
    let mut confirmed_gotchas: Vec<Record> = if context_files.is_empty() {
        // Global bootstrap: scan all gotchas (no context filter).
        let all_gotchas = store.scan_prefix("gotcha:").await?;
        all_gotchas
            .into_iter()
            .filter(is_injectable_gotcha)
            .collect()
    } else {
        // Targeted bootstrap: fetch only gotchas linked to context files.
        let mut gotchas = Vec::with_capacity(context_gotcha_keys.len());
        for key in &context_gotcha_keys {
            if let Ok(Some(record)) = store.get(key).await {
                if is_injectable_gotcha(&record) {
                    gotchas.push(record);
                }
            }
        }
        gotchas
    };

    // M-13-B: surface stale reviews from last 2 days
    {
        let now = chrono::Utc::now();
        for days_ago in 0..2 {
            let date = (now - chrono::Duration::days(days_ago)).format("%Y-%m-%d");
            let review_key = format!("analytics:stale_review_{date}");
            if let Ok(Some(record)) = store.get(&review_key).await {
                if let Some(payload) = record.payload_as::<StaleReviewPayload>() {
                    for entry in &payload.entries {
                        if seen_stale_keys.insert(entry.key.clone()) {
                            let path = entry.key.strip_prefix("file:").unwrap_or(&entry.key);
                            stale_warnings.push(format!(
                                "`{path}` staleness {:.2} ({:?}) — review recommended",
                                entry.staleness_value, entry.tier
                            ));
                        }
                    }
                }
            }
        }
    }

    // Fetch decision records — graph-linked first, fallback to scan
    let mut related_decisions = Vec::new();
    for key in &decision_keys {
        if let Ok(Some(record)) = store.get(key).await {
            related_decisions.push(record);
        }
    }
    // Fallback: when graph traversal found no decisions, scan decision:*
    // prefix so decisions always surface in bootstrap when they exist.
    if related_decisions.is_empty() {
        if let Ok(mut all_decisions) = store.scan_prefix("decision:").await {
            all_decisions.retain(|r| matches!(r.lifecycle, RecordLifecycle::Active));
            all_decisions.sort_by(|a, b| {
                b.confidence
                    .value
                    .partial_cmp(&a.confidence.value)
                    .unwrap_or(std::cmp::Ordering::Equal)
            });
            const DECISION_FALLBACK_LIMIT: usize = 5;
            related_decisions = all_decisions
                .into_iter()
                .take(DECISION_FALLBACK_LIMIT)
                .collect();
        }
    }

    // 4. Sort gotchas by confidence × priority_weight (descending)
    confirmed_gotchas.sort_by(|a, b| {
        let score_a = a.confidence.value * priority_weight(&a.priority);
        let score_b = b.confidence.value * priority_weight(&b.priority);
        score_b
            .partial_cmp(&score_a)
            .unwrap_or(std::cmp::Ordering::Equal)
    });

    // 5. Quality filter: exclude Suppressed (<0.2), caveat Poor (0.2–0.4)
    //    Context scoping is already handled in step 2: targeted fetch for non-empty
    //    context_files, full scan for global bootstrap.
    let critical_gotchas: Vec<Record> = confirmed_gotchas
        .into_iter()
        .filter(|r| r.quality.tier != QualityTier::Suppressed)
        .collect();

    // 6. Build markdown injection string within token budget
    let available_tokens = TOKEN_BUDGET - VECTOR_B_TOKENS;
    let mut sections = Vec::new();
    let mut used_tokens = 0;

    // Stage section
    if let Some(ref stage_record) = stage {
        let section = format!("## Current Stage\n{}\n", stage_record.value);
        let tokens = estimate_tokens(&section);
        if used_tokens + tokens <= available_tokens {
            sections.push(section);
            used_tokens += tokens;
        }
    }

    // Gotchas section — separate co-change gotchas (grouped) from regular gotchas (individual)
    if !critical_gotchas.is_empty() {
        let mut gotcha_section = String::from("## Gotchas\n");

        // Regular gotchas (non-co-change) — listed individually
        for record in &critical_gotchas {
            if record.key.starts_with("gotcha:cochange:") {
                continue;
            }
            let caveat = if record.staleness.tier == StalenessTier::Liability {
                " [STALE — verify]"
            } else if record.quality.tier == QualityTier::Poor {
                " [LOW QUALITY — verify]"
            } else {
                ""
            };
            let line = format!("- **{}**{}: {}\n", record.key, caveat, record.value);
            let tokens = estimate_tokens(&line);
            if used_tokens + tokens > available_tokens {
                break;
            }
            gotcha_section.push_str(&line);
            used_tokens += tokens;
        }

        // Co-change gotchas — grouped by source file into one-liners
        let mut cochange_map: std::collections::BTreeMap<String, Vec<(String, String)>> =
            std::collections::BTreeMap::new();
        for record in &critical_gotchas {
            if !record.key.starts_with("gotcha:cochange:") {
                continue;
            }
            // key format: gotcha:cochange:file_a|file_b
            if let Some(pair) = record.key.strip_prefix("gotcha:cochange:") {
                if let Some((src, tgt)) = pair.split_once('|') {
                    // Extract percentage: "... (78%)." → "78%"
                    // Robust: find last '(' then take until '%' or ')'
                    let pct = record
                        .value
                        .rfind('(')
                        .and_then(|i| {
                            record.value[i + 1..]
                                .find(')')
                                .map(|j| &record.value[i + 1..i + 1 + j])
                        })
                        .unwrap_or("?");
                    cochange_map
                        .entry(src.to_string())
                        .or_default()
                        .push((tgt.to_string(), pct.to_string()));
                }
            }
        }
        if !cochange_map.is_empty() {
            let all_pairs: Vec<String> = cochange_map
                .iter()
                .flat_map(|(src, targets)| {
                    targets
                        .iter()
                        .map(move |(tgt, pct)| format!("{src}\u{2194}{tgt} ({pct})"))
                })
                .collect();
            let total = all_pairs.len();
            // Show up to 10 pairs, truncate with count
            let display: Vec<&str> = all_pairs.iter().take(10).map(|s| s.as_str()).collect();
            let suffix = if total > 10 {
                format!(", +{} more", total - 10)
            } else {
                String::new()
            };
            let line = format!("- **Co-change partners**: {}{suffix}\n", display.join(", "));
            let tokens = estimate_tokens(&line);
            if used_tokens + tokens <= available_tokens {
                gotcha_section.push_str(&line);
                used_tokens += tokens;
            }
        }

        if gotcha_section.len() > "## Gotchas\n".len() {
            sections.push(gotcha_section);
        }
    }

    // File records section
    if !file_records.is_empty() {
        let mut file_section = String::from("## Context Files\n");
        for fr in &file_records {
            if fr.purpose.is_empty() {
                continue;
            }
            let line = format!("- **{}**: {}\n", fr.path, fr.purpose);
            let tokens = estimate_tokens(&line);
            if used_tokens + tokens > available_tokens {
                break;
            }
            file_section.push_str(&line);
            used_tokens += tokens;
        }
        if file_section.len() > "## Context Files\n".len() {
            sections.push(file_section);
        }
    }

    // Highest-impact files in context — sorted by blast radius score descending.
    // Only shown when at least one file has a non-isolated blast radius.
    {
        use crate::analysis::blast_radius::BlastTier;
        let mut impact_files: Vec<(&FileRecord, f32)> = file_records
            .iter()
            .filter_map(|fr| {
                fr.blast_radius.as_ref().and_then(|br| {
                    if br.tier == BlastTier::Isolated {
                        None
                    } else {
                        Some((fr, br.score))
                    }
                })
            })
            .collect();
        impact_files.sort_by(|a, b| b.1.partial_cmp(&a.1).unwrap_or(std::cmp::Ordering::Equal));

        if !impact_files.is_empty() {
            let mut impact_section = String::from("## Highest Impact Files\n");
            for (fr, _score) in impact_files.iter().take(3) {
                let br = fr
                    .blast_radius
                    .as_ref()
                    .expect("filter_map above kept only files with Some(blast_radius)");
                let line = format!(
                    "- `{}`: {} direct importers ({})\n",
                    fr.path,
                    br.direct,
                    br.tier.label(),
                );
                let tokens = estimate_tokens(&line);
                if used_tokens + tokens > available_tokens {
                    break;
                }
                impact_section.push_str(&line);
                used_tokens += tokens;
            }
            if impact_section.len() > "## Highest Impact Files\n".len() {
                sections.push(impact_section);
            }
        }
    }

    // M-13-B: Stale Warnings section — BEFORE Decisions
    if !stale_warnings.is_empty() {
        let mut stale_section = String::from("## Stale Warnings\n");
        for warning in &stale_warnings {
            let line = format!("- {warning}\n");
            let tokens = estimate_tokens(&line);
            if used_tokens + tokens > available_tokens {
                break;
            }
            stale_section.push_str(&line);
            used_tokens += tokens;
        }
        if stale_section.len() > "## Stale Warnings\n".len() {
            sections.push(stale_section);
        }
    }

    // Decisions section
    if !related_decisions.is_empty() {
        let mut dec_section = String::from("## Decisions\n");
        for record in &related_decisions {
            let line = format!("- **{}**: {}\n", record.key, record.value);
            let tokens = estimate_tokens(&line);
            if used_tokens + tokens > available_tokens {
                break;
            }
            dec_section.push_str(&line);
            used_tokens += tokens;
        }
        if dec_section.len() > "## Decisions\n".len() {
            sections.push(dec_section);
        }
    }

    // M-12-E: Passive nudge — detect hot files with no gotchas.
    // NOTE: This is a deliberate exception to P2 ("inject nothing by default").
    // Nudges are advisory suggestions, not knowledge injection, and are only
    // emitted when token budget allows after all knowledge sections.
    // unconfirmed_candidates were collected during the context-file traversal
    // above (step 3), so no additional store lookups are needed here.
    if !unconfirmed_candidates.is_empty() {
        let mut nudge_section = String::from("## Suggested Actions\n");
        for key in &unconfirmed_candidates {
            let path = key.strip_prefix("file:").unwrap_or(key);
            let line = format!(
                "- `{path}` is read frequently but has no recorded gotchas. The developer may want to run `mati gotcha add {path}`.\n"
            );
            let tokens = estimate_tokens(&line);
            if used_tokens + tokens > available_tokens {
                break;
            }
            nudge_section.push_str(&line);
            used_tokens += tokens;
        }
        if nudge_section.len() > "## Suggested Actions\n".len() {
            sections.push(nudge_section);
        }
    }

    let mut injection_string = sections.join("\n");
    injection_string.push_str(VECTOR_B);

    let token_estimate = estimate_tokens(&injection_string) as u32;

    Ok(ContextPacket {
        stage,
        critical_gotchas,
        file_records,
        related_decisions,
        recent_session: None,
        token_estimate,
        stale_warnings,
        unconfirmed_candidates,
        knowledge_gaps: vec![],
        compliance_rate: None,
        injection_string,
    })
}

// ── Tests ────────────────────────────────────────────────────────────────────

#[cfg(test)]
mod tests {
    use super::*;
    use crate::store::record::*;
    use crate::store::Store;
    use tempfile::TempDir;

    fn device_id() -> uuid::Uuid {
        uuid::Uuid::nil()
    }

    fn now() -> u64 {
        1_700_000_000
    }

    fn make_record(key: &str, value: &str, category: Category, quality_value: f32) -> Record {
        Record {
            key: key.to_string(),
            value: value.to_string(),
            category,
            priority: Priority::Normal,
            tags: vec![],
            created_at: now(),
            updated_at: now(),
            ref_url: None,
            staleness: StalenessScore::fresh(),
            lifecycle: RecordLifecycle::Active,
            version: RecordVersion {
                device_id: device_id(),
                logical_clock: 1,
                wall_clock: now(),
            },
            quality: QualityScore {
                value: quality_value,
                tier: QualityScore::tier_from_value(quality_value),
                signals: vec![],
                computed_at: now(),
            },
            access_count: 0,
            last_accessed: 0,
            source: RecordSource::DeveloperManual,
            confidence: ConfidenceScore {
                value: 0.8,
                confirmation_count: 1,
                contributor_count: 1,
                last_challenged: None,
                challenge_count: 0,
            },
            gap_analysis_score: 0.0,
            payload: Some(serde_json::json!({})),
        }
    }

    fn make_gotcha_record(key: &str, rule: &str, confirmed: bool, quality_value: f32) -> Record {
        let gotcha = GotchaRecord {
            rule: rule.to_string(),
            reason: "test reason".to_string(),
            severity: Priority::High,
            affected_files: vec![],
            ref_url: None,
            discovered_session: now(),
            confirmed,
        };
        let mut record = make_record(key, rule, Category::Gotcha, quality_value);
        record.payload = serde_json::to_value(&gotcha).ok();
        record
    }

    // ── γ-C3a helpers: handler-level test entry points ───────────────────────
    //
    // γ-C4 removed `MatiBackend::Direct`. These helpers replaced the
    // pre-γ pattern `MatiServer::new(graph).mem_*(Parameters(...)).await`.
    // They drive the canonical daemon-side handlers (mcp::handlers::*)
    // directly, returning a `String` so existing test assertions
    // (`result.contains(...)`, `assert_eq!(result, "null")`) keep working.

    fn handler_test_ctx() -> crate::mcp::dispatch_v2::RequestContext {
        crate::mcp::dispatch_v2::RequestContext {
            peer: crate::mcp::metadata::PeerContext {
                uid: 501,
                pid: Some(99999),
            },
            daemon_session: uuid::Uuid::nil(),
            repo_root: std::path::PathBuf::new(),
        }
    }

    async fn call_mem_get(
        graph_arc: &std::sync::Arc<tokio::sync::RwLock<crate::graph::Graph>>,
        key: &str,
    ) -> String {
        let ctx = handler_test_ctx();
        let input = crate::mcp::protocol::MemGetInput {
            key: key.to_string(),
        };
        let g = graph_arc.read().await;
        match crate::mcp::handlers::handle_mem_get(
            g.store(),
            graph_arc,
            &ctx,
            uuid::Uuid::new_v4(),
            &input,
        )
        .await
        {
            Ok(v) => serde_json::to_string_pretty(&v).unwrap_or_else(|_| "{}".into()),
            Err((_code, msg)) => format!("{{\"error\": \"{}\"}}", msg.replace('"', "\\\"")),
        }
    }

    async fn call_mem_query(
        graph_arc: &std::sync::Arc<tokio::sync::RwLock<crate::graph::Graph>>,
        query: &str,
        mode: crate::mcp::protocol::QueryMode,
        limit: u32,
    ) -> String {
        let input = crate::mcp::protocol::MemQueryInput {
            query: query.to_string(),
            mode,
            limit,
        };
        let g = graph_arc.read().await;
        match crate::mcp::handlers::handle_mem_query(g.store(), &g, &input).await {
            Ok(v) => serde_json::to_string_pretty(&v).unwrap_or_else(|_| "{}".into()),
            Err((_code, msg)) => format!("{{\"error\": \"{}\"}}", msg.replace('"', "\\\"")),
        }
    }

    async fn call_mem_bootstrap(
        graph_arc: &std::sync::Arc<tokio::sync::RwLock<crate::graph::Graph>>,
        context_files: Vec<String>,
    ) -> String {
        let ctx = handler_test_ctx();
        let input = crate::mcp::protocol::MemBootstrapInput { context_files };
        let g = graph_arc.read().await;
        match crate::mcp::handlers::handle_mem_bootstrap(
            g.store(),
            &g,
            graph_arc,
            &ctx,
            uuid::Uuid::new_v4(),
            &input,
        )
        .await
        {
            Ok(s) => s,
            Err((_code, msg)) => format!("[mati] bootstrap error: {msg}"),
        }
    }

    async fn call_mem_set(
        graph_arc: &std::sync::Arc<tokio::sync::RwLock<crate::graph::Graph>>,
        params: crate::mcp::types::MemSetParams,
    ) -> String {
        let ctx = handler_test_ctx();
        crate::mcp::handlers::handle_mem_set(graph_arc, &ctx, uuid::Uuid::new_v4(), &params).await
    }

    // ── mem_get tests ────────────────────────────────────────────────────────

    #[tokio::test]
    async fn mem_get_returns_null_for_nonexistent_key() {
        let dir = TempDir::new().unwrap();
        let store = Store::open(dir.path()).await.unwrap();
        let graph = Graph::load(store).await.unwrap();
        let graph_arc = std::sync::Arc::new(tokio::sync::RwLock::new(graph));

        let result = call_mem_get(&graph_arc, "file:nonexistent.rs").await;
        assert_eq!(result, "null");
    }

    #[tokio::test]
    async fn mem_get_returns_record_for_existing_key() {
        let dir = TempDir::new().unwrap();
        let store = Store::open(dir.path()).await.unwrap();
        let record = make_record("gotcha:test", "test value", Category::Gotcha, 0.8);
        store.put("gotcha:test", &record).await.unwrap();

        let graph = Graph::load(store).await.unwrap();
        let graph_arc = std::sync::Arc::new(tokio::sync::RwLock::new(graph));

        let result = call_mem_get(&graph_arc, "gotcha:test").await;
        assert!(result.contains("gotcha:test"));
        assert!(result.contains("test value"));
    }

    #[tokio::test]
    async fn mem_get_blast_radius_warning_for_critical_file() {
        let dir = TempDir::new().unwrap();
        let store = Store::open(dir.path()).await.unwrap();

        let fr = FileRecord {
            path: "src/core.rs".to_string(),
            purpose: "Core module".to_string(),
            entry_points: vec![],
            imports: vec![],
            gotcha_keys: vec![],
            decision_keys: vec![],
            todos: vec![],
            unsafe_count: 0,
            unwrap_count: 0,
            change_frequency: 0,
            last_author: None,
            is_hotspot: false,
            token_cost_estimate: 100,
            last_modified_session: 0,
            content_hash: None,
            line_count: 0,
            blast_radius: Some(crate::analysis::blast_radius::BlastRadius {
                direct: 45,
                transitive: 10,
                score: 48.0,
                tier: crate::analysis::blast_radius::BlastTier::Critical,
            }),
            propagated_staleness: None,
        };
        let mut record = make_record("file:src/core.rs", "Core module", Category::File, 0.5);
        record.payload = serde_json::to_value(&fr).ok();
        store.put("file:src/core.rs", &record).await.unwrap();

        let graph = Graph::load(store).await.unwrap();
        let graph_arc = std::sync::Arc::new(tokio::sync::RwLock::new(graph));

        let result = call_mem_get(&graph_arc, "file:src/core.rs").await;

        assert!(
            result.contains("HIGH IMPACT FILE"),
            "response must contain blast radius warning for critical file, got: {result}"
        );
        assert!(result.contains("45"), "warning must include direct count");
    }

    #[tokio::test]
    async fn mem_get_no_blast_warning_for_low_file() {
        let dir = TempDir::new().unwrap();
        let store = Store::open(dir.path()).await.unwrap();

        let fr = FileRecord {
            path: "src/leaf.rs".to_string(),
            purpose: "Leaf module".to_string(),
            entry_points: vec![],
            imports: vec![],
            gotcha_keys: vec![],
            decision_keys: vec![],
            todos: vec![],
            unsafe_count: 0,
            unwrap_count: 0,
            change_frequency: 0,
            last_author: None,
            is_hotspot: false,
            token_cost_estimate: 100,
            last_modified_session: 0,
            content_hash: None,
            line_count: 0,
            blast_radius: Some(crate::analysis::blast_radius::BlastRadius {
                direct: 2,
                transitive: 0,
                score: 2.0,
                tier: crate::analysis::blast_radius::BlastTier::Low,
            }),
            propagated_staleness: None,
        };
        let mut record = make_record("file:src/leaf.rs", "Leaf module", Category::File, 0.5);
        record.payload = serde_json::to_value(&fr).ok();
        store.put("file:src/leaf.rs", &record).await.unwrap();

        let graph = Graph::load(store).await.unwrap();
        let graph_arc = std::sync::Arc::new(tokio::sync::RwLock::new(graph));

        let result = call_mem_get(&graph_arc, "file:src/leaf.rs").await;

        assert!(
            !result.contains("HIGH IMPACT FILE"),
            "low blast radius file should NOT have warning"
        );
    }

    // ── mem_get enrichment_depth_hint (D2-α) ─────────────────────────────────

    #[tokio::test]
    async fn mem_get_includes_depth_hint_for_file_records() {
        let dir = TempDir::new().unwrap();
        let store = Store::open(dir.path()).await.unwrap();

        // 50 LoC, Isolated blast, no cluster, no gotchas → score 0 → Fast
        let fr = FileRecord {
            path: "src/tiny.rs".to_string(),
            purpose: "Tiny leaf module".to_string(),
            entry_points: vec![],
            imports: vec![],
            gotcha_keys: vec![],
            decision_keys: vec![],
            todos: vec![],
            unsafe_count: 0,
            unwrap_count: 0,
            change_frequency: 0,
            last_author: None,
            is_hotspot: false,
            token_cost_estimate: 100,
            last_modified_session: 0,
            content_hash: None,
            line_count: 50,
            blast_radius: Some(crate::analysis::blast_radius::BlastRadius {
                direct: 0,
                transitive: 0,
                score: 0.0,
                tier: crate::analysis::blast_radius::BlastTier::Isolated,
            }),
            propagated_staleness: None,
        };
        let mut record = make_record("file:src/tiny.rs", "Tiny leaf", Category::File, 0.5);
        record.payload = serde_json::to_value(&fr).ok();
        store.put("file:src/tiny.rs", &record).await.unwrap();

        let graph = Graph::load(store).await.unwrap();
        let graph_arc = std::sync::Arc::new(tokio::sync::RwLock::new(graph));

        let result = call_mem_get(&graph_arc, "file:src/tiny.rs").await;
        let parsed: serde_json::Value = serde_json::from_str(&result).unwrap();
        assert_eq!(
            parsed.get("enrichment_depth_hint").and_then(|v| v.as_str()),
            Some("fast"),
            "tiny isolated file should hint Fast tier; got: {result}"
        );
    }

    #[tokio::test]
    async fn mem_get_depth_hint_for_hotspot_is_deep() {
        let dir = TempDir::new().unwrap();
        let store = Store::open(dir.path()).await.unwrap();

        // 500 LoC (+3) + High blast (+2) = 5 → Deep
        let fr = FileRecord {
            path: "src/core.rs".to_string(),
            purpose: "Core hotspot".to_string(),
            entry_points: vec![],
            imports: vec![],
            gotcha_keys: vec![],
            decision_keys: vec![],
            todos: vec![],
            unsafe_count: 0,
            unwrap_count: 0,
            change_frequency: 0,
            last_author: None,
            is_hotspot: true,
            token_cost_estimate: 5000,
            last_modified_session: 0,
            content_hash: None,
            line_count: 500,
            blast_radius: Some(crate::analysis::blast_radius::BlastRadius {
                direct: 20,
                transitive: 30,
                score: 35.0,
                tier: crate::analysis::blast_radius::BlastTier::High,
            }),
            propagated_staleness: None,
        };
        let mut record = make_record("file:src/core.rs", "Core hotspot", Category::File, 0.5);
        record.payload = serde_json::to_value(&fr).ok();
        store.put("file:src/core.rs", &record).await.unwrap();

        let graph = Graph::load(store).await.unwrap();
        let graph_arc = std::sync::Arc::new(tokio::sync::RwLock::new(graph));

        let result = call_mem_get(&graph_arc, "file:src/core.rs").await;
        let parsed: serde_json::Value = serde_json::from_str(&result).unwrap();
        assert_eq!(
            parsed.get("enrichment_depth_hint").and_then(|v| v.as_str()),
            Some("deep"),
            "large hotspot file should hint Deep tier; got: {result}"
        );
    }

    #[tokio::test]
    async fn mem_get_omits_depth_hint_for_non_file_records() {
        let dir = TempDir::new().unwrap();
        let store = Store::open(dir.path()).await.unwrap();

        let record = make_record("gotcha:foo", "rule", Category::Gotcha, 0.6);
        store.put("gotcha:foo", &record).await.unwrap();

        let graph = Graph::load(store).await.unwrap();
        let graph_arc = std::sync::Arc::new(tokio::sync::RwLock::new(graph));

        let result = call_mem_get(&graph_arc, "gotcha:foo").await;
        let parsed: serde_json::Value = serde_json::from_str(&result).unwrap();
        // depth_hint is scoped to file: keys; gotcha responses must NOT carry it.
        assert!(
            parsed.get("enrichment_depth_hint").is_none(),
            "non-file records should not carry enrichment_depth_hint; got: {result}"
        );
    }

    // ── mem_query tests ──────────────────────────────────────────────────────

    #[tokio::test]
    async fn mem_query_text_mode_returns_results() {
        let dir = TempDir::new().unwrap();
        let store = Store::open(dir.path()).await.unwrap();
        let record = make_record(
            "gotcha:async-race",
            "never use inference in async context",
            Category::Gotcha,
            0.8,
        );
        store.put("gotcha:async-race", &record).await.unwrap();

        let graph = Graph::load(store).await.unwrap();
        let graph_arc = std::sync::Arc::new(tokio::sync::RwLock::new(graph));

        let result = call_mem_query(
            &graph_arc,
            "inference",
            crate::mcp::protocol::QueryMode::Text,
            10,
        )
        .await;
        assert!(result.contains("gotcha:async-race"));
    }

    // Note: γ-C3a deleted the `mem_query_unknown_mode_returns_error` test
    // that used to live here. The unknown-mode string-to-enum conversion no
    // longer happens in `tools::mem_query`'s body — after centralization,
    // typed `QueryMode` is the input. The validation now lives at the
    // protocol layer's serde Deserialize impl. Coverage moved to
    // `protocol::tests::query_mode_deserialize_rejects_unknown_variant`.

    #[tokio::test]
    async fn mem_query_semantic_returns_feature_gate_error() {
        let dir = TempDir::new().unwrap();
        let store = Store::open(dir.path()).await.unwrap();
        let graph = Graph::load(store).await.unwrap();
        let graph_arc = std::sync::Arc::new(tokio::sync::RwLock::new(graph));

        let result = call_mem_query(
            &graph_arc,
            "test",
            crate::mcp::protocol::QueryMode::Semantic,
            20,
        )
        .await;
        assert!(
            result.contains("--features semantic"),
            "semantic mode must surface feature-gate error, got: {result}"
        );
    }

    // ── mem_bootstrap tests ──────────────────────────────────────────────────

    #[tokio::test]
    async fn mem_bootstrap_empty_store_returns_vector_b() {
        let dir = TempDir::new().unwrap();
        let store = Store::open(dir.path()).await.unwrap();
        let graph = Graph::load(store).await.unwrap();
        let graph_arc = std::sync::Arc::new(tokio::sync::RwLock::new(graph));

        let result = call_mem_bootstrap(&graph_arc, vec![]).await;
        assert!(result.contains("[mati] Before reading any file"));
        assert!(result.contains("mem_get"));
    }

    #[tokio::test]
    async fn mem_bootstrap_token_budget_never_exceeds_2000() {
        let dir = TempDir::new().unwrap();
        let store = Store::open(dir.path()).await.unwrap();

        // Insert many gotchas to try to exceed the budget
        for i in 0..100 {
            let record = make_gotcha_record(
                &format!("gotcha:test-{i:03}"),
                &format!("This is a very long gotcha rule number {i} with lots of text to fill up the token budget and ensure we test the truncation logic properly"),
                true,
                0.8,
            );
            store.put(&record.key, &record).await.unwrap();
        }

        let graph = Graph::load(store).await.unwrap();

        let packet = assemble_context_packet(graph.store(), &graph, &[])
            .await
            .unwrap();
        let tokens = estimate_tokens(&packet.injection_string);
        assert!(
            tokens <= TOKEN_BUDGET,
            "token estimate {tokens} exceeds budget {TOKEN_BUDGET}"
        );
    }

    #[tokio::test]
    async fn quality_filter_suppressed_excluded() {
        let dir = TempDir::new().unwrap();
        let store = Store::open(dir.path()).await.unwrap();

        // Suppressed quality (< 0.2) — should be excluded
        let suppressed = make_gotcha_record("gotcha:suppressed", "bad rule", true, 0.10);
        store.put("gotcha:suppressed", &suppressed).await.unwrap();

        // Good quality — should be included
        let good = make_gotcha_record("gotcha:good", "good rule", true, 0.80);
        store.put("gotcha:good", &good).await.unwrap();

        let graph = Graph::load(store).await.unwrap();
        let packet = assemble_context_packet(graph.store(), &graph, &[])
            .await
            .unwrap();

        assert!(
            !packet.injection_string.contains("gotcha:suppressed"),
            "suppressed gotcha must not appear in injection"
        );
    }

    #[tokio::test]
    async fn quality_filter_poor_caveated() {
        let dir = TempDir::new().unwrap();
        let store = Store::open(dir.path()).await.unwrap();

        // Poor quality (0.2–0.4) — should be caveated but included
        let poor = make_gotcha_record("gotcha:poor", "poor rule", true, 0.30);
        store.put("gotcha:poor", &poor).await.unwrap();

        let graph = Graph::load(store).await.unwrap();
        let packet = assemble_context_packet(graph.store(), &graph, &[])
            .await
            .unwrap();

        // Poor records should appear with a caveat
        if packet.injection_string.contains("gotcha:poor") {
            assert!(
                packet.injection_string.contains("LOW QUALITY"),
                "poor quality gotcha must be caveated"
            );
        }
    }

    #[tokio::test]
    async fn assemble_context_packet_with_context_files_does_graph_traversal() {
        let dir = TempDir::new().unwrap();
        let store = Store::open(dir.path()).await.unwrap();

        // Create a gotcha record
        let gotcha = make_gotcha_record("gotcha:important", "do not use unwrap", true, 0.80);
        store.put("gotcha:important", &gotcha).await.unwrap();

        // Create a file record
        let file_record = make_record("file:src/main.rs", "{}", Category::File, 0.5);
        store.put("file:src/main.rs", &file_record).await.unwrap();

        // Build graph with HasGotcha edge
        let mut graph = Graph::load(store).await.unwrap();
        graph
            .add_edge("file:src/main.rs", EdgeKind::HasGotcha, "gotcha:important")
            .await
            .unwrap();

        let packet = assemble_context_packet(graph.store(), &graph, &["src/main.rs".to_string()])
            .await
            .unwrap();

        // The gotcha should be in the context packet
        assert!(
            packet.injection_string.contains("gotcha:important")
                || packet
                    .critical_gotchas
                    .iter()
                    .any(|g| g.key == "gotcha:important"),
            "graph-connected gotcha must appear in context packet"
        );
    }

    #[tokio::test]
    async fn assemble_context_packet_excludes_unrelated_gotchas_for_context_files() {
        let dir = TempDir::new().unwrap();
        let store = Store::open(dir.path()).await.unwrap();

        let relevant = make_gotcha_record("gotcha:relevant", "do not use unwrap", true, 0.80);
        let unrelated = make_gotcha_record("gotcha:unrelated", "keep retries bounded", true, 0.80);
        store.put("gotcha:relevant", &relevant).await.unwrap();
        store.put("gotcha:unrelated", &unrelated).await.unwrap();

        let file_record = make_record("file:src/main.rs", "{}", Category::File, 0.5);
        store.put("file:src/main.rs", &file_record).await.unwrap();

        let mut graph = Graph::load(store).await.unwrap();
        graph
            .add_edge("file:src/main.rs", EdgeKind::HasGotcha, "gotcha:relevant")
            .await
            .unwrap();

        let packet = assemble_context_packet(graph.store(), &graph, &["src/main.rs".to_string()])
            .await
            .unwrap();

        assert!(
            packet
                .critical_gotchas
                .iter()
                .any(|g| g.key == "gotcha:relevant"),
            "graph-connected gotcha must remain in context packet"
        );
        assert!(
            !packet
                .critical_gotchas
                .iter()
                .any(|g| g.key == "gotcha:unrelated"),
            "unrelated gotcha must not be injected for scoped bootstrap"
        );
        assert!(
            !packet.injection_string.contains("gotcha:unrelated"),
            "injection string must not mention unrelated gotchas"
        );
    }

    /// Regression test for the bootstrap low-confidence file bug.
    ///
    /// Scenario: file record has confidence 0.10 (Layer 0 stub from mati init),
    /// a confirmed gotcha with confidence 0.80 is linked via FileRecord.gotcha_keys,
    /// but NO HasGotcha graph edge exists (simulating CLI gotcha_write that wrote to
    /// the store but never updated the in-memory graph).
    ///
    /// Bootstrap must still surface the confirmed gotcha by falling back to
    /// FileRecord.gotcha_keys when graph edges are absent.
    #[tokio::test]
    async fn bootstrap_surfaces_confirmed_gotcha_when_graph_edge_missing() {
        let dir = TempDir::new().unwrap();
        let store = Store::open(dir.path()).await.unwrap();

        // Confirmed gotcha with high confidence/quality
        let gotcha = make_gotcha_record(
            "gotcha:never-remove-rate-limit",
            "Never remove the rate limit check on incoming pipeline events because \
             removing it caused a cascade failure in staging",
            true,
            0.80,
        );
        store
            .put("gotcha:never-remove-rate-limit", &gotcha)
            .await
            .unwrap();

        // File record: low-confidence stub (confidence 0.10), but gotcha_keys populated
        let file_record = {
            let fr = FileRecord {
                path: "src/pipeline/prefilter.rs".to_string(),
                purpose: String::new(), // no purpose — Layer 0 stub
                entry_points: vec![],
                imports: vec![],
                gotcha_keys: vec!["gotcha:never-remove-rate-limit".to_string()],
                decision_keys: vec![],
                todos: vec![],
                unsafe_count: 0,
                unwrap_count: 0,
                change_frequency: 18,
                last_author: Some("dev".to_string()),
                is_hotspot: true,
                token_cost_estimate: 0,
                last_modified_session: now(),
                content_hash: None,
                line_count: 0,
                blast_radius: None,
                propagated_staleness: None,
            };
            let mut r = make_record(
                "file:src/pipeline/prefilter.rs",
                "",
                Category::File,
                0.10, // low confidence — stub
            );
            r.payload = serde_json::to_value(&fr).ok();
            r
        };
        store
            .put("file:src/pipeline/prefilter.rs", &file_record)
            .await
            .unwrap();

        // Intentionally do NOT add a HasGotcha graph edge — simulates the CLI
        // gotcha_write bug where the persistent store edge was written but the
        // in-memory graph was never updated.
        let graph = Graph::load(store).await.unwrap();
        assert_eq!(
            graph.neighbors("file:src/pipeline/prefilter.rs", &EdgeKind::HasGotcha),
            Vec::<String>::new(),
            "test setup: graph must have no HasGotcha edge"
        );

        let packet = assemble_context_packet(
            graph.store(),
            &graph,
            &["src/pipeline/prefilter.rs".to_string()],
        )
        .await
        .unwrap();

        assert!(
            packet
                .critical_gotchas
                .iter()
                .any(|g| g.key == "gotcha:never-remove-rate-limit"),
            "bootstrap must surface confirmed gotcha even when graph edge is missing"
        );
        assert!(
            packet
                .injection_string
                .contains("gotcha:never-remove-rate-limit"),
            "injection string must include the gotcha"
        );
    }

    /// Negative case: file with confidence 0.10 and NO confirmed gotchas should
    /// produce minimal bootstrap output — no purpose text, no gotchas, no receipt.
    #[tokio::test]
    async fn bootstrap_low_confidence_file_with_no_gotchas_returns_minimal_packet() {
        let dir = TempDir::new().unwrap();
        let store = Store::open(dir.path()).await.unwrap();

        let file_record = {
            let fr = FileRecord {
                path: "src/empty.rs".to_string(),
                purpose: String::new(),
                entry_points: vec![],
                imports: vec![],
                gotcha_keys: vec![],
                decision_keys: vec![],
                todos: vec![],
                unsafe_count: 0,
                unwrap_count: 0,
                change_frequency: 1,
                last_author: None,
                is_hotspot: false,
                token_cost_estimate: 0,
                last_modified_session: now(),
                content_hash: None,
                line_count: 0,
                blast_radius: None,
                propagated_staleness: None,
            };
            let mut r = make_record("file:src/empty.rs", "", Category::File, 0.10);
            r.payload = serde_json::to_value(&fr).ok();
            r
        };
        store.put("file:src/empty.rs", &file_record).await.unwrap();

        let graph = Graph::load(store).await.unwrap();
        let packet = assemble_context_packet(graph.store(), &graph, &["src/empty.rs".to_string()])
            .await
            .unwrap();

        assert!(
            packet.critical_gotchas.is_empty(),
            "no gotchas should be surfaced for a file with no linked gotchas"
        );
        assert!(
            !packet.injection_string.contains("gotcha:"),
            "injection string must not mention any gotcha keys"
        );
    }

    // ── M-12-E: nudge detection ─────────────────────────────────────────────

    #[tokio::test]
    async fn nudge_shown_for_hot_file_with_no_gotchas() {
        let dir = TempDir::new().unwrap();
        let store = Store::open(dir.path()).await.unwrap();

        let fr = FileRecord {
            path: "src/hot.rs".to_string(),
            purpose: "Hot module".to_string(),
            entry_points: vec!["run".to_string()],
            imports: vec![],
            gotcha_keys: vec![], // no gotchas
            decision_keys: vec![],
            todos: vec![],
            unsafe_count: 0,
            unwrap_count: 0,
            change_frequency: 10,
            last_author: None,
            is_hotspot: true,
            token_cost_estimate: 100,
            last_modified_session: now(),
            content_hash: None,
            line_count: 0,
            blast_radius: None,
            propagated_staleness: None,
        };
        let mut file_record = make_record("file:src/hot.rs", &fr.purpose, Category::File, 0.5);
        file_record.payload = serde_json::to_value(&fr).ok();
        file_record.access_count = 5; // >= 3 threshold
        store.put("file:src/hot.rs", &file_record).await.unwrap();

        let graph = Graph::load(store).await.unwrap();
        let packet = assemble_context_packet(graph.store(), &graph, &["src/hot.rs".to_string()])
            .await
            .unwrap();

        assert!(
            packet
                .unconfirmed_candidates
                .contains(&"file:src/hot.rs".to_string()),
            "hot file with no gotchas should be in unconfirmed_candidates"
        );
        assert!(
            packet.injection_string.contains("Suggested Actions"),
            "nudge section should appear in injection string"
        );
        assert!(
            packet.injection_string.contains("mati gotcha add"),
            "nudge should suggest gotcha add command"
        );
    }

    #[tokio::test]
    async fn no_nudge_for_file_with_low_access_count() {
        let dir = TempDir::new().unwrap();
        let store = Store::open(dir.path()).await.unwrap();

        let fr = FileRecord {
            path: "src/cold.rs".to_string(),
            purpose: "Cold module".to_string(),
            entry_points: vec![],
            imports: vec![],
            gotcha_keys: vec![],
            decision_keys: vec![],
            todos: vec![],
            unsafe_count: 0,
            unwrap_count: 0,
            change_frequency: 0,
            last_author: None,
            is_hotspot: false,
            token_cost_estimate: 50,
            last_modified_session: now(),
            content_hash: None,
            line_count: 0,
            blast_radius: None,
            propagated_staleness: None,
        };
        let mut file_record = make_record("file:src/cold.rs", &fr.purpose, Category::File, 0.5);
        file_record.payload = serde_json::to_value(&fr).ok();
        file_record.access_count = 1; // < 3 threshold
        store.put("file:src/cold.rs", &file_record).await.unwrap();

        let graph = Graph::load(store).await.unwrap();
        let packet = assemble_context_packet(graph.store(), &graph, &["src/cold.rs".to_string()])
            .await
            .unwrap();

        assert!(
            packet.unconfirmed_candidates.is_empty(),
            "low-access file should not trigger nudge"
        );
    }

    #[tokio::test]
    async fn no_nudge_for_file_with_gotchas() {
        let dir = TempDir::new().unwrap();
        let store = Store::open(dir.path()).await.unwrap();

        let fr = FileRecord {
            path: "src/covered.rs".to_string(),
            purpose: "Covered module".to_string(),
            entry_points: vec![],
            imports: vec![],
            gotcha_keys: vec!["gotcha:existing".to_string()],
            decision_keys: vec![],
            todos: vec![],
            unsafe_count: 0,
            unwrap_count: 0,
            change_frequency: 10,
            last_author: None,
            is_hotspot: true,
            token_cost_estimate: 100,
            last_modified_session: now(),
            content_hash: None,
            line_count: 0,
            blast_radius: None,
            propagated_staleness: None,
        };
        let mut file_record = make_record(
            "file:src/covered.rs",
            &serde_json::to_string(&fr).unwrap(),
            Category::File,
            0.5,
        );
        file_record.access_count = 10;
        store
            .put("file:src/covered.rs", &file_record)
            .await
            .unwrap();

        let graph = Graph::load(store).await.unwrap();
        let packet =
            assemble_context_packet(graph.store(), &graph, &["src/covered.rs".to_string()])
                .await
                .unwrap();

        assert!(
            packet.unconfirmed_candidates.is_empty(),
            "file with gotchas should not trigger nudge"
        );
    }

    // ── M-13-B: stale warning tests ─────────────────────────────────────────

    #[tokio::test]
    async fn tombstone_gotcha_excluded_from_bootstrap() {
        let dir = TempDir::new().unwrap();
        let store = Store::open(dir.path()).await.unwrap();

        // Create a tombstone-tier gotcha
        let mut gotcha = make_gotcha_record("gotcha:tombstone", "tombstone rule", true, 0.80);
        gotcha.staleness = StalenessScore {
            value: 0.95,
            tier: StalenessTier::Tombstone,
            signals: vec![],
            computed_at: now(),
            last_record_sha: String::new(),
        };
        store.put("gotcha:tombstone", &gotcha).await.unwrap();

        // Create a normal gotcha
        let good = make_gotcha_record("gotcha:good", "good rule", true, 0.80);
        store.put("gotcha:good", &good).await.unwrap();

        let graph = Graph::load(store).await.unwrap();
        let packet = assemble_context_packet(graph.store(), &graph, &[])
            .await
            .unwrap();

        assert!(
            !packet.injection_string.contains("gotcha:tombstone"),
            "tombstone gotcha must not appear in injection"
        );
        assert!(
            packet.injection_string.contains("gotcha:good"),
            "normal gotcha should appear"
        );
    }

    #[tokio::test]
    async fn liability_gotcha_gets_stale_caveat() {
        let dir = TempDir::new().unwrap();
        let store = Store::open(dir.path()).await.unwrap();

        let mut gotcha = make_gotcha_record("gotcha:liability", "liability rule", true, 0.80);
        gotcha.staleness = StalenessScore {
            value: 0.75,
            tier: StalenessTier::Liability,
            signals: vec![],
            computed_at: now(),
            last_record_sha: String::new(),
        };
        store.put("gotcha:liability", &gotcha).await.unwrap();

        let graph = Graph::load(store).await.unwrap();
        let packet = assemble_context_packet(graph.store(), &graph, &[])
            .await
            .unwrap();

        if packet.injection_string.contains("gotcha:liability") {
            assert!(
                packet.injection_string.contains("STALE"),
                "liability gotcha must have STALE caveat"
            );
        }
    }

    #[tokio::test]
    async fn stale_file_generates_warning() {
        let dir = TempDir::new().unwrap();
        let store = Store::open(dir.path()).await.unwrap();

        let fr = FileRecord {
            path: "src/stale.rs".to_string(),
            purpose: "Stale module".to_string(),
            entry_points: vec![],
            imports: vec![],
            gotcha_keys: vec![],
            decision_keys: vec![],
            todos: vec![],
            unsafe_count: 0,
            unwrap_count: 0,
            change_frequency: 0,
            last_author: None,
            is_hotspot: false,
            token_cost_estimate: 50,
            last_modified_session: now(),
            content_hash: None,
            line_count: 0,
            blast_radius: None,
            propagated_staleness: None,
        };
        let mut file_record = make_record(
            "file:src/stale.rs",
            &serde_json::to_string(&fr).unwrap(),
            Category::File,
            0.5,
        );
        file_record.staleness = StalenessScore {
            value: 0.55,
            tier: StalenessTier::Stale,
            signals: vec![],
            computed_at: now(),
            last_record_sha: String::new(),
        };
        store.put("file:src/stale.rs", &file_record).await.unwrap();

        let graph = Graph::load(store).await.unwrap();
        let packet = assemble_context_packet(graph.store(), &graph, &["src/stale.rs".to_string()])
            .await
            .unwrap();

        assert!(
            !packet.stale_warnings.is_empty(),
            "stale file should generate a warning"
        );
        assert!(
            packet.stale_warnings.iter().any(|w| w.contains("stale.rs")),
            "warning should mention the stale file"
        );
    }

    #[tokio::test]
    async fn tombstone_file_excluded_from_traversal() {
        let dir = TempDir::new().unwrap();
        let store = Store::open(dir.path()).await.unwrap();

        let fr = FileRecord {
            path: "src/dead.rs".to_string(),
            purpose: "Dead module".to_string(),
            entry_points: vec![],
            imports: vec![],
            gotcha_keys: vec![],
            decision_keys: vec![],
            todos: vec![],
            unsafe_count: 0,
            unwrap_count: 0,
            change_frequency: 0,
            last_author: None,
            is_hotspot: false,
            token_cost_estimate: 50,
            last_modified_session: now(),
            content_hash: None,
            line_count: 0,
            blast_radius: None,
            propagated_staleness: None,
        };
        let mut file_record = make_record(
            "file:src/dead.rs",
            &serde_json::to_string(&fr).unwrap(),
            Category::File,
            0.5,
        );
        file_record.staleness = StalenessScore {
            value: 0.95,
            tier: StalenessTier::Tombstone,
            signals: vec![],
            computed_at: now(),
            last_record_sha: String::new(),
        };
        store.put("file:src/dead.rs", &file_record).await.unwrap();

        let graph = Graph::load(store).await.unwrap();
        let packet = assemble_context_packet(graph.store(), &graph, &["src/dead.rs".to_string()])
            .await
            .unwrap();

        assert!(
            packet.file_records.is_empty(),
            "tombstone file should not appear in file_records"
        );
    }

    #[tokio::test]
    async fn stale_warnings_deduplicated() {
        let dir = TempDir::new().unwrap();
        let store = Store::open(dir.path()).await.unwrap();

        let fr = FileRecord {
            path: "src/dup.rs".to_string(),
            purpose: "Dup module".to_string(),
            entry_points: vec![],
            imports: vec![],
            gotcha_keys: vec![],
            decision_keys: vec![],
            todos: vec![],
            unsafe_count: 0,
            unwrap_count: 0,
            change_frequency: 0,
            last_author: None,
            is_hotspot: false,
            token_cost_estimate: 50,
            last_modified_session: now(),
            content_hash: None,
            line_count: 0,
            blast_radius: None,
            propagated_staleness: None,
        };
        let mut file_record = make_record(
            "file:src/dup.rs",
            &serde_json::to_string(&fr).unwrap(),
            Category::File,
            0.5,
        );
        file_record.staleness = StalenessScore {
            value: 0.55,
            tier: StalenessTier::Stale,
            signals: vec![],
            computed_at: now(),
            last_record_sha: String::new(),
        };
        store.put("file:src/dup.rs", &file_record).await.unwrap();

        // Also create a stale review entry for the same key
        let review_payload = StaleReviewPayload {
            session_timestamp: now(),
            entries: vec![StaleReviewEntry {
                key: "file:src/dup.rs".to_string(),
                staleness_value: 0.55,
                tier: StalenessTier::Stale,
                last_updated: now(),
                signals: vec!["stale".to_string()],
            }],
        };
        let today = chrono::Utc::now().format("%Y-%m-%d").to_string();
        let review_key = format!("analytics:stale_review_{today}");
        let review_record = make_record(
            &review_key,
            &serde_json::to_string(&review_payload).unwrap(),
            Category::Analytics,
            0.5,
        );
        store.put(&review_key, &review_record).await.unwrap();

        let graph = Graph::load(store).await.unwrap();
        let packet = assemble_context_packet(graph.store(), &graph, &["src/dup.rs".to_string()])
            .await
            .unwrap();

        // Should have exactly 1 warning, not 2 (dedup by key)
        let dup_count = packet
            .stale_warnings
            .iter()
            .filter(|w| w.contains("dup.rs"))
            .count();
        assert_eq!(
            dup_count, 1,
            "same key should not produce duplicate warnings"
        );
    }

    #[tokio::test]
    async fn stale_warnings_section_before_decisions() {
        let dir = TempDir::new().unwrap();
        let store = Store::open(dir.path()).await.unwrap();

        // Create a stale file
        let fr = FileRecord {
            path: "src/stale.rs".to_string(),
            purpose: "Stale".to_string(),
            entry_points: vec![],
            imports: vec![],
            gotcha_keys: vec![],
            decision_keys: vec![],
            todos: vec![],
            unsafe_count: 0,
            unwrap_count: 0,
            change_frequency: 0,
            last_author: None,
            is_hotspot: false,
            token_cost_estimate: 50,
            last_modified_session: now(),
            content_hash: None,
            line_count: 0,
            blast_radius: None,
            propagated_staleness: None,
        };
        let mut file_record = make_record(
            "file:src/stale.rs",
            &serde_json::to_string(&fr).unwrap(),
            Category::File,
            0.5,
        );
        file_record.staleness = StalenessScore {
            value: 0.55,
            tier: StalenessTier::Stale,
            signals: vec![],
            computed_at: now(),
            last_record_sha: String::new(),
        };
        store.put("file:src/stale.rs", &file_record).await.unwrap();

        // Create a decision record reachable via graph edge
        let decision = make_record("decision:arch", "Use SurrealKV", Category::Decision, 0.8);
        store.put("decision:arch", &decision).await.unwrap();

        let mut graph = Graph::load(store).await.unwrap();
        graph
            .add_edge("file:src/stale.rs", EdgeKind::AffectedBy, "decision:arch")
            .await
            .unwrap();

        let packet = assemble_context_packet(graph.store(), &graph, &["src/stale.rs".to_string()])
            .await
            .unwrap();

        let stale_pos = packet.injection_string.find("## Stale Warnings");
        let dec_pos = packet.injection_string.find("## Decisions");

        if let (Some(s), Some(d)) = (stale_pos, dec_pos) {
            assert!(s < d, "Stale Warnings section must appear before Decisions");
        }
    }

    #[tokio::test]
    async fn unconfirmed_gotcha_never_injected() {
        let dir = TempDir::new().unwrap();
        let store = Store::open(dir.path()).await.unwrap();

        // Create an unconfirmed gotcha
        let unconfirmed = make_gotcha_record("gotcha:unconfirmed", "unconfirmed rule", false, 0.80);
        store.put("gotcha:unconfirmed", &unconfirmed).await.unwrap();

        let graph = Graph::load(store).await.unwrap();
        let packet = assemble_context_packet(graph.store(), &graph, &[])
            .await
            .unwrap();

        assert!(
            !packet.injection_string.contains("gotcha:unconfirmed"),
            "unconfirmed gotcha must never be injected"
        );
    }

    #[tokio::test]
    async fn empty_store_returns_only_vector_b() {
        let dir = TempDir::new().unwrap();
        let store = Store::open(dir.path()).await.unwrap();
        let graph = Graph::load(store).await.unwrap();

        let packet = assemble_context_packet(graph.store(), &graph, &[])
            .await
            .unwrap();

        assert!(packet.injection_string.contains("[mati] Before reading"));
        assert!(packet.critical_gotchas.is_empty());
        assert!(packet.file_records.is_empty());
        assert!(packet.stale_warnings.is_empty());
        assert!(packet.related_decisions.is_empty());
    }

    // ── mem_set tests ────────────────────────────────────────────────────────

    /// Direct-path mem_set must reject `file:*` writes — they are owned by
    /// the static-analysis pipeline (`mati init` Layer 0 + the
    /// `file_enrich` / `file_reparse` typed Commands). Mirrors the Socket
    /// path's rejection in `build_mem_set_command` so both backends behave
    /// identically (regression for the codex smoke-test step 57 failure).
    #[tokio::test]
    async fn mem_set_rejects_file_writes_on_direct_path() {
        let dir = TempDir::new().unwrap();
        let store = Store::open(dir.path()).await.unwrap();
        let graph = Graph::load(store).await.unwrap();
        let graph_arc = std::sync::Arc::new(tokio::sync::RwLock::new(graph));

        let result = call_mem_set(
            &graph_arc,
            MemSetParams {
                action: "write".to_string(),
                key: "file:src/main.rs".to_string(),
                value: "Handles CLI dispatch and binary entry point".to_string(),
                category: "File".to_string(),
                payload: serde_json::json!({
                    "path": "src/main.rs",
                    "purpose": "Handles CLI dispatch and binary entry point"
                }),
                tags: vec!["entry-point".to_string()],
                priority: "Normal".to_string(),
            },
        )
        .await;

        let parsed: serde_json::Value = serde_json::from_str(&result).unwrap();
        let error = parsed["error"]
            .as_str()
            .unwrap_or_else(|| panic!("expected an error envelope, got: {result}"));
        assert!(
            error.contains("must start with"),
            "file: write must be rejected by the prefix gate, got: {error}"
        );
        assert_eq!(parsed.get("ok"), None, "no record should be written");

        // Confirm no record was persisted.
        let graph = graph_arc.read().await;
        assert!(
            graph
                .store()
                .get("file:src/main.rs")
                .await
                .unwrap()
                .is_none(),
            "file: write must not create a record"
        );
    }

    #[tokio::test]
    async fn mem_set_writes_gotcha_with_quality_score() {
        let dir = TempDir::new().unwrap();
        let store = Store::open(dir.path()).await.unwrap();
        let graph = Graph::load(store).await.unwrap();
        let graph_arc = std::sync::Arc::new(tokio::sync::RwLock::new(graph));

        let result = call_mem_set(
            &graph_arc,
            MemSetParams { action: "write".to_string(),
                key: "gotcha:always-use-idempotency-keys".to_string(),
                value: "Always pass idempotency_key to Stripe charge creation because duplicate charges cause customer refund disputes".to_string(),
                category: "Gotcha".to_string(),
                payload: serde_json::json!({
                    "rule": "Always pass idempotency_key to Stripe charge creation",
                    "reason": "duplicate charges cause customer refund disputes",
                    "severity": "Critical",
                    "affected_files": ["src/payments/stripe.go"],
                    "ref_url": null,
                    "discovered_session": 0,
                    "confirmed": false
                }),
                tags: vec![],
                priority: "Critical".to_string(),
            },
        )
        .await;

        let parsed: serde_json::Value = serde_json::from_str(&result).unwrap();
        assert_eq!(parsed["ok"], true);
        // Quality should be > 0.2 (passes gate) since rule has imperative verb + reason has causality
        assert!(parsed["quality"].as_f64().unwrap() > 0.2);

        // Read back
        let graph = graph_arc.read().await;
        let record = graph
            .store()
            .get("gotcha:always-use-idempotency-keys")
            .await
            .unwrap()
            .unwrap();
        assert_eq!(record.priority, Priority::Critical);
        assert_eq!(record.source, RecordSource::ClaudeEnrich);
    }

    // `mem_set_preserves_existing_layer0_data` was removed: file: writes
    // are no longer accepted via mem_set on either backend. Layer 0
    // preservation under enrichment is now exercised by the
    // `file_enrich` typed Command's tests (see `handle_file_enrich`).

    #[tokio::test]
    async fn mem_set_rejects_invalid_key_prefix() {
        let dir = TempDir::new().unwrap();
        let store = Store::open(dir.path()).await.unwrap();
        let graph = Graph::load(store).await.unwrap();
        let graph_arc = std::sync::Arc::new(tokio::sync::RwLock::new(graph));

        let result = call_mem_set(
            &graph_arc,
            MemSetParams {
                action: "write".to_string(),
                key: "session:12345".to_string(),
                value: "test".to_string(),
                category: "Gotcha".to_string(),
                payload: serde_json::json!({}),
                tags: vec![],
                priority: "Normal".to_string(),
            },
        )
        .await;

        let parsed: serde_json::Value = serde_json::from_str(&result).unwrap();
        let error = parsed["error"].as_str().unwrap();
        assert!(error.contains("must start with"), "got: {error}");
        // file: was deliberately removed from the accepted prefix list.
        assert!(!error.contains("file:"), "got: {error}");
    }

    #[tokio::test]
    async fn mem_set_rejects_invalid_category() {
        let dir = TempDir::new().unwrap();
        let store = Store::open(dir.path()).await.unwrap();
        let graph = Graph::load(store).await.unwrap();
        let graph_arc = std::sync::Arc::new(tokio::sync::RwLock::new(graph));

        let result = call_mem_set(
            &graph_arc,
            MemSetParams {
                action: "write".to_string(),
                key: "gotcha:test".to_string(),
                value: "test".to_string(),
                category: "Unknown".to_string(),
                payload: serde_json::json!({}),
                tags: vec![],
                priority: "Normal".to_string(),
            },
        )
        .await;

        let parsed: serde_json::Value = serde_json::from_str(&result).unwrap();
        assert!(parsed["error"]
            .as_str()
            .unwrap()
            .contains("unknown category"));
    }

    #[tokio::test]
    async fn mem_set_rejects_key_category_mismatch() {
        let dir = TempDir::new().unwrap();
        let store = Store::open(dir.path()).await.unwrap();
        let graph = Graph::load(store).await.unwrap();
        let graph_arc = std::sync::Arc::new(tokio::sync::RwLock::new(graph));

        // gotcha: key with Decision category — must be rejected.
        // (File is no longer a valid category for mem_set, so the prior
        // gotcha:/File pairing now fails category parsing instead of the
        // mismatch check; pick another valid-but-wrong category to keep
        // exercising the mismatch arm.)
        let result = call_mem_set(
            &graph_arc,
            MemSetParams {
                action: "write".to_string(),
                key: "gotcha:should-fail".to_string(),
                value: "test".to_string(),
                category: "Decision".to_string(),
                payload: serde_json::json!({"summary": "x", "rationale": "y"}),
                tags: vec![],
                priority: "Normal".to_string(),
            },
        )
        .await;

        let parsed: serde_json::Value = serde_json::from_str(&result).unwrap();
        assert!(
            parsed["error"]
                .as_str()
                .unwrap()
                .contains("requires category"),
            "key-category mismatch must be rejected: {result}"
        );
    }

    #[tokio::test]
    async fn mem_set_rejects_new_gotcha_without_rule_and_reason() {
        let dir = TempDir::new().unwrap();
        let store = Store::open(dir.path()).await.unwrap();
        let graph = Graph::load(store).await.unwrap();
        let graph_arc = std::sync::Arc::new(tokio::sync::RwLock::new(graph));

        let result = call_mem_set(
            &graph_arc,
            MemSetParams {
                action: "write".to_string(),
                key: "gotcha:missing-fields".to_string(),
                value: "test".to_string(),
                category: "Gotcha".to_string(),
                payload: serde_json::json!({"severity": "Normal"}),
                tags: vec![],
                priority: "Normal".to_string(),
            },
        )
        .await;

        let parsed: serde_json::Value = serde_json::from_str(&result).unwrap();
        assert!(
            parsed["error"]
                .as_str()
                .unwrap()
                .contains("'rule' and 'reason'"),
            "new gotcha without rule/reason must be rejected: {result}"
        );
    }

    #[tokio::test]
    async fn mem_set_rejects_new_decision_without_summary_rationale() {
        let dir = TempDir::new().unwrap();
        let store = Store::open(dir.path()).await.unwrap();
        let graph = Graph::load(store).await.unwrap();
        let graph_arc = std::sync::Arc::new(tokio::sync::RwLock::new(graph));

        let result = call_mem_set(
            &graph_arc,
            MemSetParams {
                action: "write".to_string(),
                key: "decision:incomplete".to_string(),
                value: "test".to_string(),
                category: "Decision".to_string(),
                payload: serde_json::json!({}),
                tags: vec![],
                priority: "Normal".to_string(),
            },
        )
        .await;

        let parsed: serde_json::Value = serde_json::from_str(&result).unwrap();
        assert!(
            parsed["error"]
                .as_str()
                .unwrap()
                .contains("'summary' and 'rationale'"),
            "new decision without summary/rationale must be rejected: {result}"
        );
    }

    #[tokio::test]
    async fn mem_set_rejects_new_dev_note_with_empty_value() {
        let dir = TempDir::new().unwrap();
        let store = Store::open(dir.path()).await.unwrap();
        let graph = Graph::load(store).await.unwrap();
        let graph_arc = std::sync::Arc::new(tokio::sync::RwLock::new(graph));

        let result = call_mem_set(
            &graph_arc,
            MemSetParams {
                action: "write".to_string(),
                key: "dev_note:empty".to_string(),
                value: "".to_string(),
                category: "DevNote".to_string(),
                payload: serde_json::json!({}),
                tags: vec![],
                priority: "Normal".to_string(),
            },
        )
        .await;

        let parsed: serde_json::Value = serde_json::from_str(&result).unwrap();
        assert!(
            parsed["error"]
                .as_str()
                .unwrap()
                .contains("non-empty value"),
            "new dev_note with empty value must be rejected: {result}"
        );
    }

    #[tokio::test]
    async fn mem_set_allows_partial_payload_on_update() {
        let dir = TempDir::new().unwrap();
        let store = Store::open(dir.path()).await.unwrap();
        let graph = Graph::load(store).await.unwrap();
        let graph_arc = std::sync::Arc::new(tokio::sync::RwLock::new(graph));

        // First write: full payload (new record).
        let result = call_mem_set(
            &graph_arc,
            MemSetParams {
                action: "write".to_string(),
                key: "gotcha:partial-update".to_string(),
                value: "test rule because test reason".to_string(),
                category: "Gotcha".to_string(),
                payload: serde_json::json!({
                    "rule": "test rule",
                    "reason": "test reason",
                    "severity": "Normal",
                    "affected_files": [],
                }),
                tags: vec![],
                priority: "Normal".to_string(),
            },
        )
        .await;
        let parsed: serde_json::Value = serde_json::from_str(&result).unwrap();
        assert_eq!(parsed["ok"], true, "initial write must succeed");

        // Second write: partial payload (update) — must succeed because
        // payload validation is skipped for existing records (merge fills fields).
        let result = call_mem_set(
            &graph_arc,
            MemSetParams {
                action: "write".to_string(),
                key: "gotcha:partial-update".to_string(),
                value: "updated rule because updated reason".to_string(),
                category: "Gotcha".to_string(),
                payload: serde_json::json!({"reason": "updated reason"}),
                tags: vec![],
                priority: "Normal".to_string(),
            },
        )
        .await;
        let parsed: serde_json::Value = serde_json::from_str(&result).unwrap();
        assert_eq!(
            parsed["ok"], true,
            "partial-payload update must succeed: {result}"
        );
    }

    #[tokio::test]
    async fn mem_set_preserves_confirmation_state_on_update() {
        let dir = TempDir::new().unwrap();
        let store = Store::open(dir.path()).await.unwrap();

        // Create a confirmed gotcha (simulates post-mati gotcha confirm state)
        let mut record = make_gotcha_record(
            "gotcha:confirmed-edit-test",
            "Always test first",
            true,
            0.70,
        );
        record.source = RecordSource::DeveloperManual;
        record.confidence = ConfidenceScore {
            value: 0.80,
            confirmation_count: 1,
            contributor_count: 1,
            last_challenged: None,
            challenge_count: 0,
        };
        record.tags = vec!["important".to_string()];
        store
            .put("gotcha:confirmed-edit-test", &record)
            .await
            .unwrap();

        let graph = Graph::load(store).await.unwrap();
        let graph_arc = std::sync::Arc::new(tokio::sync::RwLock::new(graph));

        // Update the gotcha's value via mem_set (simulates Claude editing the reason)
        let result = call_mem_set(
            &graph_arc,
            MemSetParams {
                action: "write".to_string(),
                key: "gotcha:confirmed-edit-test".to_string(),
                value: "Always test first because untested changes cause regressions".to_string(),
                category: "Gotcha".to_string(),
                payload: serde_json::json!({
                    "rule": "Always test first",
                    "reason": "untested changes cause regressions",
                    "severity": "High",
                    "affected_files": ["src/main.rs"],
                    "ref_url": null,
                    "discovered_session": 0,
                    "confirmed": true
                }),
                tags: vec![], // empty — should NOT clear existing tags
                priority: "High".to_string(),
            },
        )
        .await;

        let parsed: serde_json::Value = serde_json::from_str(&result).unwrap();
        assert_eq!(parsed["ok"], true);

        // Verify confirmation state preserved
        let graph = graph_arc.read().await;
        let updated = graph
            .store()
            .get("gotcha:confirmed-edit-test")
            .await
            .unwrap()
            .unwrap();
        assert_eq!(updated.source, RecordSource::DeveloperManual);
        assert!(
            (updated.confidence.value - 0.80).abs() < 0.01,
            "confidence should stay 0.80, got {}",
            updated.confidence.value
        );
        assert_eq!(updated.confidence.confirmation_count, 1);
        assert_eq!(
            updated.tags,
            vec!["important".to_string()],
            "tags should be preserved when caller sends empty"
        );
    }

    #[tokio::test]
    async fn mem_set_moves_gotcha_links_and_edges_on_edit() {
        let dir = TempDir::new().unwrap();
        let store = Store::open(dir.path()).await.unwrap();

        // Seed file records for both old and new affected files.
        let old_file = Record::layer0_file_stub("file:src/old.rs", device_id(), 1, now());
        let new_file = Record::layer0_file_stub("file:src/new.rs", device_id(), 1, now());
        store.put("file:src/old.rs", &old_file).await.unwrap();
        store.put("file:src/new.rs", &new_file).await.unwrap();

        let graph = Graph::load(store).await.unwrap();
        let graph_arc = std::sync::Arc::new(tokio::sync::RwLock::new(graph));

        call_mem_set(
            &graph_arc,
            MemSetParams {
                action: "write".to_string(),
                key: "gotcha:test-move".to_string(),
                value: "Always update the paired file because drift breaks the feature".to_string(),
                category: "Gotcha".to_string(),
                payload: serde_json::json!({
                    "rule": "Always update the paired file",
                    "reason": "drift breaks the feature",
                    "severity": "High",
                    "affected_files": ["src/old.rs"],
                    "ref_url": null,
                    "discovered_session": 0,
                    "confirmed": false
                }),
                tags: vec![],
                priority: "High".to_string(),
            },
        )
        .await;

        call_mem_set(
            &graph_arc,
            MemSetParams {
                action: "write".to_string(),
                key: "gotcha:test-move".to_string(),
                value: "Always update the paired file because drift breaks the feature".to_string(),
                category: "Gotcha".to_string(),
                payload: serde_json::json!({
                    "rule": "Always update the paired file",
                    "reason": "drift breaks the feature",
                    "severity": "High",
                    "affected_files": ["src/new.rs"],
                    "ref_url": null,
                    "discovered_session": 0,
                    "confirmed": false
                }),
                tags: vec![],
                priority: "High".to_string(),
            },
        )
        .await;

        let graph = graph_arc.read().await;

        let old_file = graph.store().get("file:src/old.rs").await.unwrap().unwrap();
        let new_file = graph.store().get("file:src/new.rs").await.unwrap().unwrap();
        let old_payload = old_file.payload.unwrap();
        let new_payload = new_file.payload.unwrap();

        assert!(
            old_payload["gotcha_keys"]
                .as_array()
                .map(|arr| arr.is_empty())
                .unwrap_or(true),
            "old file should no longer reference moved gotcha"
        );
        assert_eq!(new_payload["gotcha_keys"][0], "gotcha:test-move");

        assert!(
            !graph
                .neighbors("file:src/old.rs", &EdgeKind::HasGotcha)
                .contains(&"gotcha:test-move".to_string()),
            "old file should not keep stale HasGotcha edge"
        );
        assert!(
            graph
                .neighbors("file:src/new.rs", &EdgeKind::HasGotcha)
                .contains(&"gotcha:test-move".to_string()),
            "new file should gain HasGotcha edge"
        );
    }

    // ── Regression: query limit clamp ───────────────────────────────────────

    /// Regression test: mem_query must clamp the limit to MAX_QUERY_LIMIT (50)
    /// even when the caller passes a larger value. Passing limit=100 must not
    /// error and must return at most 50 results.
    #[tokio::test]
    async fn test_query_limit_clamped_to_max() {
        let dir = TempDir::new().unwrap();
        let store = Store::open(dir.path()).await.unwrap();

        // Insert 60 records — more than MAX_QUERY_LIMIT (50).
        for i in 0..60 {
            let record = make_record(
                &format!("gotcha:clamp-test-{i:03}"),
                &format!("clamp test rule number {i}"),
                Category::Gotcha,
                0.8,
            );
            store
                .put(&format!("gotcha:clamp-test-{i:03}"), &record)
                .await
                .unwrap();
        }

        let graph = Graph::load(store).await.unwrap();
        let graph_arc = std::sync::Arc::new(tokio::sync::RwLock::new(graph));

        let result = call_mem_query(
            &graph_arc,
            "clamp test rule",
            crate::mcp::protocol::QueryMode::Text,
            100, // exceeds MAX_QUERY_LIMIT (50)
        )
        .await;

        // Must not error
        let parsed: serde_json::Value = serde_json::from_str(&result).unwrap();
        assert!(
            parsed.get("error").is_none(),
            "query with limit > 50 must not error"
        );

        // Must return at most 50 results (the clamped limit)
        let results = parsed.as_array().expect("result should be a JSON array");
        assert!(
            results.len() <= 50,
            "result count {} exceeds MAX_QUERY_LIMIT (50)",
            results.len()
        );
    }

    // ── Regression: store-read-error refusal on mem_set write ───────────────

    /// Regression test: mem_set write to a new key must succeed (proving the
    /// Ok(None) arm of the store read works). The Err(e) arm returns
    /// {"error": "store read failed — refusing to write: ..."} but cannot be
    /// triggered without injecting a store fault, which the test harness does
    /// not support. This test validates the happy path; the error format is
    /// documented here for grep-ability.
    #[tokio::test]
    async fn test_mem_set_write_new_key_succeeds() {
        let dir = TempDir::new().unwrap();
        let store = Store::open(dir.path()).await.unwrap();
        let graph = Graph::load(store).await.unwrap();
        let graph_arc = std::sync::Arc::new(tokio::sync::RwLock::new(graph));

        let result = call_mem_set(
            &graph_arc,
            MemSetParams {
                action: "write".to_string(),
                key: "gotcha:store-read-ok-none".to_string(),
                value: "Regression rule because regression reason".to_string(),
                category: "Gotcha".to_string(),
                payload: serde_json::json!({
                    "rule": "Regression rule",
                    "reason": "regression reason",
                    "severity": "Normal"
                }),
                tags: vec![],
                priority: "Normal".to_string(),
            },
        )
        .await;

        let parsed: serde_json::Value = serde_json::from_str(&result).unwrap();
        assert_eq!(
            parsed["ok"], true,
            "writing a new key must succeed (Ok(None) arm)"
        );
        assert_eq!(parsed["key"], "gotcha:store-read-ok-none");

        // Verify record persisted
        let graph = graph_arc.read().await;
        let record = graph
            .store()
            .get("gotcha:store-read-ok-none")
            .await
            .unwrap()
            .expect("record must exist after write");
        assert_eq!(record.value, "Regression rule because regression reason");

        // Note: the Err(e) path (store read failure) returns:
        //   {"error": "store read failed — refusing to write: <details>"}
        // This cannot be exercised without a store-fault injection mechanism.
        // The guard exists at tools.rs line ~605 to prevent blind overwrites
        // when the store is in a degraded state.
    }

    // ── Regression: in-memory graph cleanup after tombstone ─────────────────

    /// Regression test: after deleting a gotcha via mem_set action="delete",
    /// the in-memory graph must no longer contain HasGotcha edges pointing to
    /// the deleted gotcha. Previously, only the store was cleaned up but the
    /// in-memory petgraph retained stale edges until process restart.
    #[tokio::test]
    async fn test_tombstone_removes_in_memory_graph_edges() {
        let dir = TempDir::new().unwrap();
        let store = Store::open(dir.path()).await.unwrap();

        // Seed file record
        let file_record = Record::layer0_file_stub("file:src/target.rs", device_id(), 1, now());
        store.put("file:src/target.rs", &file_record).await.unwrap();

        let graph = Graph::load(store).await.unwrap();
        let graph_arc = std::sync::Arc::new(tokio::sync::RwLock::new(graph));

        // Step 1: Write a gotcha linked to the file via affected_files.
        let write_result = call_mem_set(
            &graph_arc,
            MemSetParams {
                action: "write".to_string(),
                key: "gotcha:graph-cleanup-test".to_string(),
                value: "Never skip validation because it causes silent data corruption".to_string(),
                category: "Gotcha".to_string(),
                payload: serde_json::json!({
                    "rule": "Never skip validation",
                    "reason": "causes silent data corruption",
                    "severity": "High",
                    "affected_files": ["src/target.rs"],
                    "ref_url": null,
                    "discovered_session": 0,
                    "confirmed": false
                }),
                tags: vec![],
                priority: "High".to_string(),
            },
        )
        .await;
        let parsed: serde_json::Value = serde_json::from_str(&write_result).unwrap();
        assert_eq!(parsed["ok"], true, "gotcha write must succeed");

        // Step 2: Verify the in-memory graph has the HasGotcha edge.
        {
            let graph = graph_arc.read().await;
            let neighbors = graph.neighbors("file:src/target.rs", &EdgeKind::HasGotcha);
            assert!(
                neighbors.contains(&"gotcha:graph-cleanup-test".to_string()),
                "HasGotcha edge must exist after write; neighbors: {neighbors:?}"
            );
        }

        // Step 3: Delete the gotcha.
        let delete_result = call_mem_set(
            &graph_arc,
            MemSetParams {
                action: "delete".to_string(),
                key: "gotcha:graph-cleanup-test".to_string(),
                value: String::new(),
                category: String::new(),
                payload: serde_json::json!({}),
                tags: vec![],
                priority: "Normal".to_string(),
            },
        )
        .await;
        let parsed: serde_json::Value = serde_json::from_str(&delete_result).unwrap();
        assert_eq!(parsed["ok"], true, "gotcha delete must succeed");
        assert_eq!(parsed["tombstoned"], true);

        // Step 4: Verify the in-memory graph no longer has the HasGotcha edge.
        {
            let graph = graph_arc.read().await;
            let neighbors = graph.neighbors("file:src/target.rs", &EdgeKind::HasGotcha);
            assert!(
                !neighbors.contains(&"gotcha:graph-cleanup-test".to_string()),
                "HasGotcha edge must be removed after delete; neighbors: {neighbors:?}"
            );
        }

        // Also verify via graph query mode that the gotcha no longer appears.
        let graph_query_result = call_mem_query(
            &graph_arc,
            "file:src/target.rs",
            crate::mcp::protocol::QueryMode::Graph,
            20,
        )
        .await;
        let parsed: serde_json::Value = serde_json::from_str(&graph_query_result).unwrap();
        let gotchas = parsed["gotchas"]
            .as_array()
            .expect("gotchas group must be an array");
        assert!(
            !gotchas
                .iter()
                .any(|g| g["key"] == "gotcha:graph-cleanup-test"),
            "deleted gotcha must not appear in graph query results"
        );
    }

    // ── Regression: graph mode respects global limit ──────────────────────

    /// Graph mode must respect the caller's `limit` as a global cap across all
    /// edge groups. With limit=3 and records in multiple groups, total results
    /// must not exceed 3.
    #[tokio::test]
    async fn test_graph_mode_respects_global_limit() {
        let dir = TempDir::new().unwrap();
        let store = Store::open(dir.path()).await.unwrap();

        // Seed file record
        let file_record =
            Record::layer0_file_stub("file:src/graph_limit.rs", device_id(), 1, now());
        store
            .put("file:src/graph_limit.rs", &file_record)
            .await
            .unwrap();

        let graph = Graph::load(store).await.unwrap();
        let graph_arc = std::sync::Arc::new(tokio::sync::RwLock::new(graph));

        // Write 5 gotchas linked to the file
        for i in 0..5 {
            let result = call_mem_set(
                &graph_arc,
                MemSetParams {
                    action: "write".to_string(),
                    key: format!("gotcha:limit-test-{i}"),
                    value: format!("Limit test gotcha {i}"),
                    category: "Gotcha".to_string(),
                    payload: serde_json::json!({
                        "rule": format!("Limit rule {i}"),
                        "reason": "testing",
                        "severity": "Normal",
                        "affected_files": ["src/graph_limit.rs"],
                        "ref_url": null,
                        "discovered_session": 0,
                        "confirmed": false
                    }),
                    tags: vec![],
                    priority: "Normal".to_string(),
                },
            )
            .await;
            let parsed: serde_json::Value = serde_json::from_str(&result).unwrap();
            assert_eq!(parsed["ok"], true, "gotcha write {i} must succeed");
        }

        // Query with limit=3 — must get at most 3 total records across all groups.
        let result = call_mem_query(
            &graph_arc,
            "file:src/graph_limit.rs",
            crate::mcp::protocol::QueryMode::Graph,
            3,
        )
        .await;
        let parsed: serde_json::Value = serde_json::from_str(&result).unwrap();
        assert!(parsed.get("error").is_none(), "graph query must not error");

        // Count total records across all groups.
        let mut total = 0;
        for group in &["gotchas", "co_changes", "imports", "decisions", "notes"] {
            if let Some(arr) = parsed[group].as_array() {
                total += arr.len();
            }
        }
        assert!(
            total <= 3,
            "graph mode with limit=3 must return at most 3 total records, got {total}"
        );
    }

    /// Graph mode with limit=0 must return zero records in all groups.
    #[tokio::test]
    async fn test_graph_mode_limit_zero_returns_empty() {
        let dir = TempDir::new().unwrap();
        let store = Store::open(dir.path()).await.unwrap();

        let file_record = Record::layer0_file_stub("file:src/zero.rs", device_id(), 1, now());
        store.put("file:src/zero.rs", &file_record).await.unwrap();

        let graph = Graph::load(store).await.unwrap();
        let graph_arc = std::sync::Arc::new(tokio::sync::RwLock::new(graph));

        // Write one gotcha so there's something to return if limit is ignored.
        let _ = call_mem_set(
            &graph_arc,
            MemSetParams {
                action: "write".to_string(),
                key: "gotcha:zero-limit-test".to_string(),
                value: "Should not appear".to_string(),
                category: "Gotcha".to_string(),
                payload: serde_json::json!({
                    "rule": "Zero limit test",
                    "reason": "testing",
                    "severity": "Normal",
                    "affected_files": ["src/zero.rs"],
                    "ref_url": null,
                    "discovered_session": 0,
                    "confirmed": false
                }),
                tags: vec![],
                priority: "Normal".to_string(),
            },
        )
        .await;

        let result = call_mem_query(
            &graph_arc,
            "file:src/zero.rs",
            crate::mcp::protocol::QueryMode::Graph,
            0,
        )
        .await;
        let parsed: serde_json::Value = serde_json::from_str(&result).unwrap();

        let mut total = 0;
        for group in &["gotchas", "co_changes", "imports", "decisions", "notes"] {
            if let Some(arr) = parsed[group].as_array() {
                total += arr.len();
            }
        }
        assert_eq!(total, 0, "limit=0 must return zero records, got {total}");
    }

    // ── Regression: mem_set preserves existing data on overwrite ──────────

    /// When overwriting an existing record, mem_set must read and preserve
    /// Layer 0 structural data from the prior record. This is the exact
    /// scenario that `.ok().flatten()` would have broken: a store error would
    /// have made mem_set treat the record as new, losing preservation behavior.
    #[tokio::test]
    async fn test_mem_set_overwrite_preserves_existing_data() {
        let dir = TempDir::new().unwrap();
        let store = Store::open(dir.path()).await.unwrap();

        // Seed a DeveloperManual record with high confidence. (Switched from
        // a file: key to a gotcha: key after file: writes were removed from
        // mem_set; the merge-on-overwrite semantics under test are the same.)
        let mut original =
            make_gotcha_record("gotcha:preserve-confirmation", "Original rule", true, 0.7);
        original.source = RecordSource::DeveloperManual;
        original.confidence.value = 0.85;
        original.confidence.confirmation_count = 3;
        store
            .put("gotcha:preserve-confirmation", &original)
            .await
            .unwrap();

        let graph = Graph::load(store).await.unwrap();
        let graph_arc = std::sync::Arc::new(tokio::sync::RwLock::new(graph));

        // Overwrite with mem_set — should preserve confirmation state.
        let result = call_mem_set(
            &graph_arc,
            MemSetParams {
                action: "write".to_string(),
                key: "gotcha:preserve-confirmation".to_string(),
                value: "Updated rule from enrichment".to_string(),
                category: "Gotcha".to_string(),
                payload: serde_json::json!({"reason": "updated reason"}),
                tags: vec![],
                priority: "Normal".to_string(),
            },
        )
        .await;
        let parsed: serde_json::Value = serde_json::from_str(&result).unwrap();
        assert_eq!(parsed["ok"], true, "overwrite must succeed");

        // Verify the record was updated but preserved confirmation state.
        let graph = graph_arc.read().await;
        let record = graph
            .store()
            .get("gotcha:preserve-confirmation")
            .await
            .unwrap()
            .expect("record must exist");
        assert_eq!(
            record.value, "Updated rule from enrichment",
            "value must be updated"
        );
        // DeveloperManual source + high confidence should be preserved
        // because the write path detects was_confirmed=true.
        assert!(
            record.confidence.value >= 0.80,
            "confirmed record confidence must be preserved, got {}",
            record.confidence.value
        );
    }

    // ── Regression: tombstone multi-file gotcha cleans all edges ──────────

    /// When a gotcha affects multiple files, tombstone must remove in-memory
    /// HasGotcha edges from ALL affected files, not just the first.
    #[tokio::test]
    async fn test_tombstone_multi_file_removes_all_edges() {
        let dir = TempDir::new().unwrap();
        let store = Store::open(dir.path()).await.unwrap();

        // Seed two file records
        let f1 = Record::layer0_file_stub("file:src/a.rs", device_id(), 1, now());
        let f2 = Record::layer0_file_stub("file:src/b.rs", device_id(), 1, now());
        store.put("file:src/a.rs", &f1).await.unwrap();
        store.put("file:src/b.rs", &f2).await.unwrap();

        let graph = Graph::load(store).await.unwrap();
        let graph_arc = std::sync::Arc::new(tokio::sync::RwLock::new(graph));

        // Write a gotcha affecting both files
        let result = call_mem_set(
            &graph_arc,
            MemSetParams {
                action: "write".to_string(),
                key: "gotcha:multi-file-tombstone".to_string(),
                value: "Cross-file gotcha".to_string(),
                category: "Gotcha".to_string(),
                payload: serde_json::json!({
                    "rule": "Cross-file rule",
                    "reason": "testing multi-file cleanup",
                    "severity": "Normal",
                    "affected_files": ["src/a.rs", "src/b.rs"],
                    "ref_url": null,
                    "discovered_session": 0,
                    "confirmed": false
                }),
                tags: vec![],
                priority: "Normal".to_string(),
            },
        )
        .await;
        let parsed: serde_json::Value = serde_json::from_str(&result).unwrap();
        assert_eq!(parsed["ok"], true);

        // Verify both files have the edge
        {
            let graph = graph_arc.read().await;
            assert!(
                graph
                    .neighbors("file:src/a.rs", &EdgeKind::HasGotcha)
                    .contains(&"gotcha:multi-file-tombstone".to_string()),
                "file:src/a.rs must have HasGotcha edge before delete"
            );
            assert!(
                graph
                    .neighbors("file:src/b.rs", &EdgeKind::HasGotcha)
                    .contains(&"gotcha:multi-file-tombstone".to_string()),
                "file:src/b.rs must have HasGotcha edge before delete"
            );
        }

        // Delete the gotcha
        let result = call_mem_set(
            &graph_arc,
            MemSetParams {
                action: "delete".to_string(),
                key: "gotcha:multi-file-tombstone".to_string(),
                value: String::new(),
                category: String::new(),
                payload: serde_json::json!({}),
                tags: vec![],
                priority: "Normal".to_string(),
            },
        )
        .await;
        let parsed: serde_json::Value = serde_json::from_str(&result).unwrap();
        assert_eq!(parsed["ok"], true);

        // Verify BOTH files lost the edge
        {
            let graph = graph_arc.read().await;
            assert!(
                !graph
                    .neighbors("file:src/a.rs", &EdgeKind::HasGotcha)
                    .contains(&"gotcha:multi-file-tombstone".to_string()),
                "file:src/a.rs must NOT have HasGotcha edge after delete"
            );
            assert!(
                !graph
                    .neighbors("file:src/b.rs", &EdgeKind::HasGotcha)
                    .contains(&"gotcha:multi-file-tombstone".to_string()),
                "file:src/b.rs must NOT have HasGotcha edge after delete"
            );
        }
    }

    // ── Regression: confirm is non-idempotent ────────────────────────────

    /// Calling confirm twice must increment confirmation_count each time,
    /// proving `idempotent_hint = false` is correct for mem_set.
    #[tokio::test]
    async fn test_confirm_is_non_idempotent() {
        let dir = TempDir::new().unwrap();
        let store = Store::open(dir.path()).await.unwrap();

        let file_record = Record::layer0_file_stub("file:src/idem.rs", device_id(), 1, now());
        store.put("file:src/idem.rs", &file_record).await.unwrap();

        let graph = Graph::load(store).await.unwrap();
        let graph_arc = std::sync::Arc::new(tokio::sync::RwLock::new(graph));

        // Write an unconfirmed gotcha
        let _ = call_mem_set(
            &graph_arc,
            MemSetParams {
                action: "write".to_string(),
                key: "gotcha:idem-test".to_string(),
                value: "Idempotency test rule".to_string(),
                category: "Gotcha".to_string(),
                payload: serde_json::json!({
                    "rule": "Idempotency test",
                    "reason": "testing",
                    "severity": "Normal",
                    "affected_files": ["src/idem.rs"],
                    "ref_url": null,
                    "discovered_session": 0,
                    "confirmed": false
                }),
                tags: vec![],
                priority: "Normal".to_string(),
            },
        )
        .await;

        // First confirm
        let r1 = call_mem_set(
            &graph_arc,
            MemSetParams {
                action: "confirm".to_string(),
                key: "gotcha:idem-test".to_string(),
                value: String::new(),
                category: String::new(),
                payload: serde_json::json!({}),
                tags: vec![],
                priority: "Normal".to_string(),
            },
        )
        .await;
        let p1: serde_json::Value = serde_json::from_str(&r1).unwrap();
        assert_eq!(p1["ok"], true, "first confirm must succeed");
        assert_eq!(p1["confirmed"], true);

        // Read confirmation_count after first confirm
        let count_after_first = {
            let graph = graph_arc.read().await;
            let record = graph
                .store()
                .get("gotcha:idem-test")
                .await
                .unwrap()
                .unwrap();
            record.confidence.confirmation_count
        };

        // Second confirm
        let r2 = call_mem_set(
            &graph_arc,
            MemSetParams {
                action: "confirm".to_string(),
                key: "gotcha:idem-test".to_string(),
                value: String::new(),
                category: String::new(),
                payload: serde_json::json!({}),
                tags: vec![],
                priority: "Normal".to_string(),
            },
        )
        .await;
        let p2: serde_json::Value = serde_json::from_str(&r2).unwrap();
        assert_eq!(p2["ok"], true, "second confirm must succeed");

        // Read confirmation_count after second confirm
        let count_after_second = {
            let graph = graph_arc.read().await;
            let record = graph
                .store()
                .get("gotcha:idem-test")
                .await
                .unwrap()
                .unwrap();
            record.confidence.confirmation_count
        };

        assert!(
            count_after_second > count_after_first,
            "confirmation_count must increase on each confirm: first={count_after_first}, second={count_after_second}"
        );
    }

    // ── Regression: store-read-error refusal (extracted helper) ───────────

    /// The Err(e) branch must return a structured JSON error and refuse to write.
    /// Previously untestable because it required a real store failure.
    #[test]
    fn test_store_read_error_refuses_write() {
        let result = resolve_existing_for_write(Err(anyhow::anyhow!("simulated disk I/O timeout")));
        assert!(result.is_err(), "store error must refuse write");
        let err = result.unwrap_err();
        let parsed: serde_json::Value = serde_json::from_str(&err).unwrap();
        assert!(
            parsed["error"]
                .as_str()
                .unwrap()
                .contains("store read failed"),
            "error must mention store read failure"
        );
        assert!(
            parsed["error"]
                .as_str()
                .unwrap()
                .contains("simulated disk I/O timeout"),
            "error must include the underlying cause"
        );
    }

    /// Ok(None) must pass through — new record, no existing data to preserve.
    #[test]
    fn test_store_read_ok_none_passes_through() {
        let result = resolve_existing_for_write(Ok(None));
        assert!(result.is_ok());
        assert!(result.unwrap().is_none());
    }

    /// Ok(Some(record)) must pass through — existing record for preservation.
    #[test]
    fn test_store_read_ok_some_passes_through() {
        let record = make_record("file:test.rs", "test", Category::File, 0.5);
        let result = resolve_existing_for_write(Ok(Some(record.clone())));
        assert!(result.is_ok());
        let resolved = result.unwrap();
        assert!(resolved.is_some());
        assert_eq!(resolved.unwrap().key, "file:test.rs");
    }

    #[tokio::test]
    async fn bootstrap_highest_impact_section_appears() {
        let dir = TempDir::new().unwrap();
        let store = Store::open(dir.path()).await.unwrap();

        // Create a critical-blast-radius file record
        let fr_critical = FileRecord {
            path: "src/core.rs".to_string(),
            purpose: "Core module".to_string(),
            entry_points: vec![],
            imports: vec![],
            gotcha_keys: vec![],
            decision_keys: vec![],
            todos: vec![],
            unsafe_count: 0,
            unwrap_count: 0,
            change_frequency: 0,
            last_author: None,
            is_hotspot: false,
            token_cost_estimate: 100,
            last_modified_session: 0,
            content_hash: None,
            line_count: 0,
            blast_radius: Some(crate::analysis::blast_radius::BlastRadius {
                direct: 45,
                transitive: 10,
                score: 48.0,
                tier: crate::analysis::blast_radius::BlastTier::Critical,
            }),
            propagated_staleness: None,
        };
        let mut rec = make_record("file:src/core.rs", "Core module", Category::File, 0.5);
        rec.payload = serde_json::to_value(&fr_critical).ok();
        store.put("file:src/core.rs", &rec).await.unwrap();

        // Create a low-blast-radius file record
        let fr_low = FileRecord {
            path: "src/leaf.rs".to_string(),
            purpose: "Leaf module".to_string(),
            entry_points: vec![],
            imports: vec![],
            gotcha_keys: vec![],
            decision_keys: vec![],
            todos: vec![],
            unsafe_count: 0,
            unwrap_count: 0,
            change_frequency: 0,
            last_author: None,
            is_hotspot: false,
            token_cost_estimate: 100,
            last_modified_session: 0,
            content_hash: None,
            line_count: 0,
            blast_radius: Some(crate::analysis::blast_radius::BlastRadius {
                direct: 3,
                transitive: 0,
                score: 3.0,
                tier: crate::analysis::blast_radius::BlastTier::Low,
            }),
            propagated_staleness: None,
        };
        let mut rec2 = make_record("file:src/leaf.rs", "Leaf module", Category::File, 0.5);
        rec2.payload = serde_json::to_value(&fr_low).ok();
        store.put("file:src/leaf.rs", &rec2).await.unwrap();

        let graph = Graph::load(store).await.unwrap();
        let packet = assemble_context_packet(
            graph.store(),
            &graph,
            &["src/core.rs".to_string(), "src/leaf.rs".to_string()],
        )
        .await
        .unwrap();

        assert!(
            packet.injection_string.contains("Highest Impact"),
            "bootstrap must include highest impact section, got: {}",
            packet.injection_string
        );
        assert!(
            packet.injection_string.contains("src/core.rs"),
            "critical file must appear in impact section"
        );
        // core.rs (score 48) should appear before leaf.rs (score 3)
        let core_pos = packet.injection_string.find("src/core.rs").unwrap();
        let leaf_pos = packet
            .injection_string
            .find("src/leaf.rs")
            .unwrap_or(usize::MAX);
        assert!(
            core_pos < leaf_pos,
            "core.rs should appear before leaf.rs in impact section"
        );
    }

    // ── Pass-29 regression: build_mem_set_command routing ──────────────
    //
    // The Socket-backend mem_set previously dispatched
    // "gotcha_confirm" / "gotcha_tombstone" / "mem_set" through the
    // legacy v1 mapper (`v1_to_v2_command`) which has no entries for
    // those commands and panicked the rmcp task. The fix routes through
    // typed Commands; these tests pin the routing logic.
    //
    // All test inputs are constructed manually instead of via JSON
    // parsing — `MemSetParams` is `Deserialize`-only.

    fn make_params(action: &str, key: &str) -> MemSetParams {
        MemSetParams {
            action: action.to_string(),
            key: key.to_string(),
            value: String::new(),
            category: String::new(),
            payload: serde_json::Value::Object(serde_json::Map::new()),
            tags: vec![],
            priority: "Normal".to_string(),
        }
    }

    #[test]
    fn mem_set_socket_routes_gotcha_confirm() {
        let p = make_params("confirm", "gotcha:foo");
        let cmd = build_mem_set_command(&p).expect("must build");
        assert_eq!(cmd.kind(), "gotcha_confirm");
        assert_eq!(cmd.target_key(), "gotcha:foo");
    }

    #[test]
    fn mem_set_socket_rejects_confirm_on_non_gotcha_key() {
        let p = make_params("confirm", "decision:not-allowed");
        let err = build_mem_set_command(&p).expect_err("must reject");
        assert!(
            err.contains("gotcha:"),
            "error must mention gotcha: prefix, got: {err}"
        );
    }

    #[test]
    fn mem_set_socket_routes_gotcha_tombstone() {
        let p = make_params("delete", "gotcha:foo");
        let cmd = build_mem_set_command(&p).expect("must build");
        assert_eq!(cmd.kind(), "gotcha_tombstone");
        assert_eq!(cmd.target_key(), "gotcha:foo");
    }

    #[test]
    fn mem_set_socket_routes_gotcha_upsert_by_key_prefix() {
        let mut p = make_params("write", "gotcha:stripe-idempotency");
        p.payload = serde_json::json!({
            "rule": "Always include an idempotency key",
            "reason": "Stripe retries cause double charges without it",
            "severity": "High",
            "affected_files": ["src/payments/stripe.rs"],
        });
        p.tags = vec!["payments".into()];
        p.priority = "High".into();
        let cmd = build_mem_set_command(&p).expect("must build");
        assert_eq!(cmd.kind(), "gotcha_upsert");
        match cmd {
            Command::GotchaUpsert(input) => {
                assert_eq!(input.key, "gotcha:stripe-idempotency");
                assert_eq!(input.rule, "Always include an idempotency key");
                assert_eq!(input.severity, proto::Severity::High);
                assert_eq!(input.priority, proto::Priority::High);
                assert_eq!(input.affected_files, vec!["src/payments/stripe.rs"]);
                assert_eq!(input.tags, vec!["payments".to_string()]);
            }
            _ => panic!("expected GotchaUpsert"),
        }
    }

    #[test]
    fn mem_set_socket_routes_decision_upsert_by_key_prefix() {
        let mut p = make_params("write", "decision:retry-strategy");
        p.value = "We use exponential backoff because linear overloads downstream".into();
        p.payload = serde_json::json!({
            "summary": "Exponential backoff for all retries",
            "rationale": "Linear retry caused cascading failures in prod 2024-01",
        });
        let cmd = build_mem_set_command(&p).expect("must build");
        assert_eq!(cmd.kind(), "decision_upsert");
        match cmd {
            Command::DecisionUpsert(input) => {
                assert_eq!(input.slug, "retry-strategy");
                assert_eq!(input.summary, "Exponential backoff for all retries");
                assert!(input.rationale.contains("cascading"));
            }
            _ => panic!("expected DecisionUpsert"),
        }
    }

    #[test]
    fn mem_set_socket_routes_dev_note_upsert_by_key_prefix() {
        let mut p = make_params("write", "dev_note:remember-changelog");
        p.value = "Remember to update the changelog before release".into();
        let cmd = build_mem_set_command(&p).expect("must build");
        assert_eq!(cmd.kind(), "dev_note_upsert");
        match cmd {
            Command::DevNoteUpsert(input) => {
                assert_eq!(input.key.as_deref(), Some("dev_note:remember-changelog"));
                assert!(input.text.contains("changelog"));
            }
            _ => panic!("expected DevNoteUpsert"),
        }
    }

    #[test]
    fn mem_set_socket_rejects_write_with_unknown_prefix() {
        // file: writes are not supported via mem_set Socket path —
        // there is no public typed Command for them.
        let p = make_params("write", "file:src/main.rs");
        let err = build_mem_set_command(&p).expect_err("must reject");
        assert!(
            err.contains("gotcha:") && err.contains("decision:") && err.contains("dev_note:"),
            "error must list valid prefixes, got: {err}"
        );
    }

    #[test]
    fn mem_set_socket_rejects_unknown_action() {
        let p = make_params("smuggle", "gotcha:foo");
        let err = build_mem_set_command(&p).expect_err("must reject");
        assert!(
            err.contains("smuggle"),
            "error must echo the bad action, got: {err}"
        );
    }

    #[test]
    fn mem_set_socket_rejects_gotcha_write_missing_payload_fields() {
        let p = make_params("write", "gotcha:incomplete");
        let err = build_mem_set_command(&p).expect_err("must reject");
        assert!(
            err.contains("rule"),
            "error must mention 'rule', got: {err}"
        );
    }

    #[test]
    fn mem_set_socket_handles_codex_string_payload() {
        // Codex sends payload as a JSON-encoded string; the typed
        // builder must transparently parse it (matching Direct path).
        let mut p = make_params("write", "gotcha:codex-style");
        p.payload = serde_json::Value::String(
            r#"{"rule":"do X","reason":"because Y","severity":"low"}"#.to_string(),
        );
        let cmd = build_mem_set_command(&p).expect("must build from stringified payload");
        match cmd {
            Command::GotchaUpsert(input) => {
                assert_eq!(input.rule, "do X");
                assert_eq!(input.severity, proto::Severity::Low);
            }
            _ => panic!("expected GotchaUpsert"),
        }
    }
}