ryo-executor 0.1.0

[experimental] Mutation execution engine for RYO - parallel execution, conflict detection, workspace management
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
//! BlueprintExecutor: Execute ParallelBlueprint against AnalysisContext
//!
//! Uses MutationRegistry to delegate all MutationSpec → Mutation conversions
//! to specialized Converter implementations.
//!
//! ```text
//! ParallelBlueprint
//!//!    ▼ execute()
//! BlueprintExecutor
//!//!    ├── Strategy Selection (Sequential / Wavefront)
//!    ├── Topological sort by dependencies
//!    ├── Delegate to MutationRegistry.convert_and_apply()
//!    │      ├── RenameConverter
//!    │      ├── FieldConverter
//!    │      ├── AddItemConverter
//!    │      ├── IdiomConverter (13 idioms)
//!    │      ├── TraitConverter
//!    │      ├── MoveConverter
//!    │      ├── PluginConverter (WASM skeleton)
//!    │      └── ... (31 converters total)
//!//!//! BlueprintResult
//! ```
//!
//! ## Execution Strategies
//!
//! - **Sequential**: Execute mutations one by one (safe, debuggable)
//! - **Wavefront**: Execute independent mutations in parallel within each wave
//!
//! ```text
//! Wave 0: [Spec_A, Spec_B, Spec_C] → parallel compute → barrier → apply
//! Wave 1: [Spec_D]                 → parallel compute → barrier → apply
//! Wave 2: [Spec_E, Spec_F]         → parallel compute → barrier → apply
//! ```

use super::blueprint::ParallelBlueprint;
use super::registry::MutationRegistry;
use super::spec::{MutationSpec, MutationTargetSymbol, StmtInsertPosition};
use crate::engine::{collect_affected_ids, MutationEvent};
use ryo_analysis::{AnalysisContext, RegistryUpdateBatch, SymbolPath};
use ryo_mutations::MutationResult;
use ryo_source::pure::ToSynError;
use ryo_symbol::{MetadataError, SymbolId, WorkspaceFilePath};
use std::collections::HashSet;
use std::sync::Arc;
use tracing::{debug, info, instrument, warn};

/// Error during file sync after blueprint execution.
#[derive(Debug, thiserror::Error)]
pub enum SyncError {
    #[error("cargo metadata unavailable: {0}")]
    Metadata(#[from] MetadataError),
    #[error("source generation failed: {0}")]
    SourceGeneration(#[from] ToSynError),
}

/// Execution strategy for BlueprintExecutor
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
pub enum ExecutionStrategy {
    /// Execute mutations one by one (safe, debuggable)
    #[default]
    Sequential,

    /// Execute independent mutations in parallel within each wave
    /// Uses Collect-then-Apply pattern for thread safety
    Wavefront,
}

/// Suggest the best execution strategy based on blueprint characteristics
pub fn suggest_strategy(blueprint: &ParallelBlueprint) -> ExecutionStrategy {
    let parallelism = blueprint.parallelism();
    let mutation_count = blueprint.mutations.len();

    // Heuristics for strategy selection:
    // - Low parallelism (≤1.2) → Sequential (no benefit from parallel)
    // - Very few mutations (≤2) → Sequential (overhead not worth it)
    // - Otherwise → Wavefront
    if parallelism <= 1.2 || mutation_count <= 2 {
        ExecutionStrategy::Sequential
    } else {
        ExecutionStrategy::Wavefront
    }
}

/// Result of executing a blueprint
#[derive(Debug, Clone)]
pub struct BlueprintResult {
    /// Results for each mutation spec
    pub results: Vec<SpecResult>,

    /// Total changes across all mutations
    pub total_changes: usize,

    /// Files that were modified
    pub modified_files: Vec<WorkspaceFilePath>,

    /// Whether execution completed successfully
    pub success: bool,

    /// Error message if failed
    pub error: Option<String>,

    /// Registry updates to apply (for Context-centric design)
    ///
    /// These updates should be applied to the SymbolRegistry after
    /// execution to keep it in sync with the AST changes.
    pub registry_updates: RegistryUpdateBatch,
}

/// Result of executing a single MutationSpec
#[derive(Debug, Clone)]
pub struct SpecResult {
    /// Index in the blueprint
    pub index: usize,

    /// The spec that was executed
    pub spec_type: String,

    /// Number of changes made
    pub changes: usize,

    /// Files affected
    pub affected_files: Vec<WorkspaceFilePath>,

    /// Symbols affected (for history tracking)
    pub affected_symbols: Vec<SymbolPath>,

    /// Whether this spec succeeded
    pub success: bool,

    /// Error message if failed
    pub error: Option<String>,

    /// Registry updates from this spec
    pub registry_updates: RegistryUpdateBatch,

    /// Mutation events emitted during execution (for incremental updates)
    pub events: Vec<MutationEvent>,
}

impl BlueprintResult {
    pub fn success(results: Vec<SpecResult>, modified_files: Vec<WorkspaceFilePath>) -> Self {
        let total_changes = results.iter().map(|r| r.changes).sum();
        // Collect all registry updates from spec results
        let mut all_updates = RegistryUpdateBatch::new();
        for result in &results {
            for update in &result.registry_updates {
                all_updates.push(update.clone());
            }
        }
        Self {
            results,
            total_changes,
            modified_files,
            success: true,
            error: None,
            registry_updates: all_updates,
        }
    }

    pub fn failure(error: impl Into<String>) -> Self {
        Self {
            results: vec![],
            total_changes: 0,
            modified_files: vec![],
            success: false,
            error: Some(error.into()),
            registry_updates: RegistryUpdateBatch::new(),
        }
    }
}

/// Resolve a `MutationTargetSymbol` to a `SymbolId` inside an `execute_spec_v2`
/// arm. On failure, build a `SpecResult` describing the lookup error and early
/// return from the enclosing function so callers see a structured failure
/// instead of a panic.
macro_rules! try_resolve {
    ($self:expr, $target:expr, $ctx:expr, $index:expr, $spec_type:expr, $affected_symbols:expr, $msg:expr $(,)?) => {
        match $self.resolve_target_symbol_simple($target, $ctx) {
            Ok(id) => id,
            Err(e) => {
                return SpecResult {
                    index: $index,
                    spec_type: $spec_type.clone(),
                    success: false,
                    changes: 0,
                    affected_files: vec![],
                    affected_symbols: $affected_symbols.clone(),
                    error: Some(format!("{}: {}", $msg, e)),
                    registry_updates: RegistryUpdateBatch::new(),
                    events: vec![],
                };
            }
        }
    };
}

/// Executor for ParallelBlueprint
#[derive(Debug)]
pub struct BlueprintExecutor {
    /// Registry for MutationSpec → Mutation conversion
    registry: MutationRegistry,

    /// Execution strategy
    pub strategy: ExecutionStrategy,

    /// Whether to verify compile after each mutation
    pub verify_after_each: bool,

    /// Whether to stop on first error
    pub stop_on_error: bool,

    /// Whether to ignore conflicts and process sequentially
    /// Default: true (conflicts are ignored, specs processed in order)
    pub ignore_conflicts: bool,
}

impl Default for BlueprintExecutor {
    fn default() -> Self {
        Self {
            registry: MutationRegistry::default(),
            strategy: ExecutionStrategy::default(),
            verify_after_each: false,
            stop_on_error: true,
            ignore_conflicts: true,
        }
    }
}

impl BlueprintExecutor {
    pub fn new() -> Self {
        Self::default()
    }

    /// Resolve MutationTargetSymbol to SymbolId (helper for Legacy fallback)
    ///
    /// This is a simplified version of ResolveTargetSymbol trait for use in
    /// legacy fallback code paths that haven't been migrated to convert_v2() yet.
    fn resolve_target_symbol_simple(
        &self,
        target: &super::spec::MutationTargetSymbol,
        ctx: &AnalysisContext,
    ) -> Result<SymbolId, String> {
        use super::spec::MutationTargetSymbol;

        match target {
            MutationTargetSymbol::ById(id) => {
                // Already resolved, verify it exists
                if ctx.registry.resolve(*id).is_none() {
                    return Err(format!("Symbol {:?} not found in registry", id));
                }
                Ok(*id)
            }
            MutationTargetSymbol::ByPath(path) => {
                // Lazy resolution by path - search registry
                ctx.registry
                    .iter()
                    .find(|(_, p)| *p == &**path)
                    .map(|(id, _)| id)
                    .ok_or_else(|| format!("Symbol at path '{}' not found", path))
            }
            MutationTargetSymbol::ByKindAndName(kind, name) => {
                // Lazy resolution by kind + name - search registry
                // For impl blocks with generics, normalize both names before comparison
                let normalized_name = normalize_generic_name(name);
                let matches: Vec<_> = ctx
                    .registry
                    .iter()
                    .filter(|(_, path)| normalize_generic_name(path.name()) == normalized_name)
                    .collect();

                match matches.len() {
                    0 => Err(format!("Symbol not found: kind={:?}, name={}", kind, name)),
                    1 => Ok(matches[0].0),
                    _ => Err(format!(
                        "Multiple symbols found: kind={:?}, name={} (found {} matches)",
                        kind,
                        name,
                        matches.len()
                    )),
                }
            }
            MutationTargetSymbol::ByAffectedId {
                parent_id,
                kind,
                name,
            } => {
                // Derived from parent mutation
                let parent_path = ctx
                    .registry
                    .resolve(*parent_id)
                    .ok_or_else(|| format!("Parent SymbolId {:?} not found", parent_id))?;

                if let Some(child_name) = name {
                    // Construct child path
                    parent_path
                        .child(child_name)
                        .map_err(|e| format!("Invalid child path: {}", e))
                        .and_then(|child_path| {
                            // Lookup child in registry
                            ctx.registry
                                .iter()
                                .find(|(_, p)| p == &&child_path)
                                .map(|(id, _)| id)
                                .ok_or_else(|| {
                                    format!(
                                        "Child symbol not found: parent={:?}, kind={:?}, name={}",
                                        parent_id, kind, child_name
                                    )
                                })
                        })
                } else {
                    // Anonymous child - not yet supported
                    Err(format!(
                        "Anonymous child symbols not yet supported: parent={:?}, kind={:?}",
                        parent_id, kind
                    ))
                }
            }
        }
    }

    // ========================================================================
    // V2 API: ASTRegistry-centric execution (new path)
    // ========================================================================

    /// Execute blueprint using ASTRegistry-centric path.
    ///
    /// This is the new execution path that:
    /// 1. Executes mutations directly on ASTRegistry (no file I/O)
    /// 2. Returns MutationEvents for incremental updates
    ///
    /// **Important**: This method only updates ASTRegistry. Callers must:
    /// - Call `ctx.sync_files_and_rebuild()` for full sync (files + graphs)
    /// - Or skip sync for lightweight precheck scenarios
    ///
    /// Unimplemented MutationSpecs will panic - this is intentional
    /// as we're building towards complete migration.
    #[instrument(skip(self, blueprint, ctx), fields(mutations = blueprint.mutations.len()))]
    pub fn execute_v2(
        &self,
        blueprint: &ParallelBlueprint,
        ctx: &mut AnalysisContext,
    ) -> BlueprintResult {
        debug!(
            "Starting blueprint execution with {} mutations",
            blueprint.mutations.len()
        );

        // Check for conflicts (skip if ignore_conflicts is true)
        if !self.ignore_conflicts && blueprint.needs_escalation() {
            warn!(
                "Blueprint has {} conflicts requiring escalation",
                blueprint.conflicts.len()
            );
            return BlueprintResult::failure(format!(
                "Blueprint has {} conflicts requiring escalation",
                blueprint.conflicts.len()
            ));
        }

        let mut results: Vec<SpecResult> = Vec::new();
        let mut completed: HashSet<usize> = HashSet::new();

        // Execute in topological order
        while completed.len() < blueprint.mutations.len() {
            let ready = blueprint
                .deps
                .ready_set(blueprint.mutations.len(), &completed);

            if ready.is_empty() {
                if completed.len() < blueprint.mutations.len() {
                    warn!("Dependency cycle detected");
                    return BlueprintResult::failure("Dependency cycle detected");
                }
                break;
            }

            debug!("Ready to execute {} specs", ready.len());

            for idx in ready {
                let spec = &blueprint.mutations[idx];
                debug!("Executing spec {}: {:?}", idx, spec);
                let result = self.execute_spec_v2(idx, spec, ctx);

                if let Some(ref error) = result.error {
                    warn!(
                        "Spec {} completed with error: success={}, changes={}, error={}",
                        idx, result.success, result.changes, error
                    );
                } else {
                    debug!(
                        "Spec {} completed: success={}, changes={}, events={}",
                        idx,
                        result.success,
                        result.changes,
                        result.events.len()
                    );
                }

                let success = result.success;
                results.push(result);
                completed.insert(idx);

                if !success && self.stop_on_error {
                    let total_changes = results.iter().map(|r| r.changes).sum();

                    // Get the error from the failed spec result
                    let spec_error = results
                        .last()
                        .and_then(|r| r.error.as_ref())
                        .map(|e| format!("Spec {} failed: {}", idx, e))
                        .unwrap_or_else(|| format!("Stopped at spec {} (no error message)", idx));

                    warn!("Stopping on error at spec {}: {}", idx, spec_error);

                    return BlueprintResult {
                        results,
                        total_changes,
                        modified_files: Vec::new(),
                        success: false,
                        error: Some(spec_error),
                        registry_updates: RegistryUpdateBatch::new(),
                    };
                }
            }
        }

        let total_changes: usize = results.iter().map(|r| r.changes).sum();
        info!(
            "Blueprint execution completed: {} results, {} total changes",
            results.len(),
            total_changes
        );

        BlueprintResult::success(results, Vec::new())
    }

    /// Synchronize files and rebuild analysis graphs after execute_v2.
    ///
    /// This method should be called after `execute_v2()` when you need:
    /// - Updated source files (for disk write or cargo check)
    /// - Updated analysis graphs (code_graph, typeflow, dataflow, detail_store)
    ///
    /// For lightweight precheck scenarios, skip this call entirely.
    ///
    /// # File Path Resolution
    ///
    /// This method handles the conversion from `RegistryGenerator`'s output
    /// (crate-relative paths like `"src/lib.rs"`) to workspace-relative paths
    /// (like `"crates/core/src/lib.rs"`).
    ///
    /// The conversion works as follows:
    ///
    /// 1. **Extract crate roots from existing files**: For each crate, find its
    ///    root directory by looking at existing `WorkspaceFilePath`s in `ctx.files`.
    ///    For example, `"crates/core/src/lib.rs"` → crate_root = `"crates/core"`.
    ///
    /// 2. **Combine crate_root + crate-relative path**: The generator outputs
    ///    `"src/lib.rs"`, and we prepend the crate_root to get the full
    ///    workspace-relative path: `"crates/core" + "src/lib.rs"` → `"crates/core/src/lib.rs"`.
    ///
    /// This approach keeps `RegistryGenerator` focused on pure SymbolPath-based
    /// generation, while the caller (this function) handles workspace layout concerns.
    ///
    /// # Arguments
    /// - `result`: The BlueprintResult from execute_v2
    /// - `ctx`: The AnalysisContext that was mutated
    ///
    /// # Returns
    /// List of modified file paths (as `WorkspaceFilePath`)
    #[instrument(skip(result, ctx), fields(total_changes = result.total_changes))]
    pub fn sync_files_and_rebuild(
        result: &BlueprintResult,
        ctx: &mut AnalysisContext,
    ) -> Result<Vec<WorkspaceFilePath>, SyncError> {
        use crate::engine::{collect_modified_symbols, RegistryGenerator};
        use ryo_symbol::CargoMetadataProvider;

        debug!(
            "Starting sync_files_and_rebuild with {} results",
            result.results.len()
        );

        // Step 1: Collect all events from execution results
        let all_events: Vec<MutationEvent> = result
            .results
            .iter()
            .flat_map(|r| r.events.clone())
            .collect();

        debug!(
            "Collected {} mutation events from results",
            all_events.len()
        );
        // INVARIANT: No mutation events → no files changed → nothing to sync.
        // This prevents the expensive generate path from running on 0-mutation results.
        if all_events.is_empty() {
            debug!("No mutation events — skipping file sync entirely");
            return Ok(Vec::new());
        }

        // Step 2: Determine modified files from events
        let modified_symbol_ids = collect_modified_symbols(&all_events, ctx.registry());
        debug!("Found {} modified symbols", modified_symbol_ids.len());
        // Step 3: Generator determines affected files and generates ONLY those files.
        //
        // DESIGN RULE: Full-workspace generation (generate/dump_all) is PROHIBITED here.
        // Only files containing modified symbols may be regenerated.
        // This is critical because:
        //   1. to_source() (prettyplease) is expensive per file
        //   2. Regenerating unmodified files causes format drift (vec![] → vec!(), shorthand expansion)
        //   3. Writing unmodified files wastes I/O and triggers unnecessary re-indexing
        let metadata = CargoMetadataProvider::from_directory(&ctx.workspace_root)?;

        let generator = RegistryGenerator::multi_file();
        let workspace = generator.generate_affected(
            &ctx.ast_registry,
            ctx.registry(),
            &modified_symbol_ids,
            &metadata,
        )?;

        debug!(
            "Generator produced {} crates with {} total files",
            workspace.crates.len(),
            workspace.total_files()
        );

        // Step 4: Convert generated files to WorkspaceFilePath and update context
        // Generator returns crate-relative paths (e.g., "src/lib.rs")
        // We need to resolve these to workspace-relative paths using CrateLayout
        let mut modified_files = Vec::new();

        for generated_crate in workspace.crates.values() {
            debug!(
                "Processing crate {} with {} files",
                generated_crate.crate_name,
                generated_crate.files.len()
            );

            // Get CrateLayout for this crate to convert paths correctly
            use ryo_symbol::{CrateName, WorkspacePathResolver};
            let crate_name = CrateName::new(&generated_crate.crate_name).expect(
                "generator-emitted crate names must already satisfy CrateName validation; \
                 reaching this expect means the generator is producing invalid names",
            );
            let layout = metadata.crate_layout(&crate_name);

            for (crate_relative_path, generated_file) in &generated_crate.files {
                // Convert crate-relative path to workspace-relative path using CrateLayout
                let workspace_relative = match &layout {
                    Some(layout) => layout.to_workspace_relative(crate_relative_path),
                    None => {
                        // Fallback: use crate-relative path as-is (single-crate workspace)
                        std::path::PathBuf::from(crate_relative_path.as_str())
                    }
                };

                // Find corresponding WorkspaceFilePath from context
                // Match by crate_name and workspace-relative path
                let workspace_file = ctx
                    .files()
                    .keys()
                    .find(|wfp| {
                        wfp.crate_name().as_str() == generated_crate.crate_name
                            && wfp.as_relative() == workspace_relative.as_path()
                    })
                    .cloned();

                let wfp = if let Some(existing) = workspace_file {
                    debug!(
                        "Updating existing file: {} ({})",
                        crate_relative_path,
                        existing.as_relative().display()
                    );
                    existing
                } else {
                    // New file: construct WorkspaceFilePath with correct workspace-relative path
                    debug!(
                        "Creating new file: {} -> {} for crate {}",
                        crate_relative_path,
                        workspace_relative.display(),
                        generated_crate.crate_name
                    );
                    let resolver =
                        WorkspacePathResolver::new(ctx.workspace_root.as_ref().to_path_buf());
                    resolver.resolve_relative_with_crate(&workspace_relative, crate_name.clone())
                };

                let parsed = ryo_source::pure::PureFile::from_source(&generated_file.source);
                let pure_file = parsed.unwrap_or_else(|_e| ryo_source::pure::PureFile::new());
                ctx.files_mut().insert(wfp.clone(), Arc::new(pure_file));
                modified_files.push(wfp);
            }
        }

        debug!(
            "Updated {} files in context from generator output",
            modified_files.len()
        );

        // Step 5: Rebuild analysis graphs using symbol-based incremental update
        if !all_events.is_empty() {
            let affected_ids = collect_affected_ids(&all_events, ctx.registry());
            debug!("Rebuilding with {} affected symbol IDs", affected_ids.len());
            ctx.rebuild_after_mutation_by_symbols(&affected_ids);
        } else if !modified_files.is_empty() {
            // Fallback to file-based update if no events were collected
            debug!(
                "Rebuilding with {} modified files (fallback)",
                modified_files.len()
            );
            ctx.rebuild_after_mutation(&modified_files);
        }

        info!(
            "sync_files_and_rebuild completed: {} files modified",
            modified_files.len()
        );
        Ok(modified_files)
    }

    /// Execute a single MutationSpec via ASTRegistry path.
    ///
    /// Uses convert_v2() when available, falls back to direct construction
    /// for specs that haven't been migrated yet.
    fn execute_spec_v2(
        &self,
        index: usize,
        spec: &MutationSpec,
        ctx: &mut AnalysisContext,
    ) -> SpecResult {
        use crate::engine::{ASTMutationEngine, ExecutionResult};
        use crate::executor::registry::ConvertError;
        use ryo_mutations::basic::{
            AddDeriveMutation, AddFieldMutation, RemoveDeriveMutation, RemoveFieldMutation,
            RemoveModMutation,
        };

        let spec_type = spec_type_name(spec);
        // Compute affected_symbols from spec targets
        let affected_symbols: Vec<SymbolPath> = spec
            .get_targets()
            .iter()
            .filter_map(|target| target.to_path(ctx.registry()))
            .collect();

        // Try V2 path first (convert_v2 → execute_ast_reg_batch_dyn)
        match self.registry.convert_v2(spec, ctx) {
            Ok(mutations) => {
                let exec_result = ASTMutationEngine::execute_ast_reg_batch_dyn(mutations, ctx);

                // For AddItem: register the newly added symbol for deferred resolution
                // This allows later intents (AddDerive, AddVariant) to reference it by name
                if let MutationSpec::AddItem {
                    target, content, ..
                } = spec
                {
                    // Only register if target is already resolved to a SymbolPath
                    if let MutationTargetSymbol::ByPath(path) = target {
                        register_item_from_content(ctx, path, content);
                    } else if let MutationTargetSymbol::ById(id) = target {
                        // Resolve SymbolId to SymbolPath and clone it
                        if let Some(path) = ctx.registry().resolve(*id).cloned() {
                            register_item_from_content(ctx, &path, content);
                        }
                    }
                }

                return SpecResult {
                    index,
                    spec_type,
                    success: true,
                    changes: exec_result.result.changes,
                    affected_files: vec![], // TODO: Extract from events
                    affected_symbols,
                    error: None,
                    registry_updates: RegistryUpdateBatch::new(),
                    events: exec_result.events,
                };
            }
            Err(ConvertError::V2NotSupported) => {
                // Fall through to legacy match-based construction
            }
            Err(e) => {
                // Other errors (UnknownSpec, etc.) are real failures
                return SpecResult {
                    index,
                    spec_type,
                    success: false,
                    changes: 0,
                    affected_files: vec![],
                    affected_symbols,
                    error: Some(format!("convert_v2 failed: {}", e)),
                    registry_updates: RegistryUpdateBatch::new(),
                    events: vec![],
                };
            }
        }

        // Legacy fallback: direct construction for specs not yet migrated to convert_v2
        let exec_result = match spec {
            MutationSpec::AddField {
                target,
                field_name,
                field_type,
                visibility,
                ..
            } => {
                // Resolve target to SymbolId
                let symbol_id = try_resolve!(
                    self,
                    target,
                    ctx,
                    index,
                    spec_type,
                    affected_symbols,
                    "Failed to resolve target symbol"
                );
                let mut mutation = AddFieldMutation::new(symbol_id, field_name, field_type);
                if matches!(visibility, super::spec::Visibility::Pub) {
                    mutation = mutation.public();
                }
                ASTMutationEngine::execute_ast_reg(&mutation, ctx)
            }

            MutationSpec::RemoveField {
                target, field_name, ..
            } => {
                // Resolve target to SymbolId
                let symbol_id = try_resolve!(
                    self,
                    target,
                    ctx,
                    index,
                    spec_type,
                    affected_symbols,
                    "Failed to resolve target symbol"
                );
                let mutation = RemoveFieldMutation::new(symbol_id, field_name);
                ASTMutationEngine::execute_ast_reg(&mutation, ctx)
            }

            MutationSpec::RemoveMod {
                target, mod_name, ..
            } => {
                use ryo_symbol::SymbolKind;

                // Resolve parent module
                let parent_id = try_resolve!(
                    self,
                    target,
                    ctx,
                    index,
                    spec_type,
                    affected_symbols,
                    "Failed to resolve parent module"
                );

                // Find child module within parent
                let parent_path = match ctx.registry.resolve(parent_id) {
                    Some(p) => p,
                    None => {
                        return SpecResult {
                            index,
                            spec_type: spec_type.clone(),
                            success: false,
                            changes: 0,
                            affected_files: vec![],
                            affected_symbols: affected_symbols.clone(),
                            error: Some(format!(
                                "Parent module path not found for SymbolId {:?}",
                                parent_id
                            )),
                            registry_updates: RegistryUpdateBatch::new(),
                            events: vec![],
                        };
                    }
                };

                let mod_path = match parent_path.child(mod_name) {
                    Ok(p) => p,
                    Err(e) => {
                        return SpecResult {
                            index,
                            spec_type: spec_type.clone(),
                            success: false,
                            changes: 0,
                            affected_files: vec![],
                            affected_symbols: affected_symbols.clone(),
                            error: Some(format!(
                                "Failed to build module path for '{}': {}",
                                mod_name, e
                            )),
                            registry_updates: RegistryUpdateBatch::new(),
                            events: vec![],
                        };
                    }
                };

                let module_id = match ctx.registry.lookup(&mod_path) {
                    Some(id) => id,
                    None => {
                        return SpecResult {
                            index,
                            spec_type: spec_type.clone(),
                            success: false,
                            changes: 0,
                            affected_files: vec![],
                            affected_symbols: affected_symbols.clone(),
                            error: Some(format!(
                                "Module '{}' not found in {}",
                                mod_name, parent_path
                            )),
                            registry_updates: RegistryUpdateBatch::new(),
                            events: vec![],
                        };
                    }
                };

                // Verify it's a module
                if ctx.registry.kind(module_id) != Some(SymbolKind::Mod) {
                    return SpecResult {
                        index,
                        spec_type: spec_type.clone(),
                        success: false,
                        changes: 0,
                        affected_files: vec![],
                        affected_symbols: affected_symbols.clone(),
                        error: Some(format!("Symbol {} is not a module", module_id)),
                        registry_updates: RegistryUpdateBatch::new(),
                        events: vec![],
                    };
                }

                let mutation = RemoveModMutation::new(module_id);
                ASTMutationEngine::execute_ast_reg(&mutation, ctx)
            }

            MutationSpec::AddDerive {
                target, derives, ..
            } => {
                // Resolve target to SymbolId
                let symbol_id = try_resolve!(
                    self,
                    target,
                    ctx,
                    index,
                    spec_type,
                    affected_symbols,
                    "Failed to resolve target symbol"
                );
                let mutation = AddDeriveMutation::new(symbol_id, derives.clone());
                ASTMutationEngine::execute_ast_reg(&mutation, ctx)
            }

            MutationSpec::RemoveDerive {
                target, derives, ..
            } => {
                // Resolve target to SymbolId
                let symbol_id = try_resolve!(
                    self,
                    target,
                    ctx,
                    index,
                    spec_type,
                    affected_symbols,
                    "Failed to resolve target symbol"
                );
                let mutation = RemoveDeriveMutation::new(symbol_id, derives.clone());
                ASTMutationEngine::execute_ast_reg(&mutation, ctx)
            }

            MutationSpec::AddVariant {
                target,
                variant_name,
                variant_kind,
                ..
            } => {
                use ryo_mutations::basic::AddVariantMutation;
                use ryo_source::pure::{PureField, PureFields, PureType, PureVis};

                // Resolve target to SymbolId
                let symbol_id = try_resolve!(
                    self,
                    target,
                    ctx,
                    index,
                    spec_type,
                    affected_symbols,
                    "Failed to resolve target symbol"
                );

                let fields = match variant_kind {
                    super::spec::VariantKind::Unit => PureFields::Unit,
                    super::spec::VariantKind::Tuple { types } => {
                        PureFields::Tuple(types.iter().map(|t| PureType::Path(t.clone())).collect())
                    }
                    super::spec::VariantKind::Struct { fields } => {
                        let pure_fields: Vec<PureField> = fields
                            .iter()
                            .map(|(n, t)| PureField {
                                attrs: Vec::new(),
                                vis: PureVis::Private,
                                name: n.clone(),
                                ty: PureType::Path(t.clone()),
                            })
                            .collect();
                        PureFields::Named(pure_fields)
                    }
                };
                let mutation = AddVariantMutation::new(symbol_id, variant_name, fields);
                ASTMutationEngine::execute_ast_reg(&mutation, ctx)
            }

            MutationSpec::RemoveVariant {
                target,
                variant_name,
                ..
            } => {
                use ryo_mutations::basic::RemoveVariantMutation;
                // Resolve target to SymbolId
                let symbol_id = try_resolve!(
                    self,
                    target,
                    ctx,
                    index,
                    spec_type,
                    affected_symbols,
                    "Failed to resolve target symbol"
                );
                let mutation = RemoveVariantMutation::new(symbol_id, variant_name);
                ASTMutationEngine::execute_ast_reg(&mutation, ctx)
            }

            MutationSpec::ChangeVisibility {
                target, visibility, ..
            } => {
                use ryo_mutations::basic::ChangeVisibilityMutation;
                use ryo_source::pure::PureVis;

                // Resolve target to SymbolId
                let symbol_id = try_resolve!(
                    self,
                    target,
                    ctx,
                    index,
                    spec_type,
                    affected_symbols,
                    "Failed to resolve target symbol"
                );

                let pure_vis = match visibility {
                    super::spec::Visibility::Private => PureVis::Private,
                    super::spec::Visibility::Pub => PureVis::Public,
                    super::spec::Visibility::PubCrate => PureVis::Crate,
                    super::spec::Visibility::PubSuper => PureVis::Super,
                    super::spec::Visibility::PubIn(_) => PureVis::Public, // Simplified
                };

                let mutation = ChangeVisibilityMutation::new(symbol_id, pure_vis);
                ASTMutationEngine::execute_ast_reg(&mutation, ctx)
            }

            MutationSpec::Rename { target, to, .. } => {
                use ryo_mutations::basic::RenameMutation;
                // Resolve target to SymbolId
                let symbol_id = try_resolve!(
                    self,
                    target,
                    ctx,
                    index,
                    spec_type,
                    affected_symbols,
                    "Failed to resolve target symbol"
                );
                let mutation = RenameMutation::new(symbol_id, to);
                ASTMutationEngine::execute_ast_reg(&mutation, ctx)
            }

            // AddItem, RemoveItem, CreateMod, AddMethod, RemoveMethod
            // all go through convert_v2() → ASTRegApply path
            MutationSpec::AddMatchArm {
                target,
                enum_name,
                pattern,
                body,
            } => {
                use ryo_mutations::basic::AddMatchArmMutation;

                let fn_id = match self.resolve_target_symbol_simple(target, ctx) {
                    Ok(id) => id,
                    Err(e) => {
                        return SpecResult {
                            index,
                            spec_type,
                            changes: 0,
                            affected_files: vec![],
                            affected_symbols: vec![],
                            success: false,
                            error: Some(e),
                            registry_updates: RegistryUpdateBatch::default(),
                            events: vec![],
                        };
                    }
                };

                let mutation = AddMatchArmMutation::new(fn_id, enum_name, pattern, body);
                ASTMutationEngine::execute_ast_reg(&mutation, ctx)
            }

            MutationSpec::RemoveMatchArm {
                target,
                enum_name,
                pattern,
            } => {
                use ryo_mutations::basic::RemoveMatchArmMutation;

                let fn_id = match self.resolve_target_symbol_simple(target, ctx) {
                    Ok(id) => id,
                    Err(e) => {
                        return SpecResult {
                            index,
                            spec_type,
                            changes: 0,
                            affected_files: vec![],
                            affected_symbols: vec![],
                            success: false,
                            error: Some(e),
                            registry_updates: RegistryUpdateBatch::default(),
                            events: vec![],
                        };
                    }
                };

                let mutation = RemoveMatchArmMutation::new(fn_id, enum_name, pattern);
                ASTMutationEngine::execute_ast_reg(&mutation, ctx)
            }

            MutationSpec::ReplaceMatchArm {
                target,
                enum_name,
                old_pattern,
                new_pattern,
                new_body,
            } => {
                use ryo_mutations::basic::ReplaceMatchArmMutation;

                let fn_id = match self.resolve_target_symbol_simple(target, ctx) {
                    Ok(id) => id,
                    Err(e) => {
                        return SpecResult {
                            index,
                            spec_type,
                            changes: 0,
                            affected_files: vec![],
                            affected_symbols: vec![],
                            success: false,
                            error: Some(e),
                            registry_updates: RegistryUpdateBatch::default(),
                            events: vec![],
                        };
                    }
                };

                let mutation = ReplaceMatchArmMutation::new(
                    fn_id,
                    enum_name,
                    old_pattern,
                    new_pattern,
                    new_body,
                );
                ASTMutationEngine::execute_ast_reg(&mutation, ctx)
            }

            MutationSpec::AddStructLiteralField {
                target,
                field_name,
                value,
                ..
            } => {
                use ryo_mutations::basic::AddStructLiteralFieldMutation;
                // Resolve target to SymbolId
                let symbol_id = try_resolve!(
                    self,
                    target,
                    ctx,
                    index,
                    spec_type,
                    affected_symbols,
                    "Failed to resolve target symbol"
                );
                let mutation = AddStructLiteralFieldMutation::new(symbol_id, field_name, value);
                ASTMutationEngine::execute_ast_reg(&mutation, ctx)
            }

            MutationSpec::RemoveStructLiteralField {
                target, field_name, ..
            } => {
                use ryo_mutations::basic::RemoveStructLiteralFieldMutation;
                // Resolve target to SymbolId
                let symbol_id = try_resolve!(
                    self,
                    target,
                    ctx,
                    index,
                    spec_type,
                    affected_symbols,
                    "Failed to resolve target symbol"
                );
                let mutation = RemoveStructLiteralFieldMutation::new(symbol_id, field_name);
                ASTMutationEngine::execute_ast_reg(&mutation, ctx)
            }

            MutationSpec::OrganizeImports {
                deduplicate,
                merge_groups,
                ..
            } => {
                use ryo_mutations::idiom::OrganizeImportsMutation;
                let mutation = OrganizeImportsMutation::new()
                    .with_deduplicate(*deduplicate)
                    .with_merge_groups(*merge_groups);
                ASTMutationEngine::execute_ast_reg(&mutation, ctx)
            }

            MutationSpec::AssignOp { .. } => {
                use ryo_mutations::idiom::AssignOpMutation;
                let mutation = AssignOpMutation::new();
                ASTMutationEngine::execute_ast_reg(&mutation, ctx)
            }

            MutationSpec::BoolSimplify { .. } => {
                use ryo_mutations::idiom::BoolSimplifyMutation;
                let mutation = BoolSimplifyMutation::new();
                ASTMutationEngine::execute_ast_reg(&mutation, ctx)
            }

            MutationSpec::ComparisonToMethod { .. } => {
                use ryo_mutations::idiom::ComparisonToMethodMutation;
                let mutation = ComparisonToMethodMutation::new();
                ASTMutationEngine::execute_ast_reg(&mutation, ctx)
            }

            MutationSpec::CollapsibleIf { .. } => {
                use ryo_mutations::idiom::CollapsibleIfMutation;
                let mutation = CollapsibleIfMutation::new();
                ASTMutationEngine::execute_ast_reg(&mutation, ctx)
            }

            MutationSpec::RedundantClosure { .. } => {
                use ryo_mutations::idiom::RedundantClosureMutation;
                let mutation = RedundantClosureMutation::new();
                ASTMutationEngine::execute_ast_reg(&mutation, ctx)
            }

            MutationSpec::FilterNext { .. } => {
                use ryo_mutations::idiom::FilterNextMutation;
                let mutation = FilterNextMutation::new();
                ASTMutationEngine::execute_ast_reg(&mutation, ctx)
            }

            MutationSpec::MapUnwrapOr { .. } => {
                use ryo_mutations::idiom::MapUnwrapOrMutation;
                let mutation = MapUnwrapOrMutation::new();
                ASTMutationEngine::execute_ast_reg(&mutation, ctx)
            }

            MutationSpec::CloneOnCopy { .. } => {
                use ryo_mutations::idiom::CloneOnCopyMutation;
                let mutation = CloneOnCopyMutation::new();
                ASTMutationEngine::execute_ast_reg(&mutation, ctx)
            }

            MutationSpec::LoopToIterator { .. } => {
                use ryo_mutations::idiom::LoopToIteratorMutation;
                let mutation = LoopToIteratorMutation::new();
                ASTMutationEngine::execute_ast_reg(&mutation, ctx)
            }

            MutationSpec::UnwrapToQuestion { .. } => {
                use ryo_mutations::idiom::UnwrapToQuestionMutation;
                let mutation = UnwrapToQuestionMutation::new();
                ASTMutationEngine::execute_ast_reg(&mutation, ctx)
            }

            MutationSpec::ManualMap { .. } => {
                use ryo_mutations::idiom::ManualMapMutation;
                let mutation = ManualMapMutation::new();
                ASTMutationEngine::execute_ast_reg(&mutation, ctx)
            }

            MutationSpec::MatchToIfLet { .. } => {
                use ryo_mutations::idiom::MatchToIfLetMutation;
                let mutation = MatchToIfLetMutation::new();
                ASTMutationEngine::execute_ast_reg(&mutation, ctx)
            }

            // Stub implementations - return pending status
            // See crates/ryo-executor/src/engine/impls/ for Quality Policy
            MutationSpec::IntroduceVariable { expr, var_name, .. } => {
                use ryo_mutations::idiom::IntroduceVariableMutation;
                use ryo_source::ToPure;
                // Parse expr string to PureExpr via syn
                let pure_expr = syn::parse_str::<syn::Expr>(expr)
                    .map(|e| e.to_pure())
                    .unwrap_or_else(|_| ryo_source::pure::PureExpr::Path(expr.clone()));
                let mutation = IntroduceVariableMutation::new(pure_expr, var_name);
                ASTMutationEngine::execute_ast_reg(&mutation, ctx)
            }

            MutationSpec::ExtractTrait {
                target,
                ref trait_name,
                ref methods,
                ..
            } => {
                use ryo_mutations::basic::ExtractTraitMutation;
                // Resolve target to SymbolId
                let symbol_id = try_resolve!(
                    self,
                    target,
                    ctx,
                    index,
                    spec_type,
                    affected_symbols,
                    "Failed to resolve target symbol"
                );
                let mut mutation = ExtractTraitMutation::new(symbol_id, trait_name.clone());
                if let Some(ref m) = methods {
                    mutation = mutation.with_methods(m.clone());
                }
                ASTMutationEngine::execute_ast_reg(&mutation, ctx)
            }

            MutationSpec::InlineTrait {
                target,
                ref struct_name,
                remove_trait,
                ..
            } => {
                use ryo_mutations::basic::InlineTraitMutation;
                // Resolve target to SymbolId
                let symbol_id = try_resolve!(
                    self,
                    target,
                    ctx,
                    index,
                    spec_type,
                    affected_symbols,
                    "Failed to resolve target symbol"
                );
                let mut mutation = InlineTraitMutation::new(symbol_id, struct_name.clone());
                if !remove_trait {
                    mutation = mutation.keep_trait();
                }
                ASTMutationEngine::execute_ast_reg(&mutation, ctx)
            }

            MutationSpec::ReplaceExpr {
                fn_id,
                old_expr,
                new_expr,
                replace_all,
                ..
            } => {
                use ryo_mutations::basic::stmt::ReplaceExprMutation;
                use ryo_source::pure::{PureExpr, ToPure};

                // V1 blueprint executor requires fn_id to be specified
                let target_fn = match fn_id {
                    Some(id) => *id,
                    None => {
                        return SpecResult {
                            index,
                            spec_type,
                            changes: 0,
                            affected_files: vec![],
                            affected_symbols: vec![],
                            success: false,
                            error: Some(
                                "ReplaceExpr requires fn_id in V1 executor. Use V2 converter for all-functions support.".to_string()
                            ),
                            registry_updates: RegistryUpdateBatch::default(),
                            events: vec![],
                        };
                    }
                };

                // Parse expressions from string, fallback to Path if parse fails
                let old_pure = syn::parse_str::<syn::Expr>(old_expr)
                    .map(|e| e.to_pure())
                    .unwrap_or_else(|_| PureExpr::Path(old_expr.clone()));
                let new_pure = syn::parse_str::<syn::Expr>(new_expr)
                    .map(|e| e.to_pure())
                    .unwrap_or_else(|_| PureExpr::Path(new_expr.clone()));

                let mut mutation = ReplaceExprMutation::new(old_pure, new_pure, target_fn);
                if !replace_all {
                    mutation = mutation.first_only();
                }
                ASTMutationEngine::execute_ast_reg(&mutation, ctx)
            }

            MutationSpec::RemoveStatement {
                fn_id,
                ref pattern,
                remove_all,
                ..
            } => {
                use crate::executor::registry::converters::StmtConverter;
                use ryo_mutations::basic::stmt::RemoveStatementMutation;

                // V1 blueprint executor requires fn_id to be specified
                let target_fn = match fn_id {
                    Some(id) => *id,
                    None => {
                        return SpecResult {
                            index,
                            spec_type,
                            changes: 0,
                            affected_files: vec![],
                            affected_symbols: vec![],
                            success: false,
                            error: Some(
                                "RemoveStatement requires fn_id in V1 executor. Use V2 converter for all-functions support.".to_string()
                            ),
                            registry_updates: RegistryUpdateBatch::default(),
                            events: vec![],
                        };
                    }
                };

                let target_stmt = match StmtConverter::parse_stmt(pattern) {
                    Ok(s) => s,
                    Err(e) => {
                        return SpecResult {
                            index,
                            spec_type,
                            changes: 0,
                            affected_files: vec![],
                            affected_symbols: vec![],
                            success: false,
                            error: Some(format!("Failed to parse statement pattern: {}", e)),
                            registry_updates: RegistryUpdateBatch::default(),
                            events: vec![],
                        };
                    }
                };

                let mut mutation =
                    RemoveStatementMutation::new(target_stmt, pattern.clone(), target_fn);
                if !*remove_all {
                    mutation = mutation.first_only();
                }
                ASTMutationEngine::execute_ast_reg(&mutation, ctx)
            }

            MutationSpec::InsertStatement {
                fn_id,
                ref stmt,
                ref position,
                ref reference_pattern,
                ..
            } => {
                use crate::executor::registry::converters::StmtConverter;
                use ryo_mutations::basic::stmt::InsertStatementMutation;

                let pure_stmt = match StmtConverter::parse_stmt(stmt) {
                    Ok(s) => s,
                    Err(e) => {
                        return SpecResult {
                            index,
                            spec_type,
                            changes: 0,
                            affected_files: vec![],
                            affected_symbols: vec![],
                            success: false,
                            error: Some(format!("Failed to parse statement: {}", e)),
                            registry_updates: RegistryUpdateBatch::default(),
                            events: vec![],
                        };
                    }
                };

                let mut mutation = InsertStatementMutation::new(pure_stmt, *fn_id);
                mutation = match position {
                    StmtInsertPosition::Start => mutation.at_start(),
                    StmtInsertPosition::End => mutation.at_end(),
                    StmtInsertPosition::BeforePattern => {
                        if let Some(ref p) = reference_pattern {
                            let reference_stmt = match StmtConverter::parse_stmt(p) {
                                Ok(s) => s,
                                Err(e) => {
                                    return SpecResult {
                                        index,
                                        spec_type,
                                        changes: 0,
                                        affected_files: vec![],
                                        affected_symbols: vec![],
                                        success: false,
                                        error: Some(format!(
                                            "Failed to parse reference pattern: {}",
                                            e
                                        )),
                                        registry_updates: RegistryUpdateBatch::default(),
                                        events: vec![],
                                    };
                                }
                            };
                            mutation.before(reference_stmt)
                        } else {
                            mutation
                        }
                    }
                    StmtInsertPosition::AfterPattern => {
                        if let Some(ref p) = reference_pattern {
                            let reference_stmt = match StmtConverter::parse_stmt(p) {
                                Ok(s) => s,
                                Err(e) => {
                                    return SpecResult {
                                        index,
                                        spec_type,
                                        changes: 0,
                                        affected_files: vec![],
                                        affected_symbols: vec![],
                                        success: false,
                                        error: Some(format!(
                                            "Failed to parse reference pattern: {}",
                                            e
                                        )),
                                        registry_updates: RegistryUpdateBatch::default(),
                                        events: vec![],
                                    };
                                }
                            };
                            mutation.after(reference_stmt)
                        } else {
                            mutation
                        }
                    }
                };
                ASTMutationEngine::execute_ast_reg(&mutation, ctx)
            }

            MutationSpec::ReplaceStatement {
                old_stmt,
                new_stmt,
                fn_id,
                ..
            } => {
                use crate::executor::registry::converters::StmtConverter;
                use ryo_mutations::basic::stmt::ReplaceStatementMutation;

                let old_pure = match StmtConverter::parse_stmt(old_stmt) {
                    Ok(s) => s,
                    Err(e) => {
                        return SpecResult {
                            index,
                            spec_type,
                            changes: 0,
                            affected_files: vec![],
                            affected_symbols: vec![],
                            success: false,
                            error: Some(format!("Failed to parse old statement: {}", e)),
                            registry_updates: RegistryUpdateBatch::default(),
                            events: vec![],
                        };
                    }
                };
                let new_pure = match StmtConverter::parse_stmt(new_stmt) {
                    Ok(s) => s,
                    Err(e) => {
                        return SpecResult {
                            index,
                            spec_type,
                            changes: 0,
                            affected_files: vec![],
                            affected_symbols: vec![],
                            success: false,
                            error: Some(format!("Failed to parse new statement: {}", e)),
                            registry_updates: RegistryUpdateBatch::default(),
                            events: vec![],
                        };
                    }
                };

                // V1 blueprint executor requires fn_id to be specified
                let target_fn = match fn_id {
                    Some(id) => *id,
                    None => {
                        return SpecResult {
                            index,
                            spec_type,
                            changes: 0,
                            affected_files: vec![],
                            affected_symbols: vec![],
                            success: false,
                            error: Some(
                                "ReplaceStatement requires fn_id in V1 executor. Use V2 converter for all-functions support.".to_string()
                            ),
                            registry_updates: RegistryUpdateBatch::default(),
                            events: vec![],
                        };
                    }
                };

                let mutation = ReplaceStatementMutation::new(old_pure, new_pure, target_fn);
                ASTMutationEngine::execute_ast_reg(&mutation, ctx)
            }

            MutationSpec::DuplicateFunction { .. }
            | MutationSpec::DuplicateStruct { .. }
            | MutationSpec::DuplicateEnum { .. }
            | MutationSpec::DuplicateModTree { .. } => {
                // Duplicate* specs are V2-only — they must be handled by
                // DuplicateConverter::convert_v2() in the V2 path above. If a
                // V1 fall-through reaches this arm it indicates the V2 path
                // returned V2NotSupported for a Duplicate spec, which is a
                // converter bug rather than a runtime error in the user's input.
                return SpecResult {
                    index,
                    spec_type,
                    success: false,
                    changes: 0,
                    affected_files: vec![],
                    affected_symbols,
                    error: Some(
                        "Duplicate mutations must be routed through \
                         DuplicateConverter::convert_v2(); the V1 executor path \
                         has been removed."
                            .to_string(),
                    ),
                    registry_updates: RegistryUpdateBatch::new(),
                    events: vec![],
                };
            }

            // Blueprint composition - not individual mutations
            MutationSpec::AddSpec { .. } => {
                // TODO: Implement as AddTypeAlias composition
                ExecutionResult::new(
                    MutationResult {
                        mutation_type: "AddSpec".to_string(),
                        changes: 0,
                        description: "V2 pending - implement as AddTypeAlias composition"
                            .to_string(),
                    },
                    vec![],
                )
            }

            // MoveItem is now handled via V2 path (MoveConverter → MoveItemMutation)
            MutationSpec::PluginTransform { .. } => {
                // WASM runtime out of scope for V2 core
                ExecutionResult::new(
                    MutationResult {
                        mutation_type: "PluginTransform".to_string(),
                        changes: 0,
                        description: "WASM plugin runtime not implemented in V2".to_string(),
                    },
                    vec![],
                )
            }

            _ => {
                return SpecResult {
                    index,
                    spec_type: spec_type.clone(),
                    success: false,
                    changes: 0,
                    affected_files: vec![],
                    affected_symbols,
                    error: Some(format!(
                        "MutationSpec::{} is not implemented in the V2 AST path \
                         (no converter or fallback covers this variant). \
                         If you need this spec, add a converter to \
                         MutationRegistry::convert_v2 or extend execute_spec_v2.",
                        spec_type
                    )),
                    registry_updates: RegistryUpdateBatch::new(),
                    events: vec![],
                };
            }
        };

        SpecResult {
            index,
            spec_type,
            changes: exec_result.result.changes,
            affected_files: vec![], // Will be determined by FileDumper at end
            affected_symbols,
            success: exec_result.has_changes() || exec_result.result.changes == 0,
            error: None,
            registry_updates: RegistryUpdateBatch::new(),
            events: exec_result.events,
        }
    }

    /// Set execution strategy
    pub fn with_strategy(mut self, strategy: ExecutionStrategy) -> Self {
        self.strategy = strategy;
        self
    }

    /// Enable compile verification after each mutation
    pub fn with_verify(mut self, verify: bool) -> Self {
        self.verify_after_each = verify;
        self
    }

    /// Stop execution on first error
    pub fn with_stop_on_error(mut self, stop: bool) -> Self {
        self.stop_on_error = stop;
        self
    }
}

/// Normalize generic type names for comparison.
///
/// The registry stores generic types with spaces due to `to_token_stream().to_string()`
/// behavior (e.g., "Generic < T , U >"), but DSL specifies them without spaces
/// (e.g., "Generic<T, U>"). This function normalizes both formats for comparison.
fn normalize_generic_name(name: &str) -> String {
    name.replace(" < ", "<")
        .replace(" > ", ">")
        .replace("< ", "<")
        .replace(" >", ">")
        .replace(", ", ",")
        .replace(" ,", ",")
}

/// Register a symbol from AddItem content for deferred resolution.
///
/// This allows later intents in a batch (e.g., AddDerive, AddVariant) to reference
/// symbols created by earlier AddItem intents.
fn register_item_from_content(
    ctx: &mut AnalysisContext,
    target: &ryo_symbol::SymbolPath,
    content: &str,
) {
    use ryo_symbol::SymbolKind;

    let trimmed = content.trim();

    // Skip attributes and find the item declaration
    let mut lines = trimmed.lines();
    let mut decl_line = "";
    for line in lines.by_ref() {
        let line = line.trim();
        if !line.starts_with('#') && !line.starts_with("//") && !line.is_empty() {
            decl_line = line;
            break;
        }
    }

    // Parse: pub? (struct|enum|fn|type|const|static|trait|mod) NAME
    let tokens: Vec<&str> = decl_line.split_whitespace().collect();
    if tokens.is_empty() {
        return;
    }

    let mut idx = 0;

    // Skip visibility
    if tokens.get(idx) == Some(&"pub") {
        idx += 1;
        // Skip pub(crate), pub(super), etc.
        if let Some(t) = tokens.get(idx) {
            if t.starts_with('(') {
                idx += 1;
            }
        }
    }

    // Get keyword
    let Some(keyword) = tokens.get(idx) else {
        return;
    };
    idx += 1;

    let kind = match *keyword {
        "struct" => SymbolKind::Struct,
        "enum" => SymbolKind::Enum,
        "fn" => SymbolKind::Function,
        "type" => SymbolKind::TypeAlias,
        "const" => SymbolKind::Const,
        "static" => SymbolKind::Static,
        "trait" => SymbolKind::Trait,
        "mod" => SymbolKind::Mod,
        "impl" => return, // Skip impl blocks - they don't create new symbols
        _ => return,
    };

    // Get name (may include generics like "Foo<T>")
    let Some(name_token) = tokens.get(idx) else {
        return;
    };
    let name = name_token
        .split(['<', '{', '(', ':'])
        .next()
        .unwrap_or(name_token);

    // Build full symbol path
    let target_str = target.to_string();
    let is_crate_root = target_str == "crate";
    let full_path = if is_crate_root {
        ryo_symbol::SymbolPath::parse(&format!("crate::{}", name))
    } else {
        ryo_symbol::SymbolPath::parse(&format!("{}::{}", target_str, name))
    };

    let Ok(path) = full_path else {
        return;
    };

    // Register in registry (ignore errors - symbol may already exist)
    let _ = ctx.registry_mut().register(path, kind);
}

/// Get a short type name for a MutationSpec
fn spec_type_name(spec: &MutationSpec) -> String {
    match spec {
        MutationSpec::Rename { .. } => "Rename".to_string(),
        MutationSpec::AddField { .. } => "AddField".to_string(),
        MutationSpec::RemoveField { .. } => "RemoveField".to_string(),
        MutationSpec::ChangeVisibility { .. } => "ChangeVisibility".to_string(),
        MutationSpec::AddDerive { .. } => "AddDerive".to_string(),
        MutationSpec::RemoveDerive { .. } => "RemoveDerive".to_string(),
        MutationSpec::AddVariant { .. } => "AddVariant".to_string(),
        MutationSpec::RemoveVariant { .. } => "RemoveVariant".to_string(),
        MutationSpec::AddMatchArm { .. } => "AddMatchArm".to_string(),
        MutationSpec::RemoveMatchArm { .. } => "RemoveMatchArm".to_string(),
        MutationSpec::ReplaceMatchArm { .. } => "ReplaceMatchArm".to_string(),
        MutationSpec::AddStructLiteralField { .. } => "AddStructLiteralField".to_string(),
        MutationSpec::RemoveStructLiteralField { .. } => "RemoveStructLiteralField".to_string(),
        MutationSpec::AddItem { .. } => "AddItem".to_string(),
        MutationSpec::RemoveItem { .. } => "RemoveItem".to_string(),
        MutationSpec::AddMethod { .. } => "AddMethod".to_string(),
        MutationSpec::RemoveMethod { .. } => "RemoveMethod".to_string(),
        MutationSpec::RemoveMod { .. } => "RemoveMod".to_string(),
        MutationSpec::CreateMod { .. } => "CreateMod".to_string(),
        MutationSpec::OrganizeImports { .. } => "OrganizeImports".to_string(),
        MutationSpec::LoopToIterator { .. } => "LoopToIterator".to_string(),
        MutationSpec::UnwrapToQuestion { .. } => "UnwrapToQuestion".to_string(),
        MutationSpec::AddSpec { .. } => "AddSpec".to_string(),
        MutationSpec::RemoveSpec { .. } => "RemoveSpec".to_string(),
        MutationSpec::ValidateSpec { .. } => "ValidateSpec".to_string(),
        MutationSpec::ExtractTrait { .. } => "ExtractTrait".to_string(),
        MutationSpec::InlineTrait { .. } => "InlineTrait".to_string(),
        MutationSpec::ReplaceType { .. } => "ReplaceType".to_string(),
        MutationSpec::EnumToTrait { .. } => "EnumToTrait".to_string(),
        MutationSpec::MoveItem { .. } => "MoveItem".to_string(),
        MutationSpec::AssignOp { .. } => "AssignOp".to_string(),
        MutationSpec::BoolSimplify { .. } => "BoolSimplify".to_string(),
        MutationSpec::CloneOnCopy { .. } => "CloneOnCopy".to_string(),
        MutationSpec::CollapsibleIf { .. } => "CollapsibleIf".to_string(),
        MutationSpec::NoOpArmToTodo { .. } => "NoOpArmToTodo".to_string(),
        MutationSpec::ComparisonToMethod { .. } => "ComparisonToMethod".to_string(),
        MutationSpec::RedundantClosure { .. } => "RedundantClosure".to_string(),
        MutationSpec::IntroduceVariable { .. } => "IntroduceVariable".to_string(),
        MutationSpec::ManualMap { .. } => "ManualMap".to_string(),
        MutationSpec::MatchToIfLet { .. } => "MatchToIfLet".to_string(),
        MutationSpec::FilterNext { .. } => "FilterNext".to_string(),
        MutationSpec::MapUnwrapOr { .. } => "MapUnwrapOr".to_string(),
        MutationSpec::ReplaceExpr { .. } => "ReplaceExpr".to_string(),
        MutationSpec::RemoveStatement { .. } => "RemoveStatement".to_string(),
        MutationSpec::InsertStatement { .. } => "InsertStatement".to_string(),
        MutationSpec::ReplaceStatement { .. } => "ReplaceStatement".to_string(),
        MutationSpec::PluginTransform { .. } => "PluginTransform".to_string(),
        MutationSpec::DuplicateFunction { .. } => "DuplicateFunction".to_string(),
        MutationSpec::DuplicateStruct { .. } => "DuplicateStruct".to_string(),
        MutationSpec::DuplicateEnum { .. } => "DuplicateEnum".to_string(),
        MutationSpec::DuplicateModTree { .. } => "DuplicateModTree".to_string(),
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::executor::spec::{Scope, SelfParam, SymbolPath, Visibility};
    use ryo_analysis::testing::{ContextBuilder, ContextTestExt};
    use ryo_symbol::SymbolId;

    /// Create a dummy SymbolId for testing
    fn dummy_id(index: u32) -> SymbolId {
        SymbolId::parse(&format!("{}v1", index)).expect("valid dummy id")
    }

    /// Helper function that executes a blueprint and syncs files.
    /// This is the standard pattern for tests that need to read from ctx.files() after execution.
    fn execute_and_sync(
        executor: &BlueprintExecutor,
        blueprint: &ParallelBlueprint,
        ctx: &mut AnalysisContext,
    ) -> BlueprintResult {
        let result = executor.execute_v2(blueprint, ctx);
        if result.success {
            BlueprintExecutor::sync_files_and_rebuild(&result, ctx).unwrap();
        }
        result
    }

    fn create_test_context() -> AnalysisContext {
        let code = r#"
struct Config {
    name: String,
}

impl Config {
    fn new() -> Self {
        Self { name: String::new() }
    }
}
"#;
        ContextBuilder::new()
            .with_file("src/config.rs", code)
            .build()
    }

    #[test]
    fn test_blueprint_executor_rename() {
        let mut ctx = create_test_context();

        // Look up the symbol_id for Config from the context's registry
        let symbol_id = ctx
            .registry()
            .lookup_by_name("Config")
            .expect("Config should exist in registry");

        let specs = vec![MutationSpec::Rename {
            target: MutationTargetSymbol::ById(symbol_id),
            to: "AppConfig".to_string(),
            scope: Scope::Project,
        }];
        let blueprint = ParallelBlueprint::from_mutations(specs);

        let executor = BlueprintExecutor::new();
        let exec_result = execute_and_sync(&executor, &blueprint, &mut ctx);

        assert!(exec_result.success);
        assert!(exec_result.total_changes > 0);

        // Verify the rename happened
        let file = ctx.test_file("src/config.rs").unwrap();
        let source = file.to_source().unwrap();
        assert!(source.contains("AppConfig"));
        assert!(!source.contains("struct Config"));
    }

    #[test]
    fn test_blueprint_executor_add_derive() {
        let mut ctx = create_test_context();

        // Lookup the actual SymbolId (file is src/config.rs, so path is crate::config::Config)
        let path = SymbolPath::parse("test_crate::config::Config").unwrap();
        let symbol_id = ctx.registry().lookup(&path).expect("Config should exist");

        let specs = vec![MutationSpec::AddDerive {
            target: MutationTargetSymbol::ById(symbol_id),
            derives: vec!["Debug".to_string(), "Clone".to_string()],
        }];
        let blueprint = ParallelBlueprint::from_mutations(specs);

        let executor = BlueprintExecutor::new();
        let exec_result = execute_and_sync(&executor, &blueprint, &mut ctx);

        assert!(exec_result.success);

        let file = ctx.test_file("src/config.rs").unwrap();
        let source = file.to_source().unwrap();
        assert!(source.contains("derive"), "Expected derive in: {}", source);
        assert!(source.contains("Debug"));
    }

    #[test]
    fn test_blueprint_executor_organize_imports() {
        let code = r#"
use std::collections::HashMap;
use std::io::Write;
use std::collections::HashSet;
use std::io::Read;

fn main() {}
"#;
        let mut ctx = ContextBuilder::new().with_file("src/main.rs", code).build();

        let specs = vec![MutationSpec::OrganizeImports {
            module_id: None,
            deduplicate: true,
            merge_groups: true,
        }];
        let blueprint = ParallelBlueprint::from_mutations(specs);

        let executor = BlueprintExecutor::new();
        let exec_result = execute_and_sync(&executor, &blueprint, &mut ctx);

        assert!(exec_result.success);
    }

    #[test]
    fn test_blueprint_with_conflicts_fails_when_not_ignored() {
        use ryo_symbol::{SymbolKind, SymbolPath, SymbolRegistry};

        let mut ctx = create_test_context();

        // Create dummy symbol IDs for testing actual conflicts
        let mut symbol_registry = SymbolRegistry::new();
        let path_a = SymbolPath::parse("test_crate::A").unwrap();
        let symbol_a = symbol_registry
            .register(path_a, SymbolKind::Struct)
            .unwrap();

        // Create blueprint with actual conflicts (same target renamed twice)
        let specs = vec![
            MutationSpec::Rename {
                target: MutationTargetSymbol::ById(symbol_a),
                to: "B".to_string(),
                scope: Scope::Project,
            },
            MutationSpec::Rename {
                target: MutationTargetSymbol::ById(symbol_a),
                to: "C".to_string(),
                scope: Scope::Project,
            },
        ];

        let blueprint = ParallelBlueprint::from_mutations(specs);

        // Verify blueprint has conflicts
        assert!(
            !blueprint.conflicts.is_empty(),
            "Blueprint should have conflicts"
        );

        // With ignore_conflicts = false, conflicts should fail
        let mut executor = BlueprintExecutor::new();
        executor.ignore_conflicts = false;
        let result = execute_and_sync(&executor, &blueprint, &mut ctx);

        // Should fail because of conflicts
        assert!(
            !result.success,
            "Execution should fail when conflicts are not ignored"
        );
        assert!(result.error.is_some(), "Should have error message");
        assert!(
            result.error.unwrap().contains("conflict"),
            "Error should mention conflicts"
        );
    }

    // Note: Intent-based tests have been removed as they use deprecated ryo_core::Intent.
    // Converter-level tests in registry/converters/ provide comprehensive coverage.
    // TODO: Add MutationSpec-based integration tests if needed.

    // === AddItem Tests ===

    #[test]
    fn test_blueprint_executor_add_item_struct() {
        let mut ctx = ContextBuilder::new()
            .with_file("src/lib.rs", "// empty file\n")
            .build();

        let spec = MutationSpec::AddItem {
            target: MutationTargetSymbol::ByPath(Box::new(
                SymbolPath::parse("test_crate").unwrap(),
            )),
            content: "pub struct Config {}".to_string(),
            position: super::super::spec::InsertPosition::Bottom,
        };

        let blueprint = ParallelBlueprint::from_mutations(vec![spec]);
        let executor = BlueprintExecutor::new();
        let exec_result = execute_and_sync(&executor, &blueprint, &mut ctx);

        assert!(
            exec_result.success,
            "AddItem struct failed: {:?}",
            exec_result.error
        );

        let file = ctx.test_file("src/lib.rs").unwrap();
        let source = file.to_source().unwrap();
        assert!(
            source.contains("pub struct Config"),
            "Struct not added: {}",
            source
        );
    }

    #[test]
    fn test_blueprint_executor_add_item_fn() {
        let mut ctx = ContextBuilder::new()
            .with_file("src/lib.rs", "// empty file\n")
            .build();

        let spec = MutationSpec::AddItem {
            target: MutationTargetSymbol::ByPath(Box::new(
                SymbolPath::parse("test_crate").unwrap(),
            )),
            content: "fn helper() {}".to_string(),
            position: super::super::spec::InsertPosition::Bottom,
        };

        let blueprint = ParallelBlueprint::from_mutations(vec![spec]);
        let executor = BlueprintExecutor::new();
        let exec_result = execute_and_sync(&executor, &blueprint, &mut ctx);

        assert!(
            exec_result.success,
            "AddItem fn failed: {:?}",
            exec_result.error
        );

        let file = ctx.test_file("src/lib.rs").unwrap();
        let source = file.to_source().unwrap();
        assert!(
            source.contains("fn helper"),
            "Function not added: {}",
            source
        );
    }

    #[test]
    fn test_blueprint_executor_add_item_use() {
        let mut ctx = ContextBuilder::new()
            .with_file("src/lib.rs", "pub struct Dummy;\n")
            .build();

        let spec = MutationSpec::AddItem {
            target: MutationTargetSymbol::ByPath(Box::new(
                SymbolPath::parse("test_crate").unwrap(),
            )),
            content: "use HashMap;".to_string(),
            position: super::super::spec::InsertPosition::Top,
        };

        let blueprint = ParallelBlueprint::from_mutations(vec![spec]);
        let executor = BlueprintExecutor::new();
        let exec_result = execute_and_sync(&executor, &blueprint, &mut ctx);

        assert!(
            exec_result.success,
            "AddItem use failed: {:?}",
            exec_result.error
        );

        let file = ctx.test_file("src/lib.rs").unwrap();
        let source = file.to_source().unwrap();
        assert!(source.contains("use HashMap"), "Use not added: {}", source);
    }

    #[test]
    fn test_blueprint_executor_add_item_impl() {
        let mut ctx = ContextBuilder::new()
            .with_file("src/lib.rs", "struct Foo {}\n")
            .build();

        let spec = MutationSpec::AddItem {
            target: MutationTargetSymbol::ByPath(Box::new(
                SymbolPath::parse("test_crate").unwrap(),
            )),
            content: "impl Foo {}".to_string(),
            position: super::super::spec::InsertPosition::Bottom,
        };

        let blueprint = ParallelBlueprint::from_mutations(vec![spec]);
        let executor = BlueprintExecutor::new();
        let exec_result = execute_and_sync(&executor, &blueprint, &mut ctx);

        assert!(
            exec_result.success,
            "AddItem impl failed: {:?}",
            exec_result.error
        );

        let file = ctx.test_file("src/lib.rs").unwrap();
        let source = file.to_source().unwrap();
        assert!(source.contains("impl Foo"), "Impl not added: {}", source);
    }

    #[test]
    fn test_blueprint_executor_add_item_enum() {
        let mut ctx = ContextBuilder::new()
            .with_file("src/lib.rs", "// empty file\n")
            .build();

        let spec = MutationSpec::AddItem {
            target: MutationTargetSymbol::ByPath(Box::new(
                SymbolPath::parse("test_crate").unwrap(),
            )),
            content: "pub enum Status { Pending, Active, Completed }".to_string(),
            position: super::super::spec::InsertPosition::Bottom,
        };

        let blueprint = ParallelBlueprint::from_mutations(vec![spec]);
        let executor = BlueprintExecutor::new();
        let exec_result = execute_and_sync(&executor, &blueprint, &mut ctx);

        assert!(
            exec_result.success,
            "AddItem enum failed: {:?}",
            exec_result.error
        );

        let file = ctx.test_file("src/lib.rs").unwrap();
        let source = file.to_source().unwrap();
        assert!(
            source.contains("pub enum Status"),
            "Enum not added: {}",
            source
        );
    }

    // === AddMethod Tests ===

    #[test]
    fn test_blueprint_executor_add_method_basic() {
        let mut ctx = ContextBuilder::new()
            .with_file("src/lib.rs", "pub struct Config {}\n\nimpl Config {}\n")
            .build();

        let spec = MutationSpec::AddMethod {
            target: MutationTargetSymbol::ByKindAndName(
                crate::executor::ItemKind::Impl,
                "Config".to_string(),
            ),
            method_name: "new".to_string(),
            params: vec![],
            return_type: Some("Self".to_string()),
            body: "Self {}".to_string(),
            is_pub: true,
            self_param: None,
        };

        let blueprint = ParallelBlueprint::from_mutations(vec![spec]);
        let executor = BlueprintExecutor::new();
        let exec_result = execute_and_sync(&executor, &blueprint, &mut ctx);

        assert!(
            exec_result.success,
            "AddMethod basic failed: {:?}",
            exec_result.error
        );

        let file = ctx.test_file("src/lib.rs").unwrap();
        let source = file.to_source().unwrap();
        assert!(
            source.contains("pub fn new"),
            "Method not added: {}",
            source
        );
        assert!(
            source.contains("-> Self"),
            "Return type not added: {}",
            source
        );
    }

    #[test]
    fn test_blueprint_executor_add_method_with_self() {
        let mut ctx = ContextBuilder::new()
            .with_file(
                "src/lib.rs",
                "pub struct Counter { value: u32 }\n\nimpl Counter {}\n",
            )
            .build();

        let spec = MutationSpec::AddMethod {
            target: MutationTargetSymbol::ByKindAndName(
                crate::executor::ItemKind::Impl,
                "Counter".to_string(),
            ),
            method_name: "get".to_string(),
            params: vec![],
            return_type: Some("u32".to_string()),
            body: "self.value".to_string(),
            is_pub: true,
            self_param: Some(SelfParam::Ref),
        };

        let blueprint = ParallelBlueprint::from_mutations(vec![spec]);
        let executor = BlueprintExecutor::new();
        let exec_result = execute_and_sync(&executor, &blueprint, &mut ctx);

        assert!(
            exec_result.success,
            "AddMethod with_self failed: {:?}",
            exec_result.error
        );

        let file = ctx.test_file("src/lib.rs").unwrap();
        let source = file.to_source().unwrap();
        assert!(source.contains("&self"), "Self param not added: {}", source);
        assert!(source.contains("fn get"), "Method not added: {}", source);
    }

    #[test]
    fn test_blueprint_executor_add_method_with_mut_self() {
        let mut ctx = ContextBuilder::new()
            .with_file(
                "src/lib.rs",
                "pub struct Counter { value: u32 }\n\nimpl Counter {}\n",
            )
            .build();

        let spec = MutationSpec::AddMethod {
            target: MutationTargetSymbol::ByKindAndName(
                crate::executor::ItemKind::Impl,
                "Counter".to_string(),
            ),
            method_name: "increment".to_string(),
            params: vec![],
            return_type: None,
            body: "self.value += 1".to_string(),
            is_pub: true,
            self_param: Some(SelfParam::Mut),
        };

        let blueprint = ParallelBlueprint::from_mutations(vec![spec]);
        let executor = BlueprintExecutor::new();
        let exec_result = execute_and_sync(&executor, &blueprint, &mut ctx);

        assert!(
            exec_result.success,
            "AddMethod with_mut_self failed: {:?}",
            exec_result.error
        );

        let file = ctx.test_file("src/lib.rs").unwrap();
        let source = file.to_source().unwrap();
        assert!(
            source.contains("&mut self"),
            "Mut self param not added: {}",
            source
        );
        assert!(
            source.contains("fn increment"),
            "Method not added: {}",
            source
        );
    }

    #[test]
    fn test_blueprint_executor_add_method_with_params() {
        let mut ctx = ContextBuilder::new()
            .with_file(
                "src/lib.rs",
                "pub struct Calculator {}\n\nimpl Calculator {}\n",
            )
            .build();

        let spec = MutationSpec::AddMethod {
            target: MutationTargetSymbol::ByKindAndName(
                crate::executor::ItemKind::Impl,
                "Calculator".to_string(),
            ),
            method_name: "add".to_string(),
            params: vec![
                ("a".to_string(), "i32".to_string()),
                ("b".to_string(), "i32".to_string()),
            ],
            return_type: Some("i32".to_string()),
            body: "a + b".to_string(),
            is_pub: true,
            self_param: None,
        };

        let blueprint = ParallelBlueprint::from_mutations(vec![spec]);
        let executor = BlueprintExecutor::new();
        let exec_result = execute_and_sync(&executor, &blueprint, &mut ctx);

        assert!(
            exec_result.success,
            "AddMethod with_params failed: {:?}",
            exec_result.error
        );

        let file = ctx.test_file("src/lib.rs").unwrap();
        let source = file.to_source().unwrap();
        assert!(source.contains("fn add"), "Method not added: {}", source);
        assert!(source.contains("a: i32"), "Param a not added: {}", source);
        assert!(source.contains("b: i32"), "Param b not added: {}", source);
    }

    // === Multi-file Tests ===

    #[test]
    fn test_blueprint_executor_multi_file_rename() {
        let mut ctx = ContextBuilder::new()
            .with_file(
                "src/lib.rs",
                r#"mod models;

fn process(task: Task) -> Task {
    task
}
"#,
            )
            .with_file(
                "src/models.rs",
                r#"pub struct Task {
    pub id: u32,
    pub name: String,
}
"#,
            )
            .build();

        // Look up the symbol_id for Task from the context's registry
        let symbol_id = ctx
            .registry()
            .lookup_by_name("Task")
            .expect("Task should exist in registry");

        // Rename Task to TodoItem across all files
        let spec = MutationSpec::Rename {
            target: MutationTargetSymbol::ById(symbol_id),
            to: "TodoItem".to_string(),
            scope: Scope::Project,
        };

        let blueprint = ParallelBlueprint::from_mutations(vec![spec]);
        let executor = BlueprintExecutor::new();
        let exec_result = execute_and_sync(&executor, &blueprint, &mut ctx);

        assert!(
            exec_result.success,
            "Multi-file rename failed: {:?}",
            exec_result.error
        );

        // Check lib.rs type annotations were renamed
        let lib = ctx.test_file("src/lib.rs").unwrap();
        let lib_source = lib.to_source().unwrap();
        assert!(
            lib_source.contains("task: TodoItem"),
            "lib.rs type not renamed: {}",
            lib_source
        );
        assert!(
            lib_source.contains("-> TodoItem"),
            "lib.rs return type not renamed: {}",
            lib_source
        );

        // Check models.rs struct was renamed
        let models = ctx.test_file("src/models.rs").unwrap();
        let models_source = models.to_source().unwrap();
        assert!(
            models_source.contains("struct TodoItem"),
            "models.rs struct not renamed: {}",
            models_source
        );
        assert!(
            !models_source.contains("struct Task"),
            "models.rs still has struct Task: {}",
            models_source
        );
    }

    #[test]
    fn test_blueprint_executor_multi_file_add_items() {
        let mut ctx = ContextBuilder::new()
            .with_file("src/lib.rs", "pub mod models;\n")
            .with_file("src/models.rs", "pub struct Placeholder;\n")
            .build();

        // Add struct to models.rs
        let spec1 = MutationSpec::AddItem {
            target: MutationTargetSymbol::ByPath(Box::new(
                SymbolPath::parse("test_crate::models").unwrap(),
            )),
            content: "pub struct User { id: u32 }".to_string(),
            position: super::super::spec::InsertPosition::Bottom,
        };

        // Add use to lib.rs
        let spec2 = MutationSpec::AddItem {
            target: MutationTargetSymbol::ByPath(Box::new(
                SymbolPath::parse("test_crate").unwrap(),
            )),
            content: "use models::User;".to_string(),
            position: super::super::spec::InsertPosition::Bottom,
        };

        let blueprint = ParallelBlueprint::from_mutations(vec![spec1, spec2]);
        let executor = BlueprintExecutor::new();
        let exec_result = execute_and_sync(&executor, &blueprint, &mut ctx);

        assert!(
            exec_result.success,
            "Multi-file add items failed: {:?}",
            exec_result.error
        );

        // Check models.rs has User struct
        let models = ctx.test_file("src/models.rs").unwrap();
        let models_source = models.to_source().unwrap();
        assert!(
            models_source.contains("pub struct User"),
            "User not added to models.rs: {}",
            models_source
        );

        // Check lib.rs has use statement
        let lib = ctx.test_file("src/lib.rs").unwrap();
        let lib_source = lib.to_source().unwrap();
        assert!(
            lib_source.contains("use models::User"),
            "Use not added to lib.rs: {}",
            lib_source
        );
    }

    // === Generic and Async Tests ===

    #[test]
    fn test_blueprint_executor_add_item_generic_struct() {
        let mut ctx = ContextBuilder::new()
            .with_file("src/lib.rs", "// empty file\n")
            .build();

        let spec = MutationSpec::AddItem {
            target: MutationTargetSymbol::ByPath(Box::new(
                SymbolPath::parse("test_crate").unwrap(),
            )),
            content: "pub struct Container<T> { value: T }".to_string(),
            position: super::super::spec::InsertPosition::Bottom,
        };

        let blueprint = ParallelBlueprint::from_mutations(vec![spec]);
        let executor = BlueprintExecutor::new();
        let exec_result = execute_and_sync(&executor, &blueprint, &mut ctx);

        assert!(
            exec_result.success,
            "AddItem generic struct failed: {:?}",
            exec_result.error
        );

        let file = ctx.test_file("src/lib.rs").unwrap();
        let source = file.to_source().unwrap();
        assert!(
            source.contains("struct Container"),
            "Generic struct not added: {}",
            source
        );
    }

    #[test]
    fn test_blueprint_executor_add_item_async_fn() {
        let mut ctx = ContextBuilder::new()
            .with_file("src/lib.rs", "// empty file\n")
            .build();

        let spec = MutationSpec::AddItem {
            target: MutationTargetSymbol::ByPath(Box::new(
                SymbolPath::parse("test_crate").unwrap(),
            )),
            content: "pub async fn fetch_data() -> String { String::new() }".to_string(),
            position: super::super::spec::InsertPosition::Bottom,
        };

        let blueprint = ParallelBlueprint::from_mutations(vec![spec]);
        let executor = BlueprintExecutor::new();
        let exec_result = execute_and_sync(&executor, &blueprint, &mut ctx);

        assert!(
            exec_result.success,
            "AddItem async fn failed: {:?}",
            exec_result.error
        );

        let file = ctx.test_file("src/lib.rs").unwrap();
        let source = file.to_source().unwrap();
        assert!(
            source.contains("fn fetch_data"),
            "Async fn not added: {}",
            source
        );
    }

    #[test]
    fn test_blueprint_executor_add_field_to_generic_struct() {
        use ryo_analysis::SymbolKind;

        let mut ctx = ContextBuilder::new()
            .with_file("src/lib.rs", "pub struct Wrapper<T> { inner: T }\n")
            .build();

        // Get symbol_id for Wrapper struct
        let symbol_id = ctx
            .registry
            .iter()
            .find(|(id, path)| {
                path.name() == "Wrapper" && ctx.registry.kind(*id) == Some(SymbolKind::Struct)
            })
            .map(|(id, _)| id)
            .expect("Wrapper struct not found in registry");

        let spec = MutationSpec::AddField {
            target: MutationTargetSymbol::ById(symbol_id),
            field_name: "count".to_string(),
            field_type: "usize".to_string(),
            visibility: Visibility::Pub,
        };

        let blueprint = ParallelBlueprint::from_mutations(vec![spec]);
        let executor = BlueprintExecutor::new();
        let exec_result = execute_and_sync(&executor, &blueprint, &mut ctx);

        assert!(
            exec_result.success,
            "AddField to generic struct failed: {:?}",
            exec_result.error
        );

        let file = ctx.test_file("src/lib.rs").unwrap();
        let source = file.to_source().unwrap();
        assert!(
            source.contains("pub count: usize"),
            "Field not added to generic struct: {}",
            source
        );
    }

    #[test]
    fn test_blueprint_executor_add_derive_to_generic_struct() {
        let mut ctx = ContextBuilder::new()
            .with_file(
                "src/lib.rs",
                "pub struct Pair<T, U> { first: T, second: U }\n",
            )
            .build();

        // Lookup the actual SymbolId
        let path = SymbolPath::parse("test_crate::Pair").unwrap();
        let symbol_id = ctx.registry().lookup(&path).expect("Pair should exist");

        let spec = MutationSpec::AddDerive {
            target: MutationTargetSymbol::ById(symbol_id),
            derives: vec!["Debug".to_string(), "Clone".to_string()],
        };

        let blueprint = ParallelBlueprint::from_mutations(vec![spec]);
        let executor = BlueprintExecutor::new();
        let exec_result = execute_and_sync(&executor, &blueprint, &mut ctx);

        assert!(
            exec_result.success,
            "AddDerive to generic struct failed: {:?}",
            exec_result.error
        );

        let file = ctx.test_file("src/lib.rs").unwrap();
        let source = file.to_source().unwrap();
        assert!(
            source.contains("Debug"),
            "Debug derive not added: {}",
            source
        );
        assert!(
            source.contains("Clone"),
            "Clone derive not added: {}",
            source
        );
    }

    // === Module Tests ===
    // Note: AddMod was consolidated into CreateMod. These tests use CreateMod with empty content
    // to test the mod declaration functionality.

    #[test]
    fn test_blueprint_executor_create_mod_declaration() {
        let mut ctx = ContextBuilder::new()
            .with_file("src/lib.rs", "use std::io;\n\nfn main() {}\n")
            .build();

        let spec = MutationSpec::CreateMod {
            target: MutationTargetSymbol::ByPath(Box::new(
                SymbolPath::parse("test_crate").unwrap(),
            )),
            mod_name: "models".to_string(),
            content: String::new(),
            is_pub: false,
        };

        let blueprint = ParallelBlueprint::from_mutations(vec![spec]);
        let executor = BlueprintExecutor::new();
        let exec_result = execute_and_sync(&executor, &blueprint, &mut ctx);

        assert!(
            exec_result.success,
            "CreateMod failed: {:?}",
            exec_result.error
        );

        let file = ctx.test_file("src/lib.rs").unwrap();
        let source = file.to_source().unwrap();
        assert!(source.contains("mod models;"), "Mod not added: {}", source);
    }

    #[test]
    fn test_blueprint_executor_create_pub_mod_declaration() {
        let mut ctx = ContextBuilder::new()
            .with_file("src/lib.rs", "fn main() {}\n")
            .build();

        let spec = MutationSpec::CreateMod {
            target: MutationTargetSymbol::ByPath(Box::new(
                SymbolPath::parse("test_crate").unwrap(),
            )),
            mod_name: "api".to_string(),
            content: String::new(),
            is_pub: true,
        };

        let blueprint = ParallelBlueprint::from_mutations(vec![spec]);
        let executor = BlueprintExecutor::new();
        let exec_result = execute_and_sync(&executor, &blueprint, &mut ctx);

        assert!(
            exec_result.success,
            "CreateMod pub failed: {:?}",
            exec_result.error
        );

        let file = ctx.test_file("src/lib.rs").unwrap();
        let source = file.to_source().unwrap();
        assert!(
            source.contains("pub mod api;"),
            "Pub mod not added: {}",
            source
        );
    }

    #[test]
    fn test_blueprint_executor_create_file() {
        // NOTE: Don't pre-declare "mod models;" - CreateMod will add both the declaration and content
        let mut ctx = ContextBuilder::new()
            .with_file("src/lib.rs", "// lib.rs\n")
            .build();

        let spec = MutationSpec::CreateMod {
            target: MutationTargetSymbol::ByPath(Box::new(
                SymbolPath::parse("test_crate").unwrap(),
            )),
            mod_name: "models".to_string(),
            content: "pub struct Model { id: u32 }".to_string(),
            is_pub: true,
        };

        let blueprint = ParallelBlueprint::from_mutations(vec![spec]);
        let executor = BlueprintExecutor::new();
        let exec_result = execute_and_sync(&executor, &blueprint, &mut ctx);

        assert!(
            exec_result.success,
            "CreateFile failed: {:?}",
            exec_result.error
        );

        // Check file was created (file style: src/models.rs - Ryo uses file-style modules by default)
        assert!(ctx.test_file("src/models.rs").is_some(), "File not created");

        let file = ctx.test_file("src/models.rs").unwrap();
        let source = file.to_source().unwrap();
        assert!(
            source.contains("struct Model"),
            "Content not correct: {}",
            source
        );
    }

    #[test]
    fn test_blueprint_executor_create_module_workflow() {
        let mut ctx = ContextBuilder::new()
            .with_file("src/lib.rs", "fn main() {}\n")
            .build();

        // CreateMod handles both mod declaration and file creation
        let spec = MutationSpec::CreateMod {
            target: MutationTargetSymbol::ByPath(Box::new(
                SymbolPath::parse("test_crate").unwrap(),
            )),
            mod_name: "utils".to_string(),
            content: "pub fn helper() {}".to_string(),
            is_pub: true,
        };

        let blueprint = ParallelBlueprint::from_mutations(vec![spec]);
        let executor = BlueprintExecutor::new();
        let exec_result = execute_and_sync(&executor, &blueprint, &mut ctx);

        assert!(
            exec_result.success,
            "Module workflow failed: {:?}",
            exec_result.error
        );

        // Check lib.rs has mod declaration
        let lib = ctx.test_file("src/lib.rs").unwrap();
        let lib_source = lib.to_source().unwrap();
        assert!(
            lib_source.contains("pub mod utils;"),
            "Mod not added to lib: {}",
            lib_source
        );

        // Check utils file exists and has function (file style: src/utils.rs)
        let utils = ctx.test_file("src/utils.rs").unwrap();
        let utils_source = utils.to_source().unwrap();
        assert!(
            utils_source.contains("fn helper"),
            "Function not in utils: {}",
            utils_source
        );
    }

    // === Wavefront Execution Tests ===

    #[test]
    fn test_wavefront_execution_basic() {
        let mut ctx = create_test_context();

        // Lookup the actual SymbolId (file is src/config.rs, so path is crate::config::Config)
        let path = SymbolPath::parse("test_crate::config::Config").unwrap();
        let symbol_id = ctx.registry().lookup(&path).expect("Config should exist");

        let specs = vec![MutationSpec::AddDerive {
            target: MutationTargetSymbol::ById(symbol_id),
            derives: vec!["Debug".to_string()],
        }];
        let blueprint = ParallelBlueprint::from_mutations(specs);

        let executor = BlueprintExecutor::new().with_strategy(ExecutionStrategy::Wavefront);
        let exec_result = execute_and_sync(&executor, &blueprint, &mut ctx);

        assert!(
            exec_result.success,
            "Wavefront basic failed: {:?}",
            exec_result.error
        );
        assert!(exec_result.total_changes > 0);

        let file = ctx.test_file("src/config.rs").unwrap();
        let source = file.to_source().unwrap();
        assert!(source.contains("Debug"), "Derive not added: {}", source);
    }

    #[test]
    fn test_wavefront_execution_multi_file() {
        let mut ctx = ContextBuilder::new()
            .with_file("src/lib.rs", "// lib\n")
            .with_file("src/models.rs", "// models\n")
            .build();

        // Add items to different files (can run in parallel)
        let spec1 = MutationSpec::AddItem {
            target: MutationTargetSymbol::ByPath(Box::new(
                SymbolPath::parse("test_crate::models").unwrap(),
            )),
            content: "pub struct User { id: u32 }".to_string(),
            position: super::super::spec::InsertPosition::Bottom,
        };

        let spec2 = MutationSpec::AddItem {
            target: MutationTargetSymbol::ByPath(Box::new(
                SymbolPath::parse("test_crate").unwrap(),
            )),
            content: "fn main() {}".to_string(),
            position: super::super::spec::InsertPosition::Bottom,
        };

        let blueprint = ParallelBlueprint::from_mutations(vec![spec1, spec2]);
        let executor = BlueprintExecutor::new().with_strategy(ExecutionStrategy::Wavefront);
        let exec_result = execute_and_sync(&executor, &blueprint, &mut ctx);

        assert!(
            exec_result.success,
            "Wavefront multi-file failed: {:?}",
            exec_result.error
        );

        let models = ctx.test_file("src/models.rs").unwrap();
        assert!(
            models.to_source().unwrap().contains("pub struct User"),
            "User not added to models.rs"
        );

        let lib = ctx.test_file("src/lib.rs").unwrap();
        assert!(
            lib.to_source().unwrap().contains("fn main"),
            "main not added to lib.rs"
        );
    }

    #[test]
    fn test_wavefront_execution_with_dependencies() {
        let mut ctx = ContextBuilder::new()
            .with_file("src/lib.rs", "fn main() {}\n")
            .build();

        // CreateMod handles both mod declaration and file creation
        let spec = MutationSpec::CreateMod {
            target: MutationTargetSymbol::ByPath(Box::new(
                SymbolPath::parse("test_crate").unwrap(),
            )),
            mod_name: "api".to_string(),
            content: "pub fn endpoint() {}".to_string(),
            is_pub: true,
        };

        let blueprint = ParallelBlueprint::from_mutations(vec![spec]);
        let executor = BlueprintExecutor::new().with_strategy(ExecutionStrategy::Wavefront);
        let exec_result = execute_and_sync(&executor, &blueprint, &mut ctx);

        assert!(
            exec_result.success,
            "Wavefront with deps failed: {:?}",
            exec_result.error
        );

        // Verify dependency order was respected
        let lib = ctx.test_file("src/lib.rs").unwrap();
        assert!(
            lib.to_source().unwrap().contains("pub mod api;"),
            "Mod not added to lib"
        );

        // Check api file (file style: src/api.rs)
        let api = ctx.test_file("src/api.rs").unwrap();
        assert!(
            api.to_source().unwrap().contains("fn endpoint"),
            "Function not in api"
        );
    }

    #[test]
    fn test_suggest_strategy() {
        // Single mutation → Sequential
        let specs = vec![MutationSpec::AddDerive {
            target: MutationTargetSymbol::ById(dummy_id(1)),
            derives: vec!["Debug".to_string()],
        }];
        let blueprint = ParallelBlueprint::from_mutations(specs);
        assert_eq!(suggest_strategy(&blueprint), ExecutionStrategy::Sequential);

        // Two mutations → Sequential (too few)
        let specs = vec![
            MutationSpec::AddDerive {
                target: MutationTargetSymbol::ById(dummy_id(1)),
                derives: vec!["Debug".to_string()],
            },
            MutationSpec::AddDerive {
                target: MutationTargetSymbol::ById(dummy_id(1)),
                derives: vec!["Clone".to_string()],
            },
        ];
        let blueprint = ParallelBlueprint::from_mutations(specs);
        assert_eq!(suggest_strategy(&blueprint), ExecutionStrategy::Sequential);

        // Multiple independent mutations → Wavefront
        let specs = vec![
            MutationSpec::AddDerive {
                target: MutationTargetSymbol::ById(dummy_id(1)),
                derives: vec!["Debug".to_string()],
            },
            MutationSpec::AddDerive {
                target: MutationTargetSymbol::ById(dummy_id(1)),
                derives: vec!["Clone".to_string()],
            },
            MutationSpec::AddDerive {
                target: MutationTargetSymbol::ById(dummy_id(1)),
                derives: vec!["Default".to_string()],
            },
            MutationSpec::AddDerive {
                target: MutationTargetSymbol::ById(dummy_id(1)),
                derives: vec!["Hash".to_string()],
            },
        ];
        let blueprint = ParallelBlueprint::from_mutations(specs);
        assert_eq!(suggest_strategy(&blueprint), ExecutionStrategy::Wavefront);
    }

    #[test]
    #[ignore = "V1 path disabled - needs V2 migration"]
    fn test_sequential_and_wavefront_produce_same_result() {
        let code = r#"
struct A {}
struct B {}
struct C {}
"#;

        let specs = vec![
            MutationSpec::AddDerive {
                target: MutationTargetSymbol::ById(dummy_id(1)),
                derives: vec!["Debug".to_string()],
            },
            MutationSpec::AddDerive {
                target: MutationTargetSymbol::ById(dummy_id(1)),
                derives: vec!["Clone".to_string()],
            },
            MutationSpec::AddDerive {
                target: MutationTargetSymbol::ById(dummy_id(1)),
                derives: vec!["Default".to_string()],
            },
        ];
        let blueprint = ParallelBlueprint::from_mutations(specs.clone());

        // Execute with Sequential
        let mut ctx_seq = ContextBuilder::new().with_file("src/lib.rs", code).build();
        let executor_seq = BlueprintExecutor::new().with_strategy(ExecutionStrategy::Sequential);
        let result_seq = execute_and_sync(&executor_seq, &blueprint, &mut ctx_seq);

        // Execute with Wavefront
        let mut ctx_wave = ContextBuilder::new().with_file("src/lib.rs", code).build();
        let executor_wave = BlueprintExecutor::new().with_strategy(ExecutionStrategy::Wavefront);
        let result_wave = execute_and_sync(&executor_wave, &blueprint, &mut ctx_wave);

        // Both should succeed
        assert!(result_seq.success, "Sequential failed");
        assert!(result_wave.success, "Wavefront failed");

        // Both should produce the same output
        let source_seq = ctx_seq
            .test_file("src/lib.rs")
            .unwrap()
            .to_source()
            .unwrap();
        let source_wave = ctx_wave
            .test_file("src/lib.rs")
            .unwrap()
            .to_source()
            .unwrap();

        assert!(source_seq.contains("Debug"), "Sequential missing Debug");
        assert!(source_seq.contains("Clone"), "Sequential missing Clone");
        assert!(source_seq.contains("Default"), "Sequential missing Default");
        assert!(source_wave.contains("Debug"), "Wavefront missing Debug");
        assert!(source_wave.contains("Clone"), "Wavefront missing Clone");
        assert!(source_wave.contains("Default"), "Wavefront missing Default");
    }

    #[test]
    #[ignore = "flaky: µs-level timing comparison depends on CPU load"]
    fn test_execute_v2_without_sync_is_faster() {
        use ryo_analysis::SymbolKind;
        use std::time::Instant;

        // Create a larger context for more realistic benchmark
        let code = r#"
pub struct Config { name: String, value: i32 }
pub struct User { id: u64, name: String, email: String }
pub struct Order { id: u64, user_id: u64, total: f64 }
pub enum Status { Pending, Active, Completed, Failed }
pub trait Processor { fn process(&self); }
impl Processor for Config { fn process(&self) {} }
impl Processor for User { fn process(&self) {} }
"#;

        // Helper to create specs with resolved symbol_ids
        fn create_specs(ctx: &ryo_analysis::AnalysisContext) -> Vec<MutationSpec> {
            let config_id = ctx
                .registry
                .iter()
                .find(|(id, path)| {
                    path.name() == "Config" && ctx.registry.kind(*id) == Some(SymbolKind::Struct)
                })
                .map(|(id, _)| id)
                .expect("Config not found");

            let user_id = ctx
                .registry
                .iter()
                .find(|(id, path)| {
                    path.name() == "User" && ctx.registry.kind(*id) == Some(SymbolKind::Struct)
                })
                .map(|(id, _)| id)
                .expect("User not found");

            vec![
                MutationSpec::AddField {
                    target: MutationTargetSymbol::ById(config_id),
                    field_name: "enabled".to_string(),
                    field_type: "bool".to_string(),
                    visibility: Visibility::Pub,
                },
                MutationSpec::AddDerive {
                    target: MutationTargetSymbol::ById(user_id),
                    derives: vec!["Debug".to_string(), "Clone".to_string()],
                },
            ]
        }

        // Benchmark execute_v2 only (no sync)
        let iterations = 10;
        let mut execute_only_times = Vec::with_capacity(iterations);

        for _ in 0..iterations {
            let mut ctx = ContextBuilder::new().with_file("src/lib.rs", code).build();
            let specs = create_specs(&ctx);
            let blueprint = ParallelBlueprint::from_mutations(specs);
            let executor = BlueprintExecutor::new();

            let t0 = Instant::now();
            let result = executor.execute_v2(&blueprint, &mut ctx);
            execute_only_times.push(t0.elapsed());

            assert!(result.success);
        }

        // Benchmark execute_v2 + sync
        let mut execute_with_sync_times = Vec::with_capacity(iterations);

        for _ in 0..iterations {
            let mut ctx = ContextBuilder::new().with_file("src/lib.rs", code).build();
            let specs = create_specs(&ctx);
            let blueprint = ParallelBlueprint::from_mutations(specs);
            let executor = BlueprintExecutor::new();

            let t0 = Instant::now();
            let result = executor.execute_v2(&blueprint, &mut ctx);
            BlueprintExecutor::sync_files_and_rebuild(&result, &mut ctx).unwrap();
            execute_with_sync_times.push(t0.elapsed());

            assert!(result.success);
        }

        let avg_execute_only: u128 = execute_only_times
            .iter()
            .map(|d| d.as_micros())
            .sum::<u128>()
            / iterations as u128;
        let avg_with_sync: u128 = execute_with_sync_times
            .iter()
            .map(|d| d.as_micros())
            .sum::<u128>()
            / iterations as u128;

        eprintln!(
            "execute_v2 only: {}µs avg, execute_v2 + sync: {}µs avg, sync overhead: {:.1}x",
            avg_execute_only,
            avg_with_sync,
            avg_with_sync as f64 / avg_execute_only as f64
        );

        // execute_v2 without sync should be faster
        assert!(
            avg_execute_only < avg_with_sync,
            "execute_v2 only ({}µs) should be faster than with sync ({}µs)",
            avg_execute_only,
            avg_with_sync
        );
    }
}