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
//! MutationRegistry: Central registry for MutationSpec → Mutation conversion
//!
//! The Registry pattern distributes the conversion logic that was previously
//! concentrated in `BlueprintExecutor::convert_and_apply()` (2,400+ lines)
//! into separate Converter implementations.
//!
//! # Architecture
//!
//! ```text
//! MutationSpec
//!//!    ▼ registry.convert(spec)
//! MutationRegistry
//!    ├─ converters: HashMap<kind, Box<dyn MutationConverter>>
//!//!    ▼ find converter by spec.kind_name()
//! MutationConverter (trait)
//!//!    ▼ convert(spec) → Box<dyn Mutation>
//! Mutation
//!//!    ▼ apply(file) → changes
//! ```

mod converter;
pub mod converters;

pub use converter::{
    opt_resolve_file_path_from_symbol, resolve_file_path_from_symbol, ApplyResult, ConvertError,
    MutationConverter, ResolvedMutation,
};

use crate::engine::ASTRegApply;
use crate::executor::spec::MutationSpec;
use ryo_analysis::{AnalysisContext, GraphChecker};
use std::collections::HashMap;

/// Central registry for MutationSpec → Mutation conversion
///
/// Routes each MutationSpec to its appropriate Converter based on kind_name().
pub struct MutationRegistry {
    converters: HashMap<&'static str, Box<dyn MutationConverter>>,
}

impl std::fmt::Debug for MutationRegistry {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.debug_struct("MutationRegistry")
            .field("registered_kinds", &self.registered_kinds())
            .finish()
    }
}

impl MutationRegistry {
    /// Create a new registry with all built-in converters registered
    ///
    /// Uses `register_all()` for converters that handle multiple spec kinds,
    /// which automatically registers all kinds from `spec_kinds()`.
    /// This prevents the "forgot to register" bug.
    pub fn new() -> Self {
        let mut registry = Self {
            converters: HashMap::new(),
        };

        // Phase 1: Basic converters (single or few kinds)
        registry.register("Rename", Box::new(converters::RenameConverter::new()));
        registry.register(
            "ChangeVisibility",
            Box::new(converters::VisibilityConverter::new()),
        );
        registry.register_all::<converters::FieldConverter>(); // AddField, RemoveField
        registry.register_all::<converters::DeriveConverter>(); // AddDerive, RemoveDerive

        // Phase 2: Complex converters
        registry.register_all::<converters::EnumConverter>(); // AddVariant, RemoveVariant
        registry.register("RemoveItem", Box::new(converters::RemoveConverter::new()));
        registry.register_all::<converters::MethodConverter>(); // AddMethod, RemoveMethod
        registry.register_all::<converters::ModuleConverter>(); // AddMod, RemoveMod, CreateMod
        registry.register("AddItem", Box::new(converters::AddItemConverter::new()));

        // Phase 3: Idiom converters (15 variants - biggest win!)
        registry.register_all::<converters::IdiomConverter>();

        // Phase 3: Other converters
        registry.register_all::<converters::TraitConverter>(); // ExtractTrait, InlineTrait
        registry.register("MoveItem", Box::new(converters::MoveConverter::new()));
        registry.register(
            "PluginTransform",
            Box::new(converters::PluginConverter::new()),
        );
        registry.register_all::<converters::StmtConverter>(); // ReplaceExpr, RemoveStatement, etc.
        registry.register_all::<converters::MatchArmConverter>(); // AddMatchArm, RemoveMatchArm
        registry.register_all::<converters::StructLiteralFieldConverter>(); // Add/RemoveStructLiteralField
        registry.register_all::<converters::DuplicateConverter>(); // DuplicateFunction, etc.

        registry
    }

    /// Register a converter for a single spec kind
    ///
    /// Note: Each spec kind can only have one converter.
    /// For converters handling multiple spec kinds, use `register_all()`.
    pub fn register(&mut self, kind: &'static str, converter: Box<dyn MutationConverter>) {
        self.converters.insert(kind, converter);
    }

    /// Register a converter for all its spec_kinds() automatically.
    ///
    /// This method creates a new instance of the converter for each spec kind
    /// it handles. Requires the converter to implement `Default`.
    ///
    /// # Example
    ///
    /// ```ignore
    /// // Instead of:
    /// registry.register("FilterNext", Box::new(IdiomConverter::new()));
    /// registry.register("MapUnwrapOr", Box::new(IdiomConverter::new()));
    /// // ... 15 more lines
    ///
    /// // Use:
    /// registry.register_all::<IdiomConverter>();
    /// ```
    pub fn register_all<C: MutationConverter + Default + 'static>(&mut self) {
        let temp = C::default();
        for kind in temp.spec_kinds() {
            self.converters.insert(*kind, Box::new(C::default()));
        }
    }

    /// Check if this registry can handle the given spec
    pub fn can_handle(&self, spec: &MutationSpec) -> bool {
        self.converters.contains_key(spec.kind_name())
    }

    /// Get the converter for a spec, if registered
    pub fn get(&self, spec: &MutationSpec) -> Option<&dyn MutationConverter> {
        self.converters.get(spec.kind_name()).map(|c| c.as_ref())
    }

    /// Convert a MutationSpec to a Mutation (DEPRECATED)
    #[deprecated(
        since = "0.1.0",
        note = "Returns Box<dyn Mutation> for legacy apply(&mut PureFile). Use convert_v2() for ASTRegApply."
    )]
    #[allow(deprecated)]
    pub fn convert(
        &self,
        spec: &MutationSpec,
    ) -> Result<Box<dyn ryo_mutations::Mutation>, ConvertError> {
        let converter = self
            .converters
            .get(spec.kind_name())
            .ok_or_else(|| ConvertError::UnknownSpec(spec.kind_name().to_string()))?;

        converter.convert(spec)
    }

    /// Convert a MutationSpec to execution units (V2 API)
    ///
    /// Returns a vector of ASTRegApply mutations that implement the spec.
    /// One spec may expand to multiple execution units.
    ///
    /// # Returns
    ///
    /// - `Ok(mutations)` - Vector of mutations to execute
    /// - `Err(V2NotSupported)` - Converter doesn't implement convert_v2 yet
    /// - `Err(UnknownSpec)` - No converter registered for this spec kind
    pub fn convert_v2(
        &self,
        spec: &MutationSpec,
        ctx: &AnalysisContext,
    ) -> Result<Vec<Box<dyn ASTRegApply>>, ConvertError> {
        let converter = self
            .converters
            .get(spec.kind_name())
            .ok_or_else(|| ConvertError::UnknownSpec(spec.kind_name().to_string()))?;

        converter.convert_v2(spec, ctx)
    }

    /// Pre-check a MutationSpec before applying.
    ///
    /// Uses GraphChecker to validate that targets exist before mutation.
    /// This catches errors early (e.g., field not found, type not found)
    /// without running `cargo check`.
    ///
    /// # Checks performed
    ///
    /// | Spec Kind | Check |
    /// |-----------|-------|
    /// | Rename | Target symbol exists |
    /// | AddField/RemoveField | Struct exists |
    /// | AddDerive/RemoveDerive | Target type exists |
    /// | AddVariant/RemoveVariant | Enum exists |
    /// | AddMethod/RemoveMethod | Target type exists |
    /// | ChangeVisibility | Target exists |
    pub fn pre_check(
        &self,
        spec: &MutationSpec,
        ctx: &AnalysisContext,
    ) -> Result<(), ConvertError> {
        let _checker = GraphChecker::new(ctx.code_graph(), ctx.typeflow_graph(), ctx.registry());

        match spec {
            // === Symbol existence and uniqueness checks ===
            // symbol_id is now required, so we trust it (O(1) access).
            // No uniqueness check needed.
            MutationSpec::Rename { .. } => {}

            // AddField/RemoveField: symbol_id is required, no uniqueness check needed
            MutationSpec::AddField { .. } | MutationSpec::RemoveField { .. } => {}

            // AddDerive/RemoveDerive: symbol_id is required, no uniqueness check needed
            MutationSpec::AddDerive { .. } | MutationSpec::RemoveDerive { .. } => {}

            // AddVariant: symbol_id is required, no uniqueness check needed
            MutationSpec::AddVariant { .. } => {}

            // RemoveVariant: symbol_id is required, no uniqueness check needed
            MutationSpec::RemoveVariant { .. } => {}

            MutationSpec::AddMethod {
                target: target_symbol,
                ..
            } => {
                // AddMethod uses target_symbol: MutationTargetSymbol (lazy resolution)
                // Pre-check validation happens at converter level
                let _ = target_symbol; // Suppress unused warning
            }

            MutationSpec::RemoveMethod { .. } => {
                // SymbolId is required, no name-based pre-check needed
            }

            MutationSpec::ChangeVisibility { .. } => {
                // SymbolId is required, no name-based pre-check needed
            }

            // === Mutations that don't need pre-check ===
            // SymbolId is required for RemoveItem, no name-based pre-check needed
            MutationSpec::RemoveItem { .. } => {
                // SymbolId is required, no name-based pre-check needed
            }

            // These create new items or operate on files directly
            MutationSpec::AddItem { .. }
            | MutationSpec::RemoveMod { .. }
            | MutationSpec::CreateMod { .. }
            | MutationSpec::AddSpec { .. }
            | MutationSpec::AddMatchArm { .. }
            | MutationSpec::RemoveMatchArm { .. }
            | MutationSpec::ReplaceMatchArm { .. }
            | MutationSpec::AddStructLiteralField { .. }
            | MutationSpec::RemoveStructLiteralField { .. } => {
                // No pre-check needed
            }

            // === Idiom transformations ===
            // These operate on code patterns, not specific symbols
            MutationSpec::OrganizeImports { .. }
            | MutationSpec::LoopToIterator { .. }
            | MutationSpec::UnwrapToQuestion { .. }
            | MutationSpec::AssignOp { .. }
            | MutationSpec::BoolSimplify { .. }
            | MutationSpec::CloneOnCopy { .. }
            | MutationSpec::CollapsibleIf { .. }
            | MutationSpec::ComparisonToMethod { .. }
            | MutationSpec::RedundantClosure { .. }
            | MutationSpec::IntroduceVariable { .. }
            | MutationSpec::ManualMap { .. }
            | MutationSpec::MatchToIfLet { .. }
            | MutationSpec::FilterNext { .. }
            | MutationSpec::MapUnwrapOr { .. } => {
                // No pre-check for idiom transformations
            }

            // === Spec operations ===
            MutationSpec::RemoveSpec { .. } => {
                // SymbolId is required, no name-based pre-check needed
            }

            MutationSpec::ValidateSpec { .. } => {
                // ValidateSpec is read-only, no pre-check needed
            }

            // === Other mutations ===
            MutationSpec::ExtractTrait { .. }
            | MutationSpec::InlineTrait { .. }
            | MutationSpec::ReplaceType { .. }
            | MutationSpec::EnumToTrait { .. }
            | MutationSpec::MoveItem { .. }
            | MutationSpec::PluginTransform { .. }
            | MutationSpec::ReplaceExpr { .. }
            | MutationSpec::RemoveStatement { .. }
            | MutationSpec::InsertStatement { .. }
            | MutationSpec::ReplaceStatement { .. }
            | MutationSpec::DuplicateFunction { .. }
            | MutationSpec::DuplicateStruct { .. }
            | MutationSpec::DuplicateEnum { .. }
            | MutationSpec::DuplicateModTree { .. }
            | MutationSpec::NoOpArmToTodo { .. } => {
                // No pre-check for these (or could be added later)
            }
        }

        Ok(())
    }

    /// Get the number of registered converters
    pub fn len(&self) -> usize {
        self.converters.len()
    }

    /// Check if the registry is empty
    pub fn is_empty(&self) -> bool {
        self.converters.is_empty()
    }

    /// Get all registered spec kinds
    pub fn registered_kinds(&self) -> Vec<&'static str> {
        self.converters.keys().copied().collect()
    }
}

impl Default for MutationRegistry {
    fn default() -> Self {
        Self::new()
    }
}

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

    #[test]
    fn test_registry_has_all_converters() {
        let registry = MutationRegistry::new();
        // All phases converters are registered
        assert!(!registry.is_empty());
        // Phase 1: Rename, AddField, RemoveField, ChangeVisibility, AddDerive, RemoveDerive (6)
        // Phase 2: AddVariant, RemoveVariant, RemoveItem, AddMethod, RemoveMethod,
        //          RemoveMod, CreateMod, AddItem (8) - Note: AddMod was consolidated into CreateMod
        // Phase 3: 15 Idiom + 3 Trait (ExtractTrait, InlineTrait, EnumToTrait) + 1 Move + 1 Plugin
        //          + 4 Stmt + 2 MatchArm + 2 StructLiteral + 4 Duplicate + 1 Default = 33
        // Note: AddSpec is handled via Blueprint composition, not a direct converter
        // Note: MergeImplBlocks removed - RegistryGenerator auto-merges impl blocks
        // Total spec kinds handled: 6 + 8 + 33 = 47
        assert_eq!(registry.len(), 47);
    }

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

        let registry = MutationRegistry::new();
        let mut sym_registry = SymbolRegistry::new();
        let path = SymbolPath::parse("test_crate::old").unwrap();
        let symbol_id = sym_registry.register(path, SymbolKind::Function).unwrap();

        let spec = MutationSpec::Rename {
            target: crate::executor::spec::MutationTargetSymbol::ById(symbol_id),
            to: "new".into(),
            scope: crate::executor::spec::Scope::Project,
        };

        assert!(registry.can_handle(&spec));
    }

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

        let registry = MutationRegistry::new();
        let mut sym_registry = SymbolRegistry::new();
        let path = SymbolPath::parse("test_crate::Config").unwrap();
        let symbol_id = sym_registry.register(path, SymbolKind::Struct).unwrap();

        let add_spec = MutationSpec::AddField {
            target: crate::executor::spec::MutationTargetSymbol::ById(symbol_id),
            field_name: "timeout".into(),
            field_type: "u64".into(),
            visibility: crate::executor::spec::Visibility::Pub,
        };
        assert!(registry.can_handle(&add_spec));

        let remove_spec = MutationSpec::RemoveField {
            target: crate::executor::spec::MutationTargetSymbol::ById(symbol_id),
            field_name: "timeout".into(),
        };
        assert!(registry.can_handle(&remove_spec));
    }

    #[test]
    fn test_registry_can_handle_add_item() {
        let registry = MutationRegistry::new();

        // AddItem is registered (Phase 2)
        let spec = MutationSpec::AddItem {
            target: crate::executor::spec::MutationTargetSymbol::ByPath(Box::new(
                crate::executor::spec::SymbolPath::parse("test_crate::lib").unwrap(),
            )),
            content: "struct Foo {}".into(),
            position: crate::executor::spec::InsertPosition::Top,
        };
        assert!(registry.can_handle(&spec));
    }

    #[test]
    fn test_registry_registered_kinds() {
        let registry = MutationRegistry::new();
        let kinds = registry.registered_kinds();

        assert!(kinds.contains(&"Rename"));
        assert!(kinds.contains(&"AddField"));
        assert!(kinds.contains(&"RemoveField"));
        assert!(kinds.contains(&"ChangeVisibility"));
        assert!(kinds.contains(&"AddDerive"));
        assert!(kinds.contains(&"RemoveDerive"));
    }

    /// Ensures all converter spec_kinds() are registered in MutationRegistry.
    /// This test prevents the "forgot to register" bug where a converter
    /// declares spec_kinds but they're not added to the registry.
    #[test]
    fn test_all_converter_spec_kinds_are_registered() {
        use std::collections::HashSet;

        let registry = MutationRegistry::new();
        let registered: HashSet<&str> = registry.registered_kinds().into_iter().collect();

        // Check IdiomConverter
        let idiom = converters::IdiomConverter::new();
        for kind in idiom.spec_kinds() {
            assert!(
                registered.contains(kind),
                "IdiomConverter::spec_kinds() contains '{}' but NOT registered in MutationRegistry. \
                Add: registry.register(\"{}\", Box::new(converters::IdiomConverter::new()));",
                kind, kind
            );
        }

        // Check RenameConverter
        let rename = converters::RenameConverter::new();
        for kind in rename.spec_kinds() {
            assert!(
                registered.contains(kind),
                "RenameConverter::spec_kinds() contains '{}' but NOT registered",
                kind
            );
        }

        // Check FieldConverter
        let field = converters::FieldConverter::new();
        for kind in field.spec_kinds() {
            assert!(
                registered.contains(kind),
                "FieldConverter::spec_kinds() contains '{}' but NOT registered",
                kind
            );
        }

        // Check EnumConverter
        let enum_conv = converters::EnumConverter::new();
        for kind in enum_conv.spec_kinds() {
            assert!(
                registered.contains(kind),
                "EnumConverter::spec_kinds() contains '{}' but NOT registered",
                kind
            );
        }

        // Check ModuleConverter
        let module = converters::ModuleConverter::new();
        for kind in module.spec_kinds() {
            assert!(
                registered.contains(kind),
                "ModuleConverter::spec_kinds() contains '{}' but NOT registered",
                kind
            );
        }

        // Check StmtConverter
        let stmt = converters::StmtConverter::new();
        for kind in stmt.spec_kinds() {
            assert!(
                registered.contains(kind),
                "StmtConverter::spec_kinds() contains '{}' but NOT registered",
                kind
            );
        }

        // Check DuplicateConverter
        let dup = converters::DuplicateConverter::new();
        for kind in dup.spec_kinds() {
            assert!(
                registered.contains(kind),
                "DuplicateConverter::spec_kinds() contains '{}' but NOT registered",
                kind
            );
        }
    }
}

#[cfg(test)]
mod tests_pre_check {
    use super::*;
    use ryo_analysis::testing::ContextBuilder;
    use ryo_source::pure::{
        PureEnum, PureField, PureFields, PureFile, PureItem, PureStruct, PureType, PureVariant,
        PureVis,
    };

    /// Create a simple PureFile with a struct
    fn make_test_file_with_struct(struct_name: &str, fields: &[(&str, &str)]) -> PureFile {
        let pure_fields = fields
            .iter()
            .map(|(name, ty)| PureField {
                name: name.to_string(),
                ty: PureType::Path(ty.to_string()),
                attrs: vec![],
                vis: PureVis::Public,
            })
            .collect();

        PureFile {
            attrs: vec![],
            items: vec![PureItem::Struct(PureStruct {
                name: struct_name.to_string(),
                vis: PureVis::Public,
                generics: Default::default(),
                fields: PureFields::Named(pure_fields),
                attrs: vec![],
            })],
        }
    }

    /// Create a simple PureFile with an enum
    fn make_test_file_with_enum(enum_name: &str, variants: &[&str]) -> PureFile {
        let pure_variants = variants
            .iter()
            .map(|name| PureVariant {
                name: name.to_string(),
                attrs: vec![],
                fields: PureFields::Unit,
                discriminant: None,
            })
            .collect();

        PureFile {
            attrs: vec![],
            items: vec![PureItem::Enum(PureEnum {
                name: enum_name.to_string(),
                vis: PureVis::Public,
                generics: Default::default(),
                variants: pure_variants,
                attrs: vec![],
            })],
        }
    }

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

        let registry = MutationRegistry::new();
        let file = make_test_file_with_struct("Config", &[("timeout", "u64")]);
        let ctx = ContextBuilder::new()
            .with_pure_file("src/lib.rs", file)
            .build();

        // Create a SymbolId (symbol_id is now required)
        let mut symbol_registry = SymbolRegistry::new();
        let path = SymbolPath::parse("test_crate::Config").unwrap();
        let symbol_id = symbol_registry.register(path, SymbolKind::Struct).unwrap();

        // Rename spec with required symbol_id
        let spec = MutationSpec::Rename {
            target: crate::executor::spec::MutationTargetSymbol::ById(symbol_id),
            to: "Settings".into(),
            scope: crate::executor::spec::Scope::Project,
        };

        // Pre-check is now a no-op for Rename (symbol_id is required, so no name-based lookup)
        let result = registry.pre_check(&spec, &ctx);
        assert!(
            result.is_ok(),
            "Pre-check should always pass for Rename with symbol_id: {:?}",
            result
        );
    }

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

        let mutation_registry = MutationRegistry::new();
        let file = make_test_file_with_struct("Config", &[("timeout", "u64")]);

        // Create a SymbolId (pre_check doesn't verify it exists in ctx)
        let mut symbol_registry = SymbolRegistry::new();
        let path = SymbolPath::parse("test_crate::Config").unwrap();
        let symbol_id = symbol_registry.register(path, SymbolKind::Struct).unwrap();

        let ctx = ContextBuilder::new()
            .with_pure_file("src/lib.rs", file)
            .build();

        let spec = MutationSpec::AddField {
            target: crate::executor::spec::MutationTargetSymbol::ById(symbol_id),
            field_name: "name".into(),
            field_type: "String".into(),
            visibility: crate::executor::spec::Visibility::Pub,
        };

        // pre_check for AddField is now a no-op since symbol_id is required
        let result = mutation_registry.pre_check(&spec, &ctx);
        assert!(
            result.is_ok(),
            "Pre-check should always pass for AddField with required symbol_id: {:?}",
            result
        );
    }

    #[test]
    fn test_pre_check_add_variant_always_passes() {
        // AddVariant has required symbol_id, pre_check always passes
        let registry = MutationRegistry::new();
        let file = make_test_file_with_enum("Status", &["Active", "Inactive"]);
        let ctx = ContextBuilder::new()
            .with_pure_file("src/lib.rs", file)
            .build();

        // Get the enum's SymbolId from registry
        let enum_id = ctx
            .registry()
            .iter()
            .find(|(_, path)| path.name() == "Status")
            .map(|(id, _)| id)
            .expect("Status enum should exist");

        let spec = MutationSpec::AddVariant {
            target: crate::executor::spec::MutationTargetSymbol::ById(enum_id),
            variant_name: "Pending".into(),
            variant_kind: crate::executor::spec::VariantKind::Unit,
        };

        let result = registry.pre_check(&spec, &ctx);
        assert!(
            result.is_ok(),
            "Pre-check should always pass for AddVariant with required symbol_id: {:?}",
            result
        );
    }

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

        let registry = MutationRegistry::new();
        let file = make_test_file_with_struct("Config", &[("timeout", "u64")]);
        let ctx = ContextBuilder::new()
            .with_pure_file("src/lib.rs", file)
            .build();

        // Create a SymbolId (symbol_id is now required)
        let mut symbol_registry = SymbolRegistry::new();
        let path = SymbolPath::parse("test_crate::Config").unwrap();
        let symbol_id = symbol_registry.register(path, SymbolKind::Struct).unwrap();

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

        // Pre-check is now a no-op for AddDerive (symbol_id is required)
        let result = registry.pre_check(&spec, &ctx);
        assert!(
            result.is_ok(),
            "Pre-check should always pass for AddDerive with symbol_id: {:?}",
            result
        );
    }

    #[test]
    fn test_pre_check_add_item_no_check_needed() {
        let registry = MutationRegistry::new();
        let file = make_test_file_with_struct("Config", &[]);
        let ctx = ContextBuilder::new()
            .with_pure_file("src/lib.rs", file)
            .build();

        // AddItem doesn't need pre-check (it adds new items)
        let spec = MutationSpec::AddItem {
            target: crate::executor::spec::MutationTargetSymbol::ByPath(Box::new(
                crate::executor::spec::SymbolPath::parse("test_crate").unwrap(),
            )),
            content: "struct NewStruct {}".into(),
            position: crate::executor::spec::InsertPosition::Bottom,
        };

        let result = registry.pre_check(&spec, &ctx);
        assert!(result.is_ok(), "AddItem should not require pre-check");
    }
}