ryo-executor 0.2.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
//! V2 ASTRegApply implementations for trait operations
//!
//! - ExtractTrait: Extract methods from impl block into a new trait
//! - InlineTrait: Inline trait methods back into inherent impl
//!
//! # Implementation Strategy
//!
//! **ExtractTrait:**
//! 1. Find the inherent impl for the struct (impl Foo { ... } where trait_ is None)
//! 2. Extract specified methods (or all if methods is None)
//! 3. Create a new trait definition with method signatures
//! 4. Create a new trait impl (impl TraitName for Foo { ... }) with method bodies
//! 5. Remove the extracted methods from the inherent impl
//!
//! **InlineTrait:**
//! 1. Find the trait impl (impl TraitName for Foo { ... })
//! 2. Find or create the inherent impl (impl Foo { ... })
//! 3. Move methods from trait impl to inherent impl
//! 4. Optionally remove the trait definition and trait impl

use std::collections::HashSet;

use ryo_analysis::{SymbolKind, SymbolRegistry};
use ryo_mutations::basic::{
    EnumToTraitMutation, EnumToTraitStrategy, ExtractTraitMutation, InlineTraitMutation,
    MatchHandling, RemoveTraitMutation,
};
use ryo_mutations::{Mutation, MutationResult};
use ryo_source::pure::{
    MacroDelimiter, PureBlock, PureExpr, PureField, PureFields, PureFn, PureGenericParam,
    PureGenerics, PureImpl, PureImplItem, PureItem, PureParam, PureStmt, PureStruct, PureTrait,
    PureTraitItem, PureType, PureUse, PureUseTree, PureVis,
};
use ryo_symbol::SymbolId;

use crate::engine::{ASTMutationContext, ASTRegApply, ModificationType};

/// Build a `use <path>;` PureItem from a `::`-separated path string.
///
/// `path` is expected to be the fully-qualified path of an importable
/// item (e.g. `"ryo_app::api::Api"`). The trailing segment becomes the
/// name binding; preceding segments become a chain of `Path` nodes.
fn build_use_item_for_path(path: &str) -> PureItem {
    let segments: Vec<&str> = path.split("::").collect();
    let tree = build_use_tree(&segments);
    PureItem::Use(PureUse {
        vis: PureVis::Private,
        tree,
    })
}

/// Rewrite a fully-qualified `<crate>::<module>::<Item>` path to its
/// same-crate `crate::<module>::<Item>` form (used by the R4 caller-side
/// `use` injection so the import resolves regardless of which file in
/// the crate hosts the caller).
fn rewrite_to_local_use_path(full_path: &str) -> String {
    let mut segments = full_path.split("::");
    let _crate_seg = segments.next();
    let mut out = String::from("crate");
    for seg in segments {
        out.push_str("::");
        out.push_str(seg);
    }
    out
}

fn build_use_tree(segments: &[&str]) -> PureUseTree {
    match segments.len() {
        0 => PureUseTree::Name(String::new()),
        1 => PureUseTree::Name(segments[0].to_string()),
        _ => PureUseTree::Path {
            path: segments[0].to_string(),
            tree: Box::new(build_use_tree(&segments[1..])),
        },
    }
}

/// Conservative check: does this `PureType::Path` string mention `Self`
/// **by value** (rather than as `&Self` / `&mut Self`)? Used by the
/// R7 supertrait inference to decide whether `Sized` needs to be added
/// to the extracted trait. We only have the type as an opaque string
/// here, so the heuristic looks for a bare `Self` segment that isn't
/// preceded by `&` (any number of spaces) — covering `Self`, `Self<T>`,
/// `Result<Self, _>`, etc., while still rejecting `&Self` and `&mut Self`.
fn pure_type_mentions_self_by_value(ty_str: &str) -> bool {
    let trimmed = ty_str.trim();
    let mut i = 0;
    let bytes = trimmed.as_bytes();
    while i + 4 <= bytes.len() {
        if &bytes[i..i + 4] == b"Self" {
            // Boundary check: previous byte (if any) must not be alnum/_.
            let prev_ok =
                i == 0 || !matches!(bytes[i - 1], b'A'..=b'Z' | b'a'..=b'z' | b'0'..=b'9' | b'_');
            // Boundary check: next byte (if any) must not be alnum/_.
            let next_ok = i + 4 == bytes.len()
                || !matches!(
                    bytes[i + 4],
                    b'A'..=b'Z' | b'a'..=b'z' | b'0'..=b'9' | b'_'
                );
            if prev_ok && next_ok {
                // Is this a by-reference Self (e.g. `&Self`, `&mut Self`,
                // `&'a Self`)? Look back for an unmatched `&` token that
                // is not closed by another type segment.
                let mut j = i;
                while j > 0 {
                    j -= 1;
                    match bytes[j] {
                        b' ' | b'\t' | b'\'' => continue,
                        b'a'..=b'z' | b'A'..=b'Z' | b'_' | b'0'..=b'9' => {
                            // Consume identifier (likely `mut`); keep walking.
                            while j > 0
                                && matches!(
                                    bytes[j - 1],
                                    b'a'..=b'z' | b'A'..=b'Z' | b'_' | b'0'..=b'9'
                                )
                            {
                                j -= 1;
                            }
                            continue;
                        }
                        b'&' => return false, // `&Self` / `&mut Self`
                        _ => break,
                    }
                }
                return true;
            }
        }
        i += 1;
    }
    false
}

/// Walk up the symbol's path until we land on a `Mod` symbol; returns
/// that module's `SymbolId`. Used to identify the containing file of a
/// caller (we inject the `use` statement at module scope).
fn walk_to_module(symbol_id: SymbolId, registry: &SymbolRegistry) -> Option<SymbolId> {
    let path = registry.path(symbol_id)?;
    let mut current = path.clone();
    while let Some(parent) = current.parent() {
        if let Some(parent_id) = registry.lookup(&parent) {
            if matches!(registry.kind(parent_id), Some(SymbolKind::Mod)) {
                return Some(parent_id);
            }
        }
        current = parent;
    }
    None
}

/// Returns `true` when `tree` already imports `target_path` (either as a
/// direct path, as part of a group, or via a glob over an enclosing
/// module). Used to suppress duplicate `use` injection.
fn use_tree_imports_path(tree: &PureUseTree, target_path: &str) -> bool {
    let target_segments: Vec<&str> = target_path.split("::").collect();
    tree_matches_segments(tree, &target_segments)
}

fn tree_matches_segments(tree: &PureUseTree, target: &[&str]) -> bool {
    match tree {
        PureUseTree::Name(name) => target.last().is_some_and(|t| t == name),
        PureUseTree::Rename { name, .. } => target.last().is_some_and(|t| t == name),
        PureUseTree::Glob => target.len() <= 1,
        PureUseTree::Path { path, tree } => {
            if target.first().is_none_or(|head| head != path) {
                false
            } else {
                tree_matches_segments(tree, &target[1..])
            }
        }
        PureUseTree::Group(children) => children.iter().any(|c| tree_matches_segments(c, target)),
    }
}

impl ASTRegApply for ExtractTraitMutation {
    fn apply_to_registry(&self, ctx: &mut ASTMutationContext) -> MutationResult {
        // Step 1: O(1) lookup for the inherent impl using symbol_id
        let impl_id = self.symbol_id;
        let impl_path = match ctx.symbol_registry.path(impl_id) {
            Some(path) => path.clone(),
            None => {
                return MutationResult {
                    mutation_type: self.mutation_type().to_string(),
                    changes: 0,
                    description: format!("SymbolId {:?} not found in registry", impl_id),
                };
            }
        };

        // Verify it's an impl and get the AST
        let inherent_impl = match ctx.ast_registry.get(impl_id) {
            Some(PureItem::Impl(imp)) => {
                // Verify it's an inherent impl (not a trait impl)
                if imp.trait_.is_some() {
                    return MutationResult {
                        mutation_type: self.mutation_type().to_string(),
                        changes: 0,
                        description: format!(
                            "SymbolId {:?} is a trait impl, not an inherent impl",
                            impl_id
                        ),
                    };
                }
                imp.clone()
            }
            Some(_) => {
                return MutationResult {
                    mutation_type: self.mutation_type().to_string(),
                    changes: 0,
                    description: format!("SymbolId {:?} is not an impl block", impl_id),
                };
            }
            None => {
                return MutationResult {
                    mutation_type: self.mutation_type().to_string(),
                    changes: 0,
                    description: format!("No AST found for SymbolId {:?}", impl_id),
                };
            }
        };

        // Get struct name from the impl's self_ty
        let struct_name = inherent_impl.self_ty.clone();

        // Step 2: Partition methods into extracted vs remaining
        let (extracted_items, remaining_items): (Vec<_>, Vec<_>) =
            inherent_impl.items.into_iter().partition(|item| {
                if let PureImplItem::Fn(f) = item {
                    match &self.methods {
                        Some(methods) => methods.contains(&f.name),
                        None => true, // Extract all methods
                    }
                } else {
                    false // Don't extract non-method items
                }
            });

        if extracted_items.is_empty() {
            return MutationResult {
                mutation_type: self.mutation_type().to_string(),
                changes: 0,
                description: "No methods to extract".to_string(),
            };
        }

        let mut changes = 0;

        // Step 3: Create trait definition with method signatures
        let trait_items: Vec<PureTraitItem> = extracted_items
            .iter()
            .filter_map(|item| {
                if let PureImplItem::Fn(f) = item {
                    // R5(b) edge-case fix: strip the `mut` qualifier off
                    // `mut self` receivers and off `mut <name>` named
                    // parameters when emitting the trait signature.
                    // Rust's grammar rejects either form inside a
                    // body-less fn declaration (it parses the `mut`
                    // binding as a pattern, hence cargo's
                    // `patterns aren't allowed in functions without
                    // bodies`). The body-bearing impl method below
                    // keeps its `mut` exactly as before.
                    let signature_params: Vec<PureParam> = f
                        .params
                        .iter()
                        .map(|p| match p {
                            PureParam::SelfValue { is_ref, .. } => PureParam::SelfValue {
                                is_ref: *is_ref,
                                is_mut: false,
                            },
                            PureParam::Typed { name, ty, pat, .. } => PureParam::Typed {
                                name: name.clone(),
                                ty: ty.clone(),
                                is_mut: false,
                                pat: pat.clone(),
                            },
                        })
                        .collect();
                    // Create trait method signature (empty body for trait definition).
                    //
                    // R14: drop the `const` qualifier when lifting the
                    // signature into the trait. Rust's grammar rejects
                    // `const fn` inside `trait` declarations
                    // ("functions in traits cannot be declared const"),
                    // and the concrete impl below keeps its `const fn`
                    // exactly as before, so the constness still applies
                    // to the call site that goes through the impl. Same
                    // shape as the R5(b) `mut` strip on signature params
                    // — only the trait-side signature gets the
                    // qualifier removed; impl-side behaviour is unchanged.
                    let trait_fn = PureFn {
                        attrs: f.attrs.clone(),
                        vis: PureVis::Private, // Trait methods use default visibility
                        is_async: f.is_async,
                        is_async_inferred: f.is_async_inferred,
                        is_const: false,
                        is_unsafe: f.is_unsafe,
                        abi: None,
                        name: f.name.clone(),
                        generics: f.generics.clone(),
                        params: signature_params,
                        ret: f.ret.clone(),
                        body: PureBlock::default(), // Empty body for trait signature
                    };
                    Some(PureTraitItem::Fn(trait_fn))
                } else {
                    None
                }
            })
            .collect();

        // R7 (Sized bound): when any extracted method's signature mentions
        // `Self` by-value — either as an owned `self` receiver (not `&self`
        // / `&mut self`) or as a `-> Self` return type — the trait
        // implicitly requires `Self: Sized`. Without it cargo rejects the
        // signature with `the size for values of type Self cannot be known
        // at compilation time` because trait `Self` is `?Sized` by default
        // and owned access needs a known size.
        //
        // Add `Sized` as a supertrait whenever the heuristic fires. This
        // is a no-op for any concrete `impl Trait for ConcreteType` whose
        // self type is already `Sized` (i.e. every non-`dyn` newtype the
        // ExtractTrait suggester ever targets).
        let needs_sized = trait_items.iter().any(|item| {
            let PureTraitItem::Fn(f) = item else {
                return false;
            };
            if matches!(&f.ret, Some(PureType::Path(p)) if pure_type_mentions_self_by_value(p)) {
                return true;
            }
            f.params
                .iter()
                .any(|p| matches!(p, PureParam::SelfValue { is_ref: false, .. }))
        });
        let supertraits = if needs_sized {
            vec!["Sized".to_string()]
        } else {
            Vec::new()
        };

        let new_trait = PureTrait {
            attrs: Vec::new(),
            vis: PureVis::Public, // Default to public trait
            is_unsafe: false,
            is_auto: false,
            name: self.trait_name.clone(),
            generics: PureGenerics::default(),
            supertraits,
            items: trait_items,
        };

        // Register the new trait
        let trait_path = match impl_path
            .parent()
            .and_then(|p| p.child(&self.trait_name).ok())
        {
            Some(path) => path,
            None => {
                return MutationResult {
                    mutation_type: self.mutation_type().to_string(),
                    changes: 0,
                    description: format!("Failed to create path for trait '{}'", self.trait_name),
                };
            }
        };

        let trait_item = PureItem::Trait(new_trait);
        if ctx
            .register_with_ast(trait_path.clone(), SymbolKind::Trait, trait_item.clone())
            .is_some()
        {
            // R6: When the parent of `trait_path` is an inline `mod foo { ... }`
            // (as opposed to a file-level module / crate root), the registry
            // generator skips this trait from the top-level symbol iter pass
            // because every "child of an inline module" path is expected to
            // live inside the parent's `PureMod.items` list. `register_with_ast`
            // only updates the `id → PureItem` map without touching the
            // parent's items list, so without this push the new trait
            // declaration never surfaces in the regenerated source —
            // downstream Step 6 then injects `use crate::<inline_mod>::<TraitName>;`
            // into every caller and cargo check fails with
            // `unresolved import 'crate::<inline_mod>::<TraitName>'` (R6
            // fixture Case32 verify diag).
            //
            // For top-level traits (parent = crate root, NOT inline) the
            // symbol iter pass already emits the trait, so we must NOT push
            // it to crate root's PureMod.items — that would create a
            // duplicate `trait <Name>` declaration. Guarded by
            // `is_inline_module(parent_id)` to scope this strictly to the
            // inline-mod case.
            //
            // The trait IMPL (Step 4 below) does an unconditional
            // `get_module_items_mut().push(...)` because impls are always
            // routed through `iter_module_items + file_level_items` filter
            // (line 463-467 of registry_generator.rs takes only Use/Impl),
            // never via the symbol iter pass — so no duplication risk for
            // that side. Traits are handled by the symbol iter pass
            // exclusively, hence the inline-mod guard here.
            if let Some(parent_path) = trait_path.parent() {
                if let Some(parent_id) = ctx.symbol_registry.lookup(&parent_path) {
                    if ctx.ast_registry.is_inline_module(parent_id) {
                        if let Some(parent_items) = ctx.ast_registry.get_module_items_mut(parent_id)
                        {
                            parent_items.push(trait_item);
                        }
                    }
                }
            }
            changes += 1;
        }

        // Step 4: Create trait impl with method bodies
        // Trait impl methods must NOT have visibility qualifiers (pub is inherited from trait)
        // R8: strip `mut` qualifier from impl-side signature params to match
        // the trait-side signature built in Step 3 (R5(b)). Without this the
        // two sides desynchronize and cargo reports `method ... has an
        // incompatible type for trait`. The body is left untouched — only the
        // signature `mut` markers are removed (mirrors Step 3 exactly).
        let trait_impl_items: Vec<PureImplItem> = extracted_items
            .into_iter()
            .map(|item| {
                if let PureImplItem::Fn(mut f) = item {
                    f.vis = PureVis::Private; // Remove pub for trait impl methods
                    f.params = f
                        .params
                        .into_iter()
                        .map(|p| match p {
                            PureParam::SelfValue { is_ref, .. } => PureParam::SelfValue {
                                is_ref,
                                is_mut: false,
                            },
                            PureParam::Typed { name, ty, pat, .. } => PureParam::Typed {
                                name,
                                ty,
                                is_mut: false,
                                pat,
                            },
                        })
                        .collect();
                    PureImplItem::Fn(f)
                } else {
                    item
                }
            })
            .collect();

        // Snapshot the extracted method names before `trait_impl_items` is
        // moved into the trait impl below. Step 6 below uses these names
        // to look up the methods' SymbolIds via `<struct>::<method>` and
        // walk the call graph for caller-side `use` injection.
        let trait_method_names: Vec<String> = trait_impl_items
            .iter()
            .filter_map(|item| {
                if let PureImplItem::Fn(f) = item {
                    Some(f.name.clone())
                } else {
                    None
                }
            })
            .collect();

        let trait_impl = PureImpl {
            attrs: Vec::new(),
            generics: inherent_impl.generics.clone(),
            is_unsafe: false,
            trait_: Some(self.trait_name.clone()),
            self_ty: struct_name.clone(),
            items: trait_impl_items,
        };

        // Register the trait impl
        let trait_impl_name = format!(
            "<impl {} for {}>",
            self.trait_name,
            struct_name
                .replace("::", "_")
                .replace('<', "_")
                .replace('>', "")
        );
        let trait_impl_path = match impl_path
            .parent()
            .and_then(|p| p.child(&trait_impl_name).ok())
        {
            Some(path) => path,
            None => {
                return MutationResult {
                    mutation_type: self.mutation_type().to_string(),
                    changes,
                    description: "Failed to create path for trait impl".to_string(),
                };
            }
        };

        if let Some(_trait_impl_id) = ctx.register_with_ast(
            trait_impl_path,
            SymbolKind::Impl,
            PureItem::Impl(trait_impl.clone()),
        ) {
            // Also add to module_items
            if let Some(parent_path) = impl_path.parent() {
                if let Some(parent_id) = ctx.symbol_registry.lookup(&parent_path) {
                    if let Some(module_items) = ctx.ast_registry.get_module_items_mut(parent_id) {
                        module_items.push(PureItem::Impl(trait_impl));
                    }
                }
            }
            changes += 1;
        }

        // Step 5: Update the inherent impl to remove extracted methods
        if remaining_items.is_empty() {
            // If no methods remain, remove the inherent impl
            ctx.remove_symbol(impl_id);
            changes += 1;
        } else {
            let updated_impl = PureImpl {
                attrs: inherent_impl.attrs,
                generics: inherent_impl.generics,
                is_unsafe: inherent_impl.is_unsafe,
                trait_: None,
                self_ty: struct_name.clone(),
                items: remaining_items,
            };
            ctx.set_ast(impl_id, PureItem::Impl(updated_impl));
            changes += 1;
        }

        // Step 7 (R6 visibility): when the impl's own module is declared
        // private to its parent (e.g. `mod multi;` in
        // `generator/mod.rs`), the trait's fully-qualified path
        // `crate::<parent>::<impl_module>::<TraitName>` is not reachable
        // from other modules — cargo reports
        // `module <impl_module> is private` on every caller's `use`.
        //
        // Re-export the trait through the parent module so the
        // public-facing path
        // `crate::<parent>::<TraitName>` resolves, mirroring the
        // pattern that production code uses when a private
        // implementation module exposes types via the parent
        // (`pub use multi::GeneratedFiles;` etc.). Skip when the impl
        // module is already public, when the lookup chain bottoms out
        // (impl at crate root, parent missing), or when a matching
        // re-export already lives in the parent's items (idempotent
        // ingestion).
        let trait_reexport_parent_id: Option<SymbolId> = (|| {
            let impl_module_path = impl_path.parent()?;
            let impl_module_id = ctx.symbol_registry.lookup(&impl_module_path)?;
            let impl_module_vis = ctx.symbol_registry.visibility(impl_module_id);
            if !matches!(impl_module_vis, Some(ryo_symbol::Visibility::Private)) {
                return None;
            }
            let impl_module_name = impl_module_path.segments().last()?.to_string();
            let parent_path = impl_module_path.parent()?;
            let parent_id = ctx.symbol_registry.lookup(&parent_path)?;
            let reexport_path = format!("{}::{}", impl_module_name, self.trait_name);
            let existing_items = ctx
                .ast_registry
                .get_module_items(parent_id)
                .cloned()
                .unwrap_or_default();
            let already_present = existing_items.iter().any(|item| {
                if let PureItem::Use(u) = item {
                    matches!(u.vis, PureVis::Public)
                        && use_tree_imports_path(&u.tree, &reexport_path)
                } else {
                    false
                }
            });
            if already_present {
                return Some(parent_id);
            }
            let mut reexport_item = build_use_item_for_path(&reexport_path);
            if let PureItem::Use(ref mut u) = reexport_item {
                u.vis = PureVis::Public;
            }
            let mut updated = existing_items;
            updated.insert(0, reexport_item);
            ctx.ast_registry.set_module_items(parent_id, updated);
            ctx.emit_modified(parent_id, ModificationType::BodyModified);
            changes += 1;
            Some(parent_id)
        })();

        // Step 6 (R4 + P3): Inject a trait import into every module that
        // calls one of the extracted methods, so existing `Type::method()`
        // / `instance.method()` sites continue to resolve through the new
        // trait rather than the (now replaced or removed) inherent impl.
        // Same-crate caller modules get `use crate::<module>::<Trait>;`,
        // cross-crate caller modules get the full
        // `use <crate_module>::<module>::<Trait>;` form (P3,
        // CrossCrateExtractTrait).
        //
        // The cross-crate form is sound without any Cargo.toml edit
        // because a caller found via `callers_of` invokes the impl's
        // methods — its crate already depends on the trait's crate. The
        // residual unsound case (a facade re-export consumer without the
        // direct dependency edge) is wholesale-skipped upstream by the
        // suggester's direct-dep guard (pattern_suggest RL061 arm,
        // WorkspaceResolver::depends_on).
        //
        // Requires the optional `code_graph` handle on ASTMutationContext;
        // when it's absent (legacy callers that construct the context
        // without a graph) the step is silently skipped.
        if let Some(code_graph) = ctx.code_graph {
            if let Some(trait_parent_path) = impl_path.parent() {
                if let Ok(struct_path) = trait_parent_path.child(&struct_name) {
                    let trait_crate_name = trait_path.crate_name().to_string();
                    let trait_module_id = ctx.symbol_registry.lookup(&trait_parent_path);

                    // Build the same-crate `use` form: `crate::<module..>::<Trait>`.
                    // `trait_path` is `<crate>::<module>::<Trait>`; we replace
                    // the leading crate segment with `crate` so the import
                    // resolves regardless of which file inside the crate
                    // sees it.
                    //
                    // R6 commit 2: when Step 7 above injected a parent
                    // `pub use <impl_module>::<TraitName>;` re-export
                    // (i.e. the impl module is private and trait
                    // visibility had to be lifted to the parent), use
                    // the parent's `crate::<parent>::<TraitName>` path
                    // instead of `crate::<parent>::<impl_module>::<TraitName>` —
                    // the latter is unreachable through the private
                    // `mod <impl_module>;` and would surface as
                    // `module <impl_module> is private` at cargo check.
                    let trait_local_path = if let Some(parent_id) = trait_reexport_parent_id {
                        if let Some(parent_path) = ctx.symbol_registry.path(parent_id) {
                            rewrite_to_local_use_path(&format!(
                                "{}::{}",
                                parent_path, self.trait_name
                            ))
                        } else {
                            rewrite_to_local_use_path(&trait_path.to_string())
                        }
                    } else {
                        rewrite_to_local_use_path(&trait_path.to_string())
                    };
                    let use_stmt = build_use_item_for_path(&trait_local_path);
                    let trait_full_path_str = trait_path.to_string();

                    // Cross-crate `use` form (P3, CrossCrateExtractTrait):
                    // the full `<crate_module>::<module..>::<Trait>` path,
                    // R6-adjusted the same way as the local form when the
                    // trait was re-exported through a parent module. The
                    // suggester's direct-dep guard has already vetted that
                    // every cross-crate caller's crate declares a
                    // `[dependencies]` edge on the trait's crate, so this
                    // path resolves there.
                    let trait_extern_path = if let Some(parent_id) = trait_reexport_parent_id {
                        if let Some(parent_path) = ctx.symbol_registry.path(parent_id) {
                            format!("{}::{}", parent_path, self.trait_name)
                        } else {
                            trait_full_path_str.clone()
                        }
                    } else {
                        trait_full_path_str.clone()
                    };
                    let extern_use_stmt = build_use_item_for_path(&trait_extern_path);

                    let mut caller_modules: HashSet<SymbolId> = HashSet::new();
                    let mut cross_caller_modules: HashSet<SymbolId> = HashSet::new();
                    for method_name in trait_method_names {
                        let Ok(method_path) = struct_path.child(&method_name) else {
                            continue;
                        };
                        let Some(method_id) = ctx.symbol_registry.lookup(&method_path) else {
                            continue;
                        };
                        for caller_id in code_graph.callers_of(method_id) {
                            let Some(caller_path) = ctx.symbol_registry.path(caller_id) else {
                                continue;
                            };
                            let is_same_crate = caller_path.crate_name() == trait_crate_name;
                            if let Some(parent_mod_id) =
                                walk_to_module(caller_id, ctx.symbol_registry)
                            {
                                if is_same_crate {
                                    caller_modules.insert(parent_mod_id);
                                } else {
                                    cross_caller_modules.insert(parent_mod_id);
                                }
                            }
                        }
                    }

                    // (module set, use path, use item) per injection form:
                    // same-crate modules get the `crate::…` form, cross-
                    // crate modules the full `<crate_module>::…` form.
                    let injections = [
                        (caller_modules, &trait_local_path, &use_stmt),
                        (cross_caller_modules, &trait_extern_path, &extern_use_stmt),
                    ];
                    for (modules, use_path, stmt) in injections {
                        for caller_mod_id in modules {
                            if Some(caller_mod_id) == trait_module_id {
                                // Trait is declared in the same module — already in scope.
                                continue;
                            }
                            let existing_items = ctx
                                .ast_registry
                                .get_module_items(caller_mod_id)
                                .cloned()
                                .unwrap_or_default();
                            // Treat both the injection form and the original
                            // `<crate>::`-prefixed form as "already imported"
                            // so an existing direct path import doesn't get a
                            // duplicate sibling.
                            let already_imported = existing_items.iter().any(|i| {
                                if let PureItem::Use(u) = i {
                                    use_tree_imports_path(&u.tree, use_path)
                                        || use_tree_imports_path(&u.tree, &trait_full_path_str)
                                } else {
                                    false
                                }
                            });
                            if already_imported {
                                continue;
                            }
                            let mut updated = existing_items;
                            updated.insert(0, stmt.clone());
                            ctx.ast_registry.set_module_items(caller_mod_id, updated);
                            ctx.emit_modified(caller_mod_id, ModificationType::BodyModified);
                            changes += 1;
                        }
                    }
                }
            }
        }

        MutationResult {
            mutation_type: self.mutation_type().to_string(),
            changes,
            description: format!(
                "Extracted trait '{}' from '{}'",
                self.trait_name, struct_name
            ),
        }
    }
}

impl ASTRegApply for InlineTraitMutation {
    fn apply_to_registry(&self, ctx: &mut ASTMutationContext) -> MutationResult {
        // Get trait name from symbol_id (O(1) lookup)
        let trait_name = match ctx.symbol_registry.path(self.symbol_id) {
            Some(path) => path.name().to_string(),
            None => {
                return MutationResult {
                    mutation_type: self.mutation_type().to_string(),
                    changes: 0,
                    description: format!("Trait symbol {:?} not found in registry", self.symbol_id),
                };
            }
        };

        // Phase 2d: Cross-crate caller scan (informational only — Phase
        // 2e will turn the result into actual caller-side rewrites).
        // Surfaces the per-caller pattern set so downstream tooling
        // (suggester gate, executor migration engine, human review) can
        // see exactly what shape the cross-crate references take before
        // any rewrite path is wired up. Scanner is read-only on both
        // registries; the subsequent mutation steps proceed unchanged.
        let cross_crate_callers = super::inline_trait_caller_scanner::scan_cross_crate_callers_raw(
            ctx.ast_registry,
            ctx.symbol_registry,
            self.symbol_id,
        );

        // Step 1: Find the trait impl (impl TraitName for Foo)
        let trait_impl_entry = ctx.symbol_registry.iter().find(|(id, _path)| {
            if !matches!(ctx.symbol_registry.kind(*id), Some(SymbolKind::Impl)) {
                return false;
            }
            if let Some(PureItem::Impl(imp)) = ctx.ast_registry.get(*id) {
                imp.trait_.as_ref() == Some(&trait_name) && imp.self_ty == self.struct_name
            } else {
                false
            }
        });

        let (trait_impl_id, trait_impl_path) = match trait_impl_entry {
            Some((id, path)) => (id, path.clone()),
            None => {
                return MutationResult {
                    mutation_type: self.mutation_type().to_string(),
                    changes: 0,
                    description: format!(
                        "No impl of '{}' for '{}' found",
                        trait_name, self.struct_name
                    ),
                };
            }
        };

        let trait_impl = match ctx.ast_registry.get(trait_impl_id) {
            Some(PureItem::Impl(imp)) => imp.clone(),
            _ => {
                return MutationResult {
                    mutation_type: self.mutation_type().to_string(),
                    changes: 0,
                    description: "No AST found for trait impl".to_string(),
                };
            }
        };

        let mut changes = 0;

        // Step 2: Find or identify the inherent impl
        let inherent_impl_entry = ctx.symbol_registry.iter().find(|(id, _path)| {
            if !matches!(ctx.symbol_registry.kind(*id), Some(SymbolKind::Impl)) {
                return false;
            }
            if let Some(PureItem::Impl(imp)) = ctx.ast_registry.get(*id) {
                imp.trait_.is_none() && imp.self_ty == self.struct_name
            } else {
                false
            }
        });

        // Step 3: Move methods to inherent impl
        if let Some((inherent_impl_id, _)) = inherent_impl_entry {
            // Existing inherent impl - add methods to it (both ASTRegistry and module_items)
            if let Some(PureItem::Impl(mut inherent_impl)) =
                ctx.ast_registry.get(inherent_impl_id).cloned()
            {
                inherent_impl.items.extend(trait_impl.items.clone());
                ctx.set_ast(inherent_impl_id, PureItem::Impl(inherent_impl.clone()));

                // Also update in module_items
                if let Some(parent_path) = trait_impl_path.parent() {
                    if let Some(parent_id) = ctx.symbol_registry.lookup(&parent_path) {
                        if let Some(module_items) = ctx.ast_registry.get_module_items_mut(parent_id)
                        {
                            for item in module_items.iter_mut() {
                                if let PureItem::Impl(impl_block) = item {
                                    if impl_block.trait_.is_none()
                                        && impl_block.self_ty == self.struct_name
                                    {
                                        impl_block.items.extend(trait_impl.items.clone());
                                        break;
                                    }
                                }
                            }
                        }
                    }
                }

                changes += 1;
            }
        } else {
            // No inherent impl exists - create one with the trait methods
            let new_inherent_impl = PureImpl {
                attrs: Vec::new(),
                generics: trait_impl.generics.clone(),
                is_unsafe: false,
                trait_: None,
                self_ty: self.struct_name.clone(),
                items: trait_impl.items.clone(),
            };

            let impl_name = format!(
                "<impl {}>",
                self.struct_name
                    .replace("::", "_")
                    .replace('<', "_")
                    .replace('>', "")
            );
            let impl_path = match trait_impl_path
                .parent()
                .and_then(|p| p.child(&impl_name).ok())
            {
                Some(path) => path,
                None => {
                    return MutationResult {
                        mutation_type: self.mutation_type().to_string(),
                        changes: 0,
                        description: "Failed to create path for inherent impl".to_string(),
                    };
                }
            };

            if let Some(_new_impl_id) = ctx.register_with_ast(
                impl_path,
                SymbolKind::Impl,
                PureItem::Impl(new_inherent_impl.clone()),
            ) {
                // Also add to module_items
                if let Some(parent_path) = trait_impl_path.parent() {
                    if let Some(parent_id) = ctx.symbol_registry.lookup(&parent_path) {
                        if let Some(module_items) = ctx.ast_registry.get_module_items_mut(parent_id)
                        {
                            module_items.push(PureItem::Impl(new_inherent_impl));
                        }
                    }
                }
                changes += 1;
            }
        }

        // Step 4: Remove the trait impl
        ctx.remove_symbol(trait_impl_id);
        changes += 1;

        // Step 5: Optionally remove the trait definition (O(1) using symbol_id)
        if self.remove_trait {
            ctx.remove_symbol(self.symbol_id);
            changes += 1;
        }

        let mut description = format!(
            "Inlined trait '{}' into '{}'{}",
            trait_name,
            self.struct_name,
            if self.remove_trait {
                " (trait removed)"
            } else {
                ""
            }
        );

        // Phase 2d/2e caller-side migration footnote: when cross-crate
        // callers reference the inlined trait, count the distribution
        // and (for the Ufcs pattern, which Phase 2e implements) rewrite
        // the caller body in-place from `Trait::method` → `Struct::m`.
        // Other patterns (GenericBound / DynDispatch) still require
        // caller-side rewrites that ship in later sub-phases; their
        // count is reported but not yet rewritten.
        if !cross_crate_callers.is_empty() {
            use ryo_mutations::basic::trait_ops::cross_crate_caller_pattern::{
                rewrite_body_ufcs, rewrite_fn_dyn_dispatch, rewrite_fn_generic_bound, CallerPattern,
            };
            let mut dot = 0usize;
            let mut ufcs = 0usize;
            let mut generic = 0usize;
            let mut dyn_dispatch = 0usize;
            let mut other = 0usize;
            let mut ufcs_paths_rewritten = 0usize;
            let mut dyn_types_rewritten = 0usize;
            let mut generic_edits = 0usize;
            let mut pub_generic_audit_callers: Vec<String> = Vec::new();
            let mut escapes_aborted_callers: Vec<String> = Vec::new();

            for r in &cross_crate_callers {
                for p in &r.patterns {
                    match p {
                        CallerPattern::Dot => dot += 1,
                        CallerPattern::Ufcs => ufcs += 1,
                        CallerPattern::GenericBound => generic += 1,
                        CallerPattern::DynDispatch => dyn_dispatch += 1,
                        CallerPattern::Other => other += 1,
                    }
                }
                // Phase 2e/2f/2g: rewrite in-place for every pattern the
                // executor can mechanically migrate. Dot is no-op
                // (post-inline dispatch unchanged). GenericBound is the
                // most invasive — it strips `T: Trait` generic params
                // and substitutes `T` with the concrete struct type
                // throughout the signature, which changes the caller's
                // external type contract. The transitive caller scanner
                // (Phase 4) must audit downstream call sites before
                // GenericBound rewrites should be considered safe in
                // production workflows.
                // Phase 4-A + 4-B: decide whether each pub
                // GenericBound caller's transitive cascade can leave
                // the current workspace. When `code_graph` is
                // attached (the normal `execute_ast_reg` path), run
                // `walk_transitive_callers` to compute the verdict;
                // an `Escapes` verdict skips the GenericBound rewrite
                // for that caller and records its name. Phase 4-A's
                // audit footnote (caller name list) is kept; Phase
                // 4-B adds the `aborted` list when any verdict came
                // back `Escapes`.
                let mut skip_generic_bound = false;
                if r.patterns.contains(&CallerPattern::GenericBound) && r.is_public {
                    if let Some(p) = ctx.symbol_registry.path(r.caller_id) {
                        pub_generic_audit_callers.push(p.name().to_string());
                    }
                    if let Some(code_graph) = ctx.code_graph {
                        use super::inline_trait_caller_scanner::{
                            walk_transitive_callers, CascadeVerdict,
                        };
                        let verdict =
                            walk_transitive_callers(code_graph, ctx.ast_registry, r.caller_id);
                        if verdict == CascadeVerdict::Escapes {
                            skip_generic_bound = true;
                            if let Some(p) = ctx.symbol_registry.path(r.caller_id) {
                                escapes_aborted_callers.push(p.name().to_string());
                            }
                        }
                    }
                }
                if r.patterns.contains(&CallerPattern::Ufcs)
                    || r.patterns.contains(&CallerPattern::DynDispatch)
                    || r.patterns.contains(&CallerPattern::GenericBound)
                {
                    if let Some(PureItem::Fn(f)) = ctx.ast_registry.get_mut(r.caller_id) {
                        if r.patterns.contains(&CallerPattern::Ufcs) {
                            ufcs_paths_rewritten +=
                                rewrite_body_ufcs(&mut f.body, &trait_name, &self.struct_name);
                        }
                        if r.patterns.contains(&CallerPattern::DynDispatch) {
                            dyn_types_rewritten +=
                                rewrite_fn_dyn_dispatch(f, &trait_name, &self.struct_name);
                        }
                        if r.patterns.contains(&CallerPattern::GenericBound) && !skip_generic_bound
                        {
                            generic_edits +=
                                rewrite_fn_generic_bound(f, &trait_name, &self.struct_name);
                        }
                    }
                }
            }
            changes += ufcs_paths_rewritten + dyn_types_rewritten + generic_edits;
            description.push_str(&format!(
                " [cross-crate callers: {} (dot={} ufcs={} generic={} dyn={} other={}); Phase 2e rewrote {} Ufcs path(s); Phase 2f rewrote {} Dyn type(s); Phase 2g performed {} GenericBound edit(s)]",
                cross_crate_callers.len(),
                dot,
                ufcs,
                generic,
                dyn_dispatch,
                other,
                ufcs_paths_rewritten,
                dyn_types_rewritten,
                generic_edits
            ));
            if !pub_generic_audit_callers.is_empty() {
                description.push_str(&format!(
                    " [Phase 4-A audit: pub GenericBound caller(s) ({}) — transitive cascade verdict pending Phase 4-B walk]",
                    pub_generic_audit_callers.join(", ")
                ));
            }
            if !escapes_aborted_callers.is_empty() {
                description.push_str(&format!(
                    " [Phase 4-B verdict: GenericBound rewrite ABORTED for caller(s) ({}) — transitive cascade Escapes workspace boundary]",
                    escapes_aborted_callers.join(", ")
                ));
            }
        }

        MutationResult {
            mutation_type: self.mutation_type().to_string(),
            changes,
            description,
        }
    }
}

impl ASTRegApply for RemoveTraitMutation {
    fn apply_to_registry(&self, ctx: &mut ASTMutationContext) -> MutationResult {
        // Use the provided SymbolId for O(1) access
        let trait_id = self.trait_id;

        // Verify the trait exists and is a trait
        if ctx.symbol_registry.kind(trait_id) != Some(SymbolKind::Trait) {
            return MutationResult {
                mutation_type: "RemoveTrait".to_string(),
                changes: 0,
                description: format!("Symbol {} is not a trait", trait_id),
            };
        }

        ctx.ast_registry.remove(trait_id);

        MutationResult {
            mutation_type: "RemoveTrait".to_string(),
            changes: 1,
            description: format!("Removed trait {}", trait_id),
        }
    }
}

impl ASTRegApply for EnumToTraitMutation {
    fn apply_to_registry(&self, ctx: &mut ASTMutationContext) -> MutationResult {
        let enum_id = self.symbol_id;

        // Verify the symbol exists and is an enum
        if !matches!(ctx.symbol_registry.kind(enum_id), Some(SymbolKind::Enum)) {
            return MutationResult {
                mutation_type: self.mutation_type().to_string(),
                changes: 0,
                description: format!("Symbol {:?} is not an enum or not found", enum_id),
            };
        }

        let enum_path = match ctx.symbol_registry.path(enum_id) {
            Some(p) => p.clone(),
            None => {
                return MutationResult {
                    mutation_type: self.mutation_type().to_string(),
                    changes: 0,
                    description: format!("Path not found for symbol {:?}", enum_id),
                };
            }
        };

        // Get enum name from path for trait name and usage replacement
        let enum_name = enum_path.name().to_string();

        // Determine trait name:
        // - If user specified trait_name, use it
        // - For MarkerOnly without specified name, use {EnumName}Trait to avoid collision
        // - Otherwise, use enum_name
        let default_trait_name;
        let trait_name = match &self.trait_name {
            Some(name) => name.as_str(),
            None => {
                match self.strategy {
                    EnumToTraitStrategy::MarkerOnly => {
                        // MarkerOnly keeps enum, so trait needs different name
                        default_trait_name = format!("{}Trait", enum_name);
                        &default_trait_name
                    }
                    _ => &enum_name,
                }
            }
        };

        // Get the enum AST
        let enum_def = match ctx.ast_registry.get(enum_id) {
            Some(PureItem::Enum(e)) => e.clone(),
            _ => {
                return MutationResult {
                    mutation_type: self.mutation_type().to_string(),
                    changes: 0,
                    description: format!("No AST found for enum '{}'", enum_name),
                };
            }
        };

        let mut changes = 0;
        let parent_path = match enum_path.parent() {
            Some(p) => p,
            None => {
                return MutationResult {
                    mutation_type: self.mutation_type().to_string(),
                    changes: 0,
                    description: "Cannot determine parent module".to_string(),
                };
            }
        };

        // Collect variant names for usage site replacement
        let variant_names: Vec<String> = enum_def.variants.iter().map(|v| v.name.clone()).collect();

        // Step 1.5: Find enum's inherent impl block and extract methods
        let enum_impl_id: Option<_> = ctx
            .symbol_registry
            .iter()
            .find(|(id, _)| {
                if !matches!(ctx.symbol_registry.kind(*id), Some(SymbolKind::Impl)) {
                    return false;
                }
                if let Some(PureItem::Impl(imp)) = ctx.ast_registry.get(*id) {
                    // Inherent impl: no trait, matches enum name
                    imp.trait_.is_none() && imp.self_ty == enum_name
                } else {
                    false
                }
            })
            .map(|(id, _)| id); // Extract just the SymbolId to end the borrow

        // Extract methods from enum's impl block
        let enum_methods: Vec<PureFn> = if let Some(impl_id) = enum_impl_id {
            if let Some(PureItem::Impl(imp)) = ctx.ast_registry.get(impl_id) {
                imp.items
                    .iter()
                    .filter_map(|item| {
                        if let PureImplItem::Fn(f) = item {
                            // Only extract instance methods (with &self or &mut self)
                            let has_self = f
                                .params
                                .iter()
                                .any(|p| matches!(p, PureParam::SelfValue { .. }));
                            if has_self {
                                Some(f.clone())
                            } else {
                                None
                            }
                        } else {
                            None
                        }
                    })
                    .collect()
            } else {
                Vec::new()
            }
        } else {
            Vec::new()
        };

        // Step 1.6: Remove enum FIRST if trait name equals enum name (to free the path)
        // This must happen before trait registration to avoid path collision
        // MarkerOnly: NEVER remove enum early (types still reference it)
        let enum_removed_early = match self.strategy {
            EnumToTraitStrategy::MarkerOnly => false, // Never remove for MarkerOnly
            _ if self.remove_enum && trait_name == enum_name => {
                ctx.remove_symbol(enum_id);
                changes += 1;
                // Also remove the enum's inherent impl block early
                if let Some(impl_id) = enum_impl_id {
                    ctx.remove_symbol(impl_id);
                    changes += 1;
                }
                true
            }
            _ => false,
        };

        // Step 2: Create trait definition with method signatures
        let trait_items: Vec<PureTraitItem> = enum_methods
            .iter()
            .map(|f| {
                // Create trait method signature (no body for trait definition)
                let trait_fn = PureFn {
                    attrs: Vec::new(),
                    vis: PureVis::Private, // Trait methods use default visibility
                    is_async: f.is_async,
                    is_async_inferred: f.is_async_inferred,
                    is_const: f.is_const,
                    is_unsafe: f.is_unsafe,
                    abi: None,
                    name: f.name.clone(),
                    generics: f.generics.clone(),
                    params: f.params.clone(),
                    ret: f.ret.clone(),
                    body: PureBlock::default(), // Empty body = abstract method in trait
                };
                PureTraitItem::Fn(trait_fn)
            })
            .collect();

        let new_trait = PureTrait {
            attrs: Vec::new(),
            vis: PureVis::Public,
            is_unsafe: false,
            is_auto: false,
            name: trait_name.to_string(),
            generics: PureGenerics::default(),
            supertraits: Vec::new(),
            items: trait_items,
        };

        let trait_path = match parent_path.child(trait_name) {
            Ok(path) => path,
            Err(_) => {
                return MutationResult {
                    mutation_type: self.mutation_type().to_string(),
                    changes: 0,
                    description: format!("Failed to create path for trait '{}'", trait_name),
                };
            }
        };

        if ctx
            .register_with_ast(
                trait_path.clone(),
                SymbolKind::Trait,
                PureItem::Trait(new_trait),
            )
            .is_some()
        {
            changes += 1;
        }

        // Step 3: Create struct + impl for each variant
        for variant in &enum_def.variants {
            // Convert variant fields to struct fields
            let struct_fields = match &variant.fields {
                PureFields::Named(fields) => PureFields::Named(
                    fields
                        .iter()
                        .map(|f| PureField {
                            attrs: Vec::new(),
                            vis: PureVis::Public,
                            name: f.name.clone(),
                            ty: f.ty.clone(),
                        })
                        .collect(),
                ),
                PureFields::Tuple(types) => PureFields::Tuple(types.clone()),
                PureFields::Unit => PureFields::Unit,
            };

            let new_struct = PureStruct {
                attrs: Vec::new(),
                vis: PureVis::Public,
                name: variant.name.clone(),
                generics: PureGenerics::default(),
                fields: struct_fields,
            };

            let struct_path = match parent_path.child(&variant.name) {
                Ok(path) => path,
                Err(_) => continue,
            };

            if ctx
                .register_with_ast(
                    struct_path.clone(),
                    SymbolKind::Struct,
                    PureItem::Struct(new_struct),
                )
                .is_some()
            {
                changes += 1;
            }

            // Create impl Trait for struct with method implementations
            let impl_items: Vec<PureImplItem> = enum_methods
                .iter()
                .map(|f| {
                    // Create method implementation with todo!() body
                    let impl_fn = PureFn {
                        attrs: Vec::new(),
                        vis: PureVis::Private, // Trait impl methods don't have visibility
                        is_async: f.is_async,
                        is_async_inferred: f.is_async_inferred,
                        is_const: f.is_const,
                        is_unsafe: f.is_unsafe,
                        abi: None,
                        name: f.name.clone(),
                        generics: f.generics.clone(),
                        params: f.params.clone(),
                        ret: f.ret.clone(),
                        body: PureBlock {
                            stmts: vec![PureStmt::Expr(PureExpr::Macro {
                                name: "todo".to_string(),
                                delimiter: MacroDelimiter::Paren,
                                tokens: format!("\"{}::{}::{}\"", trait_name, variant.name, f.name),
                            })],
                        },
                    };
                    PureImplItem::Fn(impl_fn)
                })
                .collect();

            let trait_impl = PureImpl {
                attrs: Vec::new(),
                generics: PureGenerics::default(),
                is_unsafe: false,
                trait_: Some(trait_name.to_string()),
                self_ty: variant.name.clone(),
                items: impl_items,
            };

            // NOTE: must use the dedicated trait-impl segment constructor.
            // `parent_path.child("<impl X for Y>")` goes through
            // `Segment::new`, whose identifier validation rejects the
            // space / angle-bracket segment and returned `Err` — silently
            // skipping registration of every variant trait impl (the
            // converted code then fails with "the trait bound `Variant:
            // Trait` is not satisfied" at any coercion site).
            let impl_path = parent_path.child_trait_impl(trait_name, &variant.name);

            if ctx
                .register_with_ast(
                    impl_path,
                    SymbolKind::Impl,
                    PureItem::Impl(trait_impl.clone()),
                )
                .is_some()
            {
                // Also add to module_items. File generation deliberately
                // skips Impl symbols on the ast_registry.iter() path
                // (registry_generator.rs generate_internal) and renders
                // impls ONLY from the parent module's module_items, so a
                // registered-but-not-pushed impl never reaches the output
                // file (same wiring as the ExtractTrait registration above).
                if let Some(parent_id) = ctx.symbol_registry.lookup(&parent_path) {
                    if let Some(module_items) = ctx.ast_registry.get_module_items_mut(parent_id) {
                        module_items.push(PureItem::Impl(trait_impl));
                    }
                }
                changes += 1;
            }
        }

        // Step 4: Replace usage sites (EnumName::VariantName -> VariantName)
        // MarkerOnly: Do NOT replace usage sites - enum remains as the concrete type
        let usage_changes = match self.strategy {
            EnumToTraitStrategy::MarkerOnly => 0, // Keep enum usages as-is
            _ => replace_enum_usages(ctx, &enum_name, &variant_names),
        };
        changes += usage_changes;

        // Step 5: Replace type annotations based on strategy
        // Note: MarkerOnly does NOT replace types - the enum remains as the concrete type
        let type_changes = match self.strategy {
            EnumToTraitStrategy::Dynamic => {
                // Replace `EnumName` with `Box<dyn TraitName>`
                replace_type_annotations(
                    ctx,
                    &enum_name,
                    trait_name,
                    TypeReplacement::BoxDyn,
                    &variant_names,
                )
            }
            EnumToTraitStrategy::Static => {
                // Replace `EnumName` with `impl TraitName` (falls back to Box<dyn> for fields)
                replace_type_annotations(
                    ctx,
                    &enum_name,
                    trait_name,
                    TypeReplacement::ImplTrait,
                    &variant_names,
                )
            }
            EnumToTraitStrategy::Generic => {
                // Replace `EnumName` with generic type parameter, add generics to containers
                replace_type_annotations(
                    ctx,
                    &enum_name,
                    trait_name,
                    TypeReplacement::Generic,
                    &variant_names,
                )
            }
            EnumToTraitStrategy::MarkerOnly => {
                // No type replacement - enum remains as the concrete type
                0
            }
        };
        changes += type_changes;

        // Step 6: Handle match expressions based on match_handling
        let match_changes = match self.match_handling {
            MatchHandling::WarnOnly => {
                // TODO: Emit warnings for match expressions that need manual migration
                // For now, just count them for reporting
                count_match_expressions(ctx, &enum_name)
            }
            MatchHandling::Downcast => {
                // TODO: Convert match to downcast-based dispatch
                // This requires adding Any bound to trait
                0
            }
            MatchHandling::BlockOnMatch => {
                // This should have been checked before execution
                // If we're here, there were no match expressions
                0
            }
        };
        // Note: match_changes is informational, not counted as changes

        // Step 7: Optionally remove the original enum and its inherent impl
        // MarkerOnly strategy: NEVER remove enum (types still reference it)
        // Other strategies: remove if remove_enum is true (skip if already removed in step 1.5)
        let should_remove = match self.strategy {
            EnumToTraitStrategy::MarkerOnly => false, // Never remove for MarkerOnly
            _ => self.remove_enum && !enum_removed_early,
        };
        if should_remove {
            ctx.remove_symbol(enum_id);
            changes += 1;

            // Also remove the enum's inherent impl block
            if let Some(impl_id) = enum_impl_id {
                ctx.remove_symbol(impl_id);
                changes += 1;
            }
        }

        let strategy_desc = match self.strategy {
            EnumToTraitStrategy::Dynamic => " with Box<dyn>",
            EnumToTraitStrategy::Static => " with impl Trait",
            EnumToTraitStrategy::Generic => " with generics",
            EnumToTraitStrategy::MarkerOnly => " (marker only)",
        };

        let match_warning = if match_changes > 0 {
            format!(
                " ({} match expression(s) need manual migration)",
                match_changes
            )
        } else {
            String::new()
        };

        // Track if enum was actually removed (either early or in step 7)
        let enum_actually_removed = enum_removed_early || should_remove;

        MutationResult {
            mutation_type: self.mutation_type().to_string(),
            changes,
            description: format!(
                "Converted enum '{}' to trait '{}' with {} variants{}{}{}",
                enum_name,
                trait_name,
                variant_names.len(),
                strategy_desc,
                if enum_actually_removed {
                    " (enum removed)"
                } else {
                    ""
                },
                match_warning
            ),
        }
    }
}

/// Type replacement strategy
enum TypeReplacement {
    /// Replace with `Box<dyn TraitName>`
    BoxDyn,
    /// Replace with `impl TraitName`
    ImplTrait,
    /// Replace with generic type parameter `T` (requires adding generics to container)
    Generic,
}

/// Replace type annotations in functions, structs, and impl blocks
fn replace_type_annotations(
    ctx: &mut ASTMutationContext,
    enum_name: &str,
    trait_name: &str,
    replacement: TypeReplacement,
    variant_names: &[String],
) -> usize {
    let mut changes = 0;

    // Collect all symbols to iterate
    let symbol_ids: Vec<_> = ctx.symbol_registry.iter().map(|(id, _)| id).collect();

    for symbol_id in symbol_ids {
        let item = match ctx.ast_registry.get(symbol_id) {
            Some(item) => item.clone(),
            None => continue,
        };

        let updated_item = match item {
            PureItem::Fn(mut f) => {
                let fn_changes =
                    replace_types_in_fn(&mut f, enum_name, trait_name, &replacement, variant_names);
                if fn_changes > 0 {
                    changes += fn_changes;
                    Some(PureItem::Fn(f))
                } else {
                    None
                }
            }
            PureItem::Struct(mut s) => {
                // For struct fields, impl Trait is not allowed in Rust
                // Fall back to Box<dyn Trait> for Static strategy (but keep Generic as-is)
                let field_replacement = match replacement {
                    TypeReplacement::ImplTrait => &TypeReplacement::BoxDyn,
                    _ => &replacement,
                };
                let struct_changes = replace_types_in_fields(
                    &mut s.fields,
                    enum_name,
                    trait_name,
                    field_replacement,
                );
                if struct_changes > 0 {
                    // For Generic strategy, add type parameter to struct
                    if matches!(replacement, TypeReplacement::Generic) {
                        add_generic_param(&mut s.generics, trait_name);
                    }
                    changes += struct_changes;
                    Some(PureItem::Struct(s))
                } else {
                    None
                }
            }
            PureItem::Impl(mut imp) => {
                let mut impl_changed = false;
                for item in &mut imp.items {
                    if let PureImplItem::Fn(ref mut f) = item {
                        if replace_types_in_fn(
                            f,
                            enum_name,
                            trait_name,
                            &replacement,
                            variant_names,
                        ) > 0
                        {
                            impl_changed = true;
                        }
                    }
                }
                if impl_changed {
                    changes += 1;
                    Some(PureItem::Impl(imp))
                } else {
                    None
                }
            }
            PureItem::Trait(mut t) => {
                let mut trait_changed = false;
                for item in &mut t.items {
                    if let PureTraitItem::Fn(ref mut f) = item {
                        if replace_types_in_fn(
                            f,
                            enum_name,
                            trait_name,
                            &replacement,
                            variant_names,
                        ) > 0
                        {
                            trait_changed = true;
                        }
                    }
                }
                if trait_changed {
                    changes += 1;
                    Some(PureItem::Trait(t))
                } else {
                    None
                }
            }
            _ => None,
        };

        if let Some(new_item) = updated_item {
            ctx.set_ast(symbol_id, new_item);
        }
    }

    changes
}

/// Replace types in a function signature
fn replace_types_in_fn(
    f: &mut PureFn,
    enum_name: &str,
    trait_name: &str,
    replacement: &TypeReplacement,
    variant_names: &[String],
) -> usize {
    let mut changes = 0;

    // Replace in parameters
    for param in &mut f.params {
        if let PureParam::Typed { ty, .. } = param {
            if replace_type(ty, enum_name, trait_name, replacement) {
                changes += 1;
            }
        }
    }

    // Replace in return type
    let mut ret_replaced = false;
    if let Some(ref mut ret) = f.ret {
        if replace_type(ret, enum_name, trait_name, replacement) {
            ret_replaced = true;
            changes += 1;
        }
    }

    // BoxDyn return-type rewrite changes the fn contract from `-> Enum` to
    // `-> Box<dyn Trait>`, but `replace_enum_usages` (which runs before this
    // pass) has already rewritten body constructions `Enum::Variant` →
    // `Variant` — a bare unit-struct value that no longer typechecks against
    // the boxed return type. Wrap variant constructions in return position
    // with `Box::new(...)` so the coercion to `Box<dyn Trait>` applies.
    if ret_replaced && matches!(replacement, TypeReplacement::BoxDyn) {
        changes += box_variant_returns(&mut f.body, variant_names);
    }

    // For Generic strategy, add type parameter if changes were made
    if changes > 0 && matches!(replacement, TypeReplacement::Generic) {
        add_generic_param(&mut f.generics, trait_name);
    }

    changes
}

/// Wrap variant-construction expressions in return position with `Box::new(...)`.
///
/// Covers two return positions:
/// 1. every `return <expr>` whose inner expr is a direct variant construction
/// 2. the body tail expression (implicit return)
///
/// A "direct variant construction" is a bare path (`Cold`), a tuple-variant
/// call (`Cold(x)`), or a struct-variant literal (`Cold { .. }`) whose name
/// matches one of the converted enum's variants (post-`replace_enum_usages`
/// spelling, i.e. without the `Enum::` prefix).
fn box_variant_returns(body: &mut PureBlock, variant_names: &[String]) -> usize {
    use ryo_mutations::basic::trait_ops::cross_crate_caller_pattern::walk_block_mut;

    let mut changes = 0;

    // `return <variant>` statements anywhere in the body
    walk_block_mut(body, &mut |expr| {
        if let PureExpr::Return(Some(inner)) = expr {
            if is_variant_construction(inner, variant_names) {
                wrap_in_box_new(inner);
                changes += 1;
            }
        }
    });

    // Tail expression (implicit return). A tail `return ...` was already
    // handled above and no longer matches `is_variant_construction`.
    if let Some(PureStmt::Expr(tail)) = body.stmts.last_mut() {
        if is_variant_construction(tail, variant_names) {
            wrap_in_box_new(tail);
            changes += 1;
        }
    }

    changes
}

/// Check if `expr` is a direct construction of one of `variant_names`.
fn is_variant_construction(expr: &PureExpr, variant_names: &[String]) -> bool {
    match expr {
        PureExpr::Path(p) => variant_names.iter().any(|v| v == p),
        PureExpr::Call { func, .. } => {
            matches!(&**func, PureExpr::Path(p) if variant_names.iter().any(|v| v == p))
        }
        PureExpr::Struct { path, .. } => variant_names.iter().any(|v| v == path),
        _ => false,
    }
}

/// Replace `expr` in place with `Box::new(<expr>)`.
fn wrap_in_box_new(expr: &mut PureExpr) {
    let inner = std::mem::replace(expr, PureExpr::Path(String::new()));
    *expr = PureExpr::Call {
        func: Box::new(PureExpr::Path("Box::new".to_string())),
        args: vec![inner],
    };
}

/// Replace types in struct fields
fn replace_types_in_fields(
    fields: &mut PureFields,
    enum_name: &str,
    trait_name: &str,
    replacement: &TypeReplacement,
) -> usize {
    let mut changes = 0;

    match fields {
        PureFields::Named(named_fields) => {
            for field in named_fields {
                if replace_type(&mut field.ty, enum_name, trait_name, replacement) {
                    changes += 1;
                }
            }
        }
        PureFields::Tuple(tuple_fields) => {
            for f in tuple_fields {
                if replace_type(&mut f.ty, enum_name, trait_name, replacement) {
                    changes += 1;
                }
            }
        }
        PureFields::Unit => {}
    }

    changes
}

/// Add generic type parameter `T: TraitName` to generics
fn add_generic_param(generics: &mut PureGenerics, trait_name: &str) {
    // Check if T already exists
    let has_t = generics
        .params
        .iter()
        .any(|p| matches!(p, PureGenericParam::Type { name, .. } if name == "T"));

    if !has_t {
        generics.params.push(PureGenericParam::Type {
            name: "T".to_string(),
            bounds: vec![trait_name.to_string()],
        });
    }
}

/// Replace a type if it matches the enum name
fn replace_type(
    ty: &mut PureType,
    enum_name: &str,
    trait_name: &str,
    replacement: &TypeReplacement,
) -> bool {
    match ty {
        PureType::Path(path) => {
            let type_name = path.split("::").last().unwrap_or(path);

            // Check for exact match (e.g., "Filter")
            if type_name == enum_name || path == enum_name {
                *ty = match replacement {
                    TypeReplacement::BoxDyn => PureType::Path(format!("Box<dyn {}>", trait_name)),
                    TypeReplacement::ImplTrait => PureType::ImplTrait(vec![trait_name.to_string()]),
                    TypeReplacement::Generic => {
                        // Use generic type parameter (caller adds generics to container)
                        PureType::Path("T".to_string())
                    }
                };
                return true;
            }

            // Check for generic types containing the enum (e.g., "Option<Filter>", "Vec<Filter>")
            // Replace enum name within generic arguments
            if path.contains('<') && path.contains(enum_name) {
                let replacement_str = match replacement {
                    TypeReplacement::BoxDyn => format!("Box<dyn {}>", trait_name),
                    TypeReplacement::ImplTrait => format!("impl {}", trait_name),
                    TypeReplacement::Generic => "T".to_string(),
                };

                // Simple replacement: replace "EnumName" with the replacement type
                // This handles cases like Option<Filter> -> Option<Box<dyn Filter>>
                let new_path = replace_type_in_generic_path(path, enum_name, &replacement_str);
                if new_path != *path {
                    *path = new_path;
                    return true;
                }
            }

            false
        }
        PureType::Ref { ty: inner, .. } => replace_type(inner, enum_name, trait_name, replacement),
        PureType::Tuple(types) => {
            let mut changed = false;
            for t in types {
                if replace_type(t, enum_name, trait_name, replacement) {
                    changed = true;
                }
            }
            changed
        }
        PureType::Array { ty: inner, .. } => {
            replace_type(inner, enum_name, trait_name, replacement)
        }
        PureType::Slice(inner) => replace_type(inner, enum_name, trait_name, replacement),
        PureType::Fn { params, ret } => {
            let mut changed = false;
            for p in params {
                if replace_type(p, enum_name, trait_name, replacement) {
                    changed = true;
                }
            }
            if let Some(ref mut r) = ret {
                if replace_type(r, enum_name, trait_name, replacement) {
                    changed = true;
                }
            }
            changed
        }
        _ => false,
    }
}

/// Replace enum type within a generic path string
/// e.g., "Option<Filter>" -> "Option<Box<dyn Filter>>"
fn replace_type_in_generic_path(path: &str, enum_name: &str, replacement: &str) -> String {
    // Find positions where enum_name appears as a type argument
    // We need to be careful to only replace complete type names, not substrings
    let mut result = String::new();
    let chars = path.chars().peekable();
    let mut current_word = String::new();

    for c in chars {
        if c.is_alphanumeric() || c == '_' {
            current_word.push(c);
        } else {
            // Check if current_word matches enum_name
            if current_word == enum_name {
                result.push_str(replacement);
            } else {
                result.push_str(&current_word);
            }
            current_word.clear();
            result.push(c);
        }
    }

    // Handle trailing word
    if current_word == enum_name {
        result.push_str(replacement);
    } else {
        result.push_str(&current_word);
    }

    result
}

/// Count match expressions on the enum (for warning purposes)
fn count_match_expressions(ctx: &ASTMutationContext, enum_name: &str) -> usize {
    let mut count = 0;

    let fn_ids: Vec<_> = ctx
        .symbol_registry
        .iter()
        .filter(|(id, _)| matches!(ctx.symbol_registry.kind(*id), Some(SymbolKind::Function)))
        .map(|(id, _)| id)
        .collect();

    for fn_id in fn_ids {
        if let Some(PureItem::Fn(func)) = ctx.ast_registry.get(fn_id) {
            count += count_matches_in_block(&func.body, enum_name);
        }
    }

    count
}

fn count_matches_in_block(block: &PureBlock, enum_name: &str) -> usize {
    let mut count = 0;
    for stmt in &block.stmts {
        count += count_matches_in_stmt(stmt, enum_name);
    }
    count
}

fn count_matches_in_stmt(stmt: &PureStmt, enum_name: &str) -> usize {
    match stmt {
        PureStmt::Local { init, .. } => {
            if let Some(expr) = init {
                count_matches_in_expr(expr, enum_name)
            } else {
                0
            }
        }
        PureStmt::Semi(expr) | PureStmt::Expr(expr) => count_matches_in_expr(expr, enum_name),
        PureStmt::Item(_) => 0,
        // Verbatim is opaque raw bytes — leaf for trait_ops (B-3-cont).
        PureStmt::Verbatim(_) => 0,
    }
}

fn count_matches_in_expr(expr: &PureExpr, enum_name: &str) -> usize {
    match expr {
        PureExpr::Match {
            expr: scrutinee,
            arms,
        } => {
            let mut count = count_matches_in_expr(scrutinee, enum_name);

            // Check if any arm pattern matches our enum
            for arm in arms {
                if pattern_references_enum(&arm.pattern, enum_name) {
                    count += 1;
                    break; // Count this match once
                }
            }

            // Recurse into arm bodies
            for arm in arms {
                count += count_matches_in_expr(&arm.body, enum_name);
            }
            count
        }
        PureExpr::If {
            cond,
            then_branch,
            else_branch,
        } => {
            let mut count = count_matches_in_expr(cond, enum_name);
            count += count_matches_in_block(then_branch, enum_name);
            if let Some(else_expr) = else_branch {
                count += count_matches_in_expr(else_expr, enum_name);
            }
            count
        }
        PureExpr::Block { block, .. } => count_matches_in_block(block, enum_name),
        PureExpr::Call { func, args, .. } => {
            let mut count = count_matches_in_expr(func, enum_name);
            for arg in args {
                count += count_matches_in_expr(arg, enum_name);
            }
            count
        }
        PureExpr::MethodCall { receiver, args, .. } => {
            let mut count = count_matches_in_expr(receiver, enum_name);
            for arg in args {
                count += count_matches_in_expr(arg, enum_name);
            }
            count
        }
        PureExpr::Closure { body, .. } => count_matches_in_expr(body, enum_name),
        PureExpr::Loop { body: block, .. } => count_matches_in_block(block, enum_name),
        PureExpr::While { cond, body, .. } => {
            count_matches_in_expr(cond, enum_name) + count_matches_in_block(body, enum_name)
        }
        PureExpr::For { expr, body, .. } => {
            count_matches_in_expr(expr, enum_name) + count_matches_in_block(body, enum_name)
        }
        _ => 0,
    }
}

fn pattern_references_enum(pattern: &PurePattern, enum_name: &str) -> bool {
    match pattern {
        PurePattern::Path(path) => path.starts_with(&format!("{}::", enum_name)),
        PurePattern::Struct { path, .. } => path.starts_with(&format!("{}::", enum_name)),
        PurePattern::Tuple(elements) | PurePattern::Slice(elements) => elements
            .iter()
            .any(|p| pattern_references_enum(p, enum_name)),
        PurePattern::Or(patterns) => patterns
            .iter()
            .any(|p| pattern_references_enum(p, enum_name)),
        PurePattern::Ref { pattern: inner, .. } => pattern_references_enum(inner, enum_name),
        _ => false,
    }
}

/// Replace all usages of EnumName::VariantName with VariantName in expressions
fn replace_enum_usages(
    ctx: &mut ASTMutationContext,
    enum_name: &str,
    variant_names: &[String],
) -> usize {
    let mut changes = 0;

    // Collect all function symbols to iterate
    let fn_ids: Vec<_> = ctx
        .symbol_registry
        .iter()
        .filter(|(id, _)| matches!(ctx.symbol_registry.kind(*id), Some(SymbolKind::Function)))
        .map(|(id, _)| id)
        .collect();

    for fn_id in fn_ids {
        if let Some(PureItem::Fn(mut func)) = ctx.ast_registry.get(fn_id).cloned() {
            let fn_changes = replace_in_block(&mut func.body, enum_name, variant_names);
            if fn_changes > 0 {
                ctx.set_ast(fn_id, PureItem::Fn(func));
                changes += fn_changes;
            }
        }
    }

    changes
}

fn replace_in_block(block: &mut PureBlock, enum_name: &str, variant_names: &[String]) -> usize {
    let mut changes = 0;
    for stmt in &mut block.stmts {
        changes += replace_in_stmt(stmt, enum_name, variant_names);
    }
    changes
}

fn replace_in_stmt(stmt: &mut PureStmt, enum_name: &str, variant_names: &[String]) -> usize {
    match stmt {
        PureStmt::Local { init, .. } => {
            if let Some(expr) = init {
                return replace_in_expr(expr, enum_name, variant_names);
            }
            0
        }
        PureStmt::Semi(expr) | PureStmt::Expr(expr) => {
            replace_in_expr(expr, enum_name, variant_names)
        }
        PureStmt::Item(_) => 0,
        // Verbatim is opaque raw bytes — leaf for trait_ops (B-3-cont).
        PureStmt::Verbatim(_) => 0,
    }
}

fn replace_in_expr(expr: &mut PureExpr, enum_name: &str, variant_names: &[String]) -> usize {
    match expr {
        // Check for path expressions like Status::Running
        PureExpr::Path(path) => {
            // Check if path matches EnumName::VariantName pattern
            if path.starts_with(&format!("{}::", enum_name)) {
                let variant_part = path.strip_prefix(&format!("{}::", enum_name));
                if let Some(variant) = variant_part {
                    if variant_names.contains(&variant.to_string()) {
                        // Replace EnumName::VariantName with VariantName
                        *path = variant.to_string();
                        return 1;
                    }
                }
            }
            0
        }

        // Recurse into compound expressions
        PureExpr::Call { func, args, .. } => {
            let mut changes = replace_in_expr(func, enum_name, variant_names);
            for arg in args {
                changes += replace_in_expr(arg, enum_name, variant_names);
            }
            changes
        }
        PureExpr::MethodCall { receiver, args, .. } => {
            let mut changes = replace_in_expr(receiver, enum_name, variant_names);
            for arg in args {
                changes += replace_in_expr(arg, enum_name, variant_names);
            }
            changes
        }
        PureExpr::Binary { left, right, .. } => {
            replace_in_expr(left, enum_name, variant_names)
                + replace_in_expr(right, enum_name, variant_names)
        }
        PureExpr::Unary { expr, .. } => replace_in_expr(expr, enum_name, variant_names),
        PureExpr::If {
            cond,
            then_branch,
            else_branch,
        } => {
            let mut changes = replace_in_expr(cond, enum_name, variant_names);
            changes += replace_in_block(then_branch, enum_name, variant_names);
            if let Some(else_expr) = else_branch {
                changes += replace_in_expr(else_expr, enum_name, variant_names);
            }
            changes
        }
        PureExpr::Match { expr, arms } => {
            let mut changes = replace_in_expr(expr, enum_name, variant_names);
            for arm in arms {
                // Replace in pattern (match arms may have Status::Running patterns)
                changes += replace_in_pattern(&mut arm.pattern, enum_name, variant_names);
                changes += replace_in_expr(&mut arm.body, enum_name, variant_names);
            }
            changes
        }
        PureExpr::Block { block, .. } => replace_in_block(block, enum_name, variant_names),
        PureExpr::Return(Some(v)) => replace_in_expr(v, enum_name, variant_names),
        PureExpr::Return(None) => 0,
        PureExpr::Struct { fields, .. } => {
            let mut changes = 0;
            for (_, field_expr) in fields {
                changes += replace_in_expr(field_expr, enum_name, variant_names);
            }
            changes
        }
        PureExpr::Tuple(elements) => {
            let mut changes = 0;
            for elem in elements {
                changes += replace_in_expr(elem, enum_name, variant_names);
            }
            changes
        }
        PureExpr::Array(elements) => {
            let mut changes = 0;
            for elem in elements {
                changes += replace_in_expr(elem, enum_name, variant_names);
            }
            changes
        }
        PureExpr::Index { expr, index, .. } => {
            replace_in_expr(expr, enum_name, variant_names)
                + replace_in_expr(index, enum_name, variant_names)
        }
        PureExpr::Field { expr, .. } => replace_in_expr(expr, enum_name, variant_names),
        PureExpr::Ref { expr, .. } => replace_in_expr(expr, enum_name, variant_names),
        PureExpr::Try(inner) => replace_in_expr(inner, enum_name, variant_names),
        PureExpr::Await(inner) => replace_in_expr(inner, enum_name, variant_names),
        PureExpr::Closure { body, .. } => replace_in_expr(body, enum_name, variant_names),
        PureExpr::Loop { body, .. } => replace_in_block(body, enum_name, variant_names),
        PureExpr::While { cond, body, .. } => {
            replace_in_expr(cond, enum_name, variant_names)
                + replace_in_block(body, enum_name, variant_names)
        }
        PureExpr::For { expr, body, .. } => {
            replace_in_expr(expr, enum_name, variant_names)
                + replace_in_block(body, enum_name, variant_names)
        }
        PureExpr::Let { expr, .. } => replace_in_expr(expr, enum_name, variant_names),
        PureExpr::Range { start, end, .. } => {
            let mut changes = 0;
            if let Some(s) = start {
                changes += replace_in_expr(s, enum_name, variant_names);
            }
            if let Some(e) = end {
                changes += replace_in_expr(e, enum_name, variant_names);
            }
            changes
        }
        PureExpr::Cast { expr, .. } => replace_in_expr(expr, enum_name, variant_names),
        // Literals, macros, and other expressions without sub-expressions
        _ => 0,
    }
}

use ryo_source::pure::PurePattern;

fn replace_in_pattern(
    pattern: &mut PurePattern,
    enum_name: &str,
    variant_names: &[String],
) -> usize {
    match pattern {
        // Struct pattern: `Status::Running { .. }` or `Status::Running`
        PurePattern::Struct { path, fields, .. } => {
            let mut changes = 0;
            if path.starts_with(&format!("{}::", enum_name)) {
                if let Some(variant) = path.strip_prefix(&format!("{}::", enum_name)) {
                    let base_variant = variant
                        .split(|c: char| !c.is_alphanumeric() && c != '_')
                        .next()
                        .unwrap_or(variant);
                    if variant_names.contains(&base_variant.to_string()) {
                        *path = variant.to_string();
                        changes += 1;
                    }
                }
            }
            // Recurse into field patterns
            for (_, field_pattern) in fields {
                changes += replace_in_pattern(field_pattern, enum_name, variant_names);
            }
            changes
        }
        // Tuple pattern: recurse into elements
        PurePattern::Tuple(elements) | PurePattern::Slice(elements) => {
            let mut changes = 0;
            for elem in elements {
                changes += replace_in_pattern(elem, enum_name, variant_names);
            }
            changes
        }
        // Path pattern: simple enum variant like `Status::Running`
        PurePattern::Path(path) => {
            if path.starts_with(&format!("{}::", enum_name)) {
                if let Some(variant) = path.strip_prefix(&format!("{}::", enum_name)) {
                    if variant_names.contains(&variant.to_string()) {
                        *path = variant.to_string();
                        return 1;
                    }
                }
            }
            0
        }
        // Reference pattern: recurse
        PurePattern::Ref { pattern: inner, .. } => {
            replace_in_pattern(inner, enum_name, variant_names)
        }
        // Or pattern: multiple alternatives
        PurePattern::Or(patterns) => {
            let mut changes = 0;
            for p in patterns {
                changes += replace_in_pattern(p, enum_name, variant_names);
            }
            changes
        }
        // Other patterns don't need replacement
        _ => 0,
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::engine::ASTMutationEngine;
    use ryo_analysis::testing::ContextBuilder;

    #[test]
    fn test_v2_extract_trait() {
        let mut ctx = ContextBuilder::new()
            .with_file(
                "src/lib.rs",
                r#"
struct Foo {
    value: i32,
}

impl Foo {
    fn get_value(&self) -> i32 {
        self.value
    }

    fn set_value(&mut self, v: i32) {
        self.value = v;
    }

    fn helper(&self) {}
}
"#,
            )
            .build();

        // Find the inherent impl's SymbolId
        let impl_id = ctx
            .registry
            .iter()
            .find(|(id, _path)| {
                if !matches!(ctx.registry.kind(*id), Some(SymbolKind::Impl)) {
                    return false;
                }
                if let Some(PureItem::Impl(imp)) = ctx.ast_registry.get(*id) {
                    imp.trait_.is_none() && imp.self_ty == "Foo"
                } else {
                    false
                }
            })
            .map(|(id, _)| id)
            .expect("Should find impl Foo");

        let mutation = ExtractTraitMutation::new(impl_id, "ValueAccessor")
            .with_methods(vec!["get_value".to_string(), "set_value".to_string()]);
        let result = ASTMutationEngine::execute_ast_reg(&mutation, &mut ctx);

        println!("ExtractTrait result: {:?}", result.result);
        // Should create trait + trait impl + update inherent impl
        assert!(result.result.changes >= 2, "Expected at least 2 changes");
    }

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

trait Greet {
    fn greet(&self) -> String;
}

impl Greet for Foo {
    fn greet(&self) -> String {
        "Hello".to_string()
    }
}
"#,
            )
            .build();

        // Find the trait's SymbolId
        let trait_id = ctx
            .registry
            .iter()
            .find(|(id, _path)| matches!(ctx.registry.kind(*id), Some(SymbolKind::Trait)))
            .map(|(id, _)| id)
            .expect("Should find trait Greet");

        let mutation = InlineTraitMutation::new(trait_id, "Foo");
        let result = ASTMutationEngine::execute_ast_reg(&mutation, &mut ctx);

        println!("InlineTrait result: {:?}", result.result);
        // Should move method to inherent impl + remove trait impl + remove trait
        assert!(result.result.changes >= 2, "Expected at least 2 changes");

        // Phase 2d false-positive gate: single-crate fixture has no
        // cross-crate callers, so the description must NOT carry the
        // `[cross-crate callers: ...]` footnote.
        assert!(
            !result.result.description.contains("cross-crate callers"),
            "single-crate inline must not emit cross-crate footnote; got: {}",
            result.result.description
        );
    }

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

trait Greet {
    fn greet(&self) -> String;
}

impl Greet for Foo {
    fn greet(&self) -> String {
        "Hello".to_string()
    }
}
"#,
            )
            .build();

        // Find the trait's SymbolId
        let trait_id = ctx
            .registry
            .iter()
            .find(|(id, _path)| matches!(ctx.registry.kind(*id), Some(SymbolKind::Trait)))
            .map(|(id, _)| id)
            .expect("Should find trait Greet");

        let mutation = InlineTraitMutation::new(trait_id, "Foo").keep_trait();
        let result = ASTMutationEngine::execute_ast_reg(&mutation, &mut ctx);

        println!("InlineTrait (keep_trait) result: {:?}", result.result);
        // Should move method + remove trait impl, but keep trait definition
        assert!(result.result.changes >= 2, "Expected at least 2 changes");
    }

    #[test]
    fn test_v2_enum_to_trait_dynamic_strategy() {
        let mut ctx = ContextBuilder::new()
            .with_file(
                "src/lib.rs",
                r#"
enum Status {
    Running,
    Stopped,
}

fn process(status: Status) -> Status {
    status
}

struct Config {
    current_status: Status,
}
"#,
            )
            .build();

        // Find the enum symbol id
        let enum_id = ctx
            .registry
            .iter()
            .find(|(id, path)| {
                path.name() == "Status" && matches!(ctx.registry.kind(*id), Some(SymbolKind::Enum))
            })
            .map(|(id, _)| id)
            .expect("Enum 'Status' should exist");

        let mutation = EnumToTraitMutation::from_symbol_id(enum_id)
            .with_strategy(EnumToTraitStrategy::Dynamic);
        let result = ASTMutationEngine::execute_ast_reg(&mutation, &mut ctx);

        println!("EnumToTrait (Dynamic) result: {:?}", result.result);
        // Should create: trait, 2 structs, 2 impls, type replacements, enum removal
        assert!(result.result.changes >= 5, "Expected at least 5 changes");
        assert!(
            result.result.description.contains("Box<dyn>"),
            "Should mention Box<dyn> strategy"
        );
    }

    #[test]
    fn test_v2_enum_to_trait_static_strategy() {
        let mut ctx = ContextBuilder::new()
            .with_file(
                "src/lib.rs",
                r#"
enum Filter {
    Active,
    Inactive,
}

fn apply_filter(filter: Filter) {
    let _ = filter;
}
"#,
            )
            .build();

        // Find the enum symbol id
        let enum_id = ctx
            .registry
            .iter()
            .find(|(id, path)| {
                path.name() == "Filter" && matches!(ctx.registry.kind(*id), Some(SymbolKind::Enum))
            })
            .map(|(id, _)| id)
            .expect("Enum 'Filter' should exist");

        let mutation =
            EnumToTraitMutation::from_symbol_id(enum_id).with_strategy(EnumToTraitStrategy::Static);
        let result = ASTMutationEngine::execute_ast_reg(&mutation, &mut ctx);

        println!("EnumToTrait (Static) result: {:?}", result.result);
        // Should create: trait, 2 structs, 2 impls, type replacements, enum removal
        assert!(result.result.changes >= 5, "Expected at least 5 changes");
        assert!(
            result.result.description.contains("impl Trait"),
            "Should mention impl Trait strategy"
        );
    }

    #[test]
    fn test_v2_enum_to_trait_marker_only_strategy() {
        let mut ctx = ContextBuilder::new()
            .with_file(
                "src/lib.rs",
                r#"
enum Mode {
    Fast,
    Slow,
}

fn get_mode() -> Mode {
    Mode::Fast
}
"#,
            )
            .build();

        // Find the enum symbol id
        let enum_id = ctx
            .registry
            .iter()
            .find(|(id, path)| {
                path.name() == "Mode" && matches!(ctx.registry.kind(*id), Some(SymbolKind::Enum))
            })
            .map(|(id, _)| id)
            .expect("Enum 'Mode' should exist");

        let mutation = EnumToTraitMutation::from_symbol_id(enum_id)
            .with_strategy(EnumToTraitStrategy::MarkerOnly);
        let result = ASTMutationEngine::execute_ast_reg(&mutation, &mut ctx);

        println!("EnumToTrait (MarkerOnly) result: {:?}", result.result);
        // Should create: trait, 2 structs, 2 impls, enum removal
        // But no type replacements
        assert!(result.result.changes >= 5, "Expected at least 5 changes");
        assert!(
            result.result.description.contains("marker only"),
            "Should mention marker only strategy"
        );
    }

    #[test]
    fn test_v2_enum_to_trait_generic_strategy() {
        let mut ctx = ContextBuilder::new()
            .with_file(
                "src/lib.rs",
                r#"
enum Status {
    Running,
    Stopped,
}

fn process(status: Status) -> Status {
    status
}

struct Config {
    current_status: Status,
}
"#,
            )
            .build();

        // Find the enum symbol id
        let enum_id = ctx
            .registry
            .iter()
            .find(|(id, path)| {
                path.name() == "Status" && matches!(ctx.registry.kind(*id), Some(SymbolKind::Enum))
            })
            .map(|(id, _)| id)
            .expect("Enum 'Status' should exist");

        let mutation = EnumToTraitMutation::from_symbol_id(enum_id)
            .with_strategy(EnumToTraitStrategy::Generic);
        let result = ASTMutationEngine::execute_ast_reg(&mutation, &mut ctx);

        println!("EnumToTrait (Generic) result: {:?}", result.result);
        // Should create: trait, 2 structs, 2 impls, type replacements with generics, enum removal
        assert!(result.result.changes >= 5, "Expected at least 5 changes");
        assert!(
            result.result.description.contains("generics"),
            "Should mention generics strategy"
        );
    }

    /// RL070 sweep Case06 regression: variant trait impls must be
    /// registered (and survive into the registry) when the enum has an
    /// inherent impl with instance methods. Origin: `parent_path.child(
    /// "<impl X for Y>")` was rejected by `Segment::new` validation and
    /// silently skipped via `Err(_) => continue`, so the converted code
    /// failed with "the trait bound `Variant: Trait` is not satisfied"
    /// at any `Box::new(variant)` coercion site.
    #[test]
    fn test_v2_enum_to_trait_registers_variant_trait_impls() {
        let mut ctx = ContextBuilder::new()
            .with_file(
                "src/lib.rs",
                r#"
enum Status {
    Idle,
    Running,
    Stopped,
    Failed,
}

impl Status {
    fn code(&self) -> u8 {
        0
    }
}

fn make() -> Status {
    Status::Idle
}
"#,
            )
            .build();

        let enum_id = ctx
            .registry
            .iter()
            .find(|(id, path)| {
                path.name() == "Status" && matches!(ctx.registry.kind(*id), Some(SymbolKind::Enum))
            })
            .map(|(id, _)| id)
            .expect("Enum 'Status' should exist");

        let mutation = EnumToTraitMutation::from_symbol_id(enum_id)
            .with_strategy(EnumToTraitStrategy::Dynamic);
        let result = ASTMutationEngine::execute_ast_reg(&mutation, &mut ctx);
        println!(
            "EnumToTrait (Dynamic, with impl) result: {:?}",
            result.result
        );

        // Dump the post-mutation registry for observation
        let mut impl_paths: Vec<String> = Vec::new();
        for (id, path) in ctx.registry.iter() {
            if matches!(ctx.registry.kind(id), Some(SymbolKind::Impl)) {
                impl_paths.push(path.to_string());
            }
        }
        println!("post-mutation Impl symbols: {:?}", impl_paths);

        for variant in ["Idle", "Running", "Stopped", "Failed"] {
            let expected = format!("<impl Status for {}>", variant);
            assert!(
                impl_paths.iter().any(|p| p.contains(&expected)),
                "missing variant trait impl symbol: {} (got {:?})",
                expected,
                impl_paths
            );
        }
    }
}