mdx-rust-core 1.0.0

Core library for mdx-rust safety, hardening, policy, and experiments
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
//! Plan-first guardrailed refactoring.
//!
//! v1.0 beta keeps auditable plans as the mutation boundary and adds file/function
//! evidence plus security posture to the safe executable subset.

use crate::eval::stable_hash_hex;
use crate::evidence::{load_latest_evidence_for_root, EvidenceArtifactRef, EvidenceRun};
use crate::hardening::{
    run_hardening, workspace_summary, HardeningConfig, HardeningRun, WorkspaceSummary,
};
use crate::policy::{load_project_policy, ProjectPolicy};
use crate::security::{audit_agent, AuditFinding, AuditSeverity};
use mdx_rust_analysis::{
    analyze_hardening, analyze_refactor, HardeningAnalyzeConfig, HardeningEvidenceDepth,
    HardeningFinding, ModuleEdge, RefactorAnalyzeConfig, RefactorFileSummary,
};
use schemars::JsonSchema;
use serde::{Deserialize, Serialize};
use std::path::{Component, Path, PathBuf};
use std::time::Duration;

#[derive(Debug, Clone)]
pub struct RefactorPlanConfig {
    pub target: Option<PathBuf>,
    pub policy_path: Option<PathBuf>,
    pub behavior_spec_path: Option<PathBuf>,
    pub max_files: usize,
}

impl Default for RefactorPlanConfig {
    fn default() -> Self {
        Self {
            target: None,
            policy_path: None,
            behavior_spec_path: None,
            max_files: 100,
        }
    }
}

#[derive(Debug, Clone)]
pub struct RefactorApplyConfig {
    pub plan_path: PathBuf,
    pub candidate_id: String,
    pub apply: bool,
    pub allow_public_api_impact: bool,
    pub validation_timeout: Duration,
}

#[derive(Debug, Clone)]
pub struct RefactorBatchApplyConfig {
    pub plan_path: PathBuf,
    pub apply: bool,
    pub allow_public_api_impact: bool,
    pub validation_timeout: Duration,
    pub max_candidates: usize,
    pub max_tier: RecipeTier,
    pub min_evidence: EvidenceGrade,
}

#[derive(Debug, Clone)]
pub struct CodebaseMapConfig {
    pub target: Option<PathBuf>,
    pub policy_path: Option<PathBuf>,
    pub behavior_spec_path: Option<PathBuf>,
    pub max_files: usize,
}

impl Default for CodebaseMapConfig {
    fn default() -> Self {
        Self {
            target: None,
            policy_path: None,
            behavior_spec_path: None,
            max_files: 250,
        }
    }
}

#[derive(Debug, Clone)]
pub struct AutopilotConfig {
    pub target: Option<PathBuf>,
    pub policy_path: Option<PathBuf>,
    pub behavior_spec_path: Option<PathBuf>,
    pub apply: bool,
    pub max_files: usize,
    pub max_passes: usize,
    pub max_candidates: usize,
    pub validation_timeout: Duration,
    pub allow_public_api_impact: bool,
    pub max_tier: RecipeTier,
    pub min_evidence: EvidenceGrade,
    pub budget: Option<Duration>,
}

impl Default for AutopilotConfig {
    fn default() -> Self {
        Self {
            target: None,
            policy_path: None,
            behavior_spec_path: None,
            apply: false,
            max_files: 250,
            max_passes: 3,
            max_candidates: 25,
            validation_timeout: Duration::from_secs(180),
            allow_public_api_impact: false,
            max_tier: RecipeTier::Tier1,
            min_evidence: EvidenceGrade::Compiled,
            budget: None,
        }
    }
}

#[derive(Debug, Clone, Serialize, Deserialize, JsonSchema)]
pub struct RefactorPlan {
    pub schema_version: String,
    pub plan_id: String,
    pub plan_hash: String,
    pub root: String,
    pub target: Option<String>,
    pub workspace: WorkspaceSummary,
    pub policy: Option<ProjectPolicy>,
    pub behavior_spec: Option<String>,
    pub evidence: EvidenceSummary,
    pub measured_evidence: Option<EvidenceArtifactRef>,
    #[serde(default)]
    pub security: SecurityPostureSummary,
    #[serde(default)]
    pub autonomy: AutonomyReadiness,
    pub impact: RefactorImpactSummary,
    pub source_snapshots: Vec<SourceSnapshot>,
    pub files: Vec<RefactorFileSummary>,
    pub module_edges: Vec<ModuleEdge>,
    pub candidates: Vec<RefactorCandidate>,
    pub required_gates: Vec<String>,
    pub non_goals: Vec<String>,
    pub artifact_path: Option<String>,
}

#[derive(Debug, Clone, Serialize, Deserialize, JsonSchema)]
pub struct CodebaseMap {
    pub schema_version: String,
    pub map_id: String,
    pub map_hash: String,
    pub root: String,
    pub target: Option<String>,
    pub workspace: WorkspaceSummary,
    pub policy: Option<ProjectPolicy>,
    pub behavior_spec: Option<String>,
    pub evidence: EvidenceSummary,
    pub measured_evidence: Option<EvidenceArtifactRef>,
    #[serde(default)]
    pub security: SecurityPostureSummary,
    #[serde(default)]
    pub autonomy: AutonomyReadiness,
    pub quality: CodebaseQualitySummary,
    pub capability_gates: Vec<CapabilityGate>,
    pub impact: RefactorImpactSummary,
    pub files: Vec<RefactorFileSummary>,
    pub module_edges: Vec<ModuleEdge>,
    pub findings: Vec<HardeningFinding>,
    pub recommended_actions: Vec<String>,
    pub artifact_path: Option<String>,
}

#[derive(Debug, Clone, Serialize, Deserialize, JsonSchema)]
pub struct CodebaseQualitySummary {
    pub grade: CodebaseQualityGrade,
    pub debt_score: u8,
    #[serde(default)]
    pub security_score: u8,
    pub patchable_findings: usize,
    pub review_only_findings: usize,
    pub public_api_pressure: usize,
    pub oversized_files: usize,
    pub oversized_functions: usize,
    pub test_coverage_signal: TestCoverageSignal,
}

#[derive(Debug, Clone, Serialize, Deserialize, JsonSchema)]
pub struct EvidenceSummary {
    pub grade: EvidenceGrade,
    pub max_autonomous_tier: u8,
    pub analysis_depth: EvidenceAnalysisDepth,
    pub signals: Vec<EvidenceSignal>,
    #[serde(default)]
    pub profiled_files: usize,
    pub unlocked_recipe_tiers: Vec<String>,
    pub unlock_suggestions: Vec<String>,
}

#[derive(Debug, Clone, Serialize, Deserialize, JsonSchema, PartialEq, Eq)]
pub enum EvidenceAnalysisDepth {
    None,
    Mechanical,
    BoundaryAware,
    Structural,
}

#[derive(Debug, Clone, Serialize, Deserialize, JsonSchema)]
pub struct EvidenceSignal {
    pub id: String,
    pub label: String,
    pub present: bool,
    pub detail: String,
}

#[derive(
    Debug, Clone, Copy, Serialize, Deserialize, JsonSchema, PartialEq, Eq, PartialOrd, Ord,
)]
pub enum EvidenceGrade {
    None,
    Compiled,
    Tested,
    Covered,
    Hardened,
    Proven,
}

#[derive(Debug, Clone, Serialize, Deserialize, JsonSchema, PartialEq, Eq)]
pub enum CodebaseQualityGrade {
    Excellent,
    Good,
    NeedsWork,
    HighRisk,
}

#[derive(Debug, Clone, Serialize, Deserialize, JsonSchema, PartialEq, Eq)]
pub enum TestCoverageSignal {
    Present,
    Sparse,
    Unknown,
}

#[derive(Debug, Clone, Serialize, Deserialize, JsonSchema)]
pub struct CapabilityGate {
    pub id: String,
    pub label: String,
    pub available: bool,
    pub command: String,
    pub purpose: String,
}

#[derive(Debug, Clone, Serialize, Deserialize, JsonSchema)]
pub struct CandidateEvidenceContext {
    pub grade: EvidenceGrade,
    #[serde(default)]
    pub status: CandidateEvidenceStatus,
    pub source: String,
    pub profiled_file: Option<String>,
    pub signals: Vec<String>,
}

impl Default for CandidateEvidenceContext {
    fn default() -> Self {
        Self {
            grade: EvidenceGrade::None,
            status: CandidateEvidenceStatus::Unmeasured,
            source: "legacy artifact without candidate evidence context".to_string(),
            profiled_file: None,
            signals: Vec::new(),
        }
    }
}

#[derive(Debug, Clone, Serialize, Deserialize, JsonSchema, PartialEq, Eq, Default)]
pub enum CandidateEvidenceStatus {
    #[default]
    Unmeasured,
    Compiled,
    Tested,
    Covered,
    MutationBacked,
    Proven,
}

#[derive(Debug, Clone, Serialize, Deserialize, JsonSchema)]
pub struct SecurityPostureSummary {
    pub score: u8,
    pub high: usize,
    pub medium: usize,
    pub low: usize,
    pub info: usize,
    pub top_findings: Vec<String>,
}

impl Default for SecurityPostureSummary {
    fn default() -> Self {
        Self {
            score: 100,
            high: 0,
            medium: 0,
            low: 0,
            info: 0,
            top_findings: Vec::new(),
        }
    }
}

#[derive(Debug, Clone, Serialize, Deserialize, JsonSchema)]
pub struct AutonomyReadiness {
    pub grade: AutonomyReadinessGrade,
    pub max_safe_tier: RecipeTier,
    pub executable_candidates: usize,
    pub review_only_candidates: usize,
    pub blocked_candidates: usize,
    pub blockers: Vec<String>,
    pub recommended_command: Option<String>,
}

impl Default for AutonomyReadiness {
    fn default() -> Self {
        Self {
            grade: AutonomyReadinessGrade::Blocked,
            max_safe_tier: RecipeTier::Tier1,
            executable_candidates: 0,
            review_only_candidates: 0,
            blocked_candidates: 0,
            blockers: Vec::new(),
            recommended_command: None,
        }
    }
}

#[derive(Debug, Clone, Serialize, Deserialize, JsonSchema, PartialEq, Eq)]
pub enum AutonomyReadinessGrade {
    Blocked,
    ReviewOnly,
    Tier1Ready,
    Tier2Ready,
    Tier3Planning,
}

#[derive(Debug, Clone, Serialize, Deserialize, JsonSchema)]
pub struct CandidateAutonomyDecision {
    pub decision: AutonomyDecision,
    pub reasons: Vec<String>,
}

impl Default for CandidateAutonomyDecision {
    fn default() -> Self {
        Self {
            decision: AutonomyDecision::ReviewOnly,
            reasons: vec!["legacy artifact without explicit autonomy decision".to_string()],
        }
    }
}

#[derive(Debug, Clone, Serialize, Deserialize, JsonSchema, PartialEq, Eq)]
pub enum AutonomyDecision {
    Allowed,
    Blocked,
    ReviewOnly,
}

#[derive(Debug, Clone, Serialize, Deserialize, JsonSchema)]
pub struct AutopilotRun {
    pub schema_version: String,
    pub run_id: String,
    pub root: String,
    pub target: Option<String>,
    pub mode: RefactorApplyMode,
    pub status: AutopilotStatus,
    pub budget_seconds: Option<u64>,
    pub max_passes: usize,
    pub max_candidates_per_pass: usize,
    pub quality_before: CodebaseQualitySummary,
    pub quality_after: Option<CodebaseQualitySummary>,
    pub evidence: EvidenceSummary,
    pub measured_evidence: Option<EvidenceArtifactRef>,
    pub execution_summary: AutopilotExecutionSummary,
    pub passes: Vec<AutopilotPass>,
    pub total_planned_candidates: usize,
    pub total_executed_candidates: usize,
    pub total_skipped_candidates: usize,
    pub budget_exhausted: bool,
    pub note: String,
    pub artifact_path: Option<String>,
}

#[derive(Debug, Clone, Serialize, Deserialize, JsonSchema)]
pub struct AutopilotExecutionSummary {
    pub plans_created: usize,
    pub executable_candidates_seen: usize,
    pub validated_transactions: usize,
    pub applied_transactions: usize,
    pub blocked_or_plan_only_candidates: usize,
    pub evidence_grade: EvidenceGrade,
    pub analysis_depth: EvidenceAnalysisDepth,
}

#[derive(Debug, Clone, Serialize, Deserialize, JsonSchema)]
pub struct AutopilotPass {
    pub pass_index: usize,
    pub plan_id: String,
    pub plan_hash: String,
    pub plan_artifact_path: Option<String>,
    pub planned_candidates: usize,
    pub executable_candidates: usize,
    pub batch: Option<RefactorBatchApplyRun>,
    pub status: AutopilotPassStatus,
    pub note: String,
}

#[derive(Debug, Clone, Serialize, Deserialize, JsonSchema, PartialEq, Eq)]
pub enum AutopilotStatus {
    Reviewed,
    Applied,
    PartiallyApplied,
    NoExecutableCandidates,
    Rejected,
}

#[derive(Debug, Clone, Serialize, Deserialize, JsonSchema, PartialEq, Eq)]
pub enum AutopilotPassStatus {
    Planned,
    Reviewed,
    Applied,
    PartiallyApplied,
    NoExecutableCandidates,
    Rejected,
}

#[derive(Debug, Clone, Serialize, Deserialize, JsonSchema)]
pub struct SourceSnapshot {
    pub file: String,
    pub hash: String,
}

#[derive(Debug, Clone, Serialize, Deserialize, JsonSchema)]
pub struct RefactorImpactSummary {
    pub files_scanned: usize,
    pub public_item_count: usize,
    pub public_files: usize,
    pub module_edge_count: usize,
    pub patchable_hardening_changes: usize,
    pub review_only_findings: usize,
    pub oversized_files: usize,
    pub oversized_functions: usize,
    pub risk_level: RefactorRiskLevel,
}

#[derive(Debug, Clone, Serialize, Deserialize, JsonSchema, PartialEq, Eq)]
pub enum RefactorRiskLevel {
    Low,
    Medium,
    High,
}

#[derive(Debug, Clone, Serialize, Deserialize, JsonSchema)]
pub struct RefactorCandidate {
    pub id: String,
    pub candidate_hash: String,
    pub recipe: RefactorRecipe,
    pub title: String,
    pub rationale: String,
    pub file: String,
    pub line: usize,
    pub risk: RefactorRiskLevel,
    pub status: RefactorCandidateStatus,
    pub tier: RecipeTier,
    pub required_evidence: EvidenceGrade,
    pub evidence_satisfied: bool,
    #[serde(default)]
    pub evidence_context: CandidateEvidenceContext,
    #[serde(default)]
    pub autonomy: CandidateAutonomyDecision,
    pub public_api_impact: bool,
    pub apply_command: Option<String>,
    pub required_gates: Vec<String>,
}

#[derive(Debug, Clone, Serialize, Deserialize, JsonSchema, PartialEq, Eq)]
pub enum RefactorCandidateStatus {
    ApplyViaImprove,
    PlanOnly,
    NeedsHumanDesign,
}

#[derive(
    Debug, Clone, Copy, Serialize, Deserialize, JsonSchema, PartialEq, Eq, PartialOrd, Ord,
)]
pub enum RecipeTier {
    Tier1,
    Tier2,
    Tier3,
}

#[derive(Debug, Clone, Serialize, Deserialize, JsonSchema, PartialEq, Eq)]
pub enum RefactorRecipe {
    BorrowParameterTightening,
    ClonePressureReview,
    ContextualErrorHardening,
    ErrorContextPropagation,
    ExtractFunctionCandidate,
    IteratorCloned,
    LenCheckIsEmpty,
    LongFunctionReview,
    MustUsePublicReturn,
    OptionContextPropagation,
    RepeatedStringLiteralConst,
    SecurityBoundaryReview,
    SplitModuleCandidate,
    BoundaryValidationReview,
    PublicApiReview,
}

#[derive(Debug, Clone, Serialize, Deserialize, JsonSchema)]
pub struct RecipeCatalog {
    pub schema_version: String,
    pub recipes: Vec<RecipeSpec>,
}

#[derive(Debug, Clone, Serialize, Deserialize, JsonSchema)]
pub struct RecipeSpec {
    pub id: String,
    pub recipe: RefactorRecipe,
    pub tier: RecipeTier,
    pub required_evidence: EvidenceGrade,
    pub executable: bool,
    pub risk: RefactorRiskLevel,
    pub mutation_path: String,
    pub description: String,
}

#[derive(Debug, Clone)]
pub struct EvolutionScorecardConfig {
    pub target: Option<PathBuf>,
    pub policy_path: Option<PathBuf>,
    pub behavior_spec_path: Option<PathBuf>,
    pub max_files: usize,
}

impl Default for EvolutionScorecardConfig {
    fn default() -> Self {
        Self {
            target: None,
            policy_path: None,
            behavior_spec_path: None,
            max_files: 250,
        }
    }
}

#[derive(Debug, Clone, Serialize, Deserialize, JsonSchema)]
pub struct EvolutionScorecard {
    pub schema_version: String,
    pub scorecard_id: String,
    pub root: String,
    pub target: Option<String>,
    pub readiness: AutonomyReadiness,
    pub map: CodebaseMap,
    pub plan: RefactorPlan,
    pub recipes: RecipeCatalog,
    pub next_commands: Vec<String>,
    pub artifact_path: Option<String>,
}

#[derive(Debug, Clone, Serialize, Deserialize, JsonSchema)]
pub struct AgentReadyReport {
    pub schema_version: String,
    pub product_version: String,
    pub status: AgentReadyStatus,
    pub target: Option<String>,
    pub readiness: AutonomyReadiness,
    pub evidence: EvidenceSummary,
    pub quality: CodebaseQualitySummary,
    pub security: SecurityPostureSummary,
    pub agent_contract: AgentReadyContractRefs,
    pub next_commands: Vec<String>,
}

#[derive(Debug, Clone, Serialize, Deserialize, JsonSchema, PartialEq, Eq)]
pub enum AgentReadyStatus {
    Ready,
    Review,
}

#[derive(Debug, Clone, Serialize, Deserialize, JsonSchema)]
pub struct AgentReadyContractRefs {
    pub discovery: String,
    pub runtime: String,
    pub scorecard_artifact: Option<String>,
}

pub fn recipe_catalog() -> RecipeCatalog {
    macro_rules! spec {
        (
            $id:expr,
            $recipe:expr,
            $tier:expr,
            $required_evidence:expr,
            $executable:expr,
            $risk:expr,
            $mutation_path:expr,
            $description:expr $(,)?
        ) => {
            RecipeSpec {
                id: $id.to_string(),
                recipe: $recipe,
                tier: $tier,
                required_evidence: $required_evidence,
                executable: $executable,
                risk: $risk,
                mutation_path: $mutation_path.to_string(),
                description: $description.to_string(),
            }
        };
    }

    RecipeCatalog {
        schema_version: "1.0".to_string(),
        recipes: vec![
            spec!(
                "contextual-error-hardening",
                RefactorRecipe::ContextualErrorHardening,
                RecipeTier::Tier1,
                EvidenceGrade::Compiled,
                true,
                RefactorRiskLevel::Low,
                "hardening transaction",
                "Replace panic-prone Result unwraps with contextual errors.",
            ),
            spec!(
                "error-context-propagation",
                RefactorRecipe::ErrorContextPropagation,
                RecipeTier::Tier1,
                EvidenceGrade::Compiled,
                true,
                RefactorRiskLevel::Low,
                "hardening transaction",
                "Add context to boundary errors without changing public behavior.",
            ),
            spec!(
                "borrow-parameter-tightening",
                RefactorRecipe::BorrowParameterTightening,
                RecipeTier::Tier1,
                EvidenceGrade::Compiled,
                true,
                RefactorRiskLevel::Low,
                "hardening transaction",
                "Prefer borrowed slice/string parameters in private functions.",
            ),
            spec!(
                "iterator-cloned-cleanup",
                RefactorRecipe::IteratorCloned,
                RecipeTier::Tier1,
                EvidenceGrade::Compiled,
                true,
                RefactorRiskLevel::Low,
                "hardening transaction",
                "Move cloned calls to the narrower iterator position when mechanical.",
            ),
            spec!(
                "option-context-propagation",
                RefactorRecipe::OptionContextPropagation,
                RecipeTier::Tier2,
                EvidenceGrade::Covered,
                true,
                RefactorRiskLevel::Low,
                "hardening transaction with covered evidence",
                "Convert Option ok_or string boundaries to anyhow Context under coverage gates.",
            ),
            spec!(
                "len-check-is-empty",
                RefactorRecipe::LenCheckIsEmpty,
                RecipeTier::Tier2,
                EvidenceGrade::Covered,
                true,
                RefactorRiskLevel::Low,
                "hardening transaction with covered evidence",
                "Convert zero-length comparisons to is_empty for clarity.",
            ),
            spec!(
                "repeated-string-literal-const",
                RefactorRecipe::RepeatedStringLiteralConst,
                RecipeTier::Tier2,
                EvidenceGrade::Covered,
                true,
                RefactorRiskLevel::Low,
                "hardening transaction with covered evidence",
                "Extract repeated local string literals into a constant.",
            ),
            spec!(
                "clone-pressure-review",
                RefactorRecipe::ClonePressureReview,
                RecipeTier::Tier3,
                EvidenceGrade::Hardened,
                false,
                RefactorRiskLevel::Medium,
                "plan only",
                "Identify clone-heavy code that needs semantic review before rewriting.",
            ),
            spec!(
                "extract-function",
                RefactorRecipe::ExtractFunctionCandidate,
                RecipeTier::Tier2,
                EvidenceGrade::Covered,
                false,
                RefactorRiskLevel::Medium,
                "plan only",
                "Stage long functions for behavior-gated extraction.",
            ),
            spec!(
                "split-module",
                RefactorRecipe::SplitModuleCandidate,
                RecipeTier::Tier2,
                EvidenceGrade::Covered,
                false,
                RefactorRiskLevel::Medium,
                "plan only",
                "Stage oversized modules for human-reviewed decomposition.",
            ),
            spec!(
                "security-boundary-review",
                RefactorRecipe::SecurityBoundaryReview,
                RecipeTier::Tier2,
                EvidenceGrade::Tested,
                false,
                RefactorRiskLevel::High,
                "plan only",
                "Surface process, unsafe, and boundary risks before autonomous work expands.",
            ),
        ],
    }
}

#[derive(Debug, Clone, Serialize, Deserialize, JsonSchema)]
pub struct RefactorApplyRun {
    pub schema_version: String,
    pub root: String,
    pub plan_path: String,
    pub plan_id: String,
    pub plan_hash: String,
    pub candidate_id: String,
    pub candidate_hash: Option<String>,
    pub mode: RefactorApplyMode,
    pub status: RefactorApplyStatus,
    pub public_api_impact_allowed: bool,
    pub stale_files: Vec<StaleSourceFile>,
    pub hardening_run: Option<HardeningRun>,
    pub note: String,
    pub artifact_path: Option<String>,
}

#[derive(Debug, Clone, Serialize, Deserialize, JsonSchema)]
pub struct RefactorBatchApplyRun {
    pub schema_version: String,
    pub root: String,
    pub plan_path: String,
    pub plan_id: String,
    pub plan_hash: String,
    pub mode: RefactorApplyMode,
    pub status: RefactorBatchApplyStatus,
    pub public_api_impact_allowed: bool,
    pub max_candidates: usize,
    pub requested_candidates: usize,
    pub executed_candidates: usize,
    pub skipped_candidates: usize,
    pub steps: Vec<RefactorBatchCandidateRun>,
    pub note: String,
    pub artifact_path: Option<String>,
}

#[derive(Debug, Clone, Serialize, Deserialize, JsonSchema)]
pub struct RefactorBatchCandidateRun {
    pub candidate_id: String,
    pub candidate_hash: Option<String>,
    pub file: String,
    pub status: RefactorApplyStatus,
    pub stale_file: Option<StaleSourceFile>,
    pub hardening_run: Option<HardeningRun>,
    pub note: String,
}

#[derive(Debug, Clone, Serialize, Deserialize, JsonSchema, PartialEq, Eq)]
pub enum RefactorApplyMode {
    Review,
    Apply,
}

#[derive(Debug, Clone, Serialize, Deserialize, JsonSchema, PartialEq, Eq)]
pub enum RefactorBatchApplyStatus {
    Reviewed,
    Applied,
    PartiallyApplied,
    Rejected,
    StalePlan,
    NoExecutableCandidates,
}

#[derive(Debug, Clone, Serialize, Deserialize, JsonSchema, PartialEq, Eq)]
pub enum RefactorApplyStatus {
    Reviewed,
    Applied,
    Rejected,
    StalePlan,
    Unsupported,
}

#[derive(Debug, Clone, Serialize, Deserialize, JsonSchema)]
pub struct StaleSourceFile {
    pub file: String,
    pub expected_hash: String,
    pub actual_hash: String,
}

pub fn build_refactor_plan(
    root: &Path,
    artifact_root: Option<&Path>,
    config: &RefactorPlanConfig,
) -> anyhow::Result<RefactorPlan> {
    let root = root.canonicalize().unwrap_or_else(|_| root.to_path_buf());
    let refactor = analyze_refactor(
        &root,
        RefactorAnalyzeConfig {
            target: config.target.as_deref(),
            max_files: config.max_files,
        },
    )?;
    let measured_evidence = load_latest_evidence_for_root(artifact_root, &root)?;
    let hardening = analyze_hardening(
        &root,
        HardeningAnalyzeConfig {
            target: config.target.as_deref(),
            max_files: config.max_files,
            max_recipe_tier: measured_hardening_tier(measured_evidence.as_ref()),
            evidence_depth: hardening_depth_for_evidence(measured_evidence.as_ref()),
        },
    )?;
    let policy = load_project_policy(&root, config.policy_path.as_deref())?;
    let audit_scope = audit_scope_path(&root, config.target.as_deref());
    let audit = audit_agent(&audit_scope)?;
    let security = security_posture_summary(&audit.findings);
    let workspace = workspace_summary(&root);
    let behavior_spec = config
        .behavior_spec_path
        .as_ref()
        .map(|path| path.display().to_string());
    let capability_gates = capability_gates();
    let evidence = summarize_evidence(
        &workspace,
        &refactor.files,
        &capability_gates,
        config.behavior_spec_path.is_some(),
        measured_evidence.as_ref(),
    );
    let impact = summarize_impact(
        &refactor.files,
        refactor.module_edges.len(),
        &hardening.findings,
        hardening.changes.len(),
    );
    let mut candidates = Vec::new();
    candidates.extend(hardening_candidates(
        &hardening.findings,
        config,
        &evidence,
        measured_evidence.as_ref(),
    ));
    candidates.extend(structural_candidates(
        &refactor.files,
        &evidence,
        measured_evidence.as_ref(),
    ));
    candidates.extend(security_candidates(
        &audit.findings,
        &evidence,
        measured_evidence.as_ref(),
    ));
    annotate_candidate_autonomy(&mut candidates, &evidence, &security);
    let autonomy = autonomy_readiness(&evidence, &security, &candidates);
    for candidate in &mut candidates {
        candidate.candidate_hash = candidate_hash(candidate);
    }
    candidates.sort_by(|left, right| left.id.cmp(&right.id));
    let source_snapshots = source_snapshots(&root, &refactor.files)?;

    let required_gates = required_gates(config.behavior_spec_path.is_some());
    let non_goals = vec![
        "No broad API-changing refactors without explicit human allowance.".to_string(),
        "No public API changes without explicit human review.".to_string(),
        "No plan candidate may bypass improve/apply validation gates.".to_string(),
    ];

    let plan_id = plan_id(&root, config, &impact, &candidates);
    let mut plan = RefactorPlan {
        schema_version: "1.0".to_string(),
        plan_id,
        plan_hash: String::new(),
        root: root.display().to_string(),
        target: config
            .target
            .as_ref()
            .map(|path| path.display().to_string()),
        workspace,
        policy,
        behavior_spec,
        evidence,
        measured_evidence: measured_evidence.as_ref().map(EvidenceArtifactRef::from),
        security,
        autonomy,
        impact,
        source_snapshots,
        files: refactor.files,
        module_edges: refactor.module_edges,
        candidates,
        required_gates,
        non_goals,
        artifact_path: None,
    };
    plan.plan_hash = refactor_plan_hash(&plan);

    if let Some(artifact_root) = artifact_root {
        let path = persist_refactor_plan(artifact_root, &plan)?;
        plan.artifact_path = Some(path.display().to_string());
        std::fs::write(&path, serde_json::to_string_pretty(&plan)?)?;
    }

    Ok(plan)
}

pub fn build_codebase_map(
    root: &Path,
    artifact_root: Option<&Path>,
    config: &CodebaseMapConfig,
) -> anyhow::Result<CodebaseMap> {
    let root = root.canonicalize().unwrap_or_else(|_| root.to_path_buf());
    let refactor = analyze_refactor(
        &root,
        RefactorAnalyzeConfig {
            target: config.target.as_deref(),
            max_files: config.max_files,
        },
    )?;
    let measured_evidence = load_latest_evidence_for_root(artifact_root, &root)?;
    let hardening = analyze_hardening(
        &root,
        HardeningAnalyzeConfig {
            target: config.target.as_deref(),
            max_files: config.max_files,
            max_recipe_tier: measured_hardening_tier(measured_evidence.as_ref()),
            evidence_depth: hardening_depth_for_evidence(measured_evidence.as_ref()),
        },
    )?;
    let policy = load_project_policy(&root, config.policy_path.as_deref())?;
    let audit_scope = audit_scope_path(&root, config.target.as_deref());
    let audit = audit_agent(&audit_scope)?;
    let security = security_posture_summary(&audit.findings);
    let workspace = workspace_summary(&root);
    let behavior_spec = config
        .behavior_spec_path
        .as_ref()
        .map(|path| path.display().to_string());
    let capability_gates = capability_gates();
    let evidence = summarize_evidence(
        &workspace,
        &refactor.files,
        &capability_gates,
        config.behavior_spec_path.is_some(),
        measured_evidence.as_ref(),
    );
    let impact = summarize_impact(
        &refactor.files,
        refactor.module_edges.len(),
        &hardening.findings,
        hardening.changes.len(),
    );
    let mut readiness_candidates = Vec::new();
    readiness_candidates.extend(hardening_candidates(
        &hardening.findings,
        &RefactorPlanConfig {
            target: config.target.clone(),
            policy_path: config.policy_path.clone(),
            behavior_spec_path: config.behavior_spec_path.clone(),
            max_files: config.max_files,
        },
        &evidence,
        measured_evidence.as_ref(),
    ));
    readiness_candidates.extend(structural_candidates(
        &refactor.files,
        &evidence,
        measured_evidence.as_ref(),
    ));
    readiness_candidates.extend(security_candidates(
        &audit.findings,
        &evidence,
        measured_evidence.as_ref(),
    ));
    annotate_candidate_autonomy(&mut readiness_candidates, &evidence, &security);
    let autonomy = autonomy_readiness(&evidence, &security, &readiness_candidates);
    let quality = summarize_quality(&refactor.files, &hardening.findings, &impact, &security);
    let recommended_actions =
        recommended_actions(&quality, &impact, &capability_gates, &evidence, &security);
    let map_id = codebase_map_id(&root, config, &quality, &impact);
    let mut map = CodebaseMap {
        schema_version: "1.0".to_string(),
        map_id,
        map_hash: String::new(),
        root: root.display().to_string(),
        target: config
            .target
            .as_ref()
            .map(|path| path.display().to_string()),
        workspace,
        policy,
        behavior_spec,
        evidence,
        measured_evidence: measured_evidence.as_ref().map(EvidenceArtifactRef::from),
        security,
        autonomy,
        quality,
        capability_gates,
        impact,
        files: refactor.files,
        module_edges: refactor.module_edges,
        findings: hardening.findings,
        recommended_actions,
        artifact_path: None,
    };
    map.map_hash = codebase_map_hash(&map);

    if let Some(artifact_root) = artifact_root {
        let path = persist_codebase_map(artifact_root, &map)?;
        map.artifact_path = Some(path.display().to_string());
        std::fs::write(&path, serde_json::to_string_pretty(&map)?)?;
    }

    Ok(map)
}

pub fn build_evolution_scorecard(
    root: &Path,
    artifact_root: Option<&Path>,
    config: &EvolutionScorecardConfig,
) -> anyhow::Result<EvolutionScorecard> {
    let root = root.canonicalize().unwrap_or_else(|_| root.to_path_buf());
    let map = build_codebase_map(
        &root,
        artifact_root,
        &CodebaseMapConfig {
            target: config.target.clone(),
            policy_path: config.policy_path.clone(),
            behavior_spec_path: config.behavior_spec_path.clone(),
            max_files: config.max_files,
        },
    )?;
    let plan = build_refactor_plan(
        &root,
        artifact_root,
        &RefactorPlanConfig {
            target: config.target.clone(),
            policy_path: config.policy_path.clone(),
            behavior_spec_path: config.behavior_spec_path.clone(),
            max_files: config.max_files,
        },
    )?;
    let recipes = recipe_catalog();
    let readiness = plan.autonomy.clone();
    let next_commands = scorecard_next_commands(&readiness, &plan);
    let scorecard_id = evolution_scorecard_id(&root, config, &map, &plan);
    let mut scorecard = EvolutionScorecard {
        schema_version: "1.0".to_string(),
        scorecard_id,
        root: root.display().to_string(),
        target: config
            .target
            .as_ref()
            .map(|path| path.display().to_string()),
        readiness,
        map,
        plan,
        recipes,
        next_commands,
        artifact_path: None,
    };

    if let Some(artifact_root) = artifact_root {
        let path = persist_evolution_scorecard(artifact_root, &scorecard)?;
        scorecard.artifact_path = Some(path.display().to_string());
        std::fs::write(&path, serde_json::to_string_pretty(&scorecard)?)?;
    }

    Ok(scorecard)
}

pub fn run_autopilot(
    root: &Path,
    artifact_root: Option<&Path>,
    config: &AutopilotConfig,
) -> anyhow::Result<AutopilotRun> {
    let root = root.canonicalize().unwrap_or_else(|_| root.to_path_buf());
    let map_config = CodebaseMapConfig {
        target: config.target.clone(),
        policy_path: config.policy_path.clone(),
        behavior_spec_path: config.behavior_spec_path.clone(),
        max_files: config.max_files,
    };
    let before_map = build_codebase_map(&root, artifact_root, &map_config)?;
    let evidence = before_map.evidence.clone();
    let quality_before = before_map.quality.clone();
    let mode = if config.apply {
        RefactorApplyMode::Apply
    } else {
        RefactorApplyMode::Review
    };
    let mut run = AutopilotRun {
        schema_version: "1.0".to_string(),
        run_id: autopilot_run_id(&root, config, &before_map),
        root: root.display().to_string(),
        target: config
            .target
            .as_ref()
            .map(|path| path.display().to_string()),
        mode,
        status: AutopilotStatus::NoExecutableCandidates,
        budget_seconds: config.budget.map(|duration| duration.as_secs()),
        max_passes: config.max_passes,
        max_candidates_per_pass: config.max_candidates,
        quality_before,
        quality_after: None,
        evidence,
        measured_evidence: before_map.measured_evidence.clone(),
        execution_summary: AutopilotExecutionSummary {
            plans_created: 0,
            executable_candidates_seen: 0,
            validated_transactions: 0,
            applied_transactions: 0,
            blocked_or_plan_only_candidates: 0,
            evidence_grade: before_map.evidence.grade,
            analysis_depth: before_map.evidence.analysis_depth.clone(),
        },
        passes: Vec::new(),
        total_planned_candidates: 0,
        total_executed_candidates: 0,
        total_skipped_candidates: 0,
        budget_exhausted: false,
        note: String::new(),
        artifact_path: None,
    };

    let started_at = std::time::Instant::now();
    let pass_count = config.max_passes.max(1);
    for pass_index in 1..=pass_count {
        if config
            .budget
            .is_some_and(|budget| started_at.elapsed() >= budget)
        {
            run.budget_exhausted = true;
            break;
        }
        let plan = build_refactor_plan(
            &root,
            artifact_root,
            &RefactorPlanConfig {
                target: config.target.clone(),
                policy_path: config.policy_path.clone(),
                behavior_spec_path: config.behavior_spec_path.clone(),
                max_files: config.max_files,
            },
        )?;
        let executable = count_executable_candidates(
            &plan,
            config.allow_public_api_impact,
            config.max_candidates,
            config.max_tier,
            config.min_evidence,
        );
        run.total_planned_candidates += plan.candidates.len();

        let mut pass = AutopilotPass {
            pass_index,
            plan_id: plan.plan_id.clone(),
            plan_hash: plan.plan_hash.clone(),
            plan_artifact_path: plan.artifact_path.clone(),
            planned_candidates: plan.candidates.len(),
            executable_candidates: executable,
            batch: None,
            status: AutopilotPassStatus::Planned,
            note: String::new(),
        };

        if executable == 0 {
            pass.status = AutopilotPassStatus::NoExecutableCandidates;
            pass.note = "no executable low-risk candidates remain for this pass".to_string();
            run.passes.push(pass);
            break;
        }

        let Some(plan_path) = plan.artifact_path.as_ref() else {
            pass.status = AutopilotPassStatus::Rejected;
            pass.note = "autopilot requires persisted plan artifacts before execution".to_string();
            run.passes.push(pass);
            break;
        };

        let mut validation_timeout = config.validation_timeout;
        if let Some(budget) = config.budget {
            let Some(remaining) = budget.checked_sub(started_at.elapsed()) else {
                run.budget_exhausted = true;
                pass.status = AutopilotPassStatus::NoExecutableCandidates;
                pass.note = "budget exhausted before execution could start".to_string();
                run.passes.push(pass);
                break;
            };
            if remaining.is_zero() {
                run.budget_exhausted = true;
                pass.status = AutopilotPassStatus::NoExecutableCandidates;
                pass.note = "budget exhausted before execution could start".to_string();
                run.passes.push(pass);
                break;
            }
            validation_timeout = validation_timeout.min(remaining);
        }

        let batch = apply_refactor_plan_batch(
            &root,
            artifact_root,
            &RefactorBatchApplyConfig {
                plan_path: PathBuf::from(plan_path),
                apply: config.apply,
                allow_public_api_impact: config.allow_public_api_impact,
                validation_timeout,
                max_candidates: config.max_candidates,
                max_tier: config.max_tier,
                min_evidence: config.min_evidence,
            },
        )?;
        if config
            .budget
            .is_some_and(|budget| started_at.elapsed() >= budget)
        {
            run.budget_exhausted = true;
        }
        run.total_executed_candidates += batch.executed_candidates;
        run.total_skipped_candidates += batch.skipped_candidates;
        pass.status = autopilot_pass_status(&batch.status);
        pass.note = batch.note.clone();
        let should_stop = !config.apply
            || matches!(
                batch.status,
                RefactorBatchApplyStatus::Rejected
                    | RefactorBatchApplyStatus::StalePlan
                    | RefactorBatchApplyStatus::NoExecutableCandidates
                    | RefactorBatchApplyStatus::PartiallyApplied
            )
            || batch.executed_candidates == 0;
        pass.batch = Some(batch);
        run.passes.push(pass);
        if should_stop {
            break;
        }
    }

    let after_map = if config.apply && run.total_executed_candidates > 0 {
        Some(build_codebase_map(&root, artifact_root, &map_config)?)
    } else {
        None
    };
    run.quality_after = after_map.map(|map| map.quality);
    run.status = autopilot_status(config.apply, &run.passes, run.total_executed_candidates);
    run.note = autopilot_note(&run);
    run.execution_summary = autopilot_execution_summary(&run);
    persist_autopilot_run(artifact_root, run)
}

pub fn apply_refactor_plan_candidate(
    root: &Path,
    artifact_root: Option<&Path>,
    config: &RefactorApplyConfig,
) -> anyhow::Result<RefactorApplyRun> {
    let root = root.canonicalize().unwrap_or_else(|_| root.to_path_buf());
    let plan_content = std::fs::read_to_string(&config.plan_path)?;
    let plan: RefactorPlan = serde_json::from_str(&plan_content)?;
    let mode = if config.apply {
        RefactorApplyMode::Apply
    } else {
        RefactorApplyMode::Review
    };
    let mut run = RefactorApplyRun {
        schema_version: "1.0".to_string(),
        root: root.display().to_string(),
        plan_path: config.plan_path.display().to_string(),
        plan_id: plan.plan_id.clone(),
        plan_hash: plan.plan_hash.clone(),
        candidate_id: config.candidate_id.clone(),
        candidate_hash: None,
        mode,
        status: RefactorApplyStatus::Rejected,
        public_api_impact_allowed: config.allow_public_api_impact,
        stale_files: Vec::new(),
        hardening_run: None,
        note: String::new(),
        artifact_path: None,
    };

    let actual_plan_hash = refactor_plan_hash(&plan);
    if actual_plan_hash != plan.plan_hash {
        run.status = RefactorApplyStatus::Rejected;
        run.note = format!(
            "plan hash mismatch: expected {} but recomputed {}",
            plan.plan_hash, actual_plan_hash
        );
        return persist_apply_run(artifact_root, run);
    }

    let stale_files = stale_source_files(&root, &plan.source_snapshots)?;
    if !stale_files.is_empty() {
        run.status = RefactorApplyStatus::StalePlan;
        run.stale_files = stale_files;
        run.note =
            "plan source snapshots no longer match the workspace; re-run mdx-rust plan".to_string();
        return persist_apply_run(artifact_root, run);
    }

    let Some(candidate) = plan
        .candidates
        .iter()
        .find(|candidate| candidate.id == config.candidate_id)
    else {
        run.status = RefactorApplyStatus::Rejected;
        run.note = "candidate id was not found in the refactor plan".to_string();
        return persist_apply_run(artifact_root, run);
    };
    run.candidate_hash = Some(candidate.candidate_hash.clone());

    let actual_candidate_hash = candidate_hash(candidate);
    if actual_candidate_hash != candidate.candidate_hash {
        run.status = RefactorApplyStatus::Rejected;
        run.note = format!(
            "candidate hash mismatch: expected {} but recomputed {}",
            candidate.candidate_hash, actual_candidate_hash
        );
        return persist_apply_run(artifact_root, run);
    }

    if candidate.public_api_impact && !config.allow_public_api_impact {
        run.status = RefactorApplyStatus::Rejected;
        run.note = "candidate touches public API impact area; pass --allow-public-api-impact after human review".to_string();
        return persist_apply_run(artifact_root, run);
    }

    if !candidate.evidence_satisfied {
        run.status = RefactorApplyStatus::Unsupported;
        run.note = format!(
            "candidate requires {:?} evidence but plan evidence is {:?}",
            candidate.required_evidence, plan.evidence.grade
        );
        return persist_apply_run(artifact_root, run);
    }

    if candidate.autonomy.decision != AutonomyDecision::Allowed {
        run.status = RefactorApplyStatus::Unsupported;
        run.note = format!(
            "candidate autonomy decision is {:?}: {}",
            candidate.autonomy.decision,
            candidate.autonomy.reasons.join("; ")
        );
        return persist_apply_run(artifact_root, run);
    }

    if candidate.status != RefactorCandidateStatus::ApplyViaImprove
        || !is_supported_mechanical_recipe(&candidate.recipe)
    {
        run.status = RefactorApplyStatus::Unsupported;
        run.note = "candidate is plan-only; no executable recipe is available yet".to_string();
        return persist_apply_run(artifact_root, run);
    }

    let hardening = run_hardening(
        &root,
        artifact_root,
        &HardeningConfig {
            target: Some(PathBuf::from(&candidate.file)),
            policy_path: plan
                .policy
                .as_ref()
                .map(|policy| PathBuf::from(policy.path.clone())),
            behavior_spec_path: plan.behavior_spec.as_ref().map(PathBuf::from),
            apply: config.apply,
            max_files: 1,
            max_recipe_tier: recipe_tier_number(candidate.tier),
            evidence_depth: hardening_depth_for_grade(candidate.required_evidence),
            validation_timeout: config.validation_timeout,
        },
    )?;

    run.status = if config.apply {
        if hardening.outcome.applied {
            RefactorApplyStatus::Applied
        } else {
            RefactorApplyStatus::Rejected
        }
    } else if hardening.outcome.isolated_validation_passed {
        RefactorApplyStatus::Reviewed
    } else {
        RefactorApplyStatus::Rejected
    };
    run.note = format!(
        "executed candidate through hardening transaction; hardening status: {:?}",
        hardening.outcome.status
    );
    run.hardening_run = Some(hardening);
    persist_apply_run(artifact_root, run)
}

pub fn apply_refactor_plan_batch(
    root: &Path,
    artifact_root: Option<&Path>,
    config: &RefactorBatchApplyConfig,
) -> anyhow::Result<RefactorBatchApplyRun> {
    let root = root.canonicalize().unwrap_or_else(|_| root.to_path_buf());
    let plan_content = std::fs::read_to_string(&config.plan_path)?;
    let plan: RefactorPlan = serde_json::from_str(&plan_content)?;
    let mode = if config.apply {
        RefactorApplyMode::Apply
    } else {
        RefactorApplyMode::Review
    };
    let mut run = RefactorBatchApplyRun {
        schema_version: "1.0".to_string(),
        root: root.display().to_string(),
        plan_path: config.plan_path.display().to_string(),
        plan_id: plan.plan_id.clone(),
        plan_hash: plan.plan_hash.clone(),
        mode,
        status: RefactorBatchApplyStatus::Rejected,
        public_api_impact_allowed: config.allow_public_api_impact,
        max_candidates: config.max_candidates,
        requested_candidates: 0,
        executed_candidates: 0,
        skipped_candidates: 0,
        steps: Vec::new(),
        note: String::new(),
        artifact_path: None,
    };

    let actual_plan_hash = refactor_plan_hash(&plan);
    if actual_plan_hash != plan.plan_hash {
        run.status = RefactorBatchApplyStatus::Rejected;
        run.note = format!(
            "plan hash mismatch: expected {} but recomputed {}",
            plan.plan_hash, actual_plan_hash
        );
        return persist_batch_apply_run(artifact_root, run);
    }

    let initial_stale_files = stale_source_files(&root, &plan.source_snapshots)?;
    if !initial_stale_files.is_empty() {
        run.status = RefactorBatchApplyStatus::StalePlan;
        run.steps = initial_stale_files
            .into_iter()
            .map(|stale| RefactorBatchCandidateRun {
                candidate_id: String::new(),
                candidate_hash: None,
                file: stale.file.clone(),
                status: RefactorApplyStatus::StalePlan,
                stale_file: Some(stale),
                hardening_run: None,
                note: "source snapshot no longer matches the workspace".to_string(),
            })
            .collect();
        run.note =
            "plan source snapshots no longer match the workspace; re-run mdx-rust plan".to_string();
        return persist_batch_apply_run(artifact_root, run);
    }

    let queue = executable_candidate_queue(&plan, config);
    run.requested_candidates = queue.len();
    if queue.is_empty() {
        run.status = RefactorBatchApplyStatus::NoExecutableCandidates;
        run.note = "no executable low-risk candidates were available in the plan".to_string();
        return persist_batch_apply_run(artifact_root, run);
    }

    for candidate in queue {
        let mut step = RefactorBatchCandidateRun {
            candidate_id: candidate.id.clone(),
            candidate_hash: Some(candidate.candidate_hash.clone()),
            file: candidate.file.clone(),
            status: RefactorApplyStatus::Rejected,
            stale_file: None,
            hardening_run: None,
            note: String::new(),
        };

        let actual_candidate_hash = candidate_hash(candidate);
        if actual_candidate_hash != candidate.candidate_hash {
            step.note = format!(
                "candidate hash mismatch: expected {} but recomputed {}",
                candidate.candidate_hash, actual_candidate_hash
            );
            run.skipped_candidates += 1;
            run.steps.push(step);
            if config.apply {
                break;
            }
            continue;
        }

        if let Some(stale) = stale_file_for_candidate(&root, &plan, &candidate.file)? {
            step.status = RefactorApplyStatus::StalePlan;
            step.stale_file = Some(stale);
            step.note =
                "candidate source file changed after planning; re-run mdx-rust plan".to_string();
            run.skipped_candidates += 1;
            run.steps.push(step);
            if config.apply {
                break;
            }
            continue;
        }

        let hardening = run_hardening(
            &root,
            artifact_root,
            &HardeningConfig {
                target: Some(PathBuf::from(&candidate.file)),
                policy_path: plan
                    .policy
                    .as_ref()
                    .map(|policy| PathBuf::from(policy.path.clone())),
                behavior_spec_path: plan.behavior_spec.as_ref().map(PathBuf::from),
                apply: config.apply,
                max_files: 1,
                max_recipe_tier: recipe_tier_number(candidate.tier),
                evidence_depth: hardening_depth_for_grade(candidate.required_evidence),
                validation_timeout: config.validation_timeout,
            },
        )?;

        step.status = if config.apply {
            if hardening.outcome.applied {
                RefactorApplyStatus::Applied
            } else {
                RefactorApplyStatus::Rejected
            }
        } else if hardening.outcome.isolated_validation_passed {
            RefactorApplyStatus::Reviewed
        } else {
            RefactorApplyStatus::Rejected
        };
        step.note = format!(
            "executed candidate through hardening transaction; hardening status: {:?}",
            hardening.outcome.status
        );
        step.hardening_run = Some(hardening);

        if matches!(
            step.status,
            RefactorApplyStatus::Reviewed | RefactorApplyStatus::Applied
        ) {
            run.executed_candidates += 1;
        } else {
            run.skipped_candidates += 1;
        }

        let failed_apply_step = config.apply && step.status != RefactorApplyStatus::Applied;
        run.steps.push(step);
        if failed_apply_step {
            break;
        }
    }

    run.status = batch_status(
        config.apply,
        run.executed_candidates,
        run.requested_candidates,
    );
    run.note = format!(
        "processed {} executable candidate(s); executed {}, skipped {}",
        run.requested_candidates, run.executed_candidates, run.skipped_candidates
    );
    persist_batch_apply_run(artifact_root, run)
}

fn summarize_impact(
    files: &[RefactorFileSummary],
    module_edge_count: usize,
    findings: &[HardeningFinding],
    patchable_hardening_changes: usize,
) -> RefactorImpactSummary {
    let public_item_count = files.iter().map(|file| file.public_item_count).sum();
    let public_files = files
        .iter()
        .filter(|file| file.public_item_count > 0)
        .count();
    let oversized_files = files.iter().filter(|file| file.line_count >= 300).count();
    let oversized_functions = files
        .iter()
        .filter(|file| file.largest_function_lines >= 80)
        .count();
    let review_only_findings = findings.iter().filter(|finding| !finding.patchable).count();
    let risk_level = if public_item_count > 10 || oversized_files > 2 {
        RefactorRiskLevel::High
    } else if public_item_count > 0 || oversized_files > 0 || oversized_functions > 0 {
        RefactorRiskLevel::Medium
    } else {
        RefactorRiskLevel::Low
    };

    RefactorImpactSummary {
        files_scanned: files.len(),
        public_item_count,
        public_files,
        module_edge_count,
        patchable_hardening_changes,
        review_only_findings,
        oversized_files,
        oversized_functions,
        risk_level,
    }
}

fn summarize_quality(
    files: &[RefactorFileSummary],
    findings: &[HardeningFinding],
    impact: &RefactorImpactSummary,
    security: &SecurityPostureSummary,
) -> CodebaseQualitySummary {
    let patchable_findings = findings.iter().filter(|finding| finding.patchable).count();
    let review_only_findings = findings.len().saturating_sub(patchable_findings);
    let files_with_tests = files.iter().filter(|file| file.has_tests).count();
    let test_coverage_signal = if files.is_empty() {
        TestCoverageSignal::Unknown
    } else if files_with_tests > 0 {
        TestCoverageSignal::Present
    } else {
        TestCoverageSignal::Sparse
    };

    let mut score = 0usize;
    score += patchable_findings.saturating_mul(8);
    score += review_only_findings.saturating_mul(4);
    score += impact.oversized_files.saturating_mul(10);
    score += impact.oversized_functions.saturating_mul(7);
    score += impact.public_files.saturating_mul(2);
    score += (100usize.saturating_sub(security.score as usize)) / 2;
    if test_coverage_signal == TestCoverageSignal::Sparse {
        score += 12;
    }
    let debt_score = score.min(100) as u8;
    let grade = if debt_score >= 70 {
        CodebaseQualityGrade::HighRisk
    } else if debt_score >= 35 {
        CodebaseQualityGrade::NeedsWork
    } else if debt_score >= 10 {
        CodebaseQualityGrade::Good
    } else {
        CodebaseQualityGrade::Excellent
    };

    CodebaseQualitySummary {
        grade,
        debt_score,
        security_score: security.score,
        patchable_findings,
        review_only_findings,
        public_api_pressure: impact.public_item_count,
        oversized_files: impact.oversized_files,
        oversized_functions: impact.oversized_functions,
        test_coverage_signal,
    }
}

fn summarize_evidence(
    workspace: &WorkspaceSummary,
    files: &[RefactorFileSummary],
    gates: &[CapabilityGate],
    has_behavior_spec: bool,
    measured: Option<&EvidenceRun>,
) -> EvidenceSummary {
    let has_tests = files.iter().any(|file| file.has_tests);
    let has_nextest = gates
        .iter()
        .any(|gate| gate.id == "nextest" && gate.available);
    let has_coverage_tool = gates
        .iter()
        .any(|gate| gate.id == "llvm-cov" && gate.available);
    let has_mutation_tool = gates
        .iter()
        .any(|gate| gate.id == "mutants" && gate.available);

    let inferred_grade = if !workspace.cargo_metadata_available {
        EvidenceGrade::None
    } else if has_tests || has_behavior_spec || has_nextest {
        EvidenceGrade::Tested
    } else {
        EvidenceGrade::Compiled
    };
    let grade = measured.map(|run| run.grade).unwrap_or(inferred_grade);
    let max_autonomous_tier = max_tier_for_evidence(grade);
    let analysis_depth = measured
        .map(|run| run.analysis_depth.clone())
        .unwrap_or_else(|| analysis_depth_for_evidence(grade));

    let mut signals = vec![
        EvidenceSignal {
            id: "cargo-metadata".to_string(),
            label: "Cargo metadata".to_string(),
            present: workspace.cargo_metadata_available,
            detail: if workspace.cargo_metadata_available {
                "workspace can be inspected and compile gates can run".to_string()
            } else {
                "no Cargo metadata was available for this target".to_string()
            },
        },
        EvidenceSignal {
            id: "tests-or-behavior-evals".to_string(),
            label: "Tests or behavior evals".to_string(),
            present: has_tests || has_behavior_spec,
            detail: if has_behavior_spec {
                "behavior eval spec was supplied".to_string()
            } else if has_tests {
                "at least one scanned file contains Rust test markers".to_string()
            } else {
                "no tests or behavior eval spec were detected for the scanned target".to_string()
            },
        },
        EvidenceSignal {
            id: "coverage-tool".to_string(),
            label: "Coverage tooling".to_string(),
            present: has_coverage_tool,
            detail: "cargo-llvm-cov availability is detected; run mdx-rust evidence --include-coverage to collect coverage evidence".to_string(),
        },
        EvidenceSignal {
            id: "mutation-tool".to_string(),
            label: "Mutation tooling".to_string(),
            present: has_mutation_tool,
            detail: "cargo-mutants availability is detected; run mdx-rust evidence --include-mutation to collect mutation evidence".to_string(),
        },
    ];
    if let Some(run) = measured {
        signals.push(EvidenceSignal {
            id: "measured-evidence".to_string(),
            label: "Measured evidence artifact".to_string(),
            present: true,
            detail: format!(
                "latest evidence run {} recorded {:?} evidence",
                run.run_id, run.grade
            ),
        });
    }

    let mut unlock_suggestions = Vec::new();
    if grade == EvidenceGrade::None {
        unlock_suggestions.push(
            "Run mdx-rust from a Cargo workspace before allowing autonomous changes.".to_string(),
        );
    }
    if measured.is_none() && grade < EvidenceGrade::Tested {
        unlock_suggestions.push(
            "Add Rust tests or pass --eval-spec to unlock tested evidence for future recipes."
                .to_string(),
        );
    }
    if measured.is_none() {
        unlock_suggestions.push(
            "Run mdx-rust evidence to replace inferred evidence with measured test results."
                .to_string(),
        );
    }
    if !has_coverage_tool {
        unlock_suggestions
            .push("Install cargo-llvm-cov to prepare for covered Tier 2 recipe gates.".to_string());
    }
    if !has_mutation_tool {
        unlock_suggestions.push(
            "Install cargo-mutants to prepare for hardened Tier 2 and Tier 3 recipe gates."
                .to_string(),
        );
    }

    EvidenceSummary {
        grade,
        max_autonomous_tier,
        analysis_depth,
        signals,
        profiled_files: measured.map(|run| run.file_profiles.len()).unwrap_or(0),
        unlocked_recipe_tiers: unlocked_recipe_tiers(grade),
        unlock_suggestions,
    }
}

fn security_posture_summary(findings: &[AuditFinding]) -> SecurityPostureSummary {
    let mut summary = SecurityPostureSummary::default();
    for finding in findings {
        match finding.severity {
            AuditSeverity::High => summary.high += 1,
            AuditSeverity::Medium => summary.medium += 1,
            AuditSeverity::Low => summary.low += 1,
            AuditSeverity::Info => summary.info += 1,
        }
    }
    let penalty = summary.high.saturating_mul(25)
        + summary.medium.saturating_mul(12)
        + summary.low.saturating_mul(5);
    summary.score = 100usize.saturating_sub(penalty).min(100) as u8;
    summary.top_findings = findings
        .iter()
        .filter(|finding| finding.severity != AuditSeverity::Info)
        .take(5)
        .map(|finding| {
            let file = finding.file.as_deref().unwrap_or("<workspace>");
            let line = finding
                .line
                .map(|line| line.to_string())
                .unwrap_or_else(|| "?".to_string());
            format!(
                "{:?}: {} ({}:{})",
                finding.severity, finding.title, file, line
            )
        })
        .collect();
    summary
}

fn annotate_candidate_autonomy(
    candidates: &mut [RefactorCandidate],
    evidence: &EvidenceSummary,
    security: &SecurityPostureSummary,
) {
    for candidate in candidates {
        candidate.autonomy = candidate_autonomy_decision(candidate, evidence, security);
    }
}

fn candidate_autonomy_decision(
    candidate: &RefactorCandidate,
    evidence: &EvidenceSummary,
    security: &SecurityPostureSummary,
) -> CandidateAutonomyDecision {
    let mut reasons = Vec::new();
    if evidence.grade == EvidenceGrade::None {
        reasons.push("no usable evidence grade is available".to_string());
        return CandidateAutonomyDecision {
            decision: AutonomyDecision::Blocked,
            reasons,
        };
    }
    if security.high > 0 {
        reasons.push(
            "high-severity security finding requires human review before autonomous apply"
                .to_string(),
        );
        return CandidateAutonomyDecision {
            decision: AutonomyDecision::ReviewOnly,
            reasons,
        };
    }
    if !candidate.evidence_satisfied || candidate.required_evidence > evidence.grade {
        reasons.push(format!(
            "candidate requires {:?} evidence but target has {:?}",
            candidate.required_evidence, evidence.grade
        ));
        return CandidateAutonomyDecision {
            decision: AutonomyDecision::Blocked,
            reasons,
        };
    }
    if candidate.public_api_impact {
        reasons.push("public API impact requires explicit human allowance".to_string());
        return CandidateAutonomyDecision {
            decision: AutonomyDecision::ReviewOnly,
            reasons,
        };
    }
    if candidate.status != RefactorCandidateStatus::ApplyViaImprove {
        reasons.push("candidate is plan-only or needs human design".to_string());
        return CandidateAutonomyDecision {
            decision: AutonomyDecision::ReviewOnly,
            reasons,
        };
    }
    if !is_supported_mechanical_recipe(&candidate.recipe) {
        reasons.push("candidate has no supported executable recipe".to_string());
        return CandidateAutonomyDecision {
            decision: AutonomyDecision::ReviewOnly,
            reasons,
        };
    }
    if candidate.risk != RefactorRiskLevel::Low {
        reasons.push("only low-risk candidates are autonomous by default".to_string());
        return CandidateAutonomyDecision {
            decision: AutonomyDecision::ReviewOnly,
            reasons,
        };
    }

    reasons.push("low-risk executable recipe satisfies current evidence gates".to_string());
    CandidateAutonomyDecision {
        decision: AutonomyDecision::Allowed,
        reasons,
    }
}

fn autonomy_readiness(
    evidence: &EvidenceSummary,
    security: &SecurityPostureSummary,
    candidates: &[RefactorCandidate],
) -> AutonomyReadiness {
    let executable_candidates = candidates
        .iter()
        .filter(|candidate| candidate.autonomy.decision == AutonomyDecision::Allowed)
        .count();
    let review_only_candidates = candidates
        .iter()
        .filter(|candidate| candidate.autonomy.decision == AutonomyDecision::ReviewOnly)
        .count();
    let blocked_candidates = candidates
        .iter()
        .filter(|candidate| candidate.autonomy.decision == AutonomyDecision::Blocked)
        .count();
    let mut blockers = Vec::new();
    if evidence.grade == EvidenceGrade::None {
        blockers.push("no usable evidence grade is available".to_string());
    }
    if security.high > 0 {
        blockers.push("high-severity security findings require review first".to_string());
    }
    if executable_candidates == 0 {
        blockers.push("no low-risk executable candidates are currently allowed".to_string());
    }

    let has_tier2_allowed = candidates.iter().any(|candidate| {
        candidate.autonomy.decision == AutonomyDecision::Allowed
            && candidate.tier >= RecipeTier::Tier2
    });
    let has_tier3_plan = candidates.iter().any(|candidate| {
        candidate.tier >= RecipeTier::Tier3
            && candidate.autonomy.decision != AutonomyDecision::Blocked
    });
    let grade = if evidence.grade == EvidenceGrade::None {
        AutonomyReadinessGrade::Blocked
    } else if executable_candidates > 0 && has_tier2_allowed {
        AutonomyReadinessGrade::Tier2Ready
    } else if executable_candidates > 0 {
        AutonomyReadinessGrade::Tier1Ready
    } else if has_tier3_plan {
        AutonomyReadinessGrade::Tier3Planning
    } else {
        AutonomyReadinessGrade::ReviewOnly
    };
    let max_safe_tier = candidates
        .iter()
        .filter(|candidate| candidate.autonomy.decision == AutonomyDecision::Allowed)
        .map(|candidate| candidate.tier)
        .max()
        .unwrap_or(RecipeTier::Tier1);
    let recommended_command = match grade {
        AutonomyReadinessGrade::Tier2Ready => Some(
            "mdx-rust evolve <target> --budget 10m --tier 2 --min-evidence covered".to_string(),
        ),
        AutonomyReadinessGrade::Tier1Ready => {
            Some("mdx-rust evolve <target> --budget 10m --tier 1".to_string())
        }
        AutonomyReadinessGrade::Tier3Planning => Some("mdx-rust plan <target> --json".to_string()),
        AutonomyReadinessGrade::ReviewOnly | AutonomyReadinessGrade::Blocked => {
            Some("mdx-rust map <target> --json".to_string())
        }
    };

    AutonomyReadiness {
        grade,
        max_safe_tier,
        executable_candidates,
        review_only_candidates,
        blocked_candidates,
        blockers,
        recommended_command,
    }
}

fn analysis_depth_for_evidence(grade: EvidenceGrade) -> EvidenceAnalysisDepth {
    match grade {
        EvidenceGrade::None => EvidenceAnalysisDepth::None,
        EvidenceGrade::Compiled => EvidenceAnalysisDepth::Mechanical,
        EvidenceGrade::Tested => EvidenceAnalysisDepth::BoundaryAware,
        EvidenceGrade::Covered | EvidenceGrade::Hardened | EvidenceGrade::Proven => {
            EvidenceAnalysisDepth::Structural
        }
    }
}

fn unlocked_recipe_tiers(grade: EvidenceGrade) -> Vec<String> {
    let mut tiers = Vec::new();
    if grade >= EvidenceGrade::Compiled {
        tiers.push("Tier 1 executable mechanical recipes".to_string());
    }
    if grade >= EvidenceGrade::Tested {
        tiers.push("Tier 2 boundary review candidates".to_string());
    }
    if grade >= EvidenceGrade::Covered {
        tiers.push("Tier 2 structural mechanical recipes".to_string());
    }
    if grade >= EvidenceGrade::Hardened {
        tiers.push("Tier 3 semantic candidates in review".to_string());
    }
    tiers
}

fn max_tier_for_evidence(grade: EvidenceGrade) -> u8 {
    match grade {
        EvidenceGrade::None => 0,
        EvidenceGrade::Compiled | EvidenceGrade::Tested => 1,
        EvidenceGrade::Covered => 2,
        EvidenceGrade::Hardened | EvidenceGrade::Proven => 3,
    }
}

fn measured_hardening_tier(measured: Option<&EvidenceRun>) -> u8 {
    match measured.map(|run| run.grade) {
        Some(EvidenceGrade::Hardened | EvidenceGrade::Proven) => 3,
        Some(EvidenceGrade::Covered) => 2,
        _ => 1,
    }
}

fn hardening_depth_for_evidence(measured: Option<&EvidenceRun>) -> HardeningEvidenceDepth {
    match measured.map(|run| run.grade) {
        Some(EvidenceGrade::Proven) => HardeningEvidenceDepth::Proven,
        Some(EvidenceGrade::Hardened) => HardeningEvidenceDepth::Hardened,
        Some(EvidenceGrade::Covered) => HardeningEvidenceDepth::Covered,
        Some(EvidenceGrade::Tested) => HardeningEvidenceDepth::Tested,
        _ => HardeningEvidenceDepth::Basic,
    }
}

fn hardening_depth_for_grade(grade: EvidenceGrade) -> HardeningEvidenceDepth {
    match grade {
        EvidenceGrade::Proven => HardeningEvidenceDepth::Proven,
        EvidenceGrade::Hardened => HardeningEvidenceDepth::Hardened,
        EvidenceGrade::Covered => HardeningEvidenceDepth::Covered,
        EvidenceGrade::Tested => HardeningEvidenceDepth::Tested,
        EvidenceGrade::None | EvidenceGrade::Compiled => HardeningEvidenceDepth::Basic,
    }
}

fn capability_gates() -> Vec<CapabilityGate> {
    vec![
        CapabilityGate {
            id: "nextest".to_string(),
            label: "cargo-nextest".to_string(),
            available: cargo_subcommand_exists("nextest"),
            command: "cargo nextest run".to_string(),
            purpose: "fast, isolated Rust test execution for behavior gates".to_string(),
        },
        CapabilityGate {
            id: "llvm-cov".to_string(),
            label: "cargo-llvm-cov".to_string(),
            available: cargo_subcommand_exists("llvm-cov"),
            command: "cargo llvm-cov".to_string(),
            purpose: "coverage evidence before broad autonomous refactoring".to_string(),
        },
        CapabilityGate {
            id: "mutants".to_string(),
            label: "cargo-mutants".to_string(),
            available: cargo_subcommand_exists("mutants"),
            command: "cargo mutants".to_string(),
            purpose: "mutation testing signal for high-value refactor targets".to_string(),
        },
        CapabilityGate {
            id: "semver-checks".to_string(),
            label: "cargo-semver-checks".to_string(),
            available: cargo_subcommand_exists("semver-checks"),
            command: "cargo semver-checks".to_string(),
            purpose: "public API compatibility gate for library refactors".to_string(),
        },
    ]
}

fn recommended_actions(
    quality: &CodebaseQualitySummary,
    impact: &RefactorImpactSummary,
    gates: &[CapabilityGate],
    evidence: &EvidenceSummary,
    security: &SecurityPostureSummary,
) -> Vec<String> {
    let mut actions = Vec::new();
    if security.high > 0 || security.medium > 0 {
        actions.push(
            "Run mdx-rust audit and inspect security posture before broad autonomous apply."
                .to_string(),
        );
    }
    if quality.patchable_findings > 0 && evidence.grade >= EvidenceGrade::Compiled {
        actions.push(
            "Run mdx-rust autopilot --apply to execute low-risk Tier 1 mechanical hardening passes."
                .to_string(),
        );
    } else if quality.patchable_findings > 0 {
        actions.push(
            "Autonomous execution is blocked until this target has at least compiled evidence."
                .to_string(),
        );
    }
    if quality.review_only_findings > 0 {
        actions.push(
            "Review security-sensitive findings before enabling broader recipes.".to_string(),
        );
    }
    if impact.oversized_files > 0 || impact.oversized_functions > 0 {
        actions.push(
            "Use mdx-rust plan to stage larger module and function refactors behind behavior gates."
                .to_string(),
        );
    }
    if quality.public_api_pressure > 0
        && gates
            .iter()
            .any(|gate| gate.id == "semver-checks" && !gate.available)
    {
        actions.push(
            "Install cargo-semver-checks before allowing public API impacting refactors."
                .to_string(),
        );
    }
    if quality.test_coverage_signal == TestCoverageSignal::Sparse {
        actions.push(
            "Add a behavior eval spec or stronger Rust tests before broad autonomous apply."
                .to_string(),
        );
    }
    actions.extend(evidence.unlock_suggestions.iter().cloned());
    if actions.is_empty() {
        actions.push(
            "No immediate autonomous changes found. Keep policy and behavior gates current."
                .to_string(),
        );
    }
    actions
}

fn cargo_subcommand_exists(name: &str) -> bool {
    let command = format!("cargo-{name}");
    let Some(path_var) = std::env::var_os("PATH") else {
        return false;
    };
    std::env::split_paths(&path_var).any(|dir| dir.join(&command).is_file())
}

fn hardening_candidates(
    findings: &[HardeningFinding],
    config: &RefactorPlanConfig,
    evidence: &EvidenceSummary,
    measured: Option<&EvidenceRun>,
) -> Vec<RefactorCandidate> {
    findings
        .iter()
        .filter_map(|finding| {
            let file = finding.file.display().to_string();
            let required_evidence = required_evidence_for_hardening_strategy(&finding.strategy);
            let evidence_satisfied = evidence.grade >= required_evidence;
            let recipe = recipe_for_hardening_strategy(&finding.strategy);
            if !finding.patchable && !evidence_satisfied {
                return None;
            }

            Some(RefactorCandidate {
                id: format!(
                    "plan-hardening-{}-{}-{}",
                    sanitize_id(&file),
                    sanitize_id(&format!("{:?}", finding.strategy)),
                    finding.line
                ),
                candidate_hash: String::new(),
                recipe,
                title: finding.title.clone(),
                rationale: if finding.patchable {
                    if required_evidence >= EvidenceGrade::Covered {
                        "Patchable Tier 2 structural mechanical refactor can be applied only when measured coverage evidence unlocks it.".to_string()
                    } else {
                        "Patchable Tier 1 mechanical hardening can be applied through the existing isolated validation transaction.".to_string()
                    }
                } else {
                    "Higher-evidence review candidate surfaced from security or boundary analysis; it remains plan-only until a safe executable recipe exists.".to_string()
                },
                file: file.clone(),
                line: finding.line,
                risk: risk_for_hardening_strategy(&finding.strategy),
                status: if evidence_satisfied {
                    if finding.patchable {
                        RefactorCandidateStatus::ApplyViaImprove
                    } else {
                        RefactorCandidateStatus::PlanOnly
                    }
                } else {
                    RefactorCandidateStatus::PlanOnly
                },
                tier: if required_evidence >= EvidenceGrade::Hardened {
                    RecipeTier::Tier3
                } else if required_evidence >= EvidenceGrade::Covered {
                    RecipeTier::Tier2
                } else if finding.patchable {
                    RecipeTier::Tier1
                } else {
                    RecipeTier::Tier2
                },
                required_evidence,
                evidence_satisfied,
                evidence_context: candidate_evidence_context(&file, evidence, measured),
                autonomy: CandidateAutonomyDecision::default(),
                public_api_impact: false,
                apply_command: (finding.patchable && evidence_satisfied)
                    .then(|| apply_command(&file, config, required_evidence)),
                required_gates: if finding.patchable {
                    required_gates(config.behavior_spec_path.is_some())
                } else {
                    vec![
                        "human review of boundary contract".to_string(),
                        "behavior evals or tests must cover the boundary".to_string(),
                        "future executable recipe must route through hardening transactions"
                            .to_string(),
                    ]
                },
            })
        })
        .collect()
}

fn required_evidence_for_hardening_strategy(
    strategy: &mdx_rust_analysis::HardeningStrategy,
) -> EvidenceGrade {
    match strategy {
        mdx_rust_analysis::HardeningStrategy::LenCheckIsEmpty
        | mdx_rust_analysis::HardeningStrategy::OptionContextPropagation
        | mdx_rust_analysis::HardeningStrategy::RepeatedStringLiteralConst => {
            EvidenceGrade::Covered
        }
        mdx_rust_analysis::HardeningStrategy::ClonePressureReview
        | mdx_rust_analysis::HardeningStrategy::LongFunctionReview => EvidenceGrade::Hardened,
        mdx_rust_analysis::HardeningStrategy::EnvAccessReview
        | mdx_rust_analysis::HardeningStrategy::FileIoReview
        | mdx_rust_analysis::HardeningStrategy::HttpSurfaceReview
        | mdx_rust_analysis::HardeningStrategy::ProcessExecutionReview
        | mdx_rust_analysis::HardeningStrategy::UnsafeReview => EvidenceGrade::Tested,
        _ => EvidenceGrade::Compiled,
    }
}

fn recipe_for_hardening_strategy(
    strategy: &mdx_rust_analysis::HardeningStrategy,
) -> RefactorRecipe {
    match strategy {
        mdx_rust_analysis::HardeningStrategy::BorrowParameterTightening => {
            RefactorRecipe::BorrowParameterTightening
        }
        mdx_rust_analysis::HardeningStrategy::ErrorContextPropagation => {
            RefactorRecipe::ErrorContextPropagation
        }
        mdx_rust_analysis::HardeningStrategy::IteratorCloned => RefactorRecipe::IteratorCloned,
        mdx_rust_analysis::HardeningStrategy::LenCheckIsEmpty => RefactorRecipe::LenCheckIsEmpty,
        mdx_rust_analysis::HardeningStrategy::OptionContextPropagation => {
            RefactorRecipe::OptionContextPropagation
        }
        mdx_rust_analysis::HardeningStrategy::MustUsePublicReturn => {
            RefactorRecipe::MustUsePublicReturn
        }
        mdx_rust_analysis::HardeningStrategy::ClonePressureReview => {
            RefactorRecipe::ClonePressureReview
        }
        mdx_rust_analysis::HardeningStrategy::LongFunctionReview => {
            RefactorRecipe::LongFunctionReview
        }
        mdx_rust_analysis::HardeningStrategy::RepeatedStringLiteralConst => {
            RefactorRecipe::RepeatedStringLiteralConst
        }
        mdx_rust_analysis::HardeningStrategy::HttpSurfaceReview => {
            RefactorRecipe::BoundaryValidationReview
        }
        mdx_rust_analysis::HardeningStrategy::EnvAccessReview
        | mdx_rust_analysis::HardeningStrategy::FileIoReview => {
            RefactorRecipe::BoundaryValidationReview
        }
        mdx_rust_analysis::HardeningStrategy::ProcessExecutionReview
        | mdx_rust_analysis::HardeningStrategy::UnsafeReview => {
            RefactorRecipe::SecurityBoundaryReview
        }
        _ => RefactorRecipe::ContextualErrorHardening,
    }
}

fn risk_for_hardening_strategy(
    strategy: &mdx_rust_analysis::HardeningStrategy,
) -> RefactorRiskLevel {
    match strategy {
        mdx_rust_analysis::HardeningStrategy::ProcessExecutionReview
        | mdx_rust_analysis::HardeningStrategy::UnsafeReview => RefactorRiskLevel::High,
        mdx_rust_analysis::HardeningStrategy::EnvAccessReview
        | mdx_rust_analysis::HardeningStrategy::FileIoReview
        | mdx_rust_analysis::HardeningStrategy::ClonePressureReview
        | mdx_rust_analysis::HardeningStrategy::LongFunctionReview
        | mdx_rust_analysis::HardeningStrategy::HttpSurfaceReview => RefactorRiskLevel::Medium,
        _ => RefactorRiskLevel::Low,
    }
}

fn structural_candidates(
    files: &[RefactorFileSummary],
    evidence: &EvidenceSummary,
    measured: Option<&EvidenceRun>,
) -> Vec<RefactorCandidate> {
    let mut candidates = Vec::new();
    let split_threshold = if evidence.grade >= EvidenceGrade::Hardened {
        220
    } else {
        300
    };
    let extract_threshold = if evidence.grade >= EvidenceGrade::Hardened {
        50
    } else {
        80
    };
    for file in files {
        let file_path = file.file.display().to_string();
        if file.line_count >= split_threshold {
            let required_evidence = EvidenceGrade::Covered;
            candidates.push(RefactorCandidate {
                id: format!("plan-split-module-{}", sanitize_id(&file_path)),
                candidate_hash: String::new(),
                recipe: RefactorRecipe::SplitModuleCandidate,
                title: "Split oversized module".to_string(),
                rationale: format!(
                    "{} has {} lines. Current evidence threshold is {split_threshold} lines for split-module planning.",
                    file_path, file.line_count
                ),
                file: file_path.clone(),
                line: 1,
                risk: if file.public_item_count > 0 {
                    RefactorRiskLevel::High
                } else {
                    RefactorRiskLevel::Medium
                },
                status: RefactorCandidateStatus::NeedsHumanDesign,
                tier: RecipeTier::Tier2,
                required_evidence,
                evidence_satisfied: evidence.grade >= required_evidence,
                evidence_context: candidate_evidence_context(&file_path, evidence, measured),
                autonomy: CandidateAutonomyDecision::default(),
                public_api_impact: file.public_item_count > 0,
                apply_command: None,
                required_gates: vec![
                    "human design review".to_string(),
                    "cargo check".to_string(),
                    "cargo clippy -- -D warnings".to_string(),
                    "behavior evals when configured".to_string(),
                ],
            });
        }

        if file.largest_function_lines >= extract_threshold {
            let required_evidence = EvidenceGrade::Covered;
            candidates.push(RefactorCandidate {
                id: format!("plan-extract-function-{}", sanitize_id(&file_path)),
                candidate_hash: String::new(),
                recipe: RefactorRecipe::ExtractFunctionCandidate,
                title: "Extract long function".to_string(),
                rationale: format!(
                    "Largest function in {} is {} lines. Current evidence threshold is {extract_threshold} lines for extract-function planning.",
                    file_path, file.largest_function_lines
                ),
                file: file_path.clone(),
                line: 1,
                risk: RefactorRiskLevel::Medium,
                status: RefactorCandidateStatus::PlanOnly,
                tier: RecipeTier::Tier2,
                required_evidence,
                evidence_satisfied: evidence.grade >= required_evidence,
                evidence_context: candidate_evidence_context(&file_path, evidence, measured),
                autonomy: CandidateAutonomyDecision::default(),
                public_api_impact: file.public_item_count > 0,
                apply_command: None,
                required_gates: vec![
                    "targeted tests or behavior evals".to_string(),
                    "cargo check".to_string(),
                    "cargo clippy -- -D warnings".to_string(),
                ],
            });
        }

        if file.public_item_count > 0 {
            let required_evidence = EvidenceGrade::Tested;
            candidates.push(RefactorCandidate {
                id: format!("plan-public-api-{}", sanitize_id(&file_path)),
                candidate_hash: String::new(),
                recipe: RefactorRecipe::PublicApiReview,
                title: "Protect public API before refactoring".to_string(),
                rationale: format!(
                    "{} exposes {} public item(s). Treat signature changes as semver-impacting.",
                    file_path, file.public_item_count
                ),
                file: file_path.clone(),
                line: 1,
                risk: RefactorRiskLevel::Medium,
                status: RefactorCandidateStatus::PlanOnly,
                tier: RecipeTier::Tier1,
                required_evidence,
                evidence_satisfied: evidence.grade >= required_evidence,
                evidence_context: candidate_evidence_context(&file_path, evidence, measured),
                autonomy: CandidateAutonomyDecision::default(),
                public_api_impact: true,
                apply_command: None,
                required_gates: vec![
                    "public API review".to_string(),
                    "docs and changelog review for exported changes".to_string(),
                ],
            });
        }
    }

    candidates
}

fn security_candidates(
    findings: &[AuditFinding],
    evidence: &EvidenceSummary,
    measured: Option<&EvidenceRun>,
) -> Vec<RefactorCandidate> {
    findings
        .iter()
        .filter(|finding| finding.severity != AuditSeverity::Info)
        .map(|finding| {
            let file = finding
                .file
                .clone()
                .unwrap_or_else(|| "<workspace>".to_string());
            let line = finding.line.unwrap_or(1);
            let required_evidence = match finding.severity {
                AuditSeverity::High => EvidenceGrade::Tested,
                AuditSeverity::Medium => EvidenceGrade::Tested,
                AuditSeverity::Low | AuditSeverity::Info => EvidenceGrade::Compiled,
            };
            let risk = match finding.severity {
                AuditSeverity::High => RefactorRiskLevel::High,
                AuditSeverity::Medium => RefactorRiskLevel::Medium,
                AuditSeverity::Low | AuditSeverity::Info => RefactorRiskLevel::Low,
            };
            RefactorCandidate {
                id: format!(
                    "plan-security-{}-{}-{}",
                    sanitize_id(&file),
                    sanitize_id(&finding.id),
                    line
                ),
                candidate_hash: String::new(),
                recipe: RefactorRecipe::SecurityBoundaryReview,
                title: finding.title.clone(),
                rationale: format!(
                    "Security audit flagged {:?}: {}",
                    finding.severity, finding.description
                ),
                file: file.clone(),
                line,
                risk,
                status: RefactorCandidateStatus::PlanOnly,
                tier: RecipeTier::Tier2,
                required_evidence,
                evidence_satisfied: evidence.grade >= required_evidence,
                evidence_context: candidate_evidence_context(&file, evidence, measured),
                autonomy: CandidateAutonomyDecision::default(),
                public_api_impact: false,
                apply_command: None,
                required_gates: vec![
                    "human security review".to_string(),
                    "policy update or explicit risk acceptance".to_string(),
                    "behavior evals or tests must cover the boundary".to_string(),
                ],
            }
        })
        .collect()
}

fn candidate_evidence_context(
    file: &str,
    evidence: &EvidenceSummary,
    measured: Option<&EvidenceRun>,
) -> CandidateEvidenceContext {
    if let Some(profile) = measured
        .iter()
        .flat_map(|run| run.file_profiles.iter())
        .find(|profile| profile.file == file)
    {
        return CandidateEvidenceContext {
            grade: profile.grade,
            status: candidate_evidence_status(profile.grade),
            source: "measured file evidence profile".to_string(),
            profiled_file: Some(profile.file.clone()),
            signals: profile.signals.clone(),
        };
    }
    CandidateEvidenceContext {
        grade: evidence.grade,
        status: candidate_evidence_status(evidence.grade),
        source: if measured.is_some() {
            "measured run did not include this file; using run-level evidence".to_string()
        } else {
            "inferred evidence summary".to_string()
        },
        profiled_file: None,
        signals: evidence
            .signals
            .iter()
            .filter(|signal| signal.present)
            .map(|signal| signal.label.clone())
            .collect(),
    }
}

fn candidate_evidence_status(grade: EvidenceGrade) -> CandidateEvidenceStatus {
    match grade {
        EvidenceGrade::None => CandidateEvidenceStatus::Unmeasured,
        EvidenceGrade::Compiled => CandidateEvidenceStatus::Compiled,
        EvidenceGrade::Tested => CandidateEvidenceStatus::Tested,
        EvidenceGrade::Covered => CandidateEvidenceStatus::Covered,
        EvidenceGrade::Hardened => CandidateEvidenceStatus::MutationBacked,
        EvidenceGrade::Proven => CandidateEvidenceStatus::Proven,
    }
}

fn required_gates(has_behavior_spec: bool) -> Vec<String> {
    let mut gates = vec![
        "cargo check".to_string(),
        "cargo clippy -- -D warnings".to_string(),
        "review plan artifact before applying".to_string(),
    ];
    if has_behavior_spec {
        gates.push("behavior eval spec must pass in isolation and after apply".to_string());
    }
    gates
}

fn apply_command(file: &str, config: &RefactorPlanConfig, evidence: EvidenceGrade) -> String {
    let mut command = format!("mdx-rust improve {} --apply", shell_word_str(file));
    if evidence >= EvidenceGrade::Covered {
        command.push_str(" --tier 2");
    }
    if let Some(policy) = &config.policy_path {
        command.push_str(&format!(" --policy {}", shell_word_path(policy)));
    }
    if let Some(eval_spec) = &config.behavior_spec_path {
        command.push_str(&format!(" --eval-spec {}", shell_word_path(eval_spec)));
    }
    command
}

fn shell_word_path(path: &Path) -> String {
    shell_word_str(&path.display().to_string())
}

fn shell_word_str(value: &str) -> String {
    if value
        .chars()
        .all(|ch| ch.is_ascii_alphanumeric() || matches!(ch, '/' | '.' | '_' | '-' | ':'))
    {
        value.to_string()
    } else {
        format!("'{}'", value.replace('\'', "'\\''"))
    }
}

fn plan_id(
    root: &Path,
    config: &RefactorPlanConfig,
    impact: &RefactorImpactSummary,
    candidates: &[RefactorCandidate],
) -> String {
    let mut bytes = Vec::new();
    bytes.extend_from_slice(root.display().to_string().as_bytes());
    bytes.extend_from_slice(format!("{:?}", config.target).as_bytes());
    bytes.extend_from_slice(format!("{:?}", config.policy_path).as_bytes());
    bytes.extend_from_slice(format!("{:?}", config.behavior_spec_path).as_bytes());
    bytes.extend_from_slice(format!("{impact:?}").as_bytes());
    bytes.extend_from_slice(format!("{candidates:?}").as_bytes());
    stable_hash_hex(&bytes)
}

fn codebase_map_id(
    root: &Path,
    config: &CodebaseMapConfig,
    quality: &CodebaseQualitySummary,
    impact: &RefactorImpactSummary,
) -> String {
    let mut bytes = Vec::new();
    bytes.extend_from_slice(root.display().to_string().as_bytes());
    bytes.extend_from_slice(format!("{:?}", config.target).as_bytes());
    bytes.extend_from_slice(format!("{quality:?}").as_bytes());
    bytes.extend_from_slice(format!("{impact:?}").as_bytes());
    stable_hash_hex(&bytes)
}

fn codebase_map_hash(map: &CodebaseMap) -> String {
    let mut bytes = Vec::new();
    bytes.extend_from_slice(map.schema_version.as_bytes());
    bytes.extend_from_slice(map.map_id.as_bytes());
    bytes.extend_from_slice(map.root.as_bytes());
    bytes.extend_from_slice(format!("{:?}", map.target).as_bytes());
    bytes.extend_from_slice(format!("{:?}", map.quality).as_bytes());
    bytes.extend_from_slice(format!("{:?}", map.security).as_bytes());
    bytes.extend_from_slice(format!("{:?}", map.evidence).as_bytes());
    bytes.extend_from_slice(format!("{:?}", map.measured_evidence).as_bytes());
    bytes.extend_from_slice(format!("{:?}", map.impact).as_bytes());
    bytes.extend_from_slice(format!("{:?}", map.files).as_bytes());
    bytes.extend_from_slice(format!("{:?}", map.module_edges).as_bytes());
    bytes.extend_from_slice(format!("{:?}", map.findings).as_bytes());
    stable_hash_hex(&bytes)
}

fn autopilot_run_id(root: &Path, config: &AutopilotConfig, map: &CodebaseMap) -> String {
    let mut bytes = Vec::new();
    bytes.extend_from_slice(root.display().to_string().as_bytes());
    bytes.extend_from_slice(format!("{:?}", config.target).as_bytes());
    bytes.extend_from_slice(config.apply.to_string().as_bytes());
    bytes.extend_from_slice(config.max_passes.to_string().as_bytes());
    bytes.extend_from_slice(config.max_candidates.to_string().as_bytes());
    bytes.extend_from_slice(format!("{:?}", config.max_tier).as_bytes());
    bytes.extend_from_slice(format!("{:?}", config.min_evidence).as_bytes());
    bytes.extend_from_slice(map.map_hash.as_bytes());
    stable_hash_hex(&bytes)
}

fn evolution_scorecard_id(
    root: &Path,
    config: &EvolutionScorecardConfig,
    map: &CodebaseMap,
    plan: &RefactorPlan,
) -> String {
    let mut bytes = Vec::new();
    bytes.extend_from_slice(root.display().to_string().as_bytes());
    bytes.extend_from_slice(format!("{:?}", config.target).as_bytes());
    bytes.extend_from_slice(map.map_hash.as_bytes());
    bytes.extend_from_slice(plan.plan_hash.as_bytes());
    stable_hash_hex(&bytes)
}

fn scorecard_next_commands(readiness: &AutonomyReadiness, plan: &RefactorPlan) -> Vec<String> {
    let target = plan.target.as_deref().unwrap_or("<target>");
    let target_arg = if target == "<target>" {
        target.to_string()
    } else {
        shell_quote_argument(target)
    };
    let mut commands = vec![
        format!("mdx-rust --json evidence {target_arg}"),
        format!("mdx-rust --json map {target_arg}"),
        format!("mdx-rust --json plan {target_arg}"),
    ];
    match readiness.grade {
        AutonomyReadinessGrade::Tier2Ready => commands.push(format!(
            "mdx-rust --json evolve {target_arg} --budget 10m --tier 2 --min-evidence covered"
        )),
        AutonomyReadinessGrade::Tier1Ready => commands.push(format!(
            "mdx-rust --json evolve {target_arg} --budget 10m --tier 1"
        )),
        AutonomyReadinessGrade::Tier3Planning => {
            commands.push(format!("mdx-rust --json plan {target_arg} --max-files 250"))
        }
        AutonomyReadinessGrade::ReviewOnly | AutonomyReadinessGrade::Blocked => {
            commands.push("mdx-rust --json audit".to_string())
        }
    }
    if let Some(path) = &plan.artifact_path {
        commands.push(format!(
            "mdx-rust --json explain {}",
            shell_quote_argument(path)
        ));
    }
    commands
}

fn shell_quote_argument(value: &str) -> String {
    if value
        .bytes()
        .all(|byte| byte.is_ascii_alphanumeric() || matches!(byte, b'/' | b'.' | b'-' | b'_'))
    {
        return value.to_string();
    }

    format!("'{}'", value.replace('\'', "'\\''"))
}

fn audit_scope_path(root: &Path, target: Option<&Path>) -> PathBuf {
    let Some(target) = target else {
        return root.to_path_buf();
    };
    if target.is_absolute() {
        target.to_path_buf()
    } else {
        root.join(target)
    }
}

fn refactor_plan_hash(plan: &RefactorPlan) -> String {
    let mut bytes = Vec::new();
    bytes.extend_from_slice(plan.schema_version.as_bytes());
    bytes.extend_from_slice(plan.plan_id.as_bytes());
    bytes.extend_from_slice(plan.root.as_bytes());
    bytes.extend_from_slice(format!("{:?}", plan.target).as_bytes());
    bytes.extend_from_slice(format!("{:?}", plan.evidence).as_bytes());
    bytes.extend_from_slice(format!("{:?}", plan.measured_evidence).as_bytes());
    bytes.extend_from_slice(format!("{:?}", plan.security).as_bytes());
    bytes.extend_from_slice(format!("{:?}", plan.impact).as_bytes());
    bytes.extend_from_slice(format!("{:?}", plan.source_snapshots).as_bytes());
    bytes.extend_from_slice(format!("{:?}", plan.module_edges).as_bytes());
    bytes.extend_from_slice(format!("{:?}", plan.candidates).as_bytes());
    stable_hash_hex(&bytes)
}

fn candidate_hash(candidate: &RefactorCandidate) -> String {
    let mut bytes = Vec::new();
    bytes.extend_from_slice(candidate.id.as_bytes());
    bytes.extend_from_slice(format!("{:?}", candidate.recipe).as_bytes());
    bytes.extend_from_slice(candidate.title.as_bytes());
    bytes.extend_from_slice(candidate.rationale.as_bytes());
    bytes.extend_from_slice(candidate.file.as_bytes());
    bytes.extend_from_slice(candidate.line.to_string().as_bytes());
    bytes.extend_from_slice(format!("{:?}", candidate.risk).as_bytes());
    bytes.extend_from_slice(format!("{:?}", candidate.status).as_bytes());
    bytes.extend_from_slice(format!("{:?}", candidate.tier).as_bytes());
    bytes.extend_from_slice(format!("{:?}", candidate.required_evidence).as_bytes());
    bytes.extend_from_slice(candidate.evidence_satisfied.to_string().as_bytes());
    bytes.extend_from_slice(format!("{:?}", candidate.evidence_context).as_bytes());
    bytes.extend_from_slice(format!("{:?}", candidate.autonomy).as_bytes());
    bytes.extend_from_slice(candidate.public_api_impact.to_string().as_bytes());
    bytes.extend_from_slice(format!("{:?}", candidate.apply_command).as_bytes());
    stable_hash_hex(&bytes)
}

fn source_snapshots(
    root: &Path,
    files: &[RefactorFileSummary],
) -> anyhow::Result<Vec<SourceSnapshot>> {
    let mut snapshots = Vec::new();
    for file in files {
        let content = std::fs::read(root.join(&file.file))?;
        snapshots.push(SourceSnapshot {
            file: file.file.display().to_string(),
            hash: stable_hash_hex(&content),
        });
    }
    Ok(snapshots)
}

fn stale_source_files(
    root: &Path,
    snapshots: &[SourceSnapshot],
) -> anyhow::Result<Vec<StaleSourceFile>> {
    let mut stale = Vec::new();
    for snapshot in snapshots {
        let rel = safe_relative_path(&snapshot.file)?;
        let actual_hash = std::fs::read(root.join(&rel))
            .map(|content| stable_hash_hex(&content))
            .unwrap_or_else(|_| "<missing>".to_string());
        if actual_hash != snapshot.hash {
            stale.push(StaleSourceFile {
                file: snapshot.file.clone(),
                expected_hash: snapshot.hash.clone(),
                actual_hash,
            });
        }
    }
    Ok(stale)
}

fn stale_file_for_candidate(
    root: &Path,
    plan: &RefactorPlan,
    file: &str,
) -> anyhow::Result<Option<StaleSourceFile>> {
    let Some(snapshot) = plan
        .source_snapshots
        .iter()
        .find(|snapshot| snapshot.file == file)
    else {
        return Ok(Some(StaleSourceFile {
            file: file.to_string(),
            expected_hash: "<missing-snapshot>".to_string(),
            actual_hash: "<unknown>".to_string(),
        }));
    };
    let rel = safe_relative_path(&snapshot.file)?;
    let actual_hash = std::fs::read(root.join(&rel))
        .map(|content| stable_hash_hex(&content))
        .unwrap_or_else(|_| "<missing>".to_string());
    if actual_hash == snapshot.hash {
        Ok(None)
    } else {
        Ok(Some(StaleSourceFile {
            file: snapshot.file.clone(),
            expected_hash: snapshot.hash.clone(),
            actual_hash,
        }))
    }
}

fn executable_candidate_queue<'a>(
    plan: &'a RefactorPlan,
    config: &RefactorBatchApplyConfig,
) -> Vec<&'a RefactorCandidate> {
    let mut queue = Vec::new();
    let mut seen_files = std::collections::BTreeSet::new();
    for candidate in &plan.candidates {
        if queue.len() >= config.max_candidates {
            break;
        }
        if candidate.status != RefactorCandidateStatus::ApplyViaImprove
            || !is_supported_mechanical_recipe(&candidate.recipe)
        {
            continue;
        }
        if !candidate.evidence_satisfied
            || candidate.required_evidence > plan.evidence.grade
            || plan.evidence.grade < config.min_evidence
            || candidate.tier > config.max_tier
            || candidate.autonomy.decision != AutonomyDecision::Allowed
        {
            continue;
        }
        if candidate.public_api_impact && !config.allow_public_api_impact {
            continue;
        }
        if seen_files.insert(candidate.file.clone()) {
            queue.push(candidate);
        }
    }
    queue
}

fn is_supported_mechanical_recipe(recipe: &RefactorRecipe) -> bool {
    matches!(
        recipe,
        RefactorRecipe::BorrowParameterTightening
            | RefactorRecipe::ContextualErrorHardening
            | RefactorRecipe::ErrorContextPropagation
            | RefactorRecipe::IteratorCloned
            | RefactorRecipe::LenCheckIsEmpty
            | RefactorRecipe::MustUsePublicReturn
            | RefactorRecipe::OptionContextPropagation
            | RefactorRecipe::RepeatedStringLiteralConst
    )
}

fn count_executable_candidates(
    plan: &RefactorPlan,
    allow_public_api_impact: bool,
    max_candidates: usize,
    max_tier: RecipeTier,
    min_evidence: EvidenceGrade,
) -> usize {
    executable_candidate_queue(
        plan,
        &RefactorBatchApplyConfig {
            plan_path: PathBuf::new(),
            apply: false,
            allow_public_api_impact,
            validation_timeout: Duration::from_secs(1),
            max_candidates,
            max_tier,
            min_evidence,
        },
    )
    .len()
}

fn recipe_tier_number(tier: RecipeTier) -> u8 {
    match tier {
        RecipeTier::Tier1 => 1,
        RecipeTier::Tier2 => 2,
        RecipeTier::Tier3 => 3,
    }
}

fn autopilot_pass_status(status: &RefactorBatchApplyStatus) -> AutopilotPassStatus {
    match status {
        RefactorBatchApplyStatus::Reviewed => AutopilotPassStatus::Reviewed,
        RefactorBatchApplyStatus::Applied => AutopilotPassStatus::Applied,
        RefactorBatchApplyStatus::PartiallyApplied => AutopilotPassStatus::PartiallyApplied,
        RefactorBatchApplyStatus::NoExecutableCandidates => {
            AutopilotPassStatus::NoExecutableCandidates
        }
        RefactorBatchApplyStatus::Rejected | RefactorBatchApplyStatus::StalePlan => {
            AutopilotPassStatus::Rejected
        }
    }
}

fn autopilot_status(
    apply: bool,
    passes: &[AutopilotPass],
    executed_candidates: usize,
) -> AutopilotStatus {
    if executed_candidates == 0 {
        if passes
            .iter()
            .any(|pass| pass.status == AutopilotPassStatus::Rejected)
        {
            AutopilotStatus::Rejected
        } else {
            AutopilotStatus::NoExecutableCandidates
        }
    } else if !apply {
        AutopilotStatus::Reviewed
    } else if passes
        .iter()
        .any(|pass| pass.status == AutopilotPassStatus::Rejected)
    {
        AutopilotStatus::PartiallyApplied
    } else {
        AutopilotStatus::Applied
    }
}

fn autopilot_note(run: &AutopilotRun) -> String {
    match run.status {
        AutopilotStatus::Reviewed => format!(
            "reviewed {} candidate(s) across {} pass(es); rerun with --apply to land validated transactions",
            run.total_executed_candidates,
            run.passes.len()
        ),
        AutopilotStatus::Applied => format!(
            "applied {} candidate(s) across {} pass(es) with fresh plans before each pass",
            run.total_executed_candidates,
            run.passes.len()
        ),
        AutopilotStatus::PartiallyApplied => format!(
            "applied {} candidate(s) before an execution gate stopped the run",
            run.total_executed_candidates
        ),
        AutopilotStatus::NoExecutableCandidates => {
            if run.budget_exhausted {
                "budget exhausted before more executable work could run".to_string()
            } else {
                "no executable low-risk candidates were available".to_string()
            }
        }
        AutopilotStatus::Rejected => {
            "autopilot stopped because a planning or execution gate rejected the run".to_string()
        }
    }
}

fn autopilot_execution_summary(run: &AutopilotRun) -> AutopilotExecutionSummary {
    let plans_created = run.passes.len();
    let executable_candidates_seen = run
        .passes
        .iter()
        .map(|pass| pass.executable_candidates)
        .sum();
    let validated_transactions = run
        .passes
        .iter()
        .filter_map(|pass| pass.batch.as_ref())
        .flat_map(|batch| batch.steps.iter())
        .filter(|step| {
            step.hardening_run
                .as_ref()
                .is_some_and(|hardening| hardening.outcome.isolated_validation_passed)
        })
        .count();
    let applied_transactions = run
        .passes
        .iter()
        .filter_map(|pass| pass.batch.as_ref())
        .flat_map(|batch| batch.steps.iter())
        .filter(|step| {
            step.hardening_run
                .as_ref()
                .is_some_and(|hardening| hardening.outcome.applied)
        })
        .count();
    let blocked_or_plan_only_candidates = run
        .total_planned_candidates
        .saturating_sub(executable_candidates_seen);

    AutopilotExecutionSummary {
        plans_created,
        executable_candidates_seen,
        validated_transactions,
        applied_transactions,
        blocked_or_plan_only_candidates,
        evidence_grade: run.evidence.grade,
        analysis_depth: run.evidence.analysis_depth.clone(),
    }
}

fn batch_status(apply: bool, executed: usize, requested: usize) -> RefactorBatchApplyStatus {
    if requested == 0 {
        RefactorBatchApplyStatus::NoExecutableCandidates
    } else if executed == 0 {
        RefactorBatchApplyStatus::Rejected
    } else if !apply {
        RefactorBatchApplyStatus::Reviewed
    } else if executed == requested {
        RefactorBatchApplyStatus::Applied
    } else {
        RefactorBatchApplyStatus::PartiallyApplied
    }
}

fn safe_relative_path(value: &str) -> anyhow::Result<PathBuf> {
    let path = PathBuf::from(value);
    if path.is_absolute()
        || path.components().any(|component| {
            matches!(
                component,
                Component::ParentDir | Component::RootDir | Component::Prefix(_)
            )
        })
    {
        anyhow::bail!("refactor plan contains unscoped path: {value}");
    }
    Ok(path)
}

fn sanitize_id(value: &str) -> String {
    value
        .chars()
        .map(|ch| if ch.is_ascii_alphanumeric() { ch } else { '-' })
        .collect::<String>()
        .trim_matches('-')
        .to_string()
}

fn persist_refactor_plan(artifact_root: &Path, plan: &RefactorPlan) -> anyhow::Result<PathBuf> {
    let dir = artifact_root.join("plans");
    std::fs::create_dir_all(&dir)?;
    let millis = std::time::SystemTime::now()
        .duration_since(std::time::UNIX_EPOCH)
        .map(|duration| duration.as_millis())
        .unwrap_or(0);
    Ok(dir.join(format!("refactor-plan-{millis}-{}.json", plan.plan_id)))
}

fn persist_apply_run(
    artifact_root: Option<&Path>,
    mut run: RefactorApplyRun,
) -> anyhow::Result<RefactorApplyRun> {
    if let Some(artifact_root) = artifact_root {
        let dir = artifact_root.join("plans");
        std::fs::create_dir_all(&dir)?;
        let millis = std::time::SystemTime::now()
            .duration_since(std::time::UNIX_EPOCH)
            .map(|duration| duration.as_millis())
            .unwrap_or(0);
        let path = dir.join(format!(
            "apply-plan-{millis}-{}-{}.json",
            sanitize_id(&run.plan_id),
            sanitize_id(&run.candidate_id)
        ));
        run.artifact_path = Some(path.display().to_string());
        std::fs::write(&path, serde_json::to_string_pretty(&run)?)?;
    }
    Ok(run)
}

fn persist_batch_apply_run(
    artifact_root: Option<&Path>,
    mut run: RefactorBatchApplyRun,
) -> anyhow::Result<RefactorBatchApplyRun> {
    if let Some(artifact_root) = artifact_root {
        let dir = artifact_root.join("plans");
        std::fs::create_dir_all(&dir)?;
        let millis = std::time::SystemTime::now()
            .duration_since(std::time::UNIX_EPOCH)
            .map(|duration| duration.as_millis())
            .unwrap_or(0);
        let path = dir.join(format!(
            "apply-plan-batch-{millis}-{}.json",
            sanitize_id(&run.plan_id)
        ));
        run.artifact_path = Some(path.display().to_string());
        std::fs::write(&path, serde_json::to_string_pretty(&run)?)?;
    }
    Ok(run)
}

fn persist_codebase_map(artifact_root: &Path, map: &CodebaseMap) -> anyhow::Result<PathBuf> {
    let dir = artifact_root.join("maps");
    std::fs::create_dir_all(&dir)?;
    let millis = std::time::SystemTime::now()
        .duration_since(std::time::UNIX_EPOCH)
        .map(|duration| duration.as_millis())
        .unwrap_or(0);
    Ok(dir.join(format!(
        "codebase-map-{millis}-{}.json",
        sanitize_id(&map.map_id)
    )))
}

fn persist_autopilot_run(
    artifact_root: Option<&Path>,
    mut run: AutopilotRun,
) -> anyhow::Result<AutopilotRun> {
    if let Some(artifact_root) = artifact_root {
        let dir = artifact_root.join("autopilot");
        std::fs::create_dir_all(&dir)?;
        let millis = std::time::SystemTime::now()
            .duration_since(std::time::UNIX_EPOCH)
            .map(|duration| duration.as_millis())
            .unwrap_or(0);
        let path = dir.join(format!(
            "autopilot-{millis}-{}.json",
            sanitize_id(&run.run_id)
        ));
        run.artifact_path = Some(path.display().to_string());
        std::fs::write(&path, serde_json::to_string_pretty(&run)?)?;
    }
    Ok(run)
}

fn persist_evolution_scorecard(
    artifact_root: &Path,
    scorecard: &EvolutionScorecard,
) -> anyhow::Result<PathBuf> {
    let dir = artifact_root.join("scorecards");
    std::fs::create_dir_all(&dir)?;
    let millis = std::time::SystemTime::now()
        .duration_since(std::time::UNIX_EPOCH)
        .map(|duration| duration.as_millis())
        .unwrap_or(0);
    Ok(dir.join(format!(
        "evolution-scorecard-{millis}-{}.json",
        sanitize_id(&scorecard.scorecard_id)
    )))
}

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

    #[test]
    fn refactor_plan_points_patchable_changes_to_improve() {
        let dir = tempdir().unwrap();
        std::fs::write(
            dir.path().join("Cargo.toml"),
            r#"[package]
name = "plan-fixture"
version = "0.1.0"
edition = "2021"

[dependencies]
anyhow = "1"
"#,
        )
        .unwrap();
        std::fs::create_dir_all(dir.path().join("src")).unwrap();
        std::fs::write(
            dir.path().join("src/lib.rs"),
            r#"pub fn load_config() -> anyhow::Result<String> {
    let content = std::fs::read_to_string("missing.toml").unwrap();
    Ok(content)
}
"#,
        )
        .unwrap();

        let plan = build_refactor_plan(
            dir.path(),
            None,
            &RefactorPlanConfig {
                target: Some(PathBuf::from("src/lib.rs")),
                behavior_spec_path: Some(PathBuf::from(".mdx-rust/evals.json")),
                ..RefactorPlanConfig::default()
            },
        )
        .unwrap();

        assert_eq!(plan.schema_version, "1.0");
        assert!(plan.candidates.iter().any(|candidate| candidate.status
            == RefactorCandidateStatus::ApplyViaImprove
            && candidate
                .apply_command
                .as_deref()
                .is_some_and(|command| command.contains("--eval-spec"))));
    }

    #[test]
    fn tested_evidence_surfaces_boundary_review_candidates() {
        let dir = tempdir().unwrap();
        std::fs::write(
            dir.path().join("Cargo.toml"),
            r#"[package]
name = "tested-plan-fixture"
version = "0.1.0"
edition = "2021"
"#,
        )
        .unwrap();
        std::fs::create_dir_all(dir.path().join("src")).unwrap();
        std::fs::write(
            dir.path().join("src/lib.rs"),
            r#"pub fn shell(cmd: &str) {
    std::process::Command::new(cmd);
}

#[cfg(test)]
mod tests {
    #[test]
    fn smoke() {
        assert_eq!(1, 1);
    }
}
"#,
        )
        .unwrap();

        let plan = build_refactor_plan(
            dir.path(),
            None,
            &RefactorPlanConfig {
                target: Some(PathBuf::from("src/lib.rs")),
                ..RefactorPlanConfig::default()
            },
        )
        .unwrap();

        assert_eq!(plan.evidence.grade, EvidenceGrade::Tested);
        assert_eq!(
            plan.evidence.analysis_depth,
            EvidenceAnalysisDepth::BoundaryAware
        );
        assert!(plan.candidates.iter().any(|candidate| candidate.status
            == RefactorCandidateStatus::PlanOnly
            && candidate.required_evidence == EvidenceGrade::Tested
            && candidate.tier == RecipeTier::Tier2));
    }

    #[test]
    fn measured_covered_evidence_unlocks_tier2_executable_recipe() {
        let dir = tempdir().unwrap();
        std::fs::write(
            dir.path().join("Cargo.toml"),
            r#"[package]
name = "covered-plan-fixture"
version = "0.1.0"
edition = "2021"
"#,
        )
        .unwrap();
        std::fs::create_dir_all(dir.path().join("src")).unwrap();
        std::fs::write(
            dir.path().join("src/lib.rs"),
            r#"pub fn labels(items: &[String]) -> Vec<&'static str> {
    if items.len() == 0 {
        return vec!["shared boundary label"];
    }
    vec![
        "shared boundary label",
        "shared boundary label",
        "shared boundary label",
    ]
}
"#,
        )
        .unwrap();
        let artifact_root = dir.path().join(".mdx-rust");
        std::fs::create_dir_all(artifact_root.join("evidence")).unwrap();
        let evidence = crate::evidence::EvidenceRun {
            schema_version: "1.0".to_string(),
            run_id: "covered-fixture".to_string(),
            root: dir.path().canonicalize().unwrap().display().to_string(),
            target: Some("src/lib.rs".to_string()),
            grade: EvidenceGrade::Covered,
            analysis_depth: EvidenceAnalysisDepth::Structural,
            metrics: Vec::new(),
            file_profiles: Vec::new(),
            commands: Vec::new(),
            unlocked_recipe_tiers: vec!["Tier 2 structural mechanical recipes".to_string()],
            unlock_suggestions: Vec::new(),
            note: "fixture evidence".to_string(),
            artifact_path: Some(
                artifact_root
                    .join("evidence/evidence-fixture.json")
                    .display()
                    .to_string(),
            ),
        };
        std::fs::write(
            artifact_root.join("evidence/evidence-fixture.json"),
            serde_json::to_string_pretty(&evidence).unwrap(),
        )
        .unwrap();

        let plan = build_refactor_plan(
            dir.path(),
            Some(&artifact_root),
            &RefactorPlanConfig {
                target: Some(PathBuf::from("src/lib.rs")),
                ..RefactorPlanConfig::default()
            },
        )
        .unwrap();

        assert_eq!(plan.evidence.grade, EvidenceGrade::Covered);
        assert!(plan.measured_evidence.is_some());
        assert!(plan.candidates.iter().any(|candidate| candidate.recipe
            == RefactorRecipe::RepeatedStringLiteralConst
            && candidate.status == RefactorCandidateStatus::ApplyViaImprove
            && candidate.required_evidence == EvidenceGrade::Covered
            && candidate.tier == RecipeTier::Tier2
            && candidate
                .apply_command
                .as_deref()
                .is_some_and(|command| command.contains("--tier 2"))));
        assert!(plan.candidates.iter().any(|candidate| candidate.recipe
            == RefactorRecipe::LenCheckIsEmpty
            && candidate.status == RefactorCandidateStatus::ApplyViaImprove
            && candidate.required_evidence == EvidenceGrade::Covered
            && candidate.tier == RecipeTier::Tier2));
    }
}