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
//! Intent: Public DSL for code transformation
//!
//! # Architecture: Intent vs MutationSpec
//!
//! `Intent` is the **user-facing DSL** for `ryo run` command.
//! It provides a high-level, pattern-based interface for specifying transformations.
//!
//! ```text
//! ┌─────────────────────────────────────────────────────────────────┐
//! │  Intent (this module)                                           │
//! │  - Public DSL: `ryo run -f goal.json`                           │
//! │  - Pattern-based: Pattern::Glob("*Config")                      │
//! │  - High-level: one Intent may affect multiple symbols           │
//! └───────────────────────────┬─────────────────────────────────────┘
//!                             ↓ Symbol Resolution
//! ┌─────────────────────────────────────────────────────────────────┐
//! │  MutationSpec (ryo-executor::executor::spec)                    │
//! │  - Execution-level: concrete targets                            │
//! │  - One Intent → N MutationSpecs (after pattern expansion)       │
//! │  - Direct SymbolId/name targeting                               │
//! └───────────────────────────┬─────────────────────────────────────┘
//!                             ↓ Execution
//! ┌─────────────────────────────────────────────────────────────────┐
//! │  AST Mutation                                                   │
//! └─────────────────────────────────────────────────────────────────┘
//! ```
//!
//! ## Intent vs MutationSpec: When to Use
//!
//! | Layer | Use Case | Example |
//! |-------|----------|---------|
//! | Intent | CLI users, DSL files | `AddField { target: "*Config", ... }` |
//! | MutationSpec | Suggest system, programmatic API | `AddField { struct_name: "AppConfig", ... }` |
//!
//! The `Suggest` system bypasses Intent and generates `MutationSpec` directly,
//! since it already has resolved symbols from analysis.
//!
//! # IntentExtractor (NL → Goal)
//!
//! ```text
//! ┌─────────────────────────────────────────────────────────────────┐
//! │  User Query (Natural Language)                                  │
//! │  "ConfigをDatabaseConfigに統一"                                 │
//! └───────────────────────────┬─────────────────────────────────────┘
//!//! ┌─────────────────────────────────────────────────────────────────┐
//! │  IntentExtractor                                                │
//! │  ・責務: NLクエリ → Goal (Intent + Scope + Constraints)         │
//! │  ・LLM呼び出し1回のみ                                           │
//! │  ・検索・変換には一切関与しない                                 │
//! └───────────────────────────┬─────────────────────────────────────┘
//!//! ┌─────────────────────────────────────────────────────────────────┐
//! │  Goal                                                           │
//! │  ・intent: RenameIdent { from: "Config", to: "DatabaseConfig" } │
//! │  ・scope: ScopeHint { file_patterns: ["**/*.rs"], ... }         │
//! │  ・constraints: [MustCompile]                                   │
//! └─────────────────────────────────────────────────────────────────┘
//! ```

use ryo_executor::executor::{EnumToTraitStrategy, MatchHandling};
#[cfg(feature = "schemars")]
use schemars::JsonSchema;
use serde::{Deserialize, Serialize};

fn default_true() -> bool {
    true
}

fn default_confidence() -> f64 {
    1.0
}

fn default_ident_kind_any() -> IdentKind {
    IdentKind::Any
}

fn default_variant_type() -> String {
    "unit".to_string()
}

fn default_method_body() -> String {
    "todo!()".to_string()
}

// Re-export ItemKind from ryo-source (canonical definition)
pub use ryo_source::ItemKind;

// ============================================================================
// Goal: IntentExtractorの出力
// ============================================================================

/// コンフリクト解決戦略
#[cfg_attr(feature = "schemars", derive(JsonSchema))]
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Serialize, Deserialize)]
pub enum ConflictStrategy {
    /// Intentsの順序で実行(同じターゲットでも順序付けで解決)
    #[default]
    IntentOrder,
    /// コンフリクトでエラー(厳密モード)
    Fail,
    /// 並列実行可能なもののみ実行、それ以外はスキップ
    ParallelOnly,
}

/// 抽出されたゴール
///
/// IntentExtractorの唯一の出力物。これ以降の処理には関与しない。
#[cfg_attr(feature = "schemars", derive(JsonSchema))]
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct Goal {
    /// 元のクエリテキスト(DSL直接実行時は空でOK)
    #[serde(default)]
    pub query: String,

    /// 抽出されたIntent(複数可)
    pub intents: Vec<Intent>,

    /// 検索スコープのヒント(並列Discovery用)
    #[serde(default)]
    pub scope: ScopeHint,

    /// 実行時の制約条件
    #[serde(default)]
    pub constraints: Vec<Constraint>,

    /// コンフリクト解決戦略
    #[serde(default)]
    pub conflict_strategy: ConflictStrategy,

    /// 抽出時の信頼度(0.0-1.0)
    #[serde(default = "default_confidence")]
    pub confidence: f64,
}

// ============================================================================
// Intent: 変換意図
// ============================================================================

/// 変換意図
///
/// # Future Intents (Not Yet Implemented)
///
/// The following Intents are planned for future implementation:
///
/// - `Decorator` → AddFunction + Rename (wrap function with logging/timing/retry)
/// - `ExtractFunction` → AddFunction + ReplaceExpr (extract statements into new function)
/// - `InlineFunction` → ReplaceExpr + RemoveFunction (inline function calls)
///
/// These will be implemented as compositions of existing MutationSpecs.
#[cfg_attr(feature = "schemars", derive(JsonSchema))]
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(tag = "type", deny_unknown_fields)]
pub enum Intent {
    // === 識別子リネーム系 ===
    /// 単一識別子のリネーム
    RenameIdent {
        // --- Target (3-field) ---
        /// SymbolId(O(1)確定、"7v2"形式)
        #[serde(default, skip_serializing_if = "Option::is_none")]
        symbol_id: Option<String>,
        /// シンボルパス("tokio::net::TcpStream"形式)
        #[serde(default, skip_serializing_if = "Option::is_none")]
        symbol_path: Option<String>,
        /// リネーム元の識別子名(診断用、フォールバック検索)
        #[serde(
            default,
            skip_serializing_if = "Option::is_none",
            alias = "target",
            alias = "target_name"
        )]
        target_ident: Option<String>,
        // --- Rename attributes ---
        to: String,
        #[serde(default = "default_ident_kind_any")]
        kind: IdentKind,
    },

    // === 構造変更系 ===
    /// 可視性変更
    ChangeVisibility {
        /// SymbolId(O(1)確定、"7v2"形式)
        #[serde(default, skip_serializing_if = "Option::is_none")]
        symbol_id: Option<String>,
        /// シンボルパス("crate::module::Type"形式)
        #[serde(default, skip_serializing_if = "Option::is_none")]
        symbol_path: Option<String>,
        /// ターゲット名(診断用、フォールバック検索)
        #[serde(
            default,
            skip_serializing_if = "Option::is_none",
            alias = "target",
            alias = "target_name"
        )]
        target_item: Option<String>,
        /// 変更後のvisibility
        to: Visibility,
    },

    /// アイテムを別モジュールに移動
    MoveItem {
        // --- Target (3-field) ---
        /// SymbolId(O(1)確定、"7v2"形式)
        #[serde(default, skip_serializing_if = "Option::is_none")]
        symbol_id: Option<String>,
        /// シンボルパス("tokio::net::TcpStream"形式)
        #[serde(default, skip_serializing_if = "Option::is_none")]
        symbol_path: Option<String>,
        /// 移動対象の名前(診断用、フォールバック検索)
        #[serde(
            default,
            skip_serializing_if = "Option::is_none",
            alias = "target",
            alias = "target_name"
        )]
        target_item: Option<String>,
        // --- Move attributes ---
        to_module: String,
    },

    /// implからトレイトを抽出
    ExtractTrait {
        // --- Target impl (3-field) ---
        /// SymbolId(O(1)確定、"7v2"形式)
        #[serde(default, skip_serializing_if = "Option::is_none")]
        symbol_id: Option<String>,
        /// シンボルパス("tokio::net::TcpStream"形式)
        #[serde(default, skip_serializing_if = "Option::is_none")]
        symbol_path: Option<String>,
        /// impl対象の型名(診断用、フォールバック検索)
        #[serde(
            default,
            skip_serializing_if = "Option::is_none",
            alias = "target",
            alias = "target_name"
        )]
        target_type: Option<String>,
        // --- Extract attributes ---
        trait_name: String,
        /// 抽出するメソッド(空 = 全メソッド)
        #[serde(default)]
        methods: Vec<String>,
    },

    /// トレイトをインライン化(implに戻す)
    InlineTrait {
        // --- Target trait (3-field) ---
        /// Trait SymbolId
        #[serde(default, skip_serializing_if = "Option::is_none")]
        trait_symbol_id: Option<String>,
        /// Trait シンボルパス
        #[serde(default, skip_serializing_if = "Option::is_none")]
        trait_symbol_path: Option<String>,
        /// Trait名(診断用、フォールバック検索)
        #[serde(
            default,
            skip_serializing_if = "Option::is_none",
            alias = "target",
            alias = "target_name"
        )]
        target_trait: Option<String>,
        // --- Target struct (3-field) ---
        /// Struct SymbolId
        #[serde(default, skip_serializing_if = "Option::is_none")]
        struct_symbol_id: Option<String>,
        /// Struct シンボルパス
        #[serde(default, skip_serializing_if = "Option::is_none")]
        struct_symbol_path: Option<String>,
        /// Struct名(診断用、フォールバック検索)
        #[serde(default, skip_serializing_if = "Option::is_none")]
        target_struct: Option<String>,
        // --- Inline attributes ---
        /// トレイト定義を削除するか
        #[serde(default = "default_true")]
        remove_trait: bool,
    },

    /// EnumをTraitに変換(Replace Conditional with Polymorphism)
    ///
    /// Enum variants become struct implementations of the generated trait.
    /// Use `strategy` to control type annotation replacement.
    EnumToTrait {
        // --- Target enum (3-field) ---
        /// SymbolId(O(1)確定、"7v2"形式)
        #[serde(default, skip_serializing_if = "Option::is_none")]
        symbol_id: Option<String>,
        /// シンボルパス("tokio::net::TcpStream"形式)
        #[serde(default, skip_serializing_if = "Option::is_none")]
        symbol_path: Option<String>,
        /// 変換対象のEnum名(診断用、フォールバック検索)
        #[serde(
            default,
            skip_serializing_if = "Option::is_none",
            alias = "target",
            alias = "target_name"
        )]
        target_enum: Option<String>,
        // --- Conversion attributes ---
        /// 生成するTrait名(省略時はEnum名を使用)
        #[serde(default)]
        new_trait_name: Option<String>,
        /// 元のEnumを削除するか
        #[serde(default = "default_true")]
        remove_enum: bool,
        /// 変換戦略: Dynamic (Box<dyn>), Static (impl), MarkerOnly
        #[serde(default)]
        #[cfg_attr(feature = "schemars", schemars(skip))]
        strategy: EnumToTraitStrategy,
        /// match式の処理方法
        #[serde(default)]
        #[cfg_attr(feature = "schemars", schemars(skip))]
        match_handling: MatchHandling,
    },

    // === モジュール操作系 ===
    // Note: AddMod was consolidated into CreateMod.
    /// モジュール宣言を削除
    RemoveMod {
        /// 親モジュールパス (空 = crate root)
        #[serde(default)]
        parent_mod: Vec<String>,
        /// 削除するモジュール名
        mod_name: String,
    },

    /// モジュールファイルを作成
    CreateMod {
        /// 親モジュールパス (空 = crate root)
        #[serde(default)]
        parent_mod: Vec<String>,
        /// 作成するモジュール名
        mod_name: String,
        /// 初期コンテンツ
        #[serde(default)]
        content: String,
        /// public かどうか
        #[serde(default)]
        is_pub: bool,
    },

    // === フィールド操作系 ===
    /// フィールドを追加
    AddField {
        // --- Target struct (3-field) ---
        /// SymbolId(O(1)確定、"7v2"形式)
        #[serde(default, skip_serializing_if = "Option::is_none")]
        symbol_id: Option<String>,
        /// シンボルパス("tokio::net::TcpStream"形式)
        #[serde(default, skip_serializing_if = "Option::is_none")]
        symbol_path: Option<String>,
        /// 対象の構造体名(診断用、フォールバック検索)
        #[serde(
            default,
            skip_serializing_if = "Option::is_none",
            alias = "target",
            alias = "target_name"
        )]
        target_struct: Option<String>,
        // --- Field attributes ---
        field_name: String,
        field_type: String,
        #[serde(default)]
        is_pub: bool,
    },

    /// フィールドを削除
    RemoveField {
        // --- Target struct (3-field) ---
        /// SymbolId(O(1)確定、"7v2"形式)
        #[serde(default, skip_serializing_if = "Option::is_none")]
        symbol_id: Option<String>,
        /// シンボルパス("tokio::net::TcpStream"形式)
        #[serde(default, skip_serializing_if = "Option::is_none")]
        symbol_path: Option<String>,
        /// 対象の構造体名(診断用、フォールバック検索)
        #[serde(
            default,
            skip_serializing_if = "Option::is_none",
            alias = "target",
            alias = "target_name"
        )]
        target_struct: Option<String>,
        // --- Field attributes ---
        field_name: String,
    },

    // === Derive操作系 ===
    /// Deriveマクロを追加
    AddDerive {
        // --- Target type (3-field) ---
        /// SymbolId(O(1)確定、"7v2"形式)
        #[serde(default, skip_serializing_if = "Option::is_none")]
        symbol_id: Option<String>,
        /// シンボルパス("tokio::net::TcpStream"形式)
        #[serde(default, skip_serializing_if = "Option::is_none")]
        symbol_path: Option<String>,
        /// 対象の型名(診断用、フォールバック検索)
        #[serde(
            default,
            skip_serializing_if = "Option::is_none",
            alias = "target",
            alias = "target_name"
        )]
        target_type: Option<String>,
        // --- Derive attributes ---
        derives: Vec<String>,
    },

    /// Deriveマクロを削除
    RemoveDerive {
        // --- Target type (3-field) ---
        /// SymbolId(O(1)確定、"7v2"形式)
        #[serde(default, skip_serializing_if = "Option::is_none")]
        symbol_id: Option<String>,
        /// シンボルパス("tokio::net::TcpStream"形式)
        #[serde(default, skip_serializing_if = "Option::is_none")]
        symbol_path: Option<String>,
        /// 対象の型名(診断用、フォールバック検索)
        #[serde(
            default,
            skip_serializing_if = "Option::is_none",
            alias = "target",
            alias = "target_name"
        )]
        target_type: Option<String>,
        // --- Derive attributes ---
        derives: Vec<String>,
    },

    // === Enum操作系 ===
    /// Enumを追加
    AddEnum {
        /// 追加先モジュールパス(必須: "my_crate", "my_crate::domain"等)
        symbol_path: String,
        name: String,
        #[serde(default)]
        variants: Vec<String>,
        #[serde(default)]
        is_pub: bool,
        #[serde(default)]
        derives: Vec<String>,
    },

    /// Enumにバリアントを追加
    AddVariant {
        // --- Target enum (3-field) ---
        /// SymbolId(O(1)確定、"7v2"形式)
        #[serde(default, skip_serializing_if = "Option::is_none")]
        symbol_id: Option<String>,
        /// シンボルパス("tokio::net::TcpStream"形式)
        #[serde(default, skip_serializing_if = "Option::is_none")]
        symbol_path: Option<String>,
        /// 対象のEnum名(診断用、フォールバック検索)
        #[serde(
            default,
            skip_serializing_if = "Option::is_none",
            alias = "target",
            alias = "target_name"
        )]
        target_enum: Option<String>,
        // --- Variant attributes ---
        variant_name: String,
        /// "unit", "tuple:Type1,Type2", "struct:field1:Type1,field2:Type2"
        #[serde(default = "default_variant_type")]
        variant_type: String,
    },

    /// Enumからバリアントを削除
    RemoveVariant {
        // --- Target enum (3-field) ---
        /// SymbolId(O(1)確定、"7v2"形式)
        #[serde(default, skip_serializing_if = "Option::is_none")]
        symbol_id: Option<String>,
        /// シンボルパス("tokio::net::TcpStream"形式)
        #[serde(default, skip_serializing_if = "Option::is_none")]
        symbol_path: Option<String>,
        /// 対象のEnum名(診断用、フォールバック検索)
        #[serde(
            default,
            skip_serializing_if = "Option::is_none",
            alias = "target",
            alias = "target_name"
        )]
        target_enum: Option<String>,
        // --- Variant attributes ---
        variant_name: String,
    },

    /// Match式にarmを追加(Cascade用)
    ///
    /// AddVariantと組み合わせて使用。CascadeAnalyzerで生成された
    /// AddMatchArmをIntentとして渡すことで、網羅性エラーを自動修正。
    AddMatchArm {
        // --- Target function (3-field pattern) ---
        /// SymbolId(O(1)確定、"7v2"形式)
        #[serde(default, skip_serializing_if = "Option::is_none")]
        symbol_id: Option<String>,
        /// 関数のシンボルパス (e.g., "crate::handlers::process")
        #[serde(default, skip_serializing_if = "Option::is_none")]
        symbol_path: Option<String>,
        /// 関数名(symbol_pathから自動抽出可能、明示指定も可)
        #[serde(default, skip_serializing_if = "Option::is_none")]
        target_fn: Option<String>,
        // --- Match arm parameters ---
        /// 対象のenum型名
        enum_name: String,
        /// 追加するパターン (e.g., "Status::Cancelled")
        pattern: String,
        /// Armのbody (e.g., "todo!()")
        #[serde(default = "default_method_body")]
        body: String,
    },

    /// Match式からarmを削除(Cascade用)
    ///
    /// RemoveVariantと組み合わせて使用。バリアント削除後の
    /// 不要なmatch armを削除する。
    RemoveMatchArm {
        // --- Target function (3-field pattern) ---
        /// SymbolId(O(1)確定、"7v2"形式)
        #[serde(default, skip_serializing_if = "Option::is_none")]
        symbol_id: Option<String>,
        /// 関数のシンボルパス (e.g., "crate::handlers::process")
        #[serde(default, skip_serializing_if = "Option::is_none")]
        symbol_path: Option<String>,
        /// 関数名(symbol_pathから自動抽出可能、明示指定も可)
        #[serde(default, skip_serializing_if = "Option::is_none")]
        target_fn: Option<String>,
        // --- Match arm parameters ---
        /// 対象のenum型名
        enum_name: String,
        /// 削除するパターン (e.g., "Status::Completed")
        pattern: String,
    },

    /// Match armを置換(パターン + body をセットで変更)
    ///
    /// ReplaceExprはbody(式)のみを置換するが、このIntentはパターンも
    /// 同時に置換できる。例えば `{ start: _, end: _ }` を `{ start, end }`
    /// に変更しつつ、bodyも新しい実装に置き換える場合に使用する。
    ReplaceMatchArm {
        // --- Target function (3-field pattern) ---
        /// SymbolId(O(1)確定、"7v2"形式)
        #[serde(default, skip_serializing_if = "Option::is_none")]
        symbol_id: Option<String>,
        /// 関数のシンボルパス (e.g., "crate::handlers::process")
        #[serde(default, skip_serializing_if = "Option::is_none")]
        symbol_path: Option<String>,
        /// 関数名(symbol_pathから自動抽出可能、明示指定も可)
        #[serde(default, skip_serializing_if = "Option::is_none")]
        target_fn: Option<String>,
        // --- Match arm parameters ---
        /// 対象のenum型名
        enum_name: String,
        /// 置換対象のパターン (e.g., "PathSegment::Slice { start: _, end: _ }")
        old_pattern: String,
        /// 新しいパターン (e.g., "PathSegment::Slice { start, end }")
        new_pattern: String,
        /// 新しいbody (e.g., "{ let s = start.unwrap_or(0); ... }")
        new_body: String,
    },

    /// 構造体リテラルにフィールドを追加(Cascade用)
    ///
    /// AddFieldと組み合わせて使用。フィールド追加後の構造体リテラルを
    /// 自動的に更新する。
    AddStructLiteralField {
        // --- Target struct (3-field) ---
        /// SymbolId(O(1)確定、"7v2"形式)
        #[serde(default, skip_serializing_if = "Option::is_none")]
        symbol_id: Option<String>,
        /// シンボルパス("tokio::net::TcpStream"形式)
        #[serde(default, skip_serializing_if = "Option::is_none")]
        symbol_path: Option<String>,
        /// 対象の構造体名(診断用、フォールバック検索)
        #[serde(
            default,
            skip_serializing_if = "Option::is_none",
            alias = "target",
            alias = "target_name"
        )]
        target_struct: Option<String>,
        // --- Field attributes ---
        /// 追加するフィールド名
        field_name: String,
        /// フィールドの値 (e.g., "None", "Default::default()")
        value: String,
    },

    /// 構造体リテラルからフィールドを削除(Cascade用)
    ///
    /// RemoveFieldと組み合わせて使用。フィールド削除後の構造体リテラルを
    /// 自動的に更新する。
    RemoveStructLiteralField {
        // --- Target struct (3-field) ---
        /// SymbolId(O(1)確定、"7v2"形式)
        #[serde(default, skip_serializing_if = "Option::is_none")]
        symbol_id: Option<String>,
        /// シンボルパス("tokio::net::TcpStream"形式)
        #[serde(default, skip_serializing_if = "Option::is_none")]
        symbol_path: Option<String>,
        /// 対象の構造体名(診断用、フォールバック検索)
        #[serde(
            default,
            skip_serializing_if = "Option::is_none",
            alias = "target",
            alias = "target_name"
        )]
        target_struct: Option<String>,
        // --- Field attributes ---
        /// 削除するフィールド名
        field_name: String,
    },

    // === 構造体/Enum削除系 ===
    /// 構造体を削除
    RemoveStruct {
        // --- Target struct (3-field) ---
        /// SymbolId(O(1)確定、"7v2"形式)
        #[serde(default, skip_serializing_if = "Option::is_none")]
        symbol_id: Option<String>,
        /// シンボルパス("tokio::net::TcpStream"形式)
        #[serde(default, skip_serializing_if = "Option::is_none")]
        symbol_path: Option<String>,
        /// 対象の構造体名(診断用、フォールバック検索)
        #[serde(
            default,
            skip_serializing_if = "Option::is_none",
            alias = "target",
            alias = "target_name"
        )]
        target_struct: Option<String>,
    },

    /// Enumを削除
    RemoveEnum {
        // --- Target enum (3-field) ---
        /// SymbolId(O(1)確定、"7v2"形式)
        #[serde(default, skip_serializing_if = "Option::is_none")]
        symbol_id: Option<String>,
        /// シンボルパス("tokio::net::TcpStream"形式)
        #[serde(default, skip_serializing_if = "Option::is_none")]
        symbol_path: Option<String>,
        /// 対象のEnum名(診断用、フォールバック検索)
        #[serde(
            default,
            skip_serializing_if = "Option::is_none",
            alias = "target",
            alias = "target_name"
        )]
        target_enum: Option<String>,
    },

    // === 複製系 ===
    /// 関数を複製
    DuplicateFunction {
        // --- Target function (3-field) ---
        /// SymbolId(O(1)確定、"7v2"形式)
        #[serde(default, skip_serializing_if = "Option::is_none")]
        symbol_id: Option<String>,
        /// シンボルパス("tokio::net::TcpStream"形式)
        #[serde(default, skip_serializing_if = "Option::is_none")]
        symbol_path: Option<String>,
        /// 複製元の関数名(診断用、フォールバック検索)
        #[serde(
            default,
            skip_serializing_if = "Option::is_none",
            alias = "target",
            alias = "target_name"
        )]
        target_fn: Option<String>,
        // --- Duplicate attributes ---
        /// 新しい関数名
        to: String,
    },

    /// 構造体を複製(関連impl含む)
    DuplicateStruct {
        // --- Target struct (3-field) ---
        /// SymbolId(O(1)確定、"7v2"形式)
        #[serde(default, skip_serializing_if = "Option::is_none")]
        symbol_id: Option<String>,
        /// シンボルパス("tokio::net::TcpStream"形式)
        #[serde(default, skip_serializing_if = "Option::is_none")]
        symbol_path: Option<String>,
        /// 複製元の構造体名(診断用、フォールバック検索)
        #[serde(
            default,
            skip_serializing_if = "Option::is_none",
            alias = "target",
            alias = "target_name"
        )]
        target_struct: Option<String>,
        // --- Duplicate attributes ---
        /// 新しい構造体名
        to: String,
        /// impl blockも複製するか
        #[serde(default = "default_true")]
        include_impls: bool,
    },

    /// Enumを複製(関連impl含む)
    DuplicateEnum {
        // --- Target enum (3-field) ---
        /// SymbolId(O(1)確定、"7v2"形式)
        #[serde(default, skip_serializing_if = "Option::is_none")]
        symbol_id: Option<String>,
        /// シンボルパス("tokio::net::TcpStream"形式)
        #[serde(default, skip_serializing_if = "Option::is_none")]
        symbol_path: Option<String>,
        /// 複製元のEnum名(診断用、フォールバック検索)
        #[serde(
            default,
            skip_serializing_if = "Option::is_none",
            alias = "target",
            alias = "target_name"
        )]
        target_enum: Option<String>,
        // --- Duplicate attributes ---
        /// 新しいEnum名
        to: String,
        /// impl blockも複製するか
        #[serde(default = "default_true")]
        include_impls: bool,
    },

    /// インラインモジュールを複製
    DuplicateModTree {
        // --- Target module (3-field) ---
        /// SymbolId(O(1)確定、"7v2"形式)
        #[serde(default, skip_serializing_if = "Option::is_none")]
        symbol_id: Option<String>,
        /// シンボルパス("tokio::net::TcpStream"形式)
        #[serde(default, skip_serializing_if = "Option::is_none")]
        symbol_path: Option<String>,
        /// 複製元のモジュール名(診断用、フォールバック検索)
        #[serde(
            default,
            skip_serializing_if = "Option::is_none",
            alias = "target",
            alias = "target_name"
        )]
        target_mod: Option<String>,
        // --- Duplicate attributes ---
        /// 新しいモジュール名
        to: String,
    },

    // === 定数/型エイリアス系 ===
    /// 定数を追加
    AddConst {
        /// 追加先モジュールパス(必須: "my_crate", "my_crate::domain"等)
        symbol_path: String,
        name: String,
        ty: String,
        value: String,
        #[serde(default)]
        is_pub: bool,
    },

    /// 型エイリアスを追加
    AddTypeAlias {
        /// 追加先モジュールパス(必須: "my_crate", "my_crate::domain"等)
        symbol_path: String,
        name: String,
        ty: String,
        #[serde(default)]
        is_pub: bool,
    },

    // === Spec系 ===
    /// Spec TypeAliasを追加 (ドメイン仕様マーカー)
    AddSpec {
        // --- Target type (3-field) ---
        /// SymbolId(O(1)確定、"7v2"形式)
        #[serde(default, skip_serializing_if = "Option::is_none")]
        symbol_id: Option<String>,
        /// シンボルパス("tokio::net::TcpStream"形式)
        #[serde(default, skip_serializing_if = "Option::is_none")]
        symbol_path: Option<String>,
        /// 対象の型名(診断用、フォールバック検索)
        #[serde(
            default,
            skip_serializing_if = "Option::is_none",
            alias = "target",
            alias = "target_name"
        )]
        target_type: Option<String>,

        // --- Module (3-field) ---
        /// モジュールのSymbolId
        #[serde(default, skip_serializing_if = "Option::is_none")]
        module_id: Option<String>,
        /// モジュールのシンボルパス (e.g., "crate::domain")
        #[serde(default, skip_serializing_if = "Option::is_none")]
        module_path: Option<String>,
        /// モジュール名(診断用、フォールバック検索)
        #[serde(default, skip_serializing_if = "Option::is_none")]
        target_mod: Option<String>,

        /// グループ名 (e.g., "DomainGroup", "ConfigGroup")
        group: String,
        /// エイリアス名 (省略時: "{target_type}Spec")
        #[serde(default)]
        alias_name: Option<String>,
        /// 依存関係 (最大3つ)
        #[serde(default)]
        relations: Vec<SpecRelation>,
    },

    // === メソッド追加・削除 ===
    /// implにメソッドを追加
    AddMethod {
        /// SymbolId(O(1)確定、"7v2"形式)
        #[serde(default, skip_serializing_if = "Option::is_none")]
        symbol_id: Option<String>,
        /// シンボルパス("tokio::net::TcpStream"形式)
        #[serde(default, skip_serializing_if = "Option::is_none")]
        symbol_path: Option<String>,
        /// 対象の型名(診断用、フォールバック検索)
        #[serde(
            default,
            skip_serializing_if = "Option::is_none",
            alias = "target",
            alias = "target_name"
        )]
        target_type: Option<String>,
        /// メソッド名
        method_name: String,
        /// パラメータ (name, type) のペア
        #[serde(default)]
        params: Vec<(String, String)>,
        /// 戻り値の型 (None = unit)
        #[serde(default)]
        return_type: Option<String>,
        /// メソッド本体
        #[serde(default = "default_method_body")]
        body: String,
        /// public かどうか
        #[serde(default)]
        is_pub: bool,
        /// selfパラメータ
        #[serde(default)]
        self_param: Option<SelfParam>,
    },

    /// implからメソッドを削除
    RemoveMethod {
        // --- Target impl type (3-field) ---
        /// SymbolId(O(1)確定、"7v2"形式)
        #[serde(default, skip_serializing_if = "Option::is_none")]
        symbol_id: Option<String>,
        /// シンボルパス("tokio::net::TcpStream"形式)
        #[serde(default, skip_serializing_if = "Option::is_none")]
        symbol_path: Option<String>,
        /// 対象の型名(診断用、フォールバック検索)
        #[serde(
            default,
            skip_serializing_if = "Option::is_none",
            alias = "target",
            alias = "target_name"
        )]
        target_type: Option<String>,
        // --- Method attributes ---
        method_name: String,
    },

    // === 削除系 ===
    /// 定数を削除
    RemoveConst {
        // --- Target const (3-field) ---
        /// SymbolId(O(1)確定、"7v2"形式)
        #[serde(default, skip_serializing_if = "Option::is_none")]
        symbol_id: Option<String>,
        /// シンボルパス("tokio::net::TcpStream"形式)
        #[serde(default, skip_serializing_if = "Option::is_none")]
        symbol_path: Option<String>,
        /// 対象の定数名(診断用、フォールバック検索)
        #[serde(
            default,
            skip_serializing_if = "Option::is_none",
            alias = "target",
            alias = "target_name"
        )]
        target_const: Option<String>,
    },

    /// 型エイリアスを削除
    RemoveTypeAlias {
        // --- Target type alias (3-field) ---
        /// SymbolId(O(1)確定、"7v2"形式)
        #[serde(default, skip_serializing_if = "Option::is_none")]
        symbol_id: Option<String>,
        /// シンボルパス("tokio::net::TcpStream"形式)
        #[serde(default, skip_serializing_if = "Option::is_none")]
        symbol_path: Option<String>,
        /// 対象の型エイリアス名(診断用、フォールバック検索)
        #[serde(
            default,
            skip_serializing_if = "Option::is_none",
            alias = "target",
            alias = "target_name"
        )]
        target_type_alias: Option<String>,
    },

    /// use文を削除
    RemoveUse {
        // --- Target use (3-field) ---
        /// SymbolId(O(1)確定、"7v2"形式)
        #[serde(default, skip_serializing_if = "Option::is_none")]
        symbol_id: Option<String>,
        /// シンボルパス("tokio::net::TcpStream"形式)
        #[serde(default, skip_serializing_if = "Option::is_none")]
        symbol_path: Option<String>,
        /// 対象のuseパス(診断用、フォールバック検索)
        #[serde(
            default,
            skip_serializing_if = "Option::is_none",
            alias = "target",
            alias = "target_name"
        )]
        target_use: Option<String>,
    },

    /// Traitを削除
    RemoveTrait {
        // --- Target trait (3-field) ---
        /// SymbolId(O(1)確定、"7v2"形式)
        #[serde(default, skip_serializing_if = "Option::is_none")]
        symbol_id: Option<String>,
        /// シンボルパス("tokio::net::TcpStream"形式)
        #[serde(default, skip_serializing_if = "Option::is_none")]
        symbol_path: Option<String>,
        /// 対象のTrait名(診断用、フォールバック検索)
        #[serde(
            default,
            skip_serializing_if = "Option::is_none",
            alias = "target",
            alias = "target_name"
        )]
        target_trait: Option<String>,
    },

    /// impl blockを削除
    RemoveImpl {
        // --- Target impl (3-field) ---
        /// SymbolId(O(1)確定、"7v2"形式)
        #[serde(default, skip_serializing_if = "Option::is_none")]
        symbol_id: Option<String>,
        /// シンボルパス("tokio::net::TcpStream"形式)
        #[serde(default, skip_serializing_if = "Option::is_none")]
        symbol_path: Option<String>,
        /// 対象の型名(診断用、フォールバック検索)
        #[serde(
            default,
            skip_serializing_if = "Option::is_none",
            alias = "target",
            alias = "target_name"
        )]
        target_type: Option<String>,
        // --- Impl attributes ---
        trait_name: Option<String>,
    },

    // === 追加・削除系 ===
    /// アイテム追加
    AddItem {
        // --- Target (3-field) ---
        /// SymbolId(O(1)確定、"7v2"形式)
        #[serde(default, skip_serializing_if = "Option::is_none")]
        symbol_id: Option<String>,
        /// シンボルパス("crate::module"形式)
        #[serde(default, skip_serializing_if = "Option::is_none")]
        symbol_path: Option<String>,
        /// モジュール名(診断用、フォールバック検索)
        #[serde(
            default,
            skip_serializing_if = "Option::is_none",
            alias = "target",
            alias = "target_name"
        )]
        target_mod: Option<String>,
        // --- Add attributes ---
        content: String,
        item_kind: ItemKind,
    },

    /// アイテム削除
    RemoveItem {
        // --- Target (3-field) ---
        /// SymbolId(O(1)確定、"7v2"形式)
        #[serde(default, skip_serializing_if = "Option::is_none")]
        symbol_id: Option<String>,
        /// シンボルパス("tokio::net::TcpStream"形式)
        #[serde(default, skip_serializing_if = "Option::is_none")]
        symbol_path: Option<String>,
        /// 削除対象の名前(診断用、フォールバック検索)
        #[serde(
            default,
            skip_serializing_if = "Option::is_none",
            alias = "target",
            alias = "target_name"
        )]
        target_item: Option<String>,
        // --- Remove attributes ---
        item_kind: ItemKind,
    },

    /// コードを親パスに追加(存在しなければモジュール自動作成)
    ///
    /// AddItemの簡易版。item_kindはsynパースで自動判定し、
    /// 親パスが存在しない場合は再帰的にモジュールを作成する。
    ///
    /// ## 自動モジュール作成
    ///
    /// - **SymbolRegistryあり**: 既存モジュールをスキップし、存在しないモジュールのみ作成
    /// - **SymbolRegistryなし**: 全親セグメントに対してCreateModを生成(CreateModは冪等)
    ///
    /// 例: `parent: "crate::infrastructure::memory"` の場合
    /// 1. CreateMod { parent: "crate", mod_name: "infrastructure" }
    /// 2. CreateMod { parent: "crate::infrastructure", mod_name: "memory" }
    /// 3. AddItem { target: "crate::infrastructure::memory", ... }
    ///
    /// ## parent と parent_ref
    ///
    /// どちらか一方を指定。両方指定時は parent_ref を優先。
    ///
    /// # Example (シンプル形式 - parent)
    /// ```json
    /// {
    ///   "type": "AddCode",
    ///   "parent": "crate::usecase",
    ///   "code": "pub struct CreateOrderInput { pub user_id: UserId }"
    /// }
    /// ```
    ///
    /// # Example (明示的形式 - parent_ref)
    /// ```json
    /// {
    ///   "type": "AddCode",
    ///   "parent_ref": { "type": "FilePath", "path": "src/usecase.rs" },
    ///   "code": "pub struct CreateOrderInput { ... }"
    /// }
    /// ```
    AddCode {
        /// SymbolId直接指定("7v2"形式、O(1)解決)
        #[serde(default)]
        symbol_id: Option<String>,
        /// SymbolPathまたはファイルパス
        /// "::"を含めばSymbolPath、それ以外はファイルパスとして解釈
        #[serde(default, alias = "parent")]
        symbol_path: Option<String>,
        /// モジュール名(診断/フォールバック用)
        #[serde(default, alias = "target", alias = "target_name")]
        target_mod: Option<String>,
        /// 追加するRustコード(複数Item可、synでパース)
        code: String,
    },

    // === IDIOM系 (Agent自動適用向け) ===
    /// use文の整理・ソート
    OrganizeImports {
        /// 対象モジュール(None = 全モジュール)"lib::foo::bar" 形式
        #[serde(default)]
        target_mod: Option<String>,
        /// 重複を削除
        #[serde(default = "default_true")]
        deduplicate: bool,
        /// 同一プレフィックスをグループ化
        #[serde(default = "default_true")]
        merge_groups: bool,
    },

    /// 同一型のimplブロックをマージ
    MergeImplBlocks {
        /// 対象モジュール(None = 全モジュール)
        #[serde(default)]
        target_mod: Option<String>,
        /// 対象の型名 (None = 全て)
        #[serde(default)]
        target_type: Option<String>,
        /// inherent implのみ (trait implを除外)
        #[serde(default)]
        inherent_only: bool,
    },

    /// forループをイテレータチェーンに変換
    LoopToIterator {
        /// 対象モジュール(None = 全モジュール)
        #[serde(default)]
        target_mod: Option<String>,
        /// 特定の変数名のループのみ対象
        #[serde(default)]
        target_var: Option<String>,
    },

    /// .unwrap()/.expect() を ? 演算子に変換
    UnwrapToQuestion {
        /// 対象モジュール(None = 全モジュール)
        #[serde(default)]
        target_mod: Option<String>,
        /// 特定の関数のみ対象
        #[serde(default)]
        target_fn: Option<String>,
        /// .expect()も変換対象にする
        #[serde(default = "default_true")]
        include_expect: bool,
    },

    /// 重複式を変数に抽出
    IntroduceVariable {
        /// 対象モジュール(None = 全モジュール)
        #[serde(default)]
        target_mod: Option<String>,
        /// 対象の関数名(None = 全関数)
        #[serde(default)]
        target_fn: Option<String>,
        /// 抽出対象の式(Rustコード文字列, e.g. "a + b * c")
        expr: String,
        /// 抽出する変数名
        var_name: String,
    },

    /// Builder patternを生成
    ///
    /// 指定した struct に対して Builder pattern を生成する。
    /// 以下のコードが生成される:
    /// - `{StructName}Builder` struct (Option-wrapped fields)
    /// - `impl {StructName}Builder` with `new()`, setter methods, `build()`
    /// - (オプション) `impl {StructName}` with `builder()` method
    ///
    /// # Example
    /// ```json
    /// {
    ///   "type": "GenerateBuilder",
    ///   "struct_name": "Config",
    ///   "fields": [
    ///     ["host", "String"],
    ///     ["port", "u16"],
    ///     ["timeout", "Option<u32>"]
    ///   ]
    /// }
    /// ```
    GenerateBuilder {
        // --- Target struct (3-field) ---
        /// SymbolId(O(1)確定、"7v2"形式)
        #[serde(default, skip_serializing_if = "Option::is_none")]
        symbol_id: Option<String>,
        /// シンボルパス("tokio::net::TcpStream"形式)
        #[serde(default, skip_serializing_if = "Option::is_none")]
        symbol_path: Option<String>,
        /// 対象の struct 名(診断用、フォールバック検索)
        #[serde(
            default,
            skip_serializing_if = "Option::is_none",
            alias = "target",
            alias = "target_name"
        )]
        target_struct: Option<String>,
        // --- Builder attributes ---
        /// Builder追加先のモジュールパス(例: "crate::config")
        /// symbol_id指定時は省略可(registryから解決)
        #[serde(default)]
        target_mod: Option<String>,
        /// フィールド定義 [(name, type), ...]
        fields: Vec<(String, String)>,
        /// 元の struct に builder() メソッドを追加するか(デフォルト: true)
        #[serde(default = "default_true")]
        add_builder_method: bool,
    },

    // === PureStmt/PureExpr 操作系 ===
    /// 式を別の式に置換
    ///
    /// 対象指定方法(どちらか一方を使用):
    /// - `old_expr`: パターンマッチで対象を検索
    /// - `symbol_path`: 直接位置指定(例: "crate::fn::$body::0::1")
    ReplaceExpr {
        /// 対象モジュール(None = 全モジュール)
        #[serde(default)]
        target_mod: Option<String>,
        /// 対象の関数名(None=全関数)
        #[serde(default)]
        target_fn: Option<String>,
        /// 置換元の式(Rustコード文字列)- パターンマッチ方式
        old_expr: String,
        /// 置換先の式(Rustコード文字列)
        new_expr: String,
        /// 全ての出現箇所を置換するか(デフォルト: true)
        #[serde(default = "default_true")]
        replace_all: bool,
        /// 直接位置指定(例: "my_crate::my_fn::$body::0::1::2")
        /// 指定時は old_expr を無視し、この位置の式を直接置換
        #[serde(default)]
        symbol_path: Option<String>,
    },

    /// 文を削除
    ///
    /// 対象指定方法(どちらか一方を使用):
    /// - `pattern`: パターンマッチで対象を検索
    /// - `symbol_path`: 直接位置指定(例: "crate::fn::$body::2")
    RemoveStatement {
        /// 対象モジュール(None = 全モジュール)
        #[serde(default)]
        target_mod: Option<String>,
        /// 対象の関数名(None=全関数)
        #[serde(default)]
        target_fn: Option<String>,
        /// 削除対象の文パターン(Rustコード文字列, e.g. "println!(..)")- パターンマッチ方式
        pattern: String,
        /// 全ての出現箇所を削除するか(デフォルト: true)
        #[serde(default = "default_true")]
        remove_all: bool,
        /// 直接位置指定(例: "my_crate::my_fn::$body::2")
        /// 指定時は pattern を無視し、この位置の文を直接削除
        #[serde(default)]
        symbol_path: Option<String>,
    },

    /// 文を挿入
    ///
    /// 対象指定方法:
    /// - `target_fn` + `position`: 従来方式
    /// - `symbol_path`: 直接位置指定($body::N の後に挿入)
    InsertStatement {
        /// 対象モジュール(None = 全モジュール)
        #[serde(default)]
        target_mod: Option<String>,
        /// 対象の関数名
        target_fn: String,
        /// 挿入する文(Rustコード文字列)
        stmt: String,
        /// 挿入位置
        #[serde(default)]
        position: StmtInsertPosition,
        /// 参照パターン(BeforePattern/AfterPattern用)
        #[serde(default)]
        reference_pattern: Option<String>,
        /// 直接位置指定(例: "my_crate::my_fn::$body::2")
        /// 指定時は position を無視し、この位置の後に挿入
        #[serde(default)]
        symbol_path: Option<String>,
    },

    /// 文を別の文に置換
    ///
    /// 対象指定方法(どちらか一方を使用):
    /// - `old_stmt`: パターンマッチで対象を検索
    /// - `symbol_path`: 直接位置指定(例: "crate::fn::$body::1")
    ReplaceStatement {
        /// 対象モジュール(None = 全モジュール)
        #[serde(default)]
        target_mod: Option<String>,
        /// 対象の関数名(None=全関数)
        #[serde(default)]
        target_fn: Option<String>,
        /// 置換元の文パターン(Rustコード文字列)- パターンマッチ方式
        old_stmt: String,
        /// 置換先の文(Rustコード文字列)
        new_stmt: String,
        /// 直接位置指定(例: "my_crate::my_fn::$body::1")
        /// 指定時は old_stmt を無視し、この位置の文を直接置換
        #[serde(default)]
        symbol_path: Option<String>,
    },

    // === 追加 Idiom変換系 ===
    /// 代入演算子の簡略化: `x = x + 1` → `x += 1`
    AssignOp {
        /// 対象モジュール(None = 全モジュール)
        #[serde(default)]
        target_mod: Option<String>,
        /// 特定の関数のみ対象
        #[serde(default)]
        target_fn: Option<String>,
    },

    /// bool式の簡略化: `x == true` → `x`, `x == false` → `!x`
    BoolSimplify {
        /// 対象モジュール(None = 全モジュール)
        #[serde(default)]
        target_mod: Option<String>,
    },

    /// Copy型での冗長な.clone()削除
    CloneOnCopy {
        /// 対象モジュール(None = 全モジュール)
        #[serde(default)]
        target_mod: Option<String>,
    },

    /// ネストしたifを&&で統合: `if a { if b { ... } }` → `if a && b { ... }`
    CollapsibleIf {
        /// 対象モジュール(None = 全モジュール)
        #[serde(default)]
        target_mod: Option<String>,
    },

    /// 比較をメソッド呼び出しに変換: `s == ""` → `s.is_empty()`
    ComparisonToMethod {
        /// 対象モジュール(None = 全モジュール)
        #[serde(default)]
        target_mod: Option<String>,
    },

    /// 冗長なクロージャを削除: `|x| f(x)` → `f`
    RedundantClosure {
        /// 対象モジュール(None = 全モジュール)
        #[serde(default)]
        target_mod: Option<String>,
    },

    /// matchをmap()に変換: `match opt { Some(x) => Some(f(x)), None => None }` → `opt.map(f)`
    ManualMap {
        /// 対象モジュール(None = 全モジュール)
        #[serde(default)]
        target_mod: Option<String>,
    },

    /// matchをif letに変換
    MatchToIfLet {
        /// 対象モジュール(None = 全モジュール)
        #[serde(default)]
        target_mod: Option<String>,
    },

    /// .filter().next() を .find() に変換
    FilterNext {
        /// 対象モジュール(None = 全モジュール)
        #[serde(default)]
        target_mod: Option<String>,
        /// 特定の関数のみ対象
        #[serde(default)]
        target_fn: Option<String>,
    },

    /// .map().unwrap_or() を .map_or() に変換
    MapUnwrapOr {
        /// 対象モジュール(None = 全モジュール)
        #[serde(default)]
        target_mod: Option<String>,
        /// 特定の関数のみ対象
        #[serde(default)]
        target_fn: Option<String>,
    },

    // === カスタム ===
    /// LLMが理解したが定義済みIntentにマッチしない場合
    Custom {
        description: String,
        /// LLMが推測した変換例(Before → After)
        examples: Vec<TransformExample>,
    },

    // === WASM Plugin ===
    /// Execute a WASM plugin by name
    #[cfg(feature = "wasm-plugin")]
    Plugin {
        /// Plugin name (must be registered in MutationRegistry)
        name: String,
        /// Glob patterns for multi-file targeting (e.g., ["**/*.rs", "src/lib.rs"])
        /// If empty, uses all files in project or scope.file_patterns
        #[serde(default)]
        file_patterns: Vec<String>,
    },
}

// ============================================================================
// Supporting Types
// ============================================================================

/// 文の挿入位置
#[cfg_attr(feature = "schemars", derive(JsonSchema))]
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
#[derive(Default)]
pub enum StmtInsertPosition {
    /// 関数の先頭
    Start,
    /// 関数の末尾(return文の前)
    #[default]
    End,
    /// 指定した文の前
    BeforePattern,
    /// 指定した文の後
    AfterPattern,
}

/// 識別子の種類
#[cfg_attr(feature = "schemars", derive(JsonSchema))]
#[derive(Debug, Clone, Copy, Serialize, Deserialize, PartialEq, Eq)]
pub enum IdentKind {
    /// 変数: let x
    Var,
    /// フィールド: struct.field
    Field,
    /// 関数: fn foo()
    Fn,
    /// 型: struct/enum/type alias
    Type,
    /// モジュール: mod foo
    Module,
    /// 種類不明
    Any,
}

/// 可視性
#[cfg_attr(feature = "schemars", derive(JsonSchema))]
#[derive(Debug, Clone, Copy, Serialize, Deserialize, PartialEq, Eq)]
pub enum Visibility {
    Private,
    Pub,
    PubCrate,
    PubSuper,
}

/// メソッドのselfパラメータ
#[cfg_attr(feature = "schemars", derive(JsonSchema))]
#[derive(Debug, Clone, Copy, Serialize, Deserialize, PartialEq, Eq)]
#[serde(rename_all = "lowercase")]
pub enum SelfParam {
    /// &self
    Ref,
    /// &mut self
    Mut,
    /// self (owned)
    Owned,
}

/// Spec TypeAliasの依存関係
#[cfg_attr(feature = "schemars", derive(JsonSchema))]
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
pub struct SpecRelation {
    /// 関係の種類
    pub kind: SpecRelationKind,
    /// 対象の型名
    pub target: String,
}

/// Spec依存関係の種類
#[cfg_attr(feature = "schemars", derive(JsonSchema))]
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
#[serde(rename_all = "PascalCase")]
pub enum SpecRelationKind {
    /// AがBに依存する (AはBがないと機能しない)
    DependsOn,
    /// AがBと関連する (意味的な関係)
    RelatedTo,
    /// AがBの一部である (集約メンバーシップ)
    PartOf,
}

/// 変換例(Custom用)
#[cfg_attr(feature = "schemars", derive(JsonSchema))]
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct TransformExample {
    pub before: String,
    pub after: String,
}

// ============================================================================
// ScopeHint: 並列Discovery用ヒント
// ============================================================================

/// 検索スコープのヒント
///
/// 後段のExecutorが並列Discovery戦略を決定するために使用。
/// すべてのフィールドは省略可能で、デフォルト値が使用される。
#[cfg_attr(feature = "schemars", derive(JsonSchema))]
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(default)]
pub struct ScopeHint {
    /// ファイルパターン(例: "src/**/*.rs", "crates/project-name/**")
    #[serde(skip_serializing_if = "Vec::is_empty")]
    pub file_patterns: Vec<String>,

    /// シンボルパターン(例: "*Config", "crate::domain::User")
    /// "::"を含む → SymbolPath、それ以外 → Globパターン
    #[serde(skip_serializing_if = "Vec::is_empty")]
    pub symbol_patterns: Vec<String>,

    /// 推定影響範囲
    #[serde(skip_serializing_if = "is_estimated_scope_unknown")]
    pub estimated_scope: EstimatedScope,
}

fn is_estimated_scope_unknown(scope: &EstimatedScope) -> bool {
    matches!(scope, EstimatedScope::Unknown)
}

/// 推定影響範囲
#[cfg_attr(feature = "schemars", derive(JsonSchema))]
#[derive(Debug, Clone, Copy, Serialize, Deserialize, PartialEq, Eq, Default)]
pub enum EstimatedScope {
    /// 1ファイルのみ
    SingleFile,
    /// 2-5ファイル
    FewFiles,
    /// 6+ファイル
    ManyFiles,
    /// プロジェクト全体
    ProjectWide,
    /// 不明
    #[default]
    Unknown,
}

impl EstimatedScope {
    /// Check if this is the Unknown variant (for serde skip_serializing_if)
    pub fn is_unknown(&self) -> bool {
        matches!(self, Self::Unknown)
    }
}

impl Default for ScopeHint {
    fn default() -> Self {
        Self {
            file_patterns: vec!["**/*.rs".to_string()],
            symbol_patterns: vec![],
            estimated_scope: EstimatedScope::Unknown,
        }
    }
}

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

    pub fn with_file_patterns(mut self, patterns: Vec<String>) -> Self {
        self.file_patterns = patterns;
        self
    }

    pub fn with_symbol_patterns(mut self, patterns: Vec<String>) -> Self {
        self.symbol_patterns = patterns;
        self
    }

    pub fn with_estimated_scope(mut self, scope: EstimatedScope) -> Self {
        self.estimated_scope = scope;
        self
    }
}

// ============================================================================
// Constraint: 実行時制約
// ============================================================================

/// 実行時制約
#[cfg_attr(feature = "schemars", derive(JsonSchema))]
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
pub enum Constraint {
    /// コンパイルが通ること(syn parse + cargo check)
    MustCompile,

    /// pub APIを破壊しない
    PreservePublicApi,

    /// テストが通ること
    MustPassTests,

    /// 変更しない(プレビューのみ)
    DryRun,

    /// 対話的確認が必要
    RequireConfirmation,

    /// 適用後にcargo checkを実行
    CargoCheck,

    /// cargo check失敗時に変更をロールバック(CargoCheckと併用)
    RollbackOnFailure,
}

// ============================================================================
// ExtractError
// ============================================================================

/// Intent抽出エラー
#[derive(Debug, thiserror::Error)]
pub enum ExtractError {
    #[error("LLM connection failed: {0}")]
    ConnectionFailed(String),

    #[error("Failed to parse LLM response: {0}")]
    ParseFailed(String),

    #[error("Query too ambiguous: {0}")]
    AmbiguousQuery(String),

    #[error("Unsupported query type: {0}")]
    UnsupportedQuery(String),
}

// ============================================================================
// IntentExtractor Trait
// ============================================================================

/// IntentExtractor: NLクエリ → Goal
///
/// 責務:ゴール設定のみ。検索・変換は一切行わない。
pub trait IntentExtractor: Send + Sync {
    /// クエリからGoalを抽出
    fn extract(&self, query: &str) -> Result<Goal, ExtractError>;

    /// バッチ抽出(複数クエリを並列処理)
    fn extract_batch(&self, queries: &[String]) -> Vec<Result<Goal, ExtractError>>;

    /// 使用モデル名
    fn model_name(&self) -> &str;
}

// ============================================================================
// Goal Builder
// ============================================================================

impl Goal {
    /// 新しいGoalを構築(単一Intent)
    pub fn new(query: impl Into<String>, intent: Intent) -> Self {
        Self {
            query: query.into(),
            intents: vec![intent],
            scope: ScopeHint::default(),
            constraints: vec![Constraint::MustCompile],
            conflict_strategy: ConflictStrategy::default(),
            confidence: 1.0,
        }
    }

    /// 複数Intentsで構築
    pub fn with_intents(query: impl Into<String>, intents: Vec<Intent>) -> Self {
        Self {
            query: query.into(),
            intents,
            scope: ScopeHint::default(),
            constraints: vec![Constraint::MustCompile],
            conflict_strategy: ConflictStrategy::default(),
            confidence: 1.0,
        }
    }

    /// コンフリクト解決戦略を設定
    pub fn with_conflict_strategy(mut self, strategy: ConflictStrategy) -> Self {
        self.conflict_strategy = strategy;
        self
    }

    pub fn with_scope(mut self, scope: ScopeHint) -> Self {
        self.scope = scope;
        self
    }

    pub fn with_constraints(mut self, constraints: Vec<Constraint>) -> Self {
        self.constraints = constraints;
        self
    }

    pub fn with_confidence(mut self, confidence: f64) -> Self {
        self.confidence = confidence;
        self
    }

    /// RenameIdentのGoalを簡易構築
    pub fn rename(from: impl Into<String>, to: impl Into<String>) -> Self {
        let from_str = from.into();
        let to_str = to.into();
        let query = format!("{}{}", from_str, to_str);

        Self::new(
            &query,
            Intent::RenameIdent {
                symbol_id: None,
                symbol_path: None,
                target_ident: Some(from_str.clone()),
                to: to_str,
                kind: IdentKind::Any,
            },
        )
        .with_scope(ScopeHint::new().with_estimated_scope(EstimatedScope::FewFiles))
    }

    // Note: to_mutations() and to_mutations_with_discovery() methods are
    // implemented in ryo-executor crate where Mutation execution logic resides.
}

// ============================================================================
// Fuzzy JSON Parsing (feature-gated)
// ============================================================================

#[cfg(feature = "fuzzy-parser")]
impl Goal {
    /// Parse a Goal from JSON with fuzzy correction for typos
    ///
    /// This method automatically corrects common typos in Intent type names
    /// and field names that may occur when JSON is generated by LLMs.
    ///
    /// # Example
    /// ```ignore
    /// let json = r#"{
    ///     "query": "Add derives",
    ///     "intents": [{"type": "AddDeriv", "taget": "User", "derives": ["Debug"]}]
    /// }"#;
    /// let (goal, corrections) = Goal::from_json_fuzzy(json)?;
    /// // Typos corrected: AddDeriv → AddDerive, taget → target
    /// ```
    pub fn from_json_fuzzy(
        json: &str,
    ) -> Result<(Self, Vec<ryo_fuzzy_parser::Correction>), GoalParseError> {
        Self::from_json_fuzzy_with_options(json, &ryo_fuzzy_parser::FuzzyOptions::default())
    }

    /// Parse a Goal from JSON with fuzzy correction using custom options
    pub fn from_json_fuzzy_with_options(
        json: &str,
        options: &ryo_fuzzy_parser::FuzzyOptions,
    ) -> Result<(Self, Vec<ryo_fuzzy_parser::Correction>), GoalParseError> {
        use crate::intent_schema::{intent_schema, GOAL_FIELDS};
        use ryo_fuzzy_parser::{repair_fields_with_list, repair_tagged_enum_array, ObjectSchema};

        // Parse JSON first
        let mut value: serde_json::Value =
            serde_json::from_str(json).map_err(|e| GoalParseError::JsonParse(e.to_string()))?;

        let mut all_corrections = Vec::new();

        // Repair Goal-level fields
        if let Some(obj) = value.as_object_mut() {
            let goal_schema = ObjectSchema::new(GOAL_FIELDS);
            let corrections = repair_fields_with_list(obj, goal_schema.valid_fields, "$", options);
            all_corrections.extend(corrections);

            // Repair intents array
            if let Some(intents) = obj.get_mut("intents").and_then(|v| v.as_array_mut()) {
                let schema = intent_schema();
                let corrections = repair_tagged_enum_array(intents, &schema, "$.intents", options);
                all_corrections.extend(corrections);
            }
        }

        let goal: Goal =
            serde_json::from_value(value).map_err(|e| GoalParseError::JsonParse(e.to_string()))?;

        Ok((goal, all_corrections))
    }
}

#[cfg(feature = "fuzzy-parser")]
impl Intent {
    /// Parse an Intent from JSON with fuzzy correction for typos
    ///
    /// # Example
    /// ```ignore
    /// let json = r#"{"type": "AddDeriv", "taget": "User", "derives": ["Debug"]}"#;
    /// let (intent, corrections) = Intent::from_json_fuzzy(json)?;
    /// ```
    pub fn from_json_fuzzy(
        json: &str,
    ) -> Result<(Self, Vec<ryo_fuzzy_parser::Correction>), GoalParseError> {
        Self::from_json_fuzzy_with_options(json, &ryo_fuzzy_parser::FuzzyOptions::default())
    }

    /// Parse an Intent from JSON with fuzzy correction using custom options
    pub fn from_json_fuzzy_with_options(
        json: &str,
        options: &ryo_fuzzy_parser::FuzzyOptions,
    ) -> Result<(Self, Vec<ryo_fuzzy_parser::Correction>), GoalParseError> {
        use crate::intent_schema::intent_schema;
        use ryo_fuzzy_parser::repair_tagged_enum_json;

        let schema = intent_schema();
        let result = repair_tagged_enum_json(json, &schema, options)
            .map_err(|e| GoalParseError::FuzzyRepair(e.to_string()))?;

        let intent: Intent = serde_json::from_value(result.repaired)
            .map_err(|e| GoalParseError::JsonParse(e.to_string()))?;

        Ok((intent, result.corrections))
    }
}

/// Error type for Goal/Intent parsing
#[cfg(feature = "fuzzy-parser")]
#[derive(Debug, thiserror::Error)]
pub enum GoalParseError {
    #[error("JSON parse error: {0}")]
    JsonParse(String),

    #[error("Fuzzy repair error: {0}")]
    FuzzyRepair(String),
}
// ============================================================================
// From<CascadeSpec> for Intent
// ============================================================================

impl From<ryo_analysis::cascade::CascadeSpec> for Intent {
    fn from(spec: ryo_analysis::cascade::CascadeSpec) -> Self {
        use ryo_analysis::cascade::CascadeSpec;

        match spec {
            CascadeSpec::AddMatchArm {
                target,
                function_name,
                enum_name,
                pattern,
                body,
            } => {
                // Construct full function path: target (module or module::Type) + function_name
                let fn_path = target
                    .child(&function_name)
                    .map(|p| p.to_string())
                    .unwrap_or_else(|_| format!("{}::{}", target, function_name));
                Intent::AddMatchArm {
                    symbol_id: None,
                    symbol_path: Some(fn_path),
                    target_fn: None,
                    enum_name,
                    pattern,
                    body,
                }
            }
            CascadeSpec::AddDerive { symbol_id, derives } => Intent::AddDerive {
                symbol_id: Some(format!("{:?}", symbol_id)),
                symbol_path: None,
                target_type: None,
                derives,
            },
            CascadeSpec::ChangeVisibility {
                symbol_id,
                visibility,
                ..
            } => {
                let vis = match visibility {
                    ryo_analysis::cascade::Visibility::Private => Visibility::Private,
                    ryo_analysis::cascade::Visibility::Crate => Visibility::PubCrate,
                    ryo_analysis::cascade::Visibility::Super => Visibility::PubSuper,
                    ryo_analysis::cascade::Visibility::Public => Visibility::Pub,
                };
                Intent::ChangeVisibility {
                    symbol_id: Some(format!("{:?}", symbol_id)),
                    symbol_path: None,
                    target_item: None,
                    to: vis,
                }
            }
            CascadeSpec::AddUse { path, .. } => Intent::Custom {
                description: format!("Add use statement: {}", path),
                examples: vec![],
            },
            CascadeSpec::GenerateImpl {
                target, trait_name, ..
            } => Intent::Custom {
                description: format!("Generate impl {} for {}", trait_name, target),
                examples: vec![],
            },
            CascadeSpec::RemoveMatchArm {
                target,
                function_name,
                enum_name,
                pattern,
            } => {
                // Construct full function path: target (module or module::Type) + function_name
                let fn_path = target
                    .child(&function_name)
                    .map(|p| p.to_string())
                    .unwrap_or_else(|_| format!("{}::{}", target, function_name));
                Intent::RemoveMatchArm {
                    symbol_id: None,
                    symbol_path: Some(fn_path),
                    target_fn: None,
                    enum_name,
                    pattern,
                }
            }
        }
    }
}

// ============================================================================
// Tests
// ============================================================================

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

    #[test]
    fn test_goal_builder() {
        let goal = Goal::rename("is_debug", "enable_debug");
        assert!(goal.query.contains("is_debug"));

        if let Intent::RenameIdent {
            target_ident,
            to,
            kind,
            ..
        } = &goal.intents[0]
        {
            assert_eq!(target_ident.as_deref(), Some("is_debug"));
            assert_eq!(to, "enable_debug");
            assert_eq!(kind, &IdentKind::Any);
        } else {
            panic!("Expected RenameIdent intent");
        }
    }

    #[test]
    fn test_scope_hint_builder() {
        let scope = ScopeHint::new()
            .with_file_patterns(vec!["src/**/*.rs".to_string()])
            .with_symbol_patterns(vec!["*Config".to_string()])
            .with_estimated_scope(EstimatedScope::ManyFiles);

        assert_eq!(scope.file_patterns, vec!["src/**/*.rs"]);
        assert_eq!(scope.symbol_patterns, vec!["*Config"]);
        assert_eq!(scope.estimated_scope, EstimatedScope::ManyFiles);
    }

    #[test]
    fn add_variant_rejects_unknown_field() {
        // NG-1: variant_fields is not a valid field — should error, not silently ignore
        let json = serde_json::json!({
            "type": "AddVariant",
            "target_enum": "Filter",
            "variant_name": "Add",
            "variant_fields": [["left", "Box<Filter>"], ["right", "Box<Filter>"]]
        });
        let result = serde_json::from_value::<Intent>(json);
        assert!(
            result.is_err(),
            "Unknown field 'variant_fields' should cause deserialization error, got: {:?}",
            result.unwrap()
        );
        let err_msg = result.unwrap_err().to_string();
        assert!(
            err_msg.contains("unknown field"),
            "Error should mention 'unknown field', got: {}",
            err_msg
        );
    }

    #[test]
    fn add_variant_valid_fields_accepted() {
        let json = serde_json::json!({
            "type": "AddVariant",
            "target_enum": "Filter",
            "variant_name": "Add",
            "variant_type": "tuple:Box<Filter>,Box<Filter>"
        });
        let result = serde_json::from_value::<Intent>(json);
        assert!(
            result.is_ok(),
            "Valid AddVariant should parse: {:?}",
            result.err()
        );
    }
}