ryo-executor 0.1.0

[experimental] Mutation execution engine for RYO - parallel execution, conflict detection, workspace management
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
//! MutationSpec: Atomic, serializable mutation specifications
//!
//! # Architecture: Intent vs MutationSpec
//!
//! Ryo has a two-layer mutation system:
//!
//! ```text
//! ┌─────────────────────────────────────────────────────────────────┐
//! │  Intent (ryo-app::intent)                                       │
//! │  - Public DSL for CLI users                                     │
//! │  - High-level, uses Pattern matching                            │
//! │  - One Intent may expand to multiple MutationSpecs              │
//! │  - Example: AddField { target: Pattern::Glob("*Config"), ... }  │
//! └───────────────────────────┬─────────────────────────────────────┘
//!                             ↓ Resolution & Expansion
//! ┌─────────────────────────────────────────────────────────────────┐
//! │  MutationSpec (this module)                                     │
//! │  - Execution-level specification                                │
//! │  - Concrete targets (SymbolId, exact names)                     │
//! │  - Atomic: one spec = one mutation                              │
//! │  - Example: AddField { struct_name: "AppConfig", ... }          │
//! └───────────────────────────┬─────────────────────────────────────┘
//!                             ↓ Execution
//! ┌─────────────────────────────────────────────────────────────────┐
//! │  AST Mutation                                                   │
//! │  - Actual code transformation                                   │
//! └─────────────────────────────────────────────────────────────────┘
//! ```
//!
//! ## Why Two Layers?
//!
//! - **Intent**: User-friendly, pattern-based, requires symbol resolution
//! - **MutationSpec**: Machine-friendly, direct targets, ready for execution
//!
//! This separation allows:
//! 1. CLI users to use high-level patterns (`*Config`)
//! 2. `Suggest` system to generate specs directly (bypassing Intent)
//! 3. Clear conflict detection at the MutationSpec level
//!
//! ## Usage by Suggest
//!
//! The `Suggest` trait (in `ryo-suggest`) generates `MutationSpec` directly:
//! - Detects opportunities from analyzed code
//! - Converts opportunities to `MutationSpec` via `to_mutation_specs()`
//! - Bypasses Intent layer for efficiency (no pattern resolution needed)
//!
//! See `ryo_suggest::suggest::Suggest` for the trait definition.
//!
//! # Design Goals
//!
//! Designed for:
//! - LLM-friendly: Can be generated/selected by lightweight LLMs
//! - Declarative: Pure data, no behavior
//! - Composable: Multiple specs form a ParallelBlueprint
//!
//! ## Scope: Single Crate + Multi-Module
//!
//! MutationSpec operates within a **single crate** (MonoCrate model).
//! Multi-crate workspace operations are **NOT SUPPORTED**:
//! - No cross-crate MoveItem
//! - No Cargo.toml manipulation (requires TOML parser, not AST)
//! - Use external tools for workspace-level refactoring
//!
//! ## Target Resolution
//!
//! All targeting uses `SymbolPath` (e.g., "crate::config::Settings").
//! SymbolPath provides:
//! - AST-based resolution
//! - Fine-grained conflict detection
//! - Type-safe path operations

use serde::{Deserialize, Serialize};

pub use ryo_analysis::{SymbolId, SymbolPath};
pub use ryo_mutations::{EnumToTraitStrategy, MatchHandling};
pub use ryo_source::ItemKind;

/// Target symbol specification for MutationSpec.
///
/// Supports flexible target resolution:
/// - Eager: Already resolved to SymbolId
/// - Lazy: Resolved during Wave execution (DetectConflict phase)
/// - Derived: Resolved from parent mutations (e.g., newly added struct)
///
/// # Design
///
/// Replaces the scattered `request_*` fields with a unified approach.
/// Enables batch processing of Add & Update operations within a Wave.
///
/// # Examples
///
/// ```text
/// ById(symbol_id)                      // Direct reference (already resolved)
/// ByPath("crate::config::Settings")    // Lazy resolution by path
/// ByKindAndName(Struct, "User")        // Lazy resolution by kind + name
/// ByAffectedId(parent_id, Field, "id") // Derived from parent (e.g., field in newly added struct)
/// ```
#[derive(Debug, Clone, PartialEq, Eq, Hash, Serialize, Deserialize)]
pub enum MutationTargetSymbol {
    /// Direct reference by SymbolId (already resolved)
    ById(SymbolId),
    /// Lazy resolution by SymbolPath (parsed path)
    ByPath(Box<SymbolPath>),
    /// Lazy resolution by kind and name
    ByKindAndName(ItemKind, String),
    /// Derived from affected parent symbol
    /// Example: Field in a struct that was just added in the same Wave
    ByAffectedId {
        /// Parent symbol ID
        parent_id: SymbolId,
        /// Kind of the child item
        kind: ItemKind,
        /// Optional name (None for anonymous items)
        name: Option<String>,
    },
}

impl MutationTargetSymbol {
    /// Create a direct SymbolId reference
    pub fn by_id(id: SymbolId) -> Self {
        Self::ById(id)
    }

    /// Create a lazy SymbolPath reference
    pub fn by_path(path: SymbolPath) -> Self {
        Self::ByPath(Box::new(path))
    }

    /// Create a lazy kind+name reference
    pub fn by_kind_and_name(kind: ItemKind, name: impl Into<String>) -> Self {
        Self::ByKindAndName(kind, name.into())
    }

    /// Create a derived reference from parent
    pub fn by_affected_id(parent_id: SymbolId, kind: ItemKind, name: Option<String>) -> Self {
        Self::ByAffectedId {
            parent_id,
            kind,
            name,
        }
    }

    /// Check if this is already resolved to a SymbolId
    pub fn is_resolved(&self) -> bool {
        matches!(self, Self::ById(_))
    }

    /// Resolve to SymbolPath using the registry.
    ///
    /// Returns `Some(SymbolPath)` if resolution succeeds, `None` otherwise.
    pub fn to_path(&self, registry: &ryo_symbol::SymbolRegistry) -> Option<SymbolPath> {
        match self {
            Self::ById(id) => registry.resolve(*id).cloned(),
            Self::ByPath(path) => Some(*path.clone()),
            Self::ByKindAndName(_, name) => SymbolPath::parse(name).ok(),
            Self::ByAffectedId { parent_id, .. } => registry.resolve(*parent_id).cloned(),
        }
    }
}

// ============================================================================
// Type Transformation Types (for ReplaceType and EnumToTrait)
// ============================================================================

/// Type transformation pattern for ReplaceType.
///
/// Specifies how to transform a type reference.
///
/// # Examples
///
/// ```ignore
/// // Box<dyn Trait>
/// TypeTransform::BoxDyn { trait_name: "Status".to_string() }
///
/// // impl Trait
/// TypeTransform::ImplTrait { trait_name: "Status".to_string() }
///
/// // Generic: <T: Trait>
/// TypeTransform::Generic { param_name: "S".to_string(), bound: "Status".to_string() }
/// ```
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
pub enum TypeTransform {
    /// Transform to `Box<dyn Trait>`
    ///
    /// Example: `Status` → `Box<dyn Status>`
    BoxDyn {
        /// The trait name to use
        trait_name: String,
    },

    /// Transform to `impl Trait` (argument position) or `-> impl Trait` (return position)
    ///
    /// Example: `Status` → `impl Status`
    ImplTrait {
        /// The trait name to use
        trait_name: String,
    },

    /// Transform to generic parameter with trait bound
    ///
    /// Example: `fn foo(s: Status)` → `fn foo<S: Status>(s: S)`
    Generic {
        /// Name of the generic parameter (e.g., "S", "T")
        param_name: String,
        /// Trait bound (e.g., "Status", "Status + Send")
        bound: String,
    },

    /// Transform to a literal type string (escape hatch)
    ///
    /// Example: `Status` → `Arc<dyn Status + Send + Sync>`
    Literal(String),
}

impl TypeTransform {
    /// Create a BoxDyn transform
    pub fn box_dyn(trait_name: impl Into<String>) -> Self {
        Self::BoxDyn {
            trait_name: trait_name.into(),
        }
    }

    /// Create an ImplTrait transform
    pub fn impl_trait(trait_name: impl Into<String>) -> Self {
        Self::ImplTrait {
            trait_name: trait_name.into(),
        }
    }

    /// Create a Generic transform
    pub fn generic(param_name: impl Into<String>, bound: impl Into<String>) -> Self {
        Self::Generic {
            param_name: param_name.into(),
            bound: bound.into(),
        }
    }

    /// Create a Literal transform
    pub fn literal(type_str: impl Into<String>) -> Self {
        Self::Literal(type_str.into())
    }

    /// Get the resulting type as a string representation
    pub fn to_type_string(&self) -> String {
        match self {
            Self::BoxDyn { trait_name } => format!("Box<dyn {}>", trait_name),
            Self::ImplTrait { trait_name } => format!("impl {}", trait_name),
            Self::Generic { param_name, .. } => param_name.clone(),
            Self::Literal(s) => s.clone(),
        }
    }
}

/// Context where a type is used.
///
/// Used to filter which type usages should be replaced.
#[derive(Debug, Clone, Copy, Serialize, Deserialize, PartialEq, Eq, Hash)]
pub enum TypeContext {
    /// Function parameter type
    Parameter,
    /// Function return type
    ReturnType,
    /// Struct/enum field type
    Field,
    /// Local variable type annotation
    LocalVar,
    /// Trait bound (e.g., `T: Status`)
    TraitBound,
    /// Impl target type (e.g., `impl Foo for Bar`)
    ImplTarget,
    /// Generic type argument (e.g., `Vec<Status>`)
    GenericArg,
}

/// Atomic mutation specification
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
#[serde(tag = "type")]
pub enum MutationSpec {
    // === Rename ===
    /// Rename an identifier across scope
    Rename {
        /// Target symbol (supports lazy resolution)
        target: MutationTargetSymbol,
        /// New name to rename to
        to: String,
        #[serde(default)]
        scope: Scope,
    },

    // === Struct/Field ===
    /// Add a field to a struct
    AddField {
        /// Target struct (supports lazy resolution)
        target: MutationTargetSymbol,
        field_name: String,
        field_type: String,
        #[serde(default)]
        visibility: Visibility,
    },

    /// Remove a field from a struct
    RemoveField {
        /// Target struct (supports lazy resolution)
        target: MutationTargetSymbol,
        field_name: String,
    },

    // === Visibility ===
    /// Change visibility of an item or struct field
    ChangeVisibility {
        /// Target symbol (supports lazy resolution)
        target: MutationTargetSymbol,
        visibility: Visibility,
    },

    // === Derive ===
    /// Add derive macros to a type
    AddDerive {
        /// Target type (supports lazy resolution)
        target: MutationTargetSymbol,
        derives: Vec<String>,
    },

    /// Remove derive macros from a type
    RemoveDerive {
        /// Target type (supports lazy resolution)
        target: MutationTargetSymbol,
        derives: Vec<String>,
    },

    // === Enum ===
    /// Add a variant to an enum
    AddVariant {
        /// Target enum (supports lazy resolution)
        target: MutationTargetSymbol,
        variant_name: String,
        #[serde(default)]
        variant_kind: VariantKind,
    },

    /// Remove a variant from an enum
    RemoveVariant {
        /// Target enum (supports lazy resolution)
        target: MutationTargetSymbol,
        variant_name: String,
    },

    /// Add a match arm to a match expression
    ///
    /// Used to fix exhaustiveness errors when adding enum variants.
    AddMatchArm {
        /// Target function/method containing the match expression
        target: MutationTargetSymbol,
        /// Enum type being matched (for validation)
        enum_name: String,
        /// Pattern for the new arm (e.g., "Status::Cancelled")
        pattern: String,
        /// Body of the new arm (e.g., "todo!()")
        body: String,
    },

    /// Remove a match arm from a match expression
    ///
    /// Used to remove arms when deleting enum variants.
    RemoveMatchArm {
        /// Target function/method containing the match expression
        target: MutationTargetSymbol,
        /// Enum type being matched (for validation)
        enum_name: String,
        /// Pattern to remove (e.g., "Status::Completed")
        pattern: String,
    },

    /// Replace a match arm (pattern + body) in a match expression
    ///
    /// Unlike ReplaceExpr which only replaces the body, this replaces both
    /// the pattern and body atomically. Useful when pattern bindings need
    /// to change along with the body.
    ReplaceMatchArm {
        /// Target function/method containing the match expression
        target: MutationTargetSymbol,
        /// Enum type being matched (for validation)
        enum_name: String,
        /// Pattern to find and replace (e.g., "PathSegment::Slice { start: _, end: _ }")
        old_pattern: String,
        /// New pattern (e.g., "PathSegment::Slice { start, end }")
        new_pattern: String,
        /// New body expression
        new_body: String,
    },

    /// Add a field to all struct literals of a given type
    ///
    /// Used to fix missing field errors when adding struct fields.
    AddStructLiteralField {
        /// Target struct (supports lazy resolution)
        target: MutationTargetSymbol,
        /// Field name to add
        field_name: String,
        /// Value expression (e.g., "None", "Default::default()")
        value: String,
    },

    /// Remove a field from all struct literals of a given type
    ///
    /// Used to update struct literals when removing struct fields.
    RemoveStructLiteralField {
        /// Target struct (supports lazy resolution)
        target: MutationTargetSymbol,
        /// Field name to remove
        field_name: String,
    },

    // === Items ===
    /// Add an item (struct, fn, impl, etc.)
    AddItem {
        /// Target module (supports lazy resolution)
        target: MutationTargetSymbol,
        /// Item content (Rust code)
        content: String,
        /// Insert position within the module
        #[serde(default)]
        position: InsertPosition,
    },

    /// Remove an item
    RemoveItem {
        /// Target item (supports lazy resolution)
        target: MutationTargetSymbol,
        item_kind: ItemKind,
    },

    // === Spec ===
    /// Add a Spec TypeAlias (Spec<Group, T> or SpecWith<Group, R, T>)
    AddSpec {
        /// SymbolId of the target type (required, O(1) lookup)
        type_id: SymbolId,
        /// SymbolId of the module to add the type alias (required, O(1) lookup)
        module_id: SymbolId,
        /// Group name (e.g., "ConfigGroup", "DomainGroup")
        group: String,
        /// Optional alias name (default: "{target}Spec")
        #[serde(default, skip_serializing_if = "Option::is_none")]
        alias_name: Option<String>,
        /// Relations (up to 3)
        #[serde(default)]
        relations: Vec<SpecRelation>,
    },

    /// Remove a Spec TypeAlias
    RemoveSpec {
        /// SymbolId of the spec alias to remove (required, O(1) lookup)
        type_id: SymbolId,
        /// SymbolId of the module containing the spec alias (required, O(1) lookup)
        module_id: SymbolId,
    },

    /// Validate existing Spec definitions
    ValidateSpec {
        /// Target modules as SymbolIds
        type_ids: Vec<SymbolId>,
        /// Expected group name (None = any group)
        #[serde(default, skip_serializing_if = "Option::is_none")]
        expected_group: Option<String>,
        /// Check that relations are valid (targets exist)
        #[serde(default = "default_true")]
        validate_relations: bool,
    },

    // === Method ===
    /// Add a method to an impl block
    AddMethod {
        /// Target impl block (supports lazy resolution)
        target: MutationTargetSymbol,
        /// Method name
        method_name: String,
        /// Parameters as (name, type) pairs
        #[serde(default)]
        params: Vec<(String, String)>,
        /// Return type (None for unit)
        #[serde(default, skip_serializing_if = "Option::is_none")]
        return_type: Option<String>,
        /// Method body expression
        #[serde(default = "default_body")]
        body: String,
        /// Whether the method is public
        #[serde(default)]
        is_pub: bool,
        /// Self parameter: "ref" (&self), "mut" (&mut self), "owned" (self), or None
        #[serde(default, skip_serializing_if = "Option::is_none")]
        self_param: Option<SelfParam>,
    },

    /// Remove a method from an impl block
    RemoveMethod {
        /// Target impl block (supports lazy resolution)
        target: MutationTargetSymbol,
        /// Method name to remove
        method_name: String,
    },

    // === Module ===
    /// Remove a module declaration
    RemoveMod {
        /// Target parent module (supports lazy resolution)
        target: MutationTargetSymbol,
        /// Module name to remove
        mod_name: String,
    },

    /// Create a new module (adds to module tree)
    CreateMod {
        /// Target parent module (supports lazy resolution)
        target: MutationTargetSymbol,
        /// New module name
        mod_name: String,
        /// Initial content (optional)
        #[serde(default)]
        content: String,
        /// Whether the module is public
        #[serde(default)]
        is_pub: bool,
    },

    // === Idiom Transformations ===
    /// Organize imports (sort, dedupe, merge)
    OrganizeImports {
        /// Target module (None = all modules)
        #[serde(default, skip_serializing_if = "Option::is_none")]
        module_id: Option<SymbolId>, // None = all
        #[serde(default = "default_true")]
        deduplicate: bool,
        #[serde(default = "default_true")]
        merge_groups: bool,
    },

    /// Convert loop to iterator
    LoopToIterator {
        /// Target module (None = all modules)
        #[serde(default, skip_serializing_if = "Option::is_none")]
        module_id: Option<SymbolId>, // None = all
        target_var: Option<String>,
    },

    /// Convert unwrap/expect to ? operator
    UnwrapToQuestion {
        /// Target module (None = all modules)
        #[serde(default, skip_serializing_if = "Option::is_none")]
        module_id: Option<SymbolId>, // None = all
        /// Only apply in specific function (None = all functions)
        #[serde(default)]
        target_fn: Option<SymbolId>,
        #[serde(default = "default_true")]
        include_expect: bool,
    },

    /// Simplify assign operations: `a = a + b` → `a += b`
    AssignOp {
        /// Target module (None = all modules)
        #[serde(default, skip_serializing_if = "Option::is_none")]
        module_id: Option<SymbolId>, // None = all
        /// Only apply in specific function (None = all functions)
        #[serde(default)]
        fn_id: Option<SymbolId>,
    },

    /// Simplify boolean comparisons: `x == true` → `x`, `x == false` → `!x`
    BoolSimplify {
        /// Target module (None = all modules)
        #[serde(default, skip_serializing_if = "Option::is_none")]
        module_id: Option<SymbolId>, // None = all
    },

    /// Remove redundant .clone() on Copy types
    CloneOnCopy {
        /// Target module (None = all modules)
        #[serde(default, skip_serializing_if = "Option::is_none")]
        module_id: Option<SymbolId>, // None = all
    },

    /// Merge nested if statements into single if with &&
    CollapsibleIf {
        /// Target module (None = all modules)
        #[serde(default, skip_serializing_if = "Option::is_none")]
        module_id: Option<SymbolId>, // None = all
    },

    /// Replace empty/noop match arms with todo!/unimplemented!/unreachable!
    /// `_ => {}` → `_ => todo!()` or `_ => unreachable!()`
    NoOpArmToTodo {
        /// Target module (None = all modules)
        #[serde(default, skip_serializing_if = "Option::is_none")]
        module_id: Option<SymbolId>, // None = all
        /// Replacement macro: "todo", "unimplemented", or "unreachable" (default: "todo")
        #[serde(default = "default_noop_replacement")]
        replacement: String,
    },

    /// Convert comparisons to method calls: `s == ""` → `s.is_empty()`
    ComparisonToMethod {
        /// Target module (None = all modules)
        #[serde(default, skip_serializing_if = "Option::is_none")]
        module_id: Option<SymbolId>, // None = all
    },

    /// Remove redundant closures: `|x| f(x)` → `f`
    RedundantClosure {
        /// Target module (None = all modules)
        #[serde(default, skip_serializing_if = "Option::is_none")]
        module_id: Option<SymbolId>, // None = all
    },

    /// Introduce variable for repeated expressions
    /// Expression is specified as string and parsed at runtime
    IntroduceVariable {
        /// Target module (None = all modules)
        #[serde(default, skip_serializing_if = "Option::is_none")]
        module_id: Option<SymbolId>, // None = all
        /// Target function to apply (None = all functions)
        #[serde(default)]
        fn_id: Option<SymbolId>,
        /// Expression to extract (as Rust code string, e.g. "a + b * c")
        expr: String,
        /// Name for the new variable
        var_name: String,
    },

    /// Convert manual match on Option to .map(): `match opt { Some(x) => Some(f(x)), None => None }` → `opt.map(f)`
    ManualMap {
        /// Target module (None = all modules)
        #[serde(default, skip_serializing_if = "Option::is_none")]
        module_id: Option<SymbolId>, // None = all
    },

    /// Convert simple match to if let
    MatchToIfLet {
        /// Target module (None = all modules)
        #[serde(default, skip_serializing_if = "Option::is_none")]
        module_id: Option<SymbolId>,
    },

    /// Convert .filter().next() to .find()
    FilterNext {
        /// Target module (None = all modules)
        #[serde(default, skip_serializing_if = "Option::is_none")]
        module_id: Option<SymbolId>, // None = all
        /// Target function (None = all functions)
        #[serde(default, skip_serializing_if = "Option::is_none")]
        fn_id: Option<SymbolId>,
    },

    /// Convert .map().unwrap_or() to .map_or()
    MapUnwrapOr {
        /// Target module (None = all modules)
        #[serde(default, skip_serializing_if = "Option::is_none")]
        module_id: Option<SymbolId>, // None = all
        /// Target function (None = all functions)
        #[serde(default, skip_serializing_if = "Option::is_none")]
        fn_id: Option<SymbolId>,
    },

    // === PureStmt/PureExpr Operations ===
    /// Replace an expression with another expression
    ///
    /// Target can be specified by:
    /// - `old_expr`: Pattern matching (searches for matching expressions)
    /// - `symbol_path`: Direct position (e.g., "crate::fn::$body::0::1")
    ReplaceExpr {
        /// Target module (None = all modules)
        #[serde(default, skip_serializing_if = "Option::is_none")]
        module_id: Option<SymbolId>, // None = all
        #[serde(default)]
        fn_id: Option<SymbolId>,
        /// Expression to replace (as Rust code string) - pattern match mode
        old_expr: String,
        /// Replacement expression (as Rust code string)
        new_expr: String,
        /// Replace all occurrences (default: true)
        #[serde(default = "default_true")]
        replace_all: bool,
        /// Direct position (e.g., "my_crate::my_fn::$body::0::1::2")
        /// When specified, ignores old_expr and replaces at this exact position
        #[serde(default, skip_serializing_if = "Option::is_none")]
        symbol_path: Option<String>,
    },

    /// Remove statements matching a pattern
    ///
    /// Target can be specified by:
    /// - `pattern`: Pattern matching (searches for matching statements)
    /// - `symbol_path`: Direct position (e.g., "crate::fn::$body::2")
    RemoveStatement {
        /// Target module (None = all modules)
        #[serde(default, skip_serializing_if = "Option::is_none")]
        module_id: Option<SymbolId>, // None = all
        #[serde(default)]
        fn_id: Option<SymbolId>,
        /// Statement pattern to remove (as Rust code string, e.g. "println!(..)") - pattern match mode
        pattern: String,
        /// Remove all occurrences (default: true)
        #[serde(default = "default_true")]
        remove_all: bool,
        /// Direct position (e.g., "my_crate::my_fn::$body::2")
        /// When specified, ignores pattern and removes at this exact position
        #[serde(default, skip_serializing_if = "Option::is_none")]
        symbol_path: Option<String>,
    },

    /// Insert a statement at a specific position
    ///
    /// Position can be specified by:
    /// - `position` + `reference_pattern`: Traditional mode
    /// - `symbol_path`: Direct position (inserts after $body::N)
    InsertStatement {
        /// Target module (None = all modules)
        #[serde(default, skip_serializing_if = "Option::is_none")]
        module_id: Option<SymbolId>,
        /// Target function
        #[serde(default)]
        fn_id: SymbolId,
        /// Statement to insert (as Rust code string)
        stmt: String,
        /// Insert position
        #[serde(default)]
        position: StmtInsertPosition,
        /// Reference pattern for BeforePattern/AfterPattern positions
        #[serde(default, skip_serializing_if = "Option::is_none")]
        reference_pattern: Option<String>,
        /// Direct position (e.g., "my_crate::my_fn::$body::2")
        /// When specified, ignores position and inserts after this statement
        #[serde(default, skip_serializing_if = "Option::is_none")]
        symbol_path: Option<String>,
    },

    /// Replace a statement with another statement
    ///
    /// Target can be specified by:
    /// - `old_stmt`: Pattern matching (searches for matching statements)
    /// - `symbol_path`: Direct position (e.g., "crate::fn::$body::1")
    ReplaceStatement {
        /// Target module (None = all modules)
        #[serde(default, skip_serializing_if = "Option::is_none")]
        module_id: Option<SymbolId>,
        #[serde(default, skip_serializing_if = "Option::is_none")]
        fn_id: Option<SymbolId>,
        /// Statement to replace (as Rust code string) - pattern match mode
        old_stmt: String,
        /// Replacement statement (as Rust code string)
        new_stmt: String,
        /// Direct position (e.g., "my_crate::my_fn::$body::1")
        /// When specified, ignores old_stmt and replaces at this exact position
        #[serde(default, skip_serializing_if = "Option::is_none")]
        symbol_path: Option<String>,
    },

    // === Trait Abstraction ===
    /// Extract a trait from an impl block
    ExtractTrait {
        /// Target impl block (supports lazy resolution)
        target: MutationTargetSymbol,
        /// Name for the new trait
        trait_name: String,
        /// Optional: specific methods to extract (None = all)
        #[serde(default, skip_serializing_if = "Option::is_none")]
        methods: Option<Vec<String>>,
    },

    /// Inline a trait back into inherent impl
    InlineTrait {
        /// Target trait (supports lazy resolution)
        target: MutationTargetSymbol,
        /// Struct that implements the trait
        struct_name: String,
        /// Whether to remove the trait definition
        #[serde(default = "default_true")]
        remove_trait: bool,
    },

    /// Replace all occurrences of a type with a transformed type
    ///
    /// # Examples
    ///
    /// ```ignore
    /// // Replace Status with Box<dyn Status>
    /// MutationSpec::ReplaceType {
    ///     from_type: "Status".to_string(),
    ///     to_type: TypeTransform::BoxDyn { trait_name: "Status".to_string() },
    ///     scope: None,
    ///     contexts: None,
    /// }
    /// ```
    ReplaceType {
        /// Target type to replace (supports lazy resolution)
        target: MutationTargetSymbol,
        /// How to transform the type
        to_type: TypeTransform,
        /// Scope to limit replacements (None = entire crate)
        #[serde(default, skip_serializing_if = "Option::is_none")]
        scope: Option<SymbolPath>,
        /// Which contexts to replace in (None = all contexts)
        #[serde(default, skip_serializing_if = "Option::is_none")]
        contexts: Option<Vec<TypeContext>>,
    },

    /// Convert an enum to a trait with struct implementations
    ///
    /// Transforms:
    /// - `enum Status { Running, Stopped }` into:
    /// - `pub trait Status {}`
    /// - `pub struct Running;`
    /// - `pub struct Stopped;`
    /// - `impl Status for Running {}`
    /// - `impl Status for Stopped {}`
    ///
    /// Also updates all usage sites: `Status::Running` → `Running`
    ///
    /// ## Type Replacement
    ///
    /// With `strategy: dynamic` (default):
    /// - `fn process(status: Status)` → `fn process(status: Box<dyn Status>)`
    ///
    /// With `strategy: static`:
    /// - `fn process(status: Status)` → `fn process(status: impl Status)`
    ///
    /// With `strategy: marker_only`:
    /// - No type replacement (manual migration required)
    ///
    EnumToTrait {
        /// Target enum (supports lazy resolution)
        target: MutationTargetSymbol,
        /// Optional: custom trait name (default: same as enum name)
        #[serde(default, skip_serializing_if = "Option::is_none")]
        trait_name: Option<String>,
        /// Whether to remove the original enum (default: true)
        #[serde(default = "default_true")]
        remove_enum: bool,
        /// Type replacement strategy (default: dynamic = Box<dyn Trait>)
        #[serde(default)]
        strategy: EnumToTraitStrategy,
        /// How to handle match expressions (default: warn_only)
        #[serde(default)]
        match_handling: MatchHandling,
    },

    // === Cross-file Operations ===
    /// Move an item from one file to another
    MoveItem {
        /// Source module (supports lazy resolution)
        source: MutationTargetSymbol,
        /// Target module (supports lazy resolution)
        target: MutationTargetSymbol,
        /// Item name to move
        item_name: String,
        /// Item kind (Struct, Enum, Fn, etc.)
        item_kind: ItemKind,
        /// Whether to add use statement in source file
        #[serde(default = "default_true")]
        add_use: bool,
    },

    // === Plugin Transformations ===
    /// Execute a WASM plugin transform
    PluginTransform {
        /// Plugin name (e.g., "map-unwrap-or", "custom-lint")
        plugin_name: String,
        /// Target module as SymbolId (None = all modules)
        #[serde(default, skip_serializing_if = "Option::is_none")]
        target_id: Option<SymbolId>,
        /// File glob patterns (e.g., ["src/**/*.rs", "tests/*.rs"])
        #[serde(default, skip_serializing_if = "Vec::is_empty")]
        file_patterns: Vec<String>,
        /// Plugin-specific configuration as JSON
        #[serde(default)]
        config: serde_json::Value,
    },

    // === Duplicate Operations ===
    /// Duplicate a function with a new name
    DuplicateFunction {
        /// Target function (supports lazy resolution)
        target: MutationTargetSymbol,
        /// New function name
        to: String,
    },

    /// Duplicate a struct with a new name (including impl blocks)
    DuplicateStruct {
        /// Target struct (supports lazy resolution)
        target: MutationTargetSymbol,
        /// New struct name
        to: String,
        /// Whether to also duplicate impl blocks
        #[serde(default = "default_true")]
        include_impls: bool,
    },

    /// Duplicate an enum with a new name (including impl blocks)
    DuplicateEnum {
        /// Target enum (supports lazy resolution)
        target: MutationTargetSymbol,
        /// New enum name
        to: String,
        /// Whether to also duplicate impl blocks
        #[serde(default = "default_true")]
        include_impls: bool,
    },

    /// Duplicate an inline module with a new name
    DuplicateModTree {
        /// Target module (supports lazy resolution)
        target: MutationTargetSymbol,
        /// New module name
        to: String,
    },
}

fn default_true() -> bool {
    true
}

impl MutationSpec {
    /// Get the kind name of this spec (e.g., "Rename", "AddField")
    ///
    /// Used by MutationRegistry to route specs to appropriate converters.
    /// TODO: Consider typed approach (enum variant discriminant or macro-based)
    pub fn kind_name(&self) -> &'static str {
        match self {
            Self::Rename { .. } => "Rename",
            Self::AddField { .. } => "AddField",
            Self::RemoveField { .. } => "RemoveField",
            Self::ChangeVisibility { .. } => "ChangeVisibility",
            Self::AddDerive { .. } => "AddDerive",
            Self::RemoveDerive { .. } => "RemoveDerive",
            Self::AddVariant { .. } => "AddVariant",
            Self::RemoveVariant { .. } => "RemoveVariant",
            Self::AddMatchArm { .. } => "AddMatchArm",
            Self::RemoveMatchArm { .. } => "RemoveMatchArm",
            Self::ReplaceMatchArm { .. } => "ReplaceMatchArm",
            Self::AddStructLiteralField { .. } => "AddStructLiteralField",
            Self::RemoveStructLiteralField { .. } => "RemoveStructLiteralField",
            Self::AddItem { .. } => "AddItem",
            Self::RemoveItem { .. } => "RemoveItem",
            Self::AddSpec { .. } => "AddSpec",
            Self::RemoveSpec { .. } => "RemoveSpec",
            Self::ValidateSpec { .. } => "ValidateSpec",
            Self::AddMethod { .. } => "AddMethod",
            Self::RemoveMethod { .. } => "RemoveMethod",
            Self::RemoveMod { .. } => "RemoveMod",
            Self::CreateMod { .. } => "CreateMod",
            Self::OrganizeImports { .. } => "OrganizeImports",
            Self::LoopToIterator { .. } => "LoopToIterator",
            Self::UnwrapToQuestion { .. } => "UnwrapToQuestion",
            Self::AssignOp { .. } => "AssignOp",
            Self::BoolSimplify { .. } => "BoolSimplify",
            Self::CloneOnCopy { .. } => "CloneOnCopy",
            Self::CollapsibleIf { .. } => "CollapsibleIf",
            Self::NoOpArmToTodo { .. } => "NoOpArmToTodo",
            Self::ComparisonToMethod { .. } => "ComparisonToMethod",
            Self::RedundantClosure { .. } => "RedundantClosure",
            Self::IntroduceVariable { .. } => "IntroduceVariable",
            Self::ManualMap { .. } => "ManualMap",
            Self::MatchToIfLet { .. } => "MatchToIfLet",
            Self::FilterNext { .. } => "FilterNext",
            Self::MapUnwrapOr { .. } => "MapUnwrapOr",
            Self::ReplaceExpr { .. } => "ReplaceExpr",
            Self::RemoveStatement { .. } => "RemoveStatement",
            Self::InsertStatement { .. } => "InsertStatement",
            Self::ReplaceStatement { .. } => "ReplaceStatement",
            Self::ExtractTrait { .. } => "ExtractTrait",
            Self::InlineTrait { .. } => "InlineTrait",
            Self::ReplaceType { .. } => "ReplaceType",
            Self::EnumToTrait { .. } => "EnumToTrait",
            Self::MoveItem { .. } => "MoveItem",
            Self::PluginTransform { .. } => "PluginTransform",
            Self::DuplicateFunction { .. } => "DuplicateFunction",
            Self::DuplicateStruct { .. } => "DuplicateStruct",
            Self::DuplicateEnum { .. } => "DuplicateEnum",
            Self::DuplicateModTree { .. } => "DuplicateModTree",
        }
    }

    /// Check if this mutation is a rename
    pub fn is_rename(&self) -> bool {
        matches!(self, Self::Rename { .. })
    }

    /// Check if this is an additive operation (order-independent within same target)
    ///
    /// Additive operations like AddItem, AddMethod, AddField etc. can be applied
    /// in any order to the same target without conflict, unless they add the
    /// same named item (detected via `additive_identity`).
    pub fn is_additive(&self) -> bool {
        matches!(
            self,
            Self::AddItem { .. }
                | Self::AddMethod { .. }
                | Self::AddField { .. }
                | Self::AddVariant { .. }
                | Self::AddDerive { .. }
                | Self::CreateMod { .. }
                | Self::AddMatchArm { .. }
                | Self::AddStructLiteralField { .. }
                | Self::AddSpec { .. }
        )
    }

    /// Get unique identity for additive operations (for duplicate detection)
    ///
    /// Returns a unique identifier for what this operation adds.
    /// Two additive operations with the same `additive_identity` targeting the
    /// same parent are true conflicts (trying to add the same thing twice).
    pub fn additive_identity(&self) -> Option<String> {
        match self {
            Self::AddItem { content, .. } => {
                // Extract item name from content (first identifier after pub/struct/fn/enum/etc.)
                extract_item_name_from_content(content)
            }
            Self::AddMethod { method_name, .. } => Some(method_name.clone()),
            Self::AddField { field_name, .. } => Some(field_name.clone()),
            Self::AddVariant { variant_name, .. } => Some(variant_name.clone()),
            Self::AddDerive { derives, .. } => Some(derives.join(",")),
            Self::CreateMod { mod_name, .. } => Some(mod_name.clone()),
            Self::AddMatchArm { pattern, .. } => Some(pattern.clone()),
            Self::AddStructLiteralField { field_name, .. } => Some(field_name.clone()),
            Self::AddSpec { type_id, .. } => Some(format!("{:?}", type_id)),
            _ => None,
        }
    }

    /// Check if this is an idiom transformation
    pub fn is_idiom(&self) -> bool {
        matches!(
            self,
            Self::OrganizeImports { .. }
                | Self::LoopToIterator { .. }
                | Self::UnwrapToQuestion { .. }
                | Self::AssignOp { .. }
                | Self::BoolSimplify { .. }
                | Self::CloneOnCopy { .. }
                | Self::CollapsibleIf { .. }
                | Self::NoOpArmToTodo { .. }
                | Self::ComparisonToMethod { .. }
                | Self::RedundantClosure { .. }
                | Self::IntroduceVariable { .. }
                | Self::ManualMap { .. }
                | Self::MatchToIfLet { .. }
                | Self::FilterNext { .. }
                | Self::MapUnwrapOr { .. }
                | Self::ReplaceExpr { .. }
                | Self::RemoveStatement { .. }
                | Self::InsertStatement { .. }
                | Self::ReplaceStatement { .. }
                | Self::PluginTransform { .. }
        )
    }

    /// Get target symbols from this spec.
    ///
    /// Returns references to all `MutationTargetSymbol` fields in this spec.
    /// Used for computing `affected_symbols` after mutation execution.
    pub fn get_targets(&self) -> Vec<&MutationTargetSymbol> {
        match self {
            // Specs with single target field
            Self::Rename { target, .. }
            | Self::AddField { target, .. }
            | Self::RemoveField { target, .. }
            | Self::ChangeVisibility { target, .. }
            | Self::AddDerive { target, .. }
            | Self::RemoveDerive { target, .. }
            | Self::AddVariant { target, .. }
            | Self::RemoveVariant { target, .. }
            | Self::AddMatchArm { target, .. }
            | Self::RemoveMatchArm { target, .. }
            | Self::ReplaceMatchArm { target, .. }
            | Self::AddStructLiteralField { target, .. }
            | Self::RemoveStructLiteralField { target, .. }
            | Self::AddItem { target, .. }
            | Self::RemoveItem { target, .. }
            | Self::AddMethod { target, .. }
            | Self::RemoveMethod { target, .. }
            | Self::RemoveMod { target, .. }
            | Self::CreateMod { target, .. }
            | Self::ExtractTrait { target, .. }
            | Self::InlineTrait { target, .. }
            | Self::ReplaceType { target, .. }
            | Self::EnumToTrait { target, .. }
            | Self::MoveItem { target, .. }
            | Self::DuplicateFunction { target, .. }
            | Self::DuplicateStruct { target, .. }
            | Self::DuplicateEnum { target, .. }
            | Self::DuplicateModTree { target, .. } => vec![target],

            // Specs with SymbolId fields (not MutationTargetSymbol)
            Self::AddSpec { .. } | Self::RemoveSpec { .. } | Self::ValidateSpec { .. } => vec![],

            // Idiom transformations (module-scoped, no specific target)
            Self::OrganizeImports { .. }
            | Self::LoopToIterator { .. }
            | Self::UnwrapToQuestion { .. }
            | Self::AssignOp { .. }
            | Self::BoolSimplify { .. }
            | Self::CloneOnCopy { .. }
            | Self::CollapsibleIf { .. }
            | Self::NoOpArmToTodo { .. }
            | Self::ComparisonToMethod { .. }
            | Self::RedundantClosure { .. }
            | Self::IntroduceVariable { .. }
            | Self::ManualMap { .. }
            | Self::MatchToIfLet { .. }
            | Self::FilterNext { .. }
            | Self::MapUnwrapOr { .. }
            | Self::ReplaceExpr { .. }
            | Self::RemoveStatement { .. }
            | Self::InsertStatement { .. }
            | Self::ReplaceStatement { .. }
            | Self::PluginTransform { .. } => vec![],
        }
    }
}

/// Scope for mutations
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Default)]
#[serde(tag = "type")]
pub enum Scope {
    /// All modules in project
    #[default]
    Project,

    /// Specific module by path
    Mod { path: SymbolPath },

    /// Within a specific item
    Item {
        target: SymbolPath,
        item_name: String,
    },
}

/// Visibility levels
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Default)]
#[serde(rename_all = "snake_case")]
pub enum Visibility {
    #[default]
    Private,
    Pub,
    PubCrate,
    PubSuper,
    PubIn(String),
}

impl Visibility {
    pub fn to_rust_syntax(&self) -> &str {
        match self {
            Self::Private => "",
            Self::Pub => "pub ",
            Self::PubCrate => "pub(crate) ",
            Self::PubSuper => "pub(super) ",
            Self::PubIn(_) => "pub(in ...) ", // Needs special handling
        }
    }
}

/// Enum variant kinds
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Default)]
#[serde(tag = "type")]
pub enum VariantKind {
    #[default]
    Unit,
    Tuple {
        types: Vec<String>,
    },
    Struct {
        fields: Vec<(String, String)>,
    },
}

/// Position for inserting items
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Default)]
#[serde(tag = "type")]
pub enum InsertPosition {
    #[default]
    Top,
    Bottom,
    AfterItem {
        name: String,
    },
    BeforeItem {
        name: String,
    },
}

/// Position for inserting statements within a function
#[derive(Debug, Clone, Copy, Serialize, Deserialize, PartialEq, Eq, Default)]
#[serde(rename_all = "snake_case")]
pub enum StmtInsertPosition {
    /// At the start of the function body
    Start,
    /// At the end of the function body (before return statement if any)
    #[default]
    End,
    /// Before a statement matching the reference pattern
    BeforePattern,
    /// After a statement matching the reference pattern
    AfterPattern,
}

/// Self parameter for methods
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
#[serde(rename_all = "lowercase")]
pub enum SelfParam {
    /// &self
    Ref,
    /// &mut self
    Mut,
    /// self (owned)
    Owned,
}

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

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

/// Relation for Spec TypeAlias
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
pub struct SpecRelation {
    /// Relation kind
    pub kind: SpecRelationKind,
    /// Target type name (simple name, e.g., "User")
    pub target: String,
    /// Direct SymbolId for target (from Discover result)
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub symbol_id: Option<SymbolId>,
    /// Full SymbolPath for target (for disambiguation)
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub target_path: Option<SymbolPath>,
}

impl SpecRelation {
    /// Create a new SpecRelation with just a name
    pub fn new(kind: SpecRelationKind, target: impl Into<String>) -> Self {
        Self {
            kind,
            target: target.into(),
            symbol_id: None,
            target_path: None,
        }
    }

    /// Create a new SpecRelation with a SymbolPath
    pub fn with_path(kind: SpecRelationKind, target: impl Into<String>, path: SymbolPath) -> Self {
        Self {
            kind,
            target: target.into(),
            symbol_id: None,
            target_path: Some(path),
        }
    }

    /// Create a new SpecRelation with a SymbolId
    pub fn with_symbol_id(
        kind: SpecRelationKind,
        target: impl Into<String>,
        symbol_id: SymbolId,
    ) -> Self {
        Self {
            kind,
            target: target.into(),
            symbol_id: Some(symbol_id),
            target_path: None,
        }
    }
}

/// Relation kinds for Spec
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
#[serde(rename_all = "PascalCase")]
pub enum SpecRelationKind {
    /// A depends on B (A needs B to function)
    DependsOn,
    /// A is related to B (semantic relationship)
    RelatedTo,
    /// A is part of B (aggregate membership)
    PartOf,
}

impl SpecRelationKind {
    /// Get the Rust type name for this relation
    pub fn as_type_name(&self) -> &'static str {
        match self {
            Self::DependsOn => "DependsOn",
            Self::RelatedTo => "RelatedTo",
            Self::PartOf => "PartOf",
        }
    }
}

// ItemKind is re-exported from ryo_source

/// Extract item name from Rust code content
///
/// Parses common Rust item declarations to extract the name.
/// Used by `additive_identity()` for AddItem duplicate detection.
fn extract_item_name_from_content(content: &str) -> Option<String> {
    // Simple regex-free parsing for common patterns
    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 Trait for Type or impl Type
            // For impl blocks, include the full impl signature for identity
            let rest = tokens[idx..].join(" ");

            // Extract impl signature (everything before '{' or '<')
            // This includes "Trait for Type" or just "Type"
            let impl_sig = rest
                .split(['{', '<'])
                .next()
                .map(|s| s.trim())
                .filter(|s| !s.is_empty());

            // Also extract method names from the impl block to differentiate
            // multiple impl blocks for the same type
            let methods: Vec<&str> = content
                .lines()
                .filter_map(|line| {
                    let trimmed = line.trim();
                    if trimmed.starts_with("pub fn ") || trimmed.starts_with("fn ") {
                        let after_fn = trimmed
                            .strip_prefix("pub fn ")
                            .or_else(|| trimmed.strip_prefix("fn "))?;
                        let method_name = after_fn.split('(').next()?.trim();
                        Some(method_name)
                    } else {
                        None
                    }
                })
                .collect();

            match (impl_sig, methods.is_empty()) {
                (Some(sig), false) => Some(format!(
                    "impl_{}::{}",
                    sig.replace(' ', "_"),
                    methods.join(",")
                )),
                // Use full signature for empty impl blocks (e.g., "impl_Status_for_Running")
                (Some(sig), true) => Some(format!("impl_{}", sig.replace(' ', "_"))),
                _ => None,
            }
        }
        "use" => {
            // use path::Name or use path::{A, B}
            // Return the full use statement as identity
            Some(tokens[idx..].join(" "))
        }
        _ => {
            // Unknown pattern, use first meaningful token
            Some(keyword.to_string())
        }
    }
}

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

    #[test]
    fn test_mutation_spec_serialize() {
        // Test serialization with ByPath (which contains the symbol path)
        let spec = MutationSpec::Rename {
            target: MutationTargetSymbol::ByPath(Box::new(
                SymbolPath::parse("test_crate::old_name").unwrap(),
            )),
            to: "new_name".to_string(),
            scope: Scope::Project,
        };

        let json = serde_json::to_string_pretty(&spec).unwrap();
        assert!(json.contains("Rename"), "JSON should contain Rename");
        assert!(
            json.contains("old_name"),
            "JSON should contain old_name in ByPath"
        );
        assert!(json.contains("new_name"), "JSON should contain new_name");

        let parsed: MutationSpec = serde_json::from_str(&json).unwrap();
        assert_eq!(
            spec, parsed,
            "Round-trip serialization should preserve spec"
        );
    }

    #[test]
    fn test_idiom_detection() {
        let spec = MutationSpec::OrganizeImports {
            module_id: None,
            deduplicate: true,
            merge_groups: true,
        };

        assert!(spec.is_idiom());
        assert!(!spec.is_rename());
    }
}