ryo-app 0.1.0

[preview] Application layer for RYO - Project management, Intent handling, API
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
//! Planner: Goal → Vec<MutationSpec> 変換
//!
//! IntentをMutationSpecに変換し、実行計画を生成する。
//!
//! ```text
//! Goal (Intent + Scope + Constraints)
//!     ↓ Planner::plan()
//! Vec<MutationSpec>
//!     ↓ ParallelBlueprint::from_mutations()
//! ParallelBlueprint
//!     ↓ BlueprintExecutor::execute()
//! BlueprintResult
//! ```
//!
//! # 複数Intent対応
//!
//! 複数Intentsを受け取り、全てのMutationSpecを生成する。
//! 独立したIntentsは並列実行され、マイクロ秒オーダーで完了する。
//!
//! ## Intent順序と並列実行
//!
//! **設計原則**: Intent順序はユーザー指定を尊重し、Plannerは変更しない。
//!
//! 並列実行の最適化はMutationSpec以降で行われる:
//!
//! ```text
//! Intent[0, 1, 2, 3] (ユーザー指定順序)
//!     ↓ Planner::plan() - 順序維持
//! MutationSpec[0, 1, 2, 3]
//!     ↓ ParallelBlueprint - ItemRefベースの依存解析
//! DependencyGraph + Conflict検出
//!     ↓ topological_levels() - Waveに分割
//! Wave実行: 同じItemRef → 順序維持、異なるItemRef → 並列化
//! ```
//!
//! **例**: `0[User.email], 1[User.email], 2[Order.id], 3[Product.name]`
//! - Wave 0: [0]
//! - Wave 1: [1]
//! - Wave 2: [2, 3] ← 並列実行
//!
//! 詳細は以下を参照:
//! - `ryo-executor::executor::spec` - ItemRef定義、MutationSpec
//! - `ryo-executor::executor::blueprint` - DependencyGraph、Conflict検出
//! - `ryo-executor::executor::blueprint_executor` - Wavefront実行戦略

use crate::intent::{
    Goal, Intent, ItemKind, SelfParam as IntentSelfParam, SpecRelation as IntentSpecRelation,
    SpecRelationKind as IntentSpecRelationKind, StmtInsertPosition as IntentStmtPosition,
    Visibility,
};
use ryo_analysis::{SymbolKind, SymbolPath, SymbolRegistry};
use ryo_executor::{
    InsertPosition, MutationSpec, MutationTargetSymbol, SelfParam, SpecRelation, SpecRelationKind,
    StmtInsertPosition, VariantKind,
};
use ryo_symbol::SymbolId;
use std::collections::HashSet;

/// Planning error
#[derive(Debug, thiserror::Error)]
pub enum PlanError {
    #[error("Unsupported intent: {0}")]
    UnsupportedIntent(String),

    #[error("Invalid pattern: {0}")]
    InvalidPattern(String),

    #[error("Missing required field: {0}")]
    MissingField(String),

    #[error("Invalid target '{target}': {reason}")]
    InvalidTarget { target: String, reason: String },

    #[error("Symbol not found: {name} (kind: {kind:?})")]
    SymbolNotFound {
        name: String,
        kind: Option<SymbolKind>,
    },

    #[error("Duplicate symbol: {name} (kind: {kind:?}, found {count} matches)")]
    DuplicateSymbol {
        name: String,
        kind: Option<SymbolKind>,
        count: usize,
    },

    #[error("SymbolRegistry not available to resolve '{target}'")]
    RegistryNotAvailable { target: String },

    #[error(
        "Cannot resolve target for '{intent}'.\n\n\
        Resolution requires one of:\n\
        1. symbol_id   (recommended): \"symbol_id\": \"42v1\"\n\
           → Use 'ryo discover' to find valid IDs\n\
        2. symbol_path (canonical):   \"symbol_path\": \"my_crate::module::Type\"\n\
           → Requires full path: crate_name::module::item\n\
           → NG: \"main\", \"crate::xxx\", \"self::xxx\"\n\
        3. target_xxx  (name only):   \"target_type\": \"MyStruct\"\n\
           → Must be unique in workspace\n\n\
        Tip: symbol_id is most reliable. Run:\n\
          ryo discover \"Pattern*\" --format json\n\
        to get symbol IDs for targeting."
    )]
    CannotResolve { intent: String },

    #[error(
        "Missing target module for '{intent}'.\n\n\
        This intent requires 'symbol_path' to specify where to add the item.\n\n\
        Valid symbol_path formats:\n\\"my_crate\"                 (crate root / lib.rs)\n\\"my_crate::module\"         (submodule)\n\\"main::my_app\"             (binary crate root / main.rs)\n\\"main::my_app::module\"     (binary crate submodule)\n\n\
        Invalid formats:\n\\"main\"                     (main:: requires crate name)\n\\"crate::xxx\"               (use actual crate name)\n\\"self::xxx\", \"super::xxx\"  (context-dependent)\n\n\
        Example:\n\
        {{\n\
          \"type\": \"{intent}\",\n\
          \"symbol_path\": \"my_crate::domain\",\n\
          ...\n\
        }}"
    )]
    MissingTargetModule { intent: String },

    #[error("Invalid module path: {message}")]
    InvalidModulePath { message: String },

    #[error("SymbolRegistry required: {message}")]
    RegistryRequired { message: String },

    #[error("Unknown crate '{crate_name}' in path '{path}'. Known crates: {known_crates}")]
    UnknownCrate {
        path: String,
        crate_name: String,
        known_crates: String,
    },
}

pub type PlanResult<T> = Result<T, PlanError>;

/// Planner: Goal → Vec<MutationSpec>
pub struct Planner;

impl Planner {
    /// Plan mutations from a Goal (supports multiple intents)
    ///
    /// # Arguments
    /// * `goal` - The goal containing intents to plan
    /// * `registry` - Optional SymbolRegistry for resolving Pattern::Direct to SymbolPath
    ///
    /// # Note
    /// - Duplicate CreateMod specs are automatically deduplicated to prevent conflicts
    ///   when multiple AddCode intents target nested modules.
    /// - Batch intent deferred resolution: When AddItem creates a symbol that is
    ///   referenced by a later intent (e.g., AddDerive), the symbol_id is set to None
    ///   and resolution is deferred to execution time.
    pub fn plan(goal: &Goal, registry: Option<&SymbolRegistry>) -> PlanResult<Vec<MutationSpec>> {
        // Pre-scan AddItem intents to collect pending symbol names
        let pending_symbols = Self::collect_pending_symbols(&goal.intents);

        let mut all_specs = Vec::new();
        for intent in &goal.intents {
            let specs = Self::intent_to_specs(intent, registry, &pending_symbols)?;
            all_specs.extend(specs);
        }
        // Deduplicate CreateMod specs to prevent conflicts
        Ok(Self::deduplicate_create_mods(all_specs))
    }

    /// Collect symbol names that will be created by AddItem intents.
    /// Used for deferred resolution in batch intents.
    fn collect_pending_symbols(intents: &[Intent]) -> HashSet<String> {
        let mut pending = HashSet::new();
        for intent in intents {
            if let Intent::AddItem { content, .. } = intent {
                if let Some(name) = extract_item_name_from_content(content) {
                    pending.insert(name);
                }
            }
        }
        pending
    }

    /// Remove duplicate CreateMod specs (same parent + mod_name)
    ///
    /// When multiple AddCode intents target nested modules, they may generate
    /// overlapping CreateMod specs. This function keeps only the first occurrence.
    fn deduplicate_create_mods(specs: Vec<MutationSpec>) -> Vec<MutationSpec> {
        use std::collections::HashSet;

        let mut seen_create_mods: HashSet<(String, String)> = HashSet::new();
        let mut result = Vec::with_capacity(specs.len());

        for spec in specs {
            match &spec {
                MutationSpec::CreateMod {
                    target, mod_name, ..
                } => {
                    let key = (format!("{:?}", target), mod_name.clone());
                    if seen_create_mods.insert(key) {
                        // First occurrence - keep it
                        result.push(spec);
                    }
                    // Duplicate - skip it
                }
                _ => {
                    // Non-CreateMod specs are always kept
                    result.push(spec);
                }
            }
        }

        result
    }

    /// Convert Intent to MutationSpec(s)
    ///
    /// The `pending_symbols` set contains names of symbols that will be created
    /// by AddItem intents earlier in the batch. When resolving fails for a name
    /// in this set, `symbol_id` is set to `None` for deferred resolution at execution time.
    fn intent_to_specs(
        intent: &Intent,
        registry: Option<&SymbolRegistry>,
        pending_symbols: &HashSet<String>,
    ) -> PlanResult<Vec<MutationSpec>> {
        match intent {
            // === 識別子リネーム系 ===
            Intent::RenameIdent {
                symbol_id,
                symbol_path,
                target_ident,
                to,
                ..
            } => {
                let resolved_id = resolve_from_3fields(
                    registry,
                    symbol_id.as_deref(),
                    symbol_path.as_deref(),
                    target_ident.as_deref(),
                    "RenameIdent",
                )?;

                Ok(vec![MutationSpec::Rename {
                    target: MutationTargetSymbol::ById(resolved_id),
                    to: to.clone(),
                    scope: ryo_executor::Scope::default(),
                }])
            }

            // === 構造変更系 ===
            Intent::ChangeVisibility {
                symbol_id,
                symbol_path,
                target_item,
                to,
            } => {
                let resolved_id = resolve_from_3fields(
                    registry,
                    symbol_id.as_deref(),
                    symbol_path.as_deref(),
                    target_item.as_deref(),
                    "ChangeVisibility",
                )?;
                Ok(vec![MutationSpec::ChangeVisibility {
                    target: MutationTargetSymbol::ById(resolved_id),
                    visibility: visibility_to_spec(*to),
                }])
            }

            Intent::MoveItem {
                symbol_id,
                symbol_path,
                target_item,
                to_module,
            } => {
                let resolved_id = resolve_from_3fields(
                    registry,
                    symbol_id.as_deref(),
                    symbol_path.as_deref(),
                    target_item.as_deref(),
                    "MoveItem",
                )?;
                // Get source path and crate name from registry
                let resolved_path =
                    registry.and_then(|r| r.path(resolved_id)).ok_or_else(|| {
                        PlanError::CannotResolve {
                            intent: "MoveItem".to_string(),
                        }
                    })?;
                let _source = resolved_path
                    .parent()
                    .ok_or_else(|| PlanError::InvalidTarget {
                        target: resolved_path.to_string(),
                        reason: "Cannot get parent module of item".to_string(),
                    })?;
                let crate_name = resolved_path.crate_name();

                // Resolve to_module path (may contain "test_crate" or bare module name)
                let to_path_str = if to_module == "test_crate" || to_module.starts_with("crate::") {
                    // Handle crate:: prefix
                    to_module.replacen("test_crate", crate_name, 1)
                } else if to_module.contains("::") {
                    // Already has path separators (e.g., "foo::bar")
                    to_module.to_string()
                } else {
                    // Bare module name (e.g., "core") - prepend crate root
                    format!("{}::{}", crate_name, to_module)
                };

                // Parse with registry validation if available
                let to_path = if let Some(reg) = registry {
                    SymbolPath::parse_validated(&to_path_str, reg).map_err(|e| match e {
                        ryo_symbol::ParseError::UnknownCrate {
                            path,
                            crate_name,
                            known,
                        } => PlanError::UnknownCrate {
                            path,
                            crate_name,
                            known_crates: known,
                        },
                        other => PlanError::InvalidTarget {
                            target: to_path_str.clone(),
                            reason: format!("Invalid to_module: {}", other),
                        },
                    })?
                } else {
                    SymbolPath::parse(&to_path_str).map_err(|e| PlanError::InvalidTarget {
                        target: to_path_str.clone(),
                        reason: format!("Invalid to_module: {}", e),
                    })?
                };

                Ok(vec![MutationSpec::MoveItem {
                    source: MutationTargetSymbol::ById(resolved_id),
                    target: MutationTargetSymbol::ByPath(Box::new(to_path)),
                    item_name: target_item.clone().unwrap_or_default(),
                    item_kind: ryo_executor::ItemKind::Struct,
                    add_use: true,
                }])
            }

            Intent::ExtractTrait {
                symbol_id,
                symbol_path,
                target_type,
                trait_name,
                methods,
            } => {
                // ExtractTrait needs impl block's SymbolId, not the type's
                let resolved_id = resolve_impl_from_3fields(
                    registry,
                    symbol_id.as_deref(),
                    symbol_path.as_deref(),
                    target_type.as_deref(),
                    "ExtractTrait",
                )?;

                let methods_opt = if methods.is_empty() {
                    None
                } else {
                    Some(methods.clone())
                };
                Ok(vec![MutationSpec::ExtractTrait {
                    target: MutationTargetSymbol::ById(resolved_id),
                    trait_name: trait_name.clone(),
                    methods: methods_opt,
                }])
            }

            Intent::InlineTrait {
                trait_symbol_id,
                trait_symbol_path,
                target_trait,
                struct_symbol_id: _,
                struct_symbol_path: _,
                target_struct,
                remove_trait,
            } => {
                let resolved_id = resolve_from_3fields(
                    registry,
                    trait_symbol_id.as_deref(),
                    trait_symbol_path.as_deref(),
                    target_trait.as_deref(),
                    "InlineTrait",
                )?;

                Ok(vec![MutationSpec::InlineTrait {
                    target: MutationTargetSymbol::ById(resolved_id),
                    struct_name: target_struct.clone().unwrap_or_default(),
                    remove_trait: *remove_trait,
                }])
            }

            Intent::EnumToTrait {
                symbol_id,
                symbol_path,
                target_enum,
                new_trait_name,
                remove_enum,
                strategy,
                match_handling,
            } => {
                let resolved_id = resolve_from_3fields(
                    registry,
                    symbol_id.as_deref(),
                    symbol_path.as_deref(),
                    target_enum.as_deref(),
                    "EnumToTrait",
                )?;

                Ok(vec![MutationSpec::EnumToTrait {
                    target: MutationTargetSymbol::ById(resolved_id),
                    trait_name: new_trait_name.clone(),
                    remove_enum: *remove_enum,
                    strategy: *strategy,
                    match_handling: *match_handling,
                }])
            }

            // === モジュール操作系 ===
            // Note: AddMod was consolidated into CreateMod.
            Intent::RemoveMod {
                parent_mod,
                mod_name,
            } => Ok(vec![MutationSpec::RemoveMod {
                target: MutationTargetSymbol::ByPath(Box::new(vec_to_symbol_path(
                    parent_mod, registry,
                )?)),
                mod_name: mod_name.clone(),
            }]),

            Intent::CreateMod {
                parent_mod,
                mod_name,
                content,
                is_pub,
            } => Ok(vec![MutationSpec::CreateMod {
                target: MutationTargetSymbol::ByPath(Box::new(vec_to_symbol_path(
                    parent_mod, registry,
                )?)),
                mod_name: mod_name.clone(),
                content: content.clone(),
                is_pub: *is_pub,
            }]),

            // === フィールド操作系 ===
            Intent::AddField {
                symbol_id,
                symbol_path,
                target_struct,
                field_name,
                field_type,
                is_pub,
            } => {
                let resolved_id = resolve_from_3fields(
                    registry,
                    symbol_id.as_deref(),
                    symbol_path.as_deref(),
                    target_struct.as_deref(),
                    "AddField",
                )?;

                Ok(vec![MutationSpec::AddField {
                    target: MutationTargetSymbol::ById(resolved_id),
                    field_name: field_name.clone(),
                    field_type: field_type.clone(),
                    visibility: if *is_pub {
                        ryo_executor::Visibility::Pub
                    } else {
                        ryo_executor::Visibility::Private
                    },
                }])
            }

            Intent::RemoveField {
                symbol_id,
                symbol_path,
                target_struct,
                field_name,
            } => {
                let resolved_id = resolve_from_3fields(
                    registry,
                    symbol_id.as_deref(),
                    symbol_path.as_deref(),
                    target_struct.as_deref(),
                    "RemoveField",
                )?;

                Ok(vec![MutationSpec::RemoveField {
                    target: MutationTargetSymbol::ById(resolved_id),
                    field_name: field_name.clone(),
                }])
            }

            // === Derive操作系 ===
            Intent::AddDerive {
                symbol_id,
                symbol_path,
                target_type,
                derives,
            } => {
                // Deferred resolution: if target is pending (created by earlier AddItem), set symbol_id to None
                let resolved_id = match resolve_from_3fields(
                    registry,
                    symbol_id.as_deref(),
                    symbol_path.as_deref(),
                    target_type.as_deref(),
                    "AddDerive",
                ) {
                    Ok(id) => Some(id),
                    Err(_)
                        if target_type
                            .as_ref()
                            .is_some_and(|n| pending_symbols.contains(n)) =>
                    {
                        None
                    }
                    Err(e) => return Err(e),
                };

                Ok(vec![MutationSpec::AddDerive {
                    target: match resolved_id {
                        Some(id) => MutationTargetSymbol::ById(id),
                        None => MutationTargetSymbol::ByKindAndName(
                            ryo_executor::ItemKind::Struct,
                            target_type.clone().unwrap_or_default(),
                        ),
                    },
                    derives: derives.clone(),
                }])
            }

            Intent::RemoveDerive {
                symbol_id,
                symbol_path,
                target_type,
                derives,
            } => {
                // Deferred resolution: if target is pending (created by earlier AddItem), set symbol_id to None
                let resolved_id = match resolve_from_3fields(
                    registry,
                    symbol_id.as_deref(),
                    symbol_path.as_deref(),
                    target_type.as_deref(),
                    "RemoveDerive",
                ) {
                    Ok(id) => Some(id),
                    Err(_)
                        if target_type
                            .as_ref()
                            .is_some_and(|n| pending_symbols.contains(n)) =>
                    {
                        None
                    }
                    Err(e) => return Err(e),
                };

                Ok(vec![MutationSpec::RemoveDerive {
                    target: match resolved_id {
                        Some(id) => MutationTargetSymbol::ById(id),
                        None => MutationTargetSymbol::ByKindAndName(
                            ryo_executor::ItemKind::Struct,
                            target_type.clone().unwrap_or_default(),
                        ),
                    },
                    derives: derives.clone(),
                }])
            }

            // === Enum操作系 ===
            Intent::AddEnum {
                symbol_path,
                name,
                variants,
                is_pub,
                derives,
            } => {
                let target_path =
                    SymbolPath::parse(symbol_path).map_err(|e| PlanError::InvalidTarget {
                        target: symbol_path.clone(),
                        reason: format!("{}", e),
                    })?;
                let vis = if *is_pub { "pub " } else { "" };
                let derives_attr = if derives.is_empty() {
                    String::new()
                } else {
                    format!("#[derive({})]\n", derives.join(", "))
                };
                let variants_str = if variants.is_empty() {
                    String::new()
                } else {
                    variants.join(",\n    ")
                };
                let content = format!(
                    "{}{}enum {} {{\n    {}\n}}",
                    derives_attr, vis, name, variants_str
                );

                Ok(vec![MutationSpec::AddItem {
                    target: MutationTargetSymbol::ByPath(Box::new(target_path)),
                    content,
                    position: InsertPosition::Bottom,
                }])
            }

            Intent::AddVariant {
                symbol_id,
                symbol_path,
                target_enum,
                variant_name,
                variant_type,
            } => {
                // Deferred resolution: if target is pending (created by earlier AddItem), set symbol_id to None
                let resolved_id = match resolve_from_3fields(
                    registry,
                    symbol_id.as_deref(),
                    symbol_path.as_deref(),
                    target_enum.as_deref(),
                    "AddVariant",
                ) {
                    Ok(id) => Some(id),
                    Err(_)
                        if target_enum
                            .as_ref()
                            .is_some_and(|n| pending_symbols.contains(n)) =>
                    {
                        None
                    }
                    Err(e) => return Err(e),
                };
                let variant_kind = parse_variant_type(variant_type);
                Ok(vec![MutationSpec::AddVariant {
                    target: match resolved_id {
                        Some(id) => MutationTargetSymbol::ById(id),
                        None => MutationTargetSymbol::ByKindAndName(
                            ryo_executor::ItemKind::Enum,
                            target_enum.clone().unwrap_or_default(),
                        ),
                    },
                    variant_name: variant_name.clone(),
                    variant_kind,
                }])
            }

            Intent::RemoveVariant {
                symbol_id,
                symbol_path,
                target_enum,
                variant_name,
            } => {
                // Deferred resolution: if target is pending (created by earlier AddItem), set symbol_id to None
                let resolved_id = match resolve_from_3fields(
                    registry,
                    symbol_id.as_deref(),
                    symbol_path.as_deref(),
                    target_enum.as_deref(),
                    "RemoveVariant",
                ) {
                    Ok(id) => Some(id),
                    Err(_)
                        if target_enum
                            .as_ref()
                            .is_some_and(|n| pending_symbols.contains(n)) =>
                    {
                        None
                    }
                    Err(e) => return Err(e),
                };
                Ok(vec![MutationSpec::RemoveVariant {
                    target: match resolved_id {
                        Some(id) => MutationTargetSymbol::ById(id),
                        None => MutationTargetSymbol::ByKindAndName(
                            ryo_executor::ItemKind::Enum,
                            target_enum.clone().unwrap_or_default(),
                        ),
                    },
                    variant_name: variant_name.clone(),
                }])
            }

            Intent::AddMatchArm {
                symbol_id,
                symbol_path,
                target_fn,
                enum_name,
                pattern,
                body,
            } => {
                let target = resolve_target_from_3fields(
                    registry,
                    symbol_id.as_deref(),
                    symbol_path.as_deref(),
                    target_fn.as_deref(),
                    "AddMatchArm",
                )?;
                Ok(vec![MutationSpec::AddMatchArm {
                    target,
                    enum_name: enum_name.clone(),
                    pattern: pattern.clone(),
                    body: body.clone(),
                }])
            }

            Intent::RemoveMatchArm {
                symbol_id,
                symbol_path,
                target_fn,
                enum_name,
                pattern,
            } => {
                let target = resolve_target_from_3fields(
                    registry,
                    symbol_id.as_deref(),
                    symbol_path.as_deref(),
                    target_fn.as_deref(),
                    "RemoveMatchArm",
                )?;
                Ok(vec![MutationSpec::RemoveMatchArm {
                    target,
                    enum_name: enum_name.clone(),
                    pattern: pattern.clone(),
                }])
            }

            Intent::ReplaceMatchArm {
                symbol_id,
                symbol_path,
                target_fn,
                enum_name,
                old_pattern,
                new_pattern,
                new_body,
            } => {
                let target = resolve_target_from_3fields(
                    registry,
                    symbol_id.as_deref(),
                    symbol_path.as_deref(),
                    target_fn.as_deref(),
                    "ReplaceMatchArm",
                )?;
                Ok(vec![MutationSpec::ReplaceMatchArm {
                    target,
                    enum_name: enum_name.clone(),
                    old_pattern: old_pattern.clone(),
                    new_pattern: new_pattern.clone(),
                    new_body: new_body.clone(),
                }])
            }

            Intent::AddStructLiteralField {
                symbol_id,
                symbol_path,
                target_struct,
                field_name,
                value,
            } => {
                let resolved_id = resolve_from_3fields(
                    registry,
                    symbol_id.as_deref(),
                    symbol_path.as_deref(),
                    target_struct.as_deref(),
                    "AddStructLiteralField",
                )?;

                Ok(vec![MutationSpec::AddStructLiteralField {
                    target: MutationTargetSymbol::ById(resolved_id),
                    field_name: field_name.clone(),
                    value: value.clone(),
                }])
            }

            Intent::RemoveStructLiteralField {
                symbol_id,
                symbol_path,
                target_struct,
                field_name,
            } => {
                let resolved_id = resolve_from_3fields(
                    registry,
                    symbol_id.as_deref(),
                    symbol_path.as_deref(),
                    target_struct.as_deref(),
                    "RemoveStructLiteralField",
                )?;

                Ok(vec![MutationSpec::RemoveStructLiteralField {
                    target: MutationTargetSymbol::ById(resolved_id),
                    field_name: field_name.clone(),
                }])
            }

            // === 構造体/Enum削除系 ===
            Intent::RemoveStruct {
                symbol_id,
                symbol_path,
                target_struct,
            } => {
                let resolved_id = resolve_from_3fields(
                    registry,
                    symbol_id.as_deref(),
                    symbol_path.as_deref(),
                    target_struct.as_deref(),
                    "RemoveStruct",
                )?;
                Ok(vec![MutationSpec::RemoveItem {
                    target: MutationTargetSymbol::ById(resolved_id),
                    item_kind: ryo_executor::ItemKind::Struct,
                }])
            }

            Intent::RemoveEnum {
                symbol_id,
                symbol_path,
                target_enum,
            } => {
                let resolved_id = resolve_from_3fields(
                    registry,
                    symbol_id.as_deref(),
                    symbol_path.as_deref(),
                    target_enum.as_deref(),
                    "RemoveEnum",
                )?;
                Ok(vec![MutationSpec::RemoveItem {
                    target: MutationTargetSymbol::ById(resolved_id),
                    item_kind: ryo_executor::ItemKind::Enum,
                }])
            }

            // === 定数/型エイリアス系 ===
            Intent::AddConst {
                symbol_path,
                name,
                ty,
                value,
                is_pub,
            } => {
                let target_path =
                    SymbolPath::parse(symbol_path).map_err(|e| PlanError::InvalidTarget {
                        target: symbol_path.clone(),
                        reason: format!("{}", e),
                    })?;
                let vis = if *is_pub { "pub " } else { "" };
                let content = format!("{}const {}: {} = {};", vis, name, ty, value);
                Ok(vec![MutationSpec::AddItem {
                    target: MutationTargetSymbol::ByPath(Box::new(target_path)),
                    content,
                    position: InsertPosition::Bottom,
                }])
            }

            Intent::AddTypeAlias {
                symbol_path,
                name,
                ty,
                is_pub,
            } => {
                let target_path =
                    SymbolPath::parse(symbol_path).map_err(|e| PlanError::InvalidTarget {
                        target: symbol_path.clone(),
                        reason: format!("{}", e),
                    })?;
                let vis = if *is_pub { "pub " } else { "" };
                let content = format!("{}type {} = {};", vis, name, ty);
                Ok(vec![MutationSpec::AddItem {
                    target: MutationTargetSymbol::ByPath(Box::new(target_path)),
                    content,
                    position: InsertPosition::Bottom,
                }])
            }

            // === Spec系 ===
            Intent::AddSpec {
                symbol_id,
                symbol_path,
                target_type,
                module_id,
                module_path,
                target_mod,
                group,
                alias_name,
                relations,
            } => {
                // Resolve target_type_id from 3-field specification
                let target_type_id = resolve_from_3fields(
                    registry,
                    symbol_id.as_deref(),
                    symbol_path.as_deref(),
                    target_type.as_deref(),
                    "AddSpec target_type",
                )?;

                // Resolve module_id from 3-field specification
                let resolved_module_id = resolve_from_3fields(
                    registry,
                    module_id.as_deref(),
                    module_path.as_deref(),
                    target_mod.as_deref(),
                    "AddSpec module",
                )?;

                let _target_path = symbol_path
                    .as_ref()
                    .and_then(|p| SymbolPath::parse(p).ok())
                    .or_else(|| registry.and_then(|r| r.path(target_type_id).cloned()));

                // Convert intent relations to executor relations
                let executor_relations: Vec<SpecRelation> = relations
                    .iter()
                    .map(intent_spec_relation_to_executor)
                    .collect();

                Ok(vec![MutationSpec::AddSpec {
                    type_id: target_type_id,
                    module_id: resolved_module_id,
                    group: group.clone(),
                    alias_name: alias_name.clone(),
                    relations: executor_relations,
                }])
            }

            // === メソッド追加・削除 ===
            Intent::AddMethod {
                symbol_id,
                symbol_path,
                target_type,
                method_name,
                params,
                return_type,
                body,
                is_pub,
                self_param,
            } => {
                // Resolve target SymbolPath from 3-field specification
                let target = if let Some(path_str) = symbol_path {
                    SymbolPath::parse(path_str).ok()
                } else if let Some(id_str) = symbol_id {
                    // If symbol_id provided, try to get path from registry
                    if let Some(id) = ryo_analysis::SymbolId::parse(id_str) {
                        registry.and_then(|r| r.path(id).cloned())
                    } else {
                        None
                    }
                } else {
                    None
                };

                Ok(vec![MutationSpec::AddMethod {
                    target: match target {
                        Some(path) => MutationTargetSymbol::ByPath(Box::new(path)),
                        None => {
                            // Strip generics from target_type since registry stores struct names
                            // without generic parameters (e.g., "CreateOrderUseCase" not "CreateOrderUseCase<U, P, O>")
                            let type_name =
                                strip_generics(&target_type.clone().unwrap_or_default());
                            MutationTargetSymbol::ByKindAndName(
                                ryo_executor::ItemKind::Struct,
                                type_name,
                            )
                        }
                    },
                    method_name: method_name.clone(),
                    params: params.clone(),
                    return_type: return_type.clone(),
                    body: body.clone(),
                    is_pub: *is_pub,
                    self_param: self_param.map(intent_self_param_to_spec),
                }])
            }

            Intent::RemoveMethod {
                symbol_id,
                symbol_path,
                target_type,
                method_name,
            } => {
                // RemoveMethod needs the Type's SymbolId (struct/enum), not impl block
                // Converter builds Type::method path to find the method
                let resolved_id = resolve_from_3fields(
                    registry,
                    symbol_id.as_deref(),
                    symbol_path.as_deref(),
                    target_type.as_deref(),
                    "RemoveMethod",
                )?;
                Ok(vec![MutationSpec::RemoveMethod {
                    target: MutationTargetSymbol::ById(resolved_id),
                    method_name: method_name.clone(),
                }])
            }

            // === 削除系 ===
            Intent::RemoveConst {
                symbol_id,
                symbol_path,
                target_const,
            } => {
                let resolved_id = resolve_from_3fields(
                    registry,
                    symbol_id.as_deref(),
                    symbol_path.as_deref(),
                    target_const.as_deref(),
                    "RemoveConst",
                )?;
                Ok(vec![MutationSpec::RemoveItem {
                    target: MutationTargetSymbol::ById(resolved_id),
                    item_kind: ryo_executor::ItemKind::Const,
                }])
            }

            Intent::RemoveTypeAlias {
                symbol_id,
                symbol_path,
                target_type_alias,
            } => {
                let resolved_id = resolve_from_3fields(
                    registry,
                    symbol_id.as_deref(),
                    symbol_path.as_deref(),
                    target_type_alias.as_deref(),
                    "RemoveTypeAlias",
                )?;
                Ok(vec![MutationSpec::RemoveItem {
                    target: MutationTargetSymbol::ById(resolved_id),
                    item_kind: ryo_executor::ItemKind::TypeAlias,
                }])
            }

            Intent::RemoveUse {
                symbol_id,
                symbol_path,
                target_use,
            } => {
                let resolved_id = resolve_from_3fields(
                    registry,
                    symbol_id.as_deref(),
                    symbol_path.as_deref(),
                    target_use.as_deref(),
                    "RemoveUse",
                )?;
                Ok(vec![MutationSpec::RemoveItem {
                    target: MutationTargetSymbol::ById(resolved_id),
                    item_kind: ryo_executor::ItemKind::Use,
                }])
            }

            Intent::RemoveTrait {
                symbol_id,
                symbol_path,
                target_trait,
            } => {
                let resolved_id = resolve_from_3fields(
                    registry,
                    symbol_id.as_deref(),
                    symbol_path.as_deref(),
                    target_trait.as_deref(),
                    "RemoveTrait",
                )?;
                Ok(vec![MutationSpec::RemoveItem {
                    target: MutationTargetSymbol::ById(resolved_id),
                    item_kind: ryo_executor::ItemKind::Trait,
                }])
            }

            Intent::RemoveImpl {
                symbol_id,
                symbol_path,
                target_type,
                trait_name,
            } => {
                let resolved_id = resolve_from_3fields(
                    registry,
                    symbol_id.as_deref(),
                    symbol_path.as_deref(),
                    target_type.as_deref(),
                    "RemoveImpl",
                )?;
                let _target = match (target_type.as_ref(), trait_name.as_ref()) {
                    (Some(s), Some(t)) => Some(format!("{} for {}", t, s)),
                    (Some(s), None) => Some(s.clone()),
                    _ => None,
                };
                Ok(vec![MutationSpec::RemoveItem {
                    target: MutationTargetSymbol::ById(resolved_id),
                    item_kind: ryo_executor::ItemKind::Impl,
                }])
            }

            // === アイテム追加・削除 ===
            Intent::AddItem {
                symbol_id,
                symbol_path,
                target_mod,
                content,
                item_kind: _,
            } => {
                let target = resolve_target_from_3fields(
                    registry,
                    symbol_id.as_deref(),
                    symbol_path.as_deref(),
                    target_mod.as_deref(),
                    "AddItem",
                )?;
                Ok(vec![MutationSpec::AddItem {
                    target,
                    content: content.clone(),
                    position: InsertPosition::Bottom,
                }])
            }

            Intent::RemoveItem {
                symbol_id,
                symbol_path,
                target_item,
                item_kind,
            } => {
                let resolved_id = resolve_from_3fields(
                    registry,
                    symbol_id.as_deref(),
                    symbol_path.as_deref(),
                    target_item.as_deref(),
                    "RemoveItem",
                )?;
                Ok(vec![MutationSpec::RemoveItem {
                    target: MutationTargetSymbol::ById(resolved_id),
                    item_kind: item_kind_to_spec(*item_kind),
                }])
            }

            Intent::AddCode {
                symbol_id,
                symbol_path,
                target_mod: _,
                code,
            } => {
                // 3-field解決: symbol_id優先、次にsymbol_path(必須)
                let target = if let Some(ref id_str) = symbol_id {
                    let id = SymbolId::parse(id_str).ok_or_else(|| PlanError::InvalidTarget {
                        target: id_str.clone(),
                        reason: "Invalid SymbolId format".to_string(),
                    })?;
                    symbol_id_to_symbol_path(id, registry)?
                } else if let Some(ref path) = symbol_path {
                    // Try SymbolPath first (handles both "crate_name" and "crate_name::module")
                    if let Ok(symbol_path) = SymbolPath::parse(path) {
                        symbol_path
                    } else {
                        // FilePath format - requires registry to resolve crate name
                        let reg = registry.ok_or_else(|| PlanError::CannotResolve {
                            intent: "AddCode".to_string(),
                        })?;
                        let crate_name = reg
                            .iter()
                            .next()
                            .map(|(_, p)| p.crate_name())
                            .ok_or_else(|| PlanError::CannotResolve {
                                intent: "AddCode".to_string(),
                            })?;
                        file_path_to_symbol_path(path, crate_name)?
                    }
                } else {
                    return Err(PlanError::MissingTargetModule {
                        intent: "AddCode".to_string(),
                    });
                };

                let mut specs = Vec::new();

                // Generate CreateMod specs for missing modules
                // With registry: skip existing modules
                // Without registry: generate CreateMod for all parent segments (CreateMod is idempotent)
                let create_mods = if let Some(reg) = registry {
                    generate_create_mod_specs(&target, reg)
                } else {
                    generate_create_mod_specs_without_registry(&target)
                };
                specs.extend(create_mods);

                specs.push(MutationSpec::AddItem {
                    target: MutationTargetSymbol::ByPath(Box::new(target)),
                    content: code.clone(),
                    position: InsertPosition::Bottom,
                });

                Ok(specs)
            }

            // === IDIOM系 ===
            Intent::OrganizeImports {
                target_mod: _,
                deduplicate,
                merge_groups,
            } => Ok(vec![MutationSpec::OrganizeImports {
                module_id: None, // TODO: resolve target_mod to SymbolId
                deduplicate: *deduplicate,
                merge_groups: *merge_groups,
            }]),

            Intent::MergeImplBlocks {
                target_mod: _,
                target_type: _,
                inherent_only: _,
            } => {
                // MergeImplBlocks MutationSpec was removed - not currently supported
                Err(PlanError::UnsupportedIntent(
                    "MergeImplBlocks is not currently supported".to_string(),
                ))
            }

            Intent::LoopToIterator {
                target_mod: _,
                target_var,
            } => Ok(vec![MutationSpec::LoopToIterator {
                module_id: None, // TODO: resolve target_mod to SymbolId
                target_var: target_var.clone(),
            }]),

            Intent::UnwrapToQuestion {
                target_mod: _,
                target_fn,
                include_expect,
            } => {
                // TODO: Resolve target_fn from String to SymbolId
                // Currently, target_fn filtering by name is not supported in MutationSpec
                // MutationSpec::UnwrapToQuestion expects SymbolId, but we only have String
                if target_fn.is_some() {
                    return Err(PlanError::UnsupportedIntent(
                        "UnwrapToQuestion with target_fn name filtering is not currently supported. Use SymbolId-based targeting instead.".to_string(),
                    ));
                }

                Ok(vec![MutationSpec::UnwrapToQuestion {
                    module_id: None,
                    target_fn: None,
                    include_expect: *include_expect,
                }])
            }

            Intent::IntroduceVariable {
                target_mod: _,
                target_fn: _,
                expr,
                var_name,
            } => Ok(vec![MutationSpec::IntroduceVariable {
                module_id: None, // TODO: resolve target_mod to SymbolId
                fn_id: None,     // TODO: resolve target_fn to SymbolId
                expr: expr.clone(),
                var_name: var_name.clone(),
            }]),

            // === Builder Pattern ===
            Intent::GenerateBuilder {
                symbol_id: _,
                symbol_path: _,
                target_struct,
                target_mod,
                fields,
                add_builder_method,
            } => {
                // target_mod is required - no implicit crate root fallback
                let target_mod_str =
                    target_mod
                        .as_deref()
                        .ok_or_else(|| PlanError::MissingTargetModule {
                            intent: "GenerateBuilder".to_string(),
                        })?;

                // Parse target_mod (no "test_crate" replacement - use actual crate name)
                let target = SymbolPath::parse(target_mod_str).map_err(|e| {
                    PlanError::InvalidModulePath {
                        message: format!("Failed to parse target_mod '{}': {}", target_mod_str, e),
                    }
                })?;
                let struct_name_str = target_struct
                    .clone()
                    .unwrap_or_else(|| "Unknown".to_string());
                let builder_name = format!("{}Builder", struct_name_str);

                let mut specs = Vec::new();

                // 1. Generate Builder struct
                // Note: Use Bottom to avoid position conflicts
                let builder_struct = Self::generate_builder_struct(&builder_name, fields);
                specs.push(MutationSpec::AddItem {
                    target: MutationTargetSymbol::ByPath(Box::new(target.clone())),
                    content: builder_struct,
                    position: InsertPosition::Bottom,
                });

                // 2. Generate Builder impl
                // Note: Use Bottom position to avoid circular dependency with Builder struct
                let builder_impl =
                    Self::generate_builder_impl(&struct_name_str, &builder_name, fields);
                specs.push(MutationSpec::AddItem {
                    target: MutationTargetSymbol::ByPath(Box::new(target.clone())),
                    content: builder_impl,
                    position: InsertPosition::Bottom,
                });

                // 3. (Optional) Add builder() method to original struct
                if *add_builder_method {
                    // Construct the struct's SymbolPath by appending struct_name to target module
                    let struct_path =
                        target
                            .child(&struct_name_str)
                            .map_err(|e| PlanError::InvalidTarget {
                                target: format!("{}::{}", target, struct_name_str),
                                reason: format!("Failed to create struct path: {}", e),
                            })?;
                    specs.push(MutationSpec::AddMethod {
                        target: MutationTargetSymbol::ByPath(Box::new(struct_path)),
                        method_name: "builder".to_string(),
                        params: vec![],
                        return_type: Some(builder_name.clone()),
                        body: format!("{}::new()", builder_name),
                        is_pub: true,
                        self_param: None,
                    });
                }

                Ok(specs)
            }

            // === PureStmt/PureExpr 操作系 ===
            Intent::ReplaceExpr {
                target_mod: _,
                target_fn: _,
                old_expr,
                new_expr,
                replace_all,
                symbol_path,
            } => Ok(vec![MutationSpec::ReplaceExpr {
                module_id: None, // TODO: resolve target_mod to SymbolId
                fn_id: None,     // TODO: resolve target_fn to SymbolId
                old_expr: old_expr.clone(),
                new_expr: new_expr.clone(),
                replace_all: *replace_all,
                symbol_path: symbol_path.clone(),
            }]),

            Intent::RemoveStatement {
                target_mod: _,
                target_fn: _,
                pattern,
                remove_all,
                symbol_path,
            } => Ok(vec![MutationSpec::RemoveStatement {
                module_id: None, // TODO: resolve target_mod to SymbolId
                fn_id: None,     // TODO: resolve target_fn to SymbolId
                pattern: pattern.clone(),
                remove_all: *remove_all,
                symbol_path: symbol_path.clone(),
            }]),

            Intent::InsertStatement {
                target_mod: _,
                target_fn,
                stmt,
                position,
                reference_pattern,
                symbol_path,
            } => {
                let fn_id = if let Some(reg) = registry {
                    resolve_symbol_by_name(target_fn, SymbolKind::Function, reg)?
                } else {
                    return Err(PlanError::SymbolNotFound {
                        name: target_fn.clone(),
                        kind: Some(SymbolKind::Function),
                    });
                };
                Ok(vec![MutationSpec::InsertStatement {
                    module_id: None,
                    fn_id,
                    stmt: stmt.clone(),
                    position: intent_stmt_position_to_spec(position),
                    reference_pattern: reference_pattern.clone(),
                    symbol_path: symbol_path.clone(),
                }])
            }

            Intent::ReplaceStatement {
                target_mod: _,
                target_fn: _,
                old_stmt,
                new_stmt,
                symbol_path,
            } => Ok(vec![MutationSpec::ReplaceStatement {
                module_id: None, // TODO: resolve target_mod to SymbolId
                fn_id: None,     // TODO: resolve target_fn to SymbolId
                old_stmt: old_stmt.clone(),
                new_stmt: new_stmt.clone(),
                symbol_path: symbol_path.clone(),
            }]),

            // === 追加 Idiom変換系 ===
            Intent::AssignOp {
                target_mod: _,
                target_fn: _,
            } => Ok(vec![MutationSpec::AssignOp {
                module_id: None, // TODO: resolve target_mod to SymbolId
                fn_id: None,     // TODO: resolve target_fn to SymbolId
            }]),

            Intent::BoolSimplify { target_mod: _ } => Ok(vec![MutationSpec::BoolSimplify {
                module_id: None, // TODO: resolve target_mod to SymbolId
            }]),

            Intent::CloneOnCopy { target_mod: _ } => Ok(vec![MutationSpec::CloneOnCopy {
                module_id: None, // TODO: resolve target_mod to SymbolId
            }]),

            Intent::CollapsibleIf { target_mod: _ } => Ok(vec![MutationSpec::CollapsibleIf {
                module_id: None, // TODO: resolve target_mod to SymbolId
            }]),

            Intent::ComparisonToMethod { target_mod: _ } => {
                Ok(vec![MutationSpec::ComparisonToMethod {
                    module_id: None, // TODO: resolve target_mod to SymbolId
                }])
            }

            Intent::RedundantClosure { target_mod: _ } => {
                Ok(vec![MutationSpec::RedundantClosure {
                    module_id: None, // TODO: resolve target_mod to SymbolId
                }])
            }

            Intent::ManualMap { target_mod: _ } => Ok(vec![MutationSpec::ManualMap {
                module_id: None, // TODO: resolve target_mod to SymbolId
            }]),

            Intent::MatchToIfLet { target_mod: _ } => Ok(vec![MutationSpec::MatchToIfLet {
                module_id: None, // TODO: resolve target_mod to SymbolId
            }]),

            Intent::FilterNext {
                target_mod: _,
                target_fn: _,
            } => Ok(vec![MutationSpec::FilterNext {
                module_id: None, // TODO: resolve target_mod to SymbolId
                fn_id: None,     // TODO: resolve target_fn to SymbolId
            }]),

            Intent::MapUnwrapOr {
                target_mod: _,
                target_fn: _,
            } => Ok(vec![MutationSpec::MapUnwrapOr {
                module_id: None, // TODO: resolve target_mod to SymbolId
                fn_id: None,     // TODO: resolve target_fn to SymbolId
            }]),

            // === 複製系 ===
            Intent::DuplicateFunction {
                symbol_id,
                symbol_path,
                target_fn,
                to,
            } => {
                let resolved_id = resolve_from_3fields(
                    registry,
                    symbol_id.as_deref(),
                    symbol_path.as_deref(),
                    target_fn.as_deref(),
                    "DuplicateFunction",
                )?;
                Ok(vec![MutationSpec::DuplicateFunction {
                    target: MutationTargetSymbol::ById(resolved_id),
                    to: to.clone(),
                }])
            }

            Intent::DuplicateStruct {
                symbol_id,
                symbol_path,
                target_struct,
                to,
                include_impls,
            } => {
                let resolved_id = resolve_from_3fields(
                    registry,
                    symbol_id.as_deref(),
                    symbol_path.as_deref(),
                    target_struct.as_deref(),
                    "DuplicateStruct",
                )?;
                Ok(vec![MutationSpec::DuplicateStruct {
                    target: MutationTargetSymbol::ById(resolved_id),
                    to: to.clone(),
                    include_impls: *include_impls,
                }])
            }

            Intent::DuplicateEnum {
                symbol_id,
                symbol_path,
                target_enum,
                to,
                include_impls,
            } => {
                let resolved_id = resolve_from_3fields(
                    registry,
                    symbol_id.as_deref(),
                    symbol_path.as_deref(),
                    target_enum.as_deref(),
                    "DuplicateEnum",
                )?;
                Ok(vec![MutationSpec::DuplicateEnum {
                    target: MutationTargetSymbol::ById(resolved_id),
                    to: to.clone(),
                    include_impls: *include_impls,
                }])
            }

            Intent::DuplicateModTree {
                symbol_id,
                symbol_path,
                target_mod,
                to,
            } => {
                let resolved_id = resolve_from_3fields(
                    registry,
                    symbol_id.as_deref(),
                    symbol_path.as_deref(),
                    target_mod.as_deref(),
                    "DuplicateModTree",
                )?;
                Ok(vec![MutationSpec::DuplicateModTree {
                    target: MutationTargetSymbol::ById(resolved_id),
                    to: to.clone(),
                }])
            }

            // === カスタム ===
            Intent::Custom { description, .. } => Err(PlanError::UnsupportedIntent(format!(
                "Custom intent not directly supported: {}",
                description
            ))),

            // === WASM Plugin ===
            #[cfg(feature = "wasm-plugin")]
            Intent::Plugin {
                name,
                file_patterns,
            } => Ok(vec![MutationSpec::PluginTransform {
                plugin_name: name.clone(),
                target: None,
                file_patterns: file_patterns.clone(),
                config: serde_json::Value::Null,
            }]),
        }
    }

    // === Builder Pattern Helpers ===

    /// Generate Builder struct code
    fn generate_builder_struct(builder_name: &str, fields: &[(String, String)]) -> String {
        let mut code = format!("pub struct {} {{\n", builder_name);
        for (name, ty) in fields {
            code.push_str(&format!("    {}: Option<{}>,\n", name, ty));
        }
        code.push('}');
        code
    }

    /// Generate Builder impl code
    fn generate_builder_impl(
        struct_name: &str,
        builder_name: &str,
        fields: &[(String, String)],
    ) -> String {
        let mut code = format!("impl {} {{\n", builder_name);

        // new() method
        code.push_str("    pub fn new() -> Self {\n");
        code.push_str("        Self {\n");
        for (name, _) in fields {
            code.push_str(&format!("            {}: None,\n", name));
        }
        code.push_str("        }\n");
        code.push_str("    }\n\n");

        // setter methods
        for (name, ty) in fields {
            code.push_str(&format!(
                "    pub fn {}(mut self, {}: {}) -> Self {{\n",
                name, name, ty
            ));
            code.push_str(&format!("        self.{} = Some({});\n", name, name));
            code.push_str("        self\n");
            code.push_str("    }\n\n");
        }

        // build() method
        code.push_str(&format!(
            "    pub fn build(self) -> Result<{}, &'static str> {{\n",
            struct_name
        ));
        code.push_str(&format!("        Ok({} {{\n", struct_name));
        for (name, _) in fields {
            code.push_str(&format!(
                "            {}: self.{}.ok_or(\"{} is required\")?,\n",
                name, name, name
            ));
        }
        code.push_str("        })\n");
        code.push_str("    }\n");
        code.push('}');
        code
    }
}

// === Helper functions ===

// === Symbol Resolution Helpers ===

/// Resolve SymbolId from optional id or path
///
/// Priority:
/// 1. `symbol_id: Some(id)` → return as-is
/// 2. `symbol_path: Some(path)` → resolve via registry.lookup()
/// 3. Both None → CannotResolve error
///
/// For name-based resolution (when only a String name is available),
/// use `resolve_symbol_by_name()` separately as it requires kind filtering.
/// Get crate name from registry (required for canonical SymbolPath construction)
///
/// Convert file path to SymbolPath using crate name
///
/// Converts relative file paths (e.g., "src/foo/bar.rs") to canonical SymbolPath
/// (e.g., "my_crate::foo::bar").
///
/// # Examples
/// - "src/foo/bar.rs" → "my_crate::foo::bar"
/// - "src/lib.rs" → "my_crate"
/// - "foo/bar.rs" → "my_crate::foo::bar" (without src/ prefix)
fn file_path_to_symbol_path(file_path: &str, crate_name: &str) -> Result<SymbolPath, PlanError> {
    let path_str = file_path.trim_start_matches("src/");
    let path_str = path_str.trim_end_matches(".rs");
    let path_str = path_str.trim_end_matches("/mod");

    // lib.rs or empty path -> crate root
    if path_str == "lib" || path_str.is_empty() {
        return SymbolPath::parse(crate_name).map_err(|e| PlanError::InvalidTarget {
            target: crate_name.to_string(),
            reason: format!("Invalid crate name: {}", e),
        });
    }

    // Convert path separators to :: and prepend crate name
    let symbol_str = format!("{}::{}", crate_name, path_str.replace('/', "::"));
    SymbolPath::parse(&symbol_str).map_err(|e| PlanError::InvalidTarget {
        target: symbol_str.clone(),
        reason: format!("Invalid file path: {}", e),
    })
}

/// Resolve SymbolId by SymbolPath from registry
///
/// Returns error if not found.
fn resolve_symbol_by_path(
    path: &SymbolPath,
    registry: &SymbolRegistry,
) -> PlanResult<ryo_analysis::SymbolId> {
    registry
        .lookup(path)
        .ok_or_else(|| PlanError::SymbolNotFound {
            name: path.to_string(),
            kind: None,
        })
}

/// Resolve SymbolId by name and kind from registry
///
/// Returns error if not found or if multiple matches exist (duplicate).
fn resolve_symbol_by_name(
    name: &str,
    kind: SymbolKind,
    registry: &SymbolRegistry,
) -> PlanResult<ryo_analysis::SymbolId> {
    let matches: Vec<_> = registry
        .iter()
        .filter(|(id, path)| path.name() == name && registry.kind(*id) == Some(kind))
        .collect();

    match matches.len() {
        0 => Err(PlanError::SymbolNotFound {
            name: name.to_string(),
            kind: Some(kind),
        }),
        1 => Ok(matches[0].0),
        count => Err(PlanError::DuplicateSymbol {
            name: name.to_string(),
            kind: Some(kind),
            count,
        }),
    }
}

/// Resolve SymbolId by name from registry (any kind)
///
/// Used for Rename operations which can target any symbol kind.
/// Returns error if not found or if multiple matches exist (duplicate).
///
/// If the name contains "::", it is treated as a path and resolved via path lookup.
fn resolve_symbol_by_name_any_kind(
    name: &str,
    registry: &SymbolRegistry,
) -> PlanResult<ryo_analysis::SymbolId> {
    // If name contains "::", treat it as a path (e.g., "crate::user::UserStatus")
    if name.contains("::") {
        if let Ok(path) = SymbolPath::parse(name) {
            return resolve_symbol_by_path(&path, registry);
        }
        // If path parsing fails, fall through to name search
    }

    let matches: Vec<_> = registry
        .iter()
        .filter(|(_, path)| path.name() == name)
        .collect();

    match matches.len() {
        0 => Err(PlanError::SymbolNotFound {
            name: name.to_string(),
            kind: None,
        }),
        1 => Ok(matches[0].0),
        count => Err(PlanError::DuplicateSymbol {
            name: name.to_string(),
            kind: None,
            count,
        }),
    }
}

/// Resolve SymbolId from 3-field specification (new unified format)
///
/// Priority:
/// 1. `symbol_id: Some(str)` → parse as SymbolId ("7v2" format)
/// 2. `symbol_path: Some(str)` → parse as SymbolPath and lookup
/// 3. `target_name: Some(str)` → name search (any kind)
fn resolve_from_3fields(
    registry: Option<&SymbolRegistry>,
    symbol_id: Option<&str>,
    symbol_path: Option<&str>,
    target_name: Option<&str>,
    context: &str,
) -> PlanResult<ryo_analysis::SymbolId> {
    // Priority 1: Direct SymbolId
    if let Some(id_str) = symbol_id {
        return ryo_analysis::SymbolId::parse(id_str).ok_or_else(|| PlanError::InvalidTarget {
            target: id_str.to_string(),
            reason: "invalid SymbolId format (expected 'NvM' format like '7v2')".to_string(),
        });
    }

    // Priority 2: Resolve from SymbolPath
    if let Some(path_str) = symbol_path {
        let reg = registry.ok_or_else(|| PlanError::RegistryNotAvailable {
            target: path_str.to_string(),
        })?;
        let path = SymbolPath::parse(path_str).map_err(|e| PlanError::InvalidTarget {
            target: path_str.to_string(),
            reason: format!("invalid SymbolPath: {:?}", e),
        })?;
        return resolve_symbol_by_path(&path, reg);
    }

    // Priority 3: Name search
    if let Some(name) = target_name {
        let reg = registry.ok_or_else(|| PlanError::RegistryNotAvailable {
            target: name.to_string(),
        })?;
        return resolve_symbol_by_name_any_kind(name, reg);
    }

    // All None
    Err(PlanError::CannotResolve {
        intent: context.to_string(),
    })
}

/// Resolve target from 3-field specification, returning MutationTargetSymbol
///
/// For AddItem, returns ByPath or ById depending on what's specified.
/// Returns error if all fields are None (no implicit fallback to crate root).
fn resolve_target_from_3fields(
    registry: Option<&SymbolRegistry>,
    symbol_id: Option<&str>,
    symbol_path: Option<&str>,
    module_name: Option<&str>,
    context: &str,
) -> PlanResult<MutationTargetSymbol> {
    // Priority 1: Direct SymbolId
    if let Some(id_str) = symbol_id {
        let id = ryo_analysis::SymbolId::parse(id_str).ok_or_else(|| PlanError::InvalidTarget {
            target: id_str.to_string(),
            reason: "invalid SymbolId format (expected 'NvM' format like '7v2')".to_string(),
        })?;
        return Ok(MutationTargetSymbol::ById(id));
    }

    // Priority 2: Use SymbolPath directly
    if let Some(path_str) = symbol_path {
        // Use parse_validated if registry available to check crate name exists
        let path = if let Some(reg) = registry {
            SymbolPath::parse_validated(path_str, reg).map_err(|e| match e {
                ryo_symbol::ParseError::UnknownCrate {
                    path,
                    crate_name,
                    known,
                } => PlanError::UnknownCrate {
                    path,
                    crate_name,
                    known_crates: known,
                },
                other => PlanError::InvalidTarget {
                    target: path_str.to_string(),
                    reason: format!("invalid SymbolPath: {:?}", other),
                },
            })?
        } else {
            SymbolPath::parse(path_str).map_err(|e| PlanError::InvalidTarget {
                target: path_str.to_string(),
                reason: format!("invalid SymbolPath: {:?}", e),
            })?
        };

        return Ok(MutationTargetSymbol::ByPath(Box::new(path)));
    }

    // Priority 3: Name search → ById
    if let Some(name) = module_name {
        let reg = registry.ok_or_else(|| PlanError::RegistryNotAvailable {
            target: name.to_string(),
        })?;
        let id = resolve_symbol_by_name_any_kind(name, reg)?;
        return Ok(MutationTargetSymbol::ById(id));
    }

    // All None → Error (no implicit fallback to crate root)
    Err(PlanError::CannotResolve {
        intent: format!(
            "{}: at least one of symbol_id, symbol_path, or target_mod must be specified",
            context
        ),
    })
}

/// Resolve impl block SymbolId from 3-field specification
///
/// For RemoveMethod/AddMethod, we need the impl block's SymbolId, not the type's.
/// When target_type_name is specified (e.g., "Status"), we search for `<impl Status>`.
fn resolve_impl_from_3fields(
    registry: Option<&SymbolRegistry>,
    symbol_id: Option<&str>,
    symbol_path: Option<&str>,
    target_type_name: Option<&str>,
    context: &str,
) -> PlanResult<ryo_analysis::SymbolId> {
    // Priority 1: Direct SymbolId (assumed to be impl block's ID)
    if let Some(id_str) = symbol_id {
        return ryo_analysis::SymbolId::parse(id_str).ok_or_else(|| PlanError::InvalidTarget {
            target: id_str.to_string(),
            reason: "invalid SymbolId format (expected 'NvM' format like '7v2')".to_string(),
        });
    }

    // Priority 2: Resolve from SymbolPath (assumed to be impl block's path like "crate::types::<impl Status>")
    if let Some(path_str) = symbol_path {
        let reg = registry.ok_or_else(|| PlanError::RegistryNotAvailable {
            target: path_str.to_string(),
        })?;
        let path = SymbolPath::parse(path_str).map_err(|e| PlanError::InvalidTarget {
            target: path_str.to_string(),
            reason: format!("invalid SymbolPath: {:?}", e),
        })?;
        return resolve_symbol_by_path(&path, reg);
    }

    // Priority 3: Search for impl block by type name
    // e.g., target_type_name="Status" -> search for `<impl Status>`
    if let Some(type_name) = target_type_name {
        let reg = registry.ok_or_else(|| PlanError::RegistryNotAvailable {
            target: type_name.to_string(),
        })?;

        // Search for impl block with matching self_ty name pattern
        // Note: Registry stores generic types with spaces (e.g., "Generic < T , U >")
        // due to to_token_stream().to_string() behavior, so we normalize both for comparison
        let impl_name = format!("<impl {}>", type_name);
        let normalized_expected = normalize_generic_name(&impl_name);
        let matches: Vec<_> = reg
            .iter()
            .filter(|(id, path)| {
                // Check if it's an impl block and name matches (normalized)
                reg.kind(*id) == Some(SymbolKind::Impl)
                    && normalize_generic_name(path.name()) == normalized_expected
            })
            .collect();

        return match matches.len() {
            0 => Err(PlanError::SymbolNotFound {
                name: impl_name,
                kind: Some(SymbolKind::Impl),
            }),
            1 => Ok(matches[0].0),
            count => Err(PlanError::DuplicateSymbol {
                name: impl_name,
                kind: Some(SymbolKind::Impl),
                count,
            }),
        };
    }

    // All None
    Err(PlanError::CannotResolve {
        intent: context.to_string(),
    })
}

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

/// Strip generic parameters from a type name.
///
/// The symbol registry stores struct/enum names without generic parameters
/// (e.g., "CreateOrderUseCase"), but DSL may specify them with generics
/// (e.g., "CreateOrderUseCase<U, P, O>"). This function strips the generics
/// for symbol lookup purposes.
///
/// # Examples
/// - "CreateOrderUseCase<U, P, O>" → "CreateOrderUseCase"
/// - "Vec<String>" → "Vec"
/// - "HashMap<K, V>" → "HashMap"
/// - "SimpleType" → "SimpleType"
fn strip_generics(name: &str) -> String {
    if let Some(idx) = name.find('<') {
        name[..idx].to_string()
    } else {
        name.to_string()
    }
}

/// Convert Vec<String> (module names) to SymbolPath
///
/// # Arguments
/// * `segments` - Module name segments (e.g., ["infrastructure", "memory"])
/// * `registry` - SymbolRegistry to resolve crate name
///
/// # Rules
/// - `segments` must NOT contain "test_crate" literal (use empty array for crate root)
/// - Empty array `[]` → crate root (e.g., "my_crate")
/// - Non-empty → crate::module::... (e.g., "my_crate::infrastructure::memory")
///
/// # Errors
/// Returns PlanError if:
/// - segments contains "test_crate" literal
/// - registry is None (required for resolution)
fn vec_to_symbol_path(
    segments: &[String],
    registry: Option<&SymbolRegistry>,
) -> PlanResult<SymbolPath> {
    // CRITICAL: "test_crate" literal is forbidden (relative path)
    if segments.iter().any(|s| s == "test_crate") {
        return Err(PlanError::InvalidModulePath {
            message: format!(
                "Module path must NOT contain 'crate' literal (got: {:?}). \
                 Use empty array [] for crate root, or actual module names like ['infrastructure', 'memory']",
                segments
            ),
        });
    }

    // Registry is required to resolve crate name
    let reg = registry.ok_or_else(|| PlanError::RegistryRequired {
        message: "Cannot resolve module path without SymbolRegistry".to_string(),
    })?;

    // Get crate name from any symbol in registry
    let crate_name_str = reg
        .iter()
        .next()
        .map(|(_, path)| path.crate_name().to_string())
        .ok_or_else(|| PlanError::RegistryRequired {
            message: "Registry is empty - cannot determine crate name".to_string(),
        })?;
    let crate_name = crate_name_str.as_str();

    if segments.is_empty() {
        // Empty array = crate root
        SymbolPath::parse(crate_name).map_err(|e| PlanError::InvalidModulePath {
            message: format!("Failed to create crate root path '{}': {}", crate_name, e),
        })
    } else {
        // Non-empty = crate::module::...
        let mut full_path = vec![crate_name];
        full_path.extend(segments.iter().map(|s| s.as_str()));
        SymbolPath::from_segments(full_path.iter().copied()).map_err(|e| {
            PlanError::InvalidModulePath {
                message: format!("Failed to create module path '{:?}': {}", full_path, e),
            }
        })
    }
}

fn visibility_to_spec(vis: Visibility) -> ryo_executor::Visibility {
    match vis {
        Visibility::Private => ryo_executor::Visibility::Private,
        Visibility::Pub => ryo_executor::Visibility::Pub,
        Visibility::PubCrate => ryo_executor::Visibility::PubCrate,
        Visibility::PubSuper => ryo_executor::Visibility::PubSuper,
    }
}

fn intent_stmt_position_to_spec(pos: &IntentStmtPosition) -> StmtInsertPosition {
    match pos {
        IntentStmtPosition::Start => StmtInsertPosition::Start,
        IntentStmtPosition::End => StmtInsertPosition::End,
        IntentStmtPosition::BeforePattern => StmtInsertPosition::BeforePattern,
        IntentStmtPosition::AfterPattern => StmtInsertPosition::AfterPattern,
    }
}

fn item_kind_to_spec(kind: ItemKind) -> ryo_executor::ItemKind {
    match kind {
        ItemKind::Struct => ryo_executor::ItemKind::Struct,
        ItemKind::Enum => ryo_executor::ItemKind::Enum,
        ItemKind::Trait => ryo_executor::ItemKind::Trait,
        ItemKind::Impl => ryo_executor::ItemKind::Impl,
        ItemKind::Function => ryo_executor::ItemKind::Function,
        ItemKind::Const => ryo_executor::ItemKind::Const,
        ItemKind::Static => ryo_executor::ItemKind::Static,
        ItemKind::TypeAlias => ryo_executor::ItemKind::TypeAlias,
        ItemKind::Use => ryo_executor::ItemKind::Use,
        ItemKind::Mod => ryo_executor::ItemKind::Mod,
        ItemKind::Macro => ryo_executor::ItemKind::Macro,
        // Nested items - map to closest equivalent
        ItemKind::Method => ryo_executor::ItemKind::Function,
        ItemKind::Field | ItemKind::TupleField => ryo_executor::ItemKind::Struct,
        ItemKind::Variant => ryo_executor::ItemKind::Enum,
        // Variable-level items (for DataFlow analysis)
        ItemKind::LocalVar | ItemKind::Parameter => ryo_executor::ItemKind::Function,
        // Wildcard/other
        ItemKind::Any | ItemKind::Other => ryo_executor::ItemKind::Struct, // fallback
    }
}

/// Extract item name from Rust code content.
/// Used for deferred resolution in batch intents.
fn extract_item_name_from_content(content: &str) -> Option<String> {
    let trimmed = content.trim();

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

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

    let mut idx = 0;

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

    // Get keyword
    let keyword = tokens.get(idx)?;
    idx += 1;

    match *keyword {
        "struct" | "enum" | "fn" | "type" | "const" | "static" | "trait" | "mod" => {
            // Next token is the name (may include generics)
            let name = tokens.get(idx)?;
            // Strip generics <...> and trailing punctuation
            let name = name.split('<').next().unwrap_or(name);
            let name = name.trim_end_matches(|c: char| !c.is_alphanumeric() && c != '_');
            Some(name.to_string())
        }
        "impl" => {
            // impl blocks don't define a named symbol we can reference by simple name
            None
        }
        _ => None,
    }
}

/// Convert SymbolId to SymbolPath using registry (internal use)
///
/// SymbolId is an internal identifier from Discover/Registry operations.
/// Requires SymbolRegistry to resolve back to SymbolPath.
fn symbol_id_to_symbol_path(
    id: ryo_analysis::SymbolId,
    registry: Option<&SymbolRegistry>,
) -> Result<SymbolPath, PlanError> {
    if let Some(reg) = registry {
        if let Some(path) = reg.resolve(id) {
            return Ok(path.clone());
        }
    }
    Err(PlanError::InvalidTarget {
        target: format!("SymbolId({:?})", id),
        reason: "SymbolId not found in registry. SymbolId is an internal identifier \
             that requires SymbolRegistry for resolution. Ensure the registry is \
             provided and contains this symbol (from Discover operation)."
            .to_string(),
    })
}

/// Generate CreateMod specs for all parent modules without registry
///
/// Used when SymbolRegistry is not available. Generates CreateMod specs
/// for all segments of the path (except "test_crate"). CreateMod mutations
/// are idempotent - they skip if the module already exists.
///
/// # Example
/// If target is "test_crate::domain::model", generates:
/// 1. CreateMod { parent: "test_crate", mod_name: "domain" }
/// 2. CreateMod { parent: "test_crate::domain", mod_name: "model" }
fn generate_create_mod_specs_without_registry(target: &SymbolPath) -> Vec<MutationSpec> {
    let segments: Vec<&str> = target.segments().collect();

    // Skip "test_crate" (index 0), generate CreateMod for each remaining segment
    let mut specs = Vec::new();
    for depth in 1..segments.len() {
        let parent_path = segments[..depth].join("::");
        let mod_name = segments[depth].to_string();

        if let Ok(parent) = SymbolPath::parse(&parent_path) {
            specs.push(MutationSpec::CreateMod {
                target: MutationTargetSymbol::ByPath(Box::new(parent)),
                mod_name,
                content: String::new(),
                is_pub: true, // Default to pub for auto-created modules
            });
        }
    }

    specs
}

/// Generate CreateMod specs for missing modules in a path
///
/// Checks each segment of the SymbolPath against the registry.
/// For missing modules, generates CreateMod specs in order from
/// closest existing ancestor to target.
///
/// # Example
/// If target is "crate::domain::model::entity" and only "test_crate" exists,
/// generates:
/// 1. CreateMod { parent: "test_crate", mod_name: "domain" }
/// 2. CreateMod { parent: "test_crate::domain", mod_name: "model" }
/// 3. CreateMod { parent: "test_crate::domain::model", mod_name: "entity" }
fn generate_create_mod_specs(target: &SymbolPath, registry: &SymbolRegistry) -> Vec<MutationSpec> {
    let segments: Vec<&str> = target.segments().collect();

    // Find the deepest existing ancestor
    let mut existing_depth = 0;
    for depth in 1..=segments.len() {
        let partial_path = segments[..depth].join("::");
        if let Ok(path) = SymbolPath::parse(&partial_path) {
            if registry.lookup(&path).is_some() {
                existing_depth = depth;
            } else {
                break;
            }
        }
    }

    // Generate CreateMod for each missing segment
    let mut specs = Vec::new();
    for depth in existing_depth..segments.len() {
        if depth == 0 {
            // Can't create crate root
            continue;
        }

        let parent_path = segments[..depth].join("::");
        let mod_name = segments[depth].to_string();

        if let Ok(parent) = SymbolPath::parse(&parent_path) {
            specs.push(MutationSpec::CreateMod {
                target: MutationTargetSymbol::ByPath(Box::new(parent)),
                mod_name,
                content: String::new(),
                is_pub: true, // Default to pub for auto-created modules
            });
        }
    }

    specs
}

fn parse_variant_type(variant_type: &str) -> VariantKind {
    if variant_type == "unit" || variant_type.is_empty() {
        VariantKind::Unit
    } else if let Some(types) = variant_type.strip_prefix("tuple:") {
        let types: Vec<String> = types.split(',').map(|s| s.trim().to_string()).collect();
        VariantKind::Tuple { types }
    } else if let Some(fields) = variant_type.strip_prefix("struct:") {
        let fields: Vec<(String, String)> = fields
            .split(',')
            .filter_map(|f| {
                let parts: Vec<&str> = f.trim().split(':').collect();
                if parts.len() == 2 {
                    Some((parts[0].trim().to_string(), parts[1].trim().to_string()))
                } else {
                    None
                }
            })
            .collect();
        VariantKind::Struct { fields }
    } else {
        VariantKind::Unit
    }
}

fn intent_self_param_to_spec(intent_param: IntentSelfParam) -> SelfParam {
    match intent_param {
        IntentSelfParam::Ref => SelfParam::Ref,
        IntentSelfParam::Mut => SelfParam::Mut,
        IntentSelfParam::Owned => SelfParam::Owned,
    }
}

/// Convert Intent's SpecRelation to executor's SpecRelation
fn intent_spec_relation_to_executor(rel: &IntentSpecRelation) -> SpecRelation {
    SpecRelation {
        kind: intent_spec_relation_kind_to_executor(&rel.kind),
        target: rel.target.clone(),
        symbol_id: None,
        target_path: None,
    }
}

/// Convert Intent's SpecRelationKind to executor's SpecRelationKind
fn intent_spec_relation_kind_to_executor(kind: &IntentSpecRelationKind) -> SpecRelationKind {
    match kind {
        IntentSpecRelationKind::DependsOn => SpecRelationKind::DependsOn,
        IntentSpecRelationKind::RelatedTo => SpecRelationKind::RelatedTo,
        IntentSpecRelationKind::PartOf => SpecRelationKind::PartOf,
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::intent::IdentKind;

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

        // Create registry with foo symbol
        let mut registry = SymbolRegistry::new();
        let path = SymbolPath::parse("test_crate::foo").unwrap();
        let symbol_id = registry.register(path, SymbolKind::Function).unwrap();

        let goal = Goal::new(
            "rename foo to bar".to_string(),
            Intent::RenameIdent {
                symbol_id: Some(format!("{:?}", symbol_id)),
                symbol_path: None,
                target_ident: Some("foo".to_string()),
                to: "bar".to_string(),
                kind: IdentKind::Any,
            },
        );

        let specs = Planner::plan(&goal, Some(&registry)).unwrap();
        assert_eq!(specs.len(), 1);
        match &specs[0] {
            MutationSpec::Rename { target, to, .. } => {
                assert_eq!(*target, MutationTargetSymbol::ById(symbol_id));
                assert_eq!(to, "bar");
            }
            _ => panic!("Expected Rename spec"),
        }
    }

    #[test]
    fn test_add_field_intent() {
        // Create a dummy SymbolId for testing (symbol_id is now required)
        let dummy_id = ryo_analysis::SymbolId::parse("0v1").expect("valid dummy id");

        let goal = Goal::new(
            "add field".to_string(),
            Intent::AddField {
                symbol_id: Some(format!("{:?}", dummy_id)),
                symbol_path: None,
                target_struct: Some("User".to_string()),
                field_name: "email".to_string(),
                field_type: "String".to_string(),
                is_pub: true,
            },
        );

        let specs = Planner::plan(&goal, None).unwrap();
        assert_eq!(specs.len(), 1);
        match &specs[0] {
            MutationSpec::AddField {
                field_name,
                field_type,
                visibility,
                ..
            } => {
                assert_eq!(field_name, "email");
                assert_eq!(field_type, "String");
                assert_eq!(*visibility, ryo_executor::Visibility::Pub);
            }
            _ => panic!("Expected AddField spec"),
        }
    }

    // === AddCode Intent Tests ===

    #[test]
    fn test_add_code_with_parent_symbol_path() {
        let goal = Goal::new(
            "add code".to_string(),
            Intent::AddCode {
                symbol_id: None,
                symbol_path: Some("test_crate::domain::model".to_string()),
                target_mod: None,
                code: "pub struct User { pub id: u64 }".to_string(),
            },
        );

        let specs = Planner::plan(&goal, None).unwrap();
        // Without registry: generates CreateMod for each missing segment + AddItem
        // 2 CreateMods (domain, model) + 1 AddItem = 3
        assert_eq!(specs.len(), 3);
        // Last spec should be AddItem
        match specs.last().unwrap() {
            MutationSpec::AddItem {
                target,
                content,
                position,
            } => {
                if let MutationTargetSymbol::ByPath(path) = target {
                    assert_eq!(path.to_string(), "test_crate::domain::model");
                } else {
                    panic!("Expected ByPath target");
                }
                assert_eq!(content, "pub struct User { pub id: u64 }");
                assert_eq!(*position, InsertPosition::Bottom);
            }
            _ => panic!("Expected AddItem spec"),
        }
    }

    #[test]
    fn test_add_code_with_nested_symbol_path() {
        // Use SymbolPath format (contains ::)
        let goal = Goal::new(
            "add code".to_string(),
            Intent::AddCode {
                symbol_id: None,
                symbol_path: Some("test_crate::domain::model".to_string()),
                target_mod: None,
                code: "pub struct Order { pub id: u64 }".to_string(),
            },
        );

        let specs = Planner::plan(&goal, None).unwrap();
        // Without registry: generates CreateMod for each missing segment + AddItem
        // 2 CreateMods (domain, model) + 1 AddItem = 3
        assert_eq!(specs.len(), 3);
        // Last spec should be AddItem
        match specs.last().unwrap() {
            MutationSpec::AddItem {
                target, content, ..
            } => {
                if let MutationTargetSymbol::ByPath(path) = target {
                    assert_eq!(path.to_string(), "test_crate::domain::model");
                } else {
                    panic!("Expected ByPath target");
                }
                assert_eq!(content, "pub struct Order { pub id: u64 }");
            }
            _ => panic!("Expected AddItem spec"),
        }
    }

    #[test]
    fn test_add_code_with_parent_ref_symbol_path() {
        let goal = Goal::new(
            "add code".to_string(),
            Intent::AddCode {
                symbol_id: None,
                symbol_path: Some("test_crate::usecase".to_string()),
                target_mod: None,
                code: "pub fn create_user() {}".to_string(),
            },
        );

        let specs = Planner::plan(&goal, None).unwrap();
        // Without registry: generates CreateMod for each missing segment + AddItem
        // 1 CreateMod (usecase) + 1 AddItem = 2
        assert_eq!(specs.len(), 2);
        // Last spec should be AddItem
        match specs.last().unwrap() {
            MutationSpec::AddItem {
                target, content, ..
            } => {
                if let MutationTargetSymbol::ByPath(path) = target {
                    assert_eq!(path.to_string(), "test_crate::usecase");
                } else {
                    panic!("Expected ByPath target");
                }
                assert_eq!(content, "pub fn create_user() {}");
            }
            _ => panic!("Expected AddItem spec"),
        }
    }

    #[test]
    fn test_add_code_with_single_module_path() {
        // Use SymbolPath format (contains ::)
        let goal = Goal::new(
            "add code".to_string(),
            Intent::AddCode {
                symbol_id: None,
                symbol_path: Some("test_crate::handlers".to_string()),
                target_mod: None,
                code: "pub fn handle() {}".to_string(),
            },
        );

        let specs = Planner::plan(&goal, None).unwrap();
        // Without registry: generates CreateMod for each missing segment + AddItem
        // 1 CreateMod (handlers) + 1 AddItem = 2
        assert_eq!(specs.len(), 2);
        // Last spec should be AddItem
        match specs.last().unwrap() {
            MutationSpec::AddItem {
                target, content, ..
            } => {
                if let MutationTargetSymbol::ByPath(path) = target {
                    assert_eq!(path.to_string(), "test_crate::handlers");
                } else {
                    panic!("Expected ByPath target");
                }
                assert_eq!(content, "pub fn handle() {}");
            }
            _ => panic!("Expected AddItem spec"),
        }
    }

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

        // Create minimal registry with crate root
        let mut registry = SymbolRegistry::new();
        let crate_root = SymbolPath::parse("test_crate").unwrap();
        registry
            .register(crate_root.clone(), SymbolKind::Mod)
            .unwrap();

        // Explicit symbol_path to crate root
        let goal = Goal::new(
            "add code".to_string(),
            Intent::AddCode {
                symbol_id: None,
                symbol_path: Some("test_crate".to_string()),
                target_mod: None,
                code: "pub const VERSION: &str = \"1.0\";".to_string(),
            },
        );

        let specs = Planner::plan(&goal, Some(&registry)).unwrap();
        assert_eq!(specs.len(), 1);
        match &specs[0] {
            MutationSpec::AddItem {
                target, content, ..
            } => {
                if let MutationTargetSymbol::ByPath(path) = target {
                    assert_eq!(path.to_string(), "test_crate");
                } else {
                    panic!("Expected ByPath target");
                }
                assert_eq!(content, "pub const VERSION: &str = \"1.0\";");
            }
            _ => panic!("Expected AddItem spec"),
        }
    }

    #[test]
    fn test_add_code_missing_symbol_path_returns_error() {
        // symbol_path: None should return MissingTargetModule error
        let goal = Goal::new(
            "add code".to_string(),
            Intent::AddCode {
                symbol_id: None,
                symbol_path: None,
                target_mod: None,
                code: "pub const VERSION: &str = \"1.0\";".to_string(),
            },
        );

        let result = Planner::plan(&goal, None);
        assert!(matches!(
            result,
            Err(PlanError::MissingTargetModule { intent }) if intent == "AddCode"
        ));
    }

    #[test]
    fn test_add_code_generates_create_mod_for_missing_modules() {
        use ryo_analysis::{SymbolKind, SymbolRegistry};

        // Setup: registry with only "test_crate" registered
        let mut registry = SymbolRegistry::new();
        let crate_path = SymbolPath::parse("test_crate").unwrap();
        registry.register(crate_path, SymbolKind::Mod).unwrap();

        let goal = Goal::new(
            "add code to nested module".to_string(),
            Intent::AddCode {
                symbol_id: None,
                symbol_path: Some("test_crate::domain::model".to_string()),
                target_mod: None,
                code: "pub struct Entity;".to_string(),
            },
        );

        let specs = Planner::plan(&goal, Some(&registry)).unwrap();

        // Should generate: CreateMod(domain), CreateMod(model), AddItem
        assert_eq!(specs.len(), 3);

        // First: CreateMod for "domain"
        match &specs[0] {
            MutationSpec::CreateMod {
                target,
                mod_name,
                is_pub,
                ..
            } => {
                // FIXME: MutationTargetSymbol does not have to_string()
                // assert_eq!(target.to_string(), "test_crate");
                match target {
                    ryo_executor::MutationTargetSymbol::ByPath(path) => {
                        assert_eq!(path.to_string().as_str(), "test_crate");
                    }
                    _ => panic!("Expected ByPath variant"),
                }
                assert_eq!(mod_name, "domain");
                assert!(*is_pub);
            }
            _ => panic!("Expected CreateMod spec for domain"),
        }

        // Second: CreateMod for "model"
        match &specs[1] {
            MutationSpec::CreateMod {
                target,
                mod_name,
                is_pub,
                ..
            } => {
                // FIXME: MutationTargetSymbol does not have to_string()
                // assert_eq!(target.to_string(), "test_crate::domain");
                match target {
                    ryo_executor::MutationTargetSymbol::ByPath(path) => {
                        assert_eq!(path.to_string().as_str(), "test_crate::domain");
                    }
                    _ => panic!("Expected ByPath variant"),
                }
                assert_eq!(mod_name, "model");
                assert!(*is_pub);
            }
            _ => panic!("Expected CreateMod spec for model"),
        }

        // Third: AddItem
        match &specs[2] {
            MutationSpec::AddItem {
                target, content, ..
            } => {
                if let MutationTargetSymbol::ByPath(path) = target {
                    assert_eq!(path.to_string(), "test_crate::domain::model");
                } else {
                    panic!("Expected ByPath target");
                }
                assert_eq!(content, "pub struct Entity;");
            }
            _ => panic!("Expected AddItem spec"),
        }
    }

    #[test]
    fn test_add_code_no_create_mod_when_module_exists() {
        use ryo_analysis::{SymbolKind, SymbolRegistry};

        // Setup: registry with "test_crate" and "test_crate::domain" registered
        let mut registry = SymbolRegistry::new();
        registry
            .register(SymbolPath::parse("test_crate").unwrap(), SymbolKind::Mod)
            .unwrap();
        registry
            .register(
                SymbolPath::parse("test_crate::domain").unwrap(),
                SymbolKind::Mod,
            )
            .unwrap();

        let goal = Goal::new(
            "add code to existing module".to_string(),
            Intent::AddCode {
                symbol_id: None,
                symbol_path: Some("test_crate::domain".to_string()),
                target_mod: None,
                code: "pub struct User;".to_string(),
            },
        );

        let specs = Planner::plan(&goal, Some(&registry)).unwrap();

        // Should only have AddItem (no CreateMod needed)
        assert_eq!(specs.len(), 1);
        match &specs[0] {
            MutationSpec::AddItem { target, .. } => {
                if let MutationTargetSymbol::ByPath(path) = target {
                    assert_eq!(path.to_string(), "test_crate::domain");
                } else {
                    panic!("Expected ByPath target");
                }
            }
            _ => panic!("Expected AddItem spec"),
        }
    }

    #[test]
    fn test_add_code_without_registry_generates_create_mods() {
        // Without registry, AddCode should generate CreateMod for all parent segments
        let goal = Goal::new(
            "add code without registry".to_string(),
            Intent::AddCode {
                symbol_id: None,
                symbol_path: Some("test_crate::infrastructure::memory".to_string()),
                target_mod: None,
                code: "pub struct InMemoryRepo;".to_string(),
            },
        );

        // Plan WITHOUT registry (None)
        let specs = Planner::plan(&goal, None).unwrap();

        // Should generate: CreateMod(infrastructure), CreateMod(memory), AddItem
        assert_eq!(
            specs.len(),
            3,
            "Expected 3 specs (2 CreateMod + 1 AddItem), got {}",
            specs.len()
        );

        // First: CreateMod for "infrastructure"
        match &specs[0] {
            MutationSpec::CreateMod {
                target,
                mod_name,
                is_pub,
                ..
            } => {
                // FIXME: MutationTargetSymbol does not have to_string()
                // assert_eq!(target.to_string(), "test_crate");
                match target {
                    ryo_executor::MutationTargetSymbol::ByPath(path) => {
                        assert_eq!(path.to_string().as_str(), "test_crate");
                    }
                    _ => panic!("Expected ByPath variant"),
                }
                assert_eq!(mod_name, "infrastructure");
                assert!(*is_pub);
            }
            _ => panic!(
                "Expected CreateMod spec for infrastructure, got {:?}",
                specs[0]
            ),
        }

        // Second: CreateMod for "memory"
        match &specs[1] {
            MutationSpec::CreateMod {
                target,
                mod_name,
                is_pub,
                ..
            } => {
                // FIXME: MutationTargetSymbol does not have to_string()
                // assert_eq!(target.to_string(), "test_crate::infrastructure");
                match target {
                    ryo_executor::MutationTargetSymbol::ByPath(path) => {
                        assert_eq!(path.to_string().as_str(), "test_crate::infrastructure");
                    }
                    _ => panic!("Expected ByPath variant"),
                }
                assert_eq!(mod_name, "memory");
                assert!(*is_pub);
            }
            _ => panic!("Expected CreateMod spec for memory, got {:?}", specs[1]),
        }

        // Third: AddItem
        match &specs[2] {
            MutationSpec::AddItem {
                target, content, ..
            } => {
                if let MutationTargetSymbol::ByPath(path) = target {
                    assert_eq!(path.to_string(), "test_crate::infrastructure::memory");
                } else {
                    panic!("Expected ByPath target");
                }
                assert_eq!(content, "pub struct InMemoryRepo;");
            }
            _ => panic!("Expected AddItem spec, got {:?}", specs[2]),
        }
    }

    #[test]
    fn test_add_code_crate_root_no_create_mod() {
        // AddCode to crate root should not generate any CreateMod
        let goal = Goal::new(
            "add code to crate root".to_string(),
            Intent::AddCode {
                symbol_id: None,
                symbol_path: Some("test_crate".to_string()), // Explicit crate root
                target_mod: None,
                code: "pub const VERSION: &str = \"1.0\";".to_string(),
            },
        );

        let specs = Planner::plan(&goal, None).unwrap();

        // Should only have AddItem (no CreateMod for crate root)
        assert_eq!(specs.len(), 1);
        match &specs[0] {
            MutationSpec::AddItem { target, .. } => {
                if let MutationTargetSymbol::ByPath(path) = target {
                    assert_eq!(path.to_string(), "test_crate");
                } else {
                    panic!("Expected ByPath target");
                }
            }
            _ => panic!("Expected AddItem spec"),
        }
    }

    // === GenerateBuilder Intent Tests ===

    #[test]
    fn test_generate_builder_intent() {
        let goal = Goal::new(
            "generate builder".to_string(),
            Intent::GenerateBuilder {
                symbol_id: None,
                symbol_path: None,
                target_struct: Some("Config".to_string()),
                target_mod: Some("test_crate::config".to_string()),
                fields: vec![
                    ("host".to_string(), "String".to_string()),
                    ("port".to_string(), "u16".to_string()),
                ],
                add_builder_method: true,
            },
        );

        let specs = Planner::plan(&goal, None).unwrap();

        // Should have 3 specs: AddItem (struct), AddItem (impl), AddMethod (builder)
        assert_eq!(specs.len(), 3);

        // First spec: Builder struct
        match &specs[0] {
            MutationSpec::AddItem {
                target,
                content,
                position,
            } => {
                if let MutationTargetSymbol::ByPath(path) = target {
                    assert_eq!(path.to_string(), "test_crate::config");
                } else {
                    panic!("Expected ByPath target");
                }
                assert!(content.contains("pub struct ConfigBuilder"));
                assert!(content.contains("host: Option<String>"));
                assert!(content.contains("port: Option<u16>"));
                assert!(matches!(position, InsertPosition::Bottom));
            }
            _ => panic!("Expected AddItem spec for Builder struct"),
        }

        // Second spec: Builder impl
        match &specs[1] {
            MutationSpec::AddItem {
                target, content, ..
            } => {
                if let MutationTargetSymbol::ByPath(path) = target {
                    assert_eq!(path.to_string(), "test_crate::config");
                } else {
                    panic!("Expected ByPath target");
                }
                assert!(content.contains("impl ConfigBuilder"));
                assert!(content.contains("pub fn new()"));
                assert!(content.contains("pub fn host("));
                assert!(content.contains("pub fn port("));
                assert!(content.contains("pub fn build("));
            }
            _ => panic!("Expected AddItem spec for Builder impl"),
        }

        // Third spec: builder() method on Config
        match &specs[2] {
            MutationSpec::AddMethod {
                method_name,
                return_type,
                ..
            } => {
                assert_eq!(method_name, "builder");
                assert_eq!(return_type.as_deref(), Some("ConfigBuilder"));
            }
            _ => panic!("Expected AddMethod spec"),
        }
    }

    #[test]
    fn test_generate_builder_without_builder_method() {
        let goal = Goal::new(
            "generate builder".to_string(),
            Intent::GenerateBuilder {
                symbol_id: None,
                symbol_path: None,
                target_struct: Some("User".to_string()),
                target_mod: Some("test_crate".to_string()), // Explicit target module
                fields: vec![("name".to_string(), "String".to_string())],
                add_builder_method: false,
            },
        );

        let specs = Planner::plan(&goal, None).unwrap();

        // Should have 2 specs: AddItem (struct), AddItem (impl)
        // No AddMethod because add_builder_method is false
        assert_eq!(specs.len(), 2);

        // Target should be the specified module
        match &specs[0] {
            MutationSpec::AddItem { target, .. } => {
                if let MutationTargetSymbol::ByPath(path) = target {
                    assert_eq!(path.to_string(), "test_crate");
                } else {
                    panic!("Expected ByPath target");
                }
            }
            _ => panic!("Expected AddItem spec"),
        }
    }

    #[test]
    fn test_generate_builder_missing_target_mod_returns_error() {
        // target_mod: None should return MissingTargetModule error
        let goal = Goal::new(
            "generate builder".to_string(),
            Intent::GenerateBuilder {
                symbol_id: None,
                symbol_path: None,
                target_struct: Some("User".to_string()),
                target_mod: None,
                fields: vec![("name".to_string(), "String".to_string())],
                add_builder_method: false,
            },
        );

        let result = Planner::plan(&goal, None);
        assert!(matches!(
            result,
            Err(PlanError::MissingTargetModule { intent }) if intent == "GenerateBuilder"
        ));
    }
}