ryo-storage 0.1.0

Persistent storage and transaction log for RYO
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
//! Mutation replay engine for deterministic session reproduction.
//!
//! This module provides the ability to replay recorded mutations on files,
//! enabling Git-like reproducibility of coding sessions.
//!
//! # Architecture
//!
//! ```text
//! TxLog (recorded session)
//!//!   ├── MutationApplied { mutation_data, pre_state, post_state }
//!   │         │
//!   │         └── SerializableMutation
//!   │                   │
//!   │                   └── to_mutation() → Box<dyn Mutation>
//!//!   └── ReplayEngine
//!//!             ├── replay_all() → Apply all mutations sequentially
//!             ├── replay_verified() → Verify pre/post states during replay
//!             └── replay_to() → Replay to specific checkpoint
//! ```
//!
//! # Example
//!
//! ```ignore
//! use ryo_core::txlog::{TxLog, ReplayEngine, ReplayMode};
//! use ryo_source::pure::PureFile;
//!
//! // Load a recorded session
//! let log = storage.load("session-id")?;
//!
//! // Start with initial file state
//! let mut file = PureFile::from_source("fn main() {}")?;
//!
//! // Replay all mutations
//! let engine = ReplayEngine::new(&log);
//! let result = engine.replay_all(&mut file)?;
//!
//! println!("Replayed {} mutations, {} changes", result.mutations_applied, result.total_changes);
//! ```

use super::{TxAction, TxEntry, TxLog};
use crate::storage::{InMemoryStateStore, StateRef, StateStore};
use ryo_mutations::SerializableMutation;
use ryo_source::pure::PureFile;
use std::path::Path;
use thiserror::Error;

/// Errors that can occur during replay.
#[derive(Debug, Error)]
pub enum ReplayError {
    /// The entry is replayable in principle but its serialized mutation
    /// payload is absent. Carries the entry id.
    #[error("Mutation data missing for entry #{0}")]
    MissingMutationData(u64),

    /// The serialized mutation payload failed to deserialize.
    #[error("Failed to parse mutation data: {0}")]
    ParseError(String),

    /// The mutation type is a generic placeholder that cannot be executed
    /// during replay. Carries the offending mutation type name.
    #[error("Mutation type '{0}' cannot be replayed (Generic mutation)")]
    UnreplayableMutation(String),

    /// Pre-state verification failed for an entry.
    #[error("Pre-state mismatch at entry #{id}: expected {expected}, got {actual}")]
    PreStateMismatch {
        /// Entry id at which verification failed.
        id: u64,
        /// Rendered expected state reference.
        expected: String,
        /// Rendered actual state reference.
        actual: String,
    },

    /// Post-state verification failed for an entry.
    #[error("Post-state mismatch at entry #{id}: expected {expected}, got {actual}")]
    PostStateMismatch {
        /// Entry id at which verification failed.
        id: u64,
        /// Rendered expected state reference.
        expected: String,
        /// Rendered actual state reference.
        actual: String,
    },

    /// The mutation engine reported a failure while replaying the entry.
    #[error("Mutation failed: {0}")]
    MutationFailed(String),
}

/// Result of a replay operation.
#[derive(Debug, Clone)]
pub struct ReplayResult {
    /// Number of mutations successfully applied.
    pub mutations_applied: usize,
    /// Total number of changes made.
    pub total_changes: usize,
    /// Number of entries skipped (non-mutation or missing data).
    pub skipped: usize,
    /// Warnings during replay (non-fatal issues).
    pub warnings: Vec<String>,
}

impl ReplayResult {
    fn new() -> Self {
        Self {
            mutations_applied: 0,
            total_changes: 0,
            skipped: 0,
            warnings: Vec::new(),
        }
    }
}

/// Replay mode configuration.
#[derive(Debug, Clone, Copy, Default)]
pub enum ReplayMode {
    /// Apply mutations without verification (fastest).
    #[default]
    Fast,
    /// Verify pre-state before each mutation.
    VerifyPre,
    /// Verify post-state after each mutation.
    VerifyPost,
    /// Verify both pre and post states (strictest).
    VerifyBoth,
}

impl ReplayMode {
    /// Returns `true` if this mode requires pre-state verification before
    /// applying each mutation.
    pub fn verify_pre(&self) -> bool {
        matches!(self, ReplayMode::VerifyPre | ReplayMode::VerifyBoth)
    }

    /// Returns `true` if this mode requires post-state verification after
    /// applying each mutation.
    pub fn verify_post(&self) -> bool {
        matches!(self, ReplayMode::VerifyPost | ReplayMode::VerifyBoth)
    }
}

/// Engine for replaying recorded mutations.
pub struct ReplayEngine<'a> {
    log: &'a TxLog,
    mode: ReplayMode,
    state_store: InMemoryStateStore,
}

impl<'a> ReplayEngine<'a> {
    /// Create a new replay engine.
    pub fn new(log: &'a TxLog) -> Self {
        Self {
            log,
            mode: ReplayMode::default(),
            state_store: InMemoryStateStore::new(),
        }
    }

    /// Set the replay mode.
    pub fn with_mode(mut self, mode: ReplayMode) -> Self {
        self.mode = mode;
        self
    }

    /// Replay all mutations in the log to a single file.
    ///
    /// This is the simplest replay mode - applies all mutations sequentially.
    pub fn replay_all(&mut self, file: &mut PureFile) -> Result<ReplayResult, ReplayError> {
        let mut result = ReplayResult::new();

        for entry in self.log.entries() {
            match &entry.action {
                TxAction::MutationApplied {
                    mutation_type,
                    mutation_data,
                    pre_state,
                    post_state,
                    ..
                } => {
                    // Try to replay this mutation
                    match self.replay_mutation_entry(
                        entry,
                        mutation_type,
                        mutation_data,
                        pre_state.as_ref(),
                        post_state.as_ref(),
                        file,
                    ) {
                        Ok(changes) => {
                            result.mutations_applied += 1;
                            result.total_changes += changes;
                        }
                        Err(ReplayError::UnreplayableMutation(t)) => {
                            result.skipped += 1;
                            result.warnings.push(format!(
                                "Skipped unreplayable mutation: {} (entry #{})",
                                t, entry.id
                            ));
                        }
                        Err(ReplayError::MissingMutationData(_)) => {
                            result.skipped += 1;
                            result.warnings.push(format!(
                                "Skipped mutation without data (entry #{})",
                                entry.id
                            ));
                        }
                        Err(e) => return Err(e),
                    }
                }
                _ => {
                    // Skip non-mutation entries
                }
            }
        }

        Ok(result)
    }

    /// Replay mutations for a specific file path.
    ///
    /// Only applies mutations that target the given file.
    pub fn replay_file(
        &mut self,
        target_path: &Path,
        file: &mut PureFile,
    ) -> Result<ReplayResult, ReplayError> {
        let mut result = ReplayResult::new();

        for entry in self.log.entries() {
            if let TxAction::MutationApplied {
                mutation_type,
                mutation_data,
                file_path,
                pre_state,
                post_state,
                ..
            } = &entry.action
            {
                // Check if this mutation targets our file
                let matches = file_path.as_ref().map(|p| p == target_path).unwrap_or(true); // If no path specified, assume it matches

                if !matches {
                    continue;
                }

                match self.replay_mutation_entry(
                    entry,
                    mutation_type,
                    mutation_data,
                    pre_state.as_ref(),
                    post_state.as_ref(),
                    file,
                ) {
                    Ok(changes) => {
                        result.mutations_applied += 1;
                        result.total_changes += changes;
                    }
                    Err(ReplayError::UnreplayableMutation(t)) => {
                        result.skipped += 1;
                        result.warnings.push(format!(
                            "Skipped unreplayable mutation: {} (entry #{})",
                            t, entry.id
                        ));
                    }
                    Err(ReplayError::MissingMutationData(_)) => {
                        result.skipped += 1;
                        result.warnings.push(format!(
                            "Skipped mutation without data (entry #{})",
                            entry.id
                        ));
                    }
                    Err(e) => return Err(e),
                }
            }
        }

        Ok(result)
    }

    /// Replay a single mutation entry.
    fn replay_mutation_entry(
        &mut self,
        entry: &TxEntry,
        mutation_type: &str,
        mutation_data: &Option<serde_json::Value>,
        pre_state: Option<&StateRef>,
        post_state: Option<&StateRef>,
        file: &mut PureFile,
    ) -> Result<usize, ReplayError> {
        // Verify pre-state if required
        if self.mode.verify_pre() {
            if let Some(expected_pre) = pre_state {
                let current = self.state_store.store(
                    &file
                        .to_source()
                        .map_err(|e| ReplayError::MutationFailed(e.to_string()))?,
                );
                if &current != expected_pre {
                    return Err(ReplayError::PreStateMismatch {
                        id: entry.id,
                        expected: expected_pre.short().to_string(),
                        actual: current.short().to_string(),
                    });
                }
            }
        }

        // Get mutation data
        let data = mutation_data
            .as_ref()
            .ok_or(ReplayError::MissingMutationData(entry.id))?;

        // Parse to SerializableMutation
        let serializable: SerializableMutation = serde_json::from_value(data.clone())
            .map_err(|e| ReplayError::ParseError(e.to_string()))?;

        // Convert to Mutation
        let mutation = serializable
            .to_mutation()
            .ok_or_else(|| ReplayError::UnreplayableMutation(mutation_type.to_string()))?;

        // Apply mutation
        // TODO: Mutation::apply was removed. Replay functionality is currently broken.
        // Migration to ASTRegApply is required for replay to work again.
        // let result = mutation.apply(file);
        let _mutation = mutation; // suppress unused warning
        let changes = 0usize; // placeholder until migration

        // Verify post-state if required
        if self.mode.verify_post() {
            if let Some(expected_post) = post_state {
                let current = self.state_store.store(
                    &file
                        .to_source()
                        .map_err(|e| ReplayError::MutationFailed(e.to_string()))?,
                );
                if &current != expected_post {
                    return Err(ReplayError::PostStateMismatch {
                        id: entry.id,
                        expected: expected_post.short().to_string(),
                        actual: current.short().to_string(),
                    });
                }
            }
        }

        Ok(changes)
    }

    /// Get statistics about replayable mutations in the log.
    pub fn analyze(&self) -> ReplayAnalysis {
        let mut analysis = ReplayAnalysis::default();

        for entry in self.log.entries() {
            if let TxAction::MutationApplied {
                mutation_type,
                mutation_data,
                pre_state,
                post_state,
                ..
            } = &entry.action
            {
                analysis.total_mutations += 1;

                // Check if data is present
                if mutation_data.is_none() {
                    analysis.missing_data += 1;
                    analysis
                        .unreplayable_types
                        .push(format!("{} (entry #{}, no data)", mutation_type, entry.id));
                    continue;
                }

                // Check if state refs are present
                if pre_state.is_some() {
                    analysis.with_pre_state += 1;
                }
                if post_state.is_some() {
                    analysis.with_post_state += 1;
                }

                // Try to parse and check if replayable
                if let Some(data) = mutation_data {
                    match serde_json::from_value::<SerializableMutation>(data.clone()) {
                        Ok(sm) => {
                            if sm.to_mutation().is_some() {
                                analysis.replayable += 1;
                            } else {
                                analysis.unreplayable_types.push(format!(
                                    "{} (entry #{}, Generic)",
                                    mutation_type, entry.id
                                ));
                            }
                        }
                        Err(_) => {
                            analysis.parse_errors += 1;
                            analysis.unreplayable_types.push(format!(
                                "{} (entry #{}, parse error)",
                                mutation_type, entry.id
                            ));
                        }
                    }
                }
            }
        }

        analysis
    }
}

/// Analysis of replay capability for a log.
#[derive(Debug, Default)]
pub struct ReplayAnalysis {
    /// Total mutation entries in the log.
    pub total_mutations: usize,
    /// Mutations that can be replayed.
    pub replayable: usize,
    /// Mutations missing mutation_data.
    pub missing_data: usize,
    /// Mutations with parse errors.
    pub parse_errors: usize,
    /// Mutations with pre_state recorded.
    pub with_pre_state: usize,
    /// Mutations with post_state recorded.
    pub with_post_state: usize,
    /// Types that cannot be replayed (with reasons).
    pub unreplayable_types: Vec<String>,
}

impl ReplayAnalysis {
    /// Percentage of mutations that can be replayed.
    pub fn replayable_percentage(&self) -> f64 {
        if self.total_mutations == 0 {
            100.0
        } else {
            (self.replayable as f64 / self.total_mutations as f64) * 100.0
        }
    }

    /// Check if full replay is possible.
    pub fn is_fully_replayable(&self) -> bool {
        self.replayable == self.total_mutations
    }

    /// Check if verified replay is possible (all states recorded).
    pub fn can_verify(&self) -> bool {
        self.with_pre_state == self.total_mutations && self.with_post_state == self.total_mutations
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::txlog::TxAction;
    use ryo_analysis::{SymbolId, SymbolKind, SymbolPath, SymbolRegistry};
    use ryo_mutations::RenameMutation;

    /// Create a dummy SymbolId for testing purposes using SymbolRegistry
    fn dummy_symbol_id() -> SymbolId {
        let mut registry = SymbolRegistry::new();
        let path = SymbolPath::parse("test_crate::test_dummy").unwrap();
        registry.register(path, SymbolKind::Function).unwrap()
    }

    fn create_test_log_with_mutation() -> TxLog {
        let mut log = TxLog::new();

        // Add a replayable mutation
        let mutation = RenameMutation {
            symbol_id: dummy_symbol_id(),
            to: "bar".to_string(),
        };
        use ryo_mutations::ToSerializable;
        let serializable = mutation.to_serializable();

        log.log(TxAction::MutationApplied {
            mutation_type: "Rename".to_string(),
            target: "foo -> bar".to_string(),
            changes: 1,
            mutation_data: Some(serializable.to_json()),
            file_path: None,
            pre_state: None,
            post_state: None,
            affected_symbols: vec![],
        });

        log
    }

    #[test]
    fn test_replay_engine_analyze() {
        let log = create_test_log_with_mutation();
        let engine = ReplayEngine::new(&log);
        let analysis = engine.analyze();

        assert_eq!(analysis.total_mutations, 1);
        assert_eq!(analysis.replayable, 1);
        assert!(analysis.is_fully_replayable());
    }

    #[test]
    #[ignore = "V1 path disabled - Mutation::apply removed, needs V2 migration"]
    fn test_replay_simple_mutation() {
        let log = create_test_log_with_mutation();
        let mut engine = ReplayEngine::new(&log);

        // Create a file with 'foo' that can be renamed
        let mut file = PureFile::from_source("fn foo() {}").unwrap();

        let result = engine.replay_all(&mut file).unwrap();

        assert_eq!(result.mutations_applied, 1);
        assert!(result.total_changes > 0);

        // Verify the rename happened
        let source = file.to_source().unwrap();
        assert!(source.contains("bar"));
        assert!(!source.contains("foo"));
    }

    #[test]
    fn test_analyze_missing_data() {
        let mut log = TxLog::new();

        // Add mutation without data
        log.log(TxAction::MutationApplied {
            mutation_type: "Rename".to_string(),
            target: "foo -> bar".to_string(),
            changes: 1,
            mutation_data: None, // Missing!
            file_path: None,
            pre_state: None,
            post_state: None,
            affected_symbols: vec![],
        });

        let engine = ReplayEngine::new(&log);
        let analysis = engine.analyze();

        assert_eq!(analysis.total_mutations, 1);
        assert_eq!(analysis.missing_data, 1);
        assert_eq!(analysis.replayable, 0);
        assert!(!analysis.is_fully_replayable());
    }

    // =========================================================================
    // 検証テスト: 現場でのReplay可能性を明確化
    // =========================================================================

    /// 検証1: 複数のMutationタイプのReplay可能性
    #[test]
    fn test_verify_multiple_mutation_types() {
        use ryo_mutations::{AddDeriveMutation, AddFunctionMutation, ToSerializable};

        let mut log = TxLog::new();

        // 1. Rename - Replayable
        let rename = RenameMutation {
            symbol_id: dummy_symbol_id(),
            to: "new_name".to_string(),
        };
        log.log(TxAction::MutationApplied {
            mutation_type: "Rename".to_string(),
            target: "old_name -> new_name".to_string(),
            changes: 1,
            mutation_data: Some(rename.to_serializable().to_json()),
            file_path: None,
            pre_state: None,
            post_state: None,
            affected_symbols: vec![],
        });

        // 2. AddFunction - NOT Replayable (SymbolId cannot be deserialized)
        let add_fn = AddFunctionMutation {
            parent: dummy_symbol_id(),
            name: "new_fn".to_string(),
            params: vec![("x".to_string(), "i32".to_string())],
            return_type: Some("i32".to_string()),
            body: "x + 1".to_string(),
            is_pub: true,
        };
        log.log(TxAction::MutationApplied {
            mutation_type: "AddFunction".to_string(),
            target: "new_fn".to_string(),
            changes: 1,
            mutation_data: Some(add_fn.to_serializable().to_json()),
            file_path: None,
            pre_state: None,
            post_state: None,
            affected_symbols: vec![],
        });

        // 3. AddDerive - Replayable
        let add_derive = AddDeriveMutation {
            symbol_id: dummy_symbol_id(),
            derives: vec!["Debug".to_string(), "Clone".to_string()],
        };
        log.log(TxAction::MutationApplied {
            mutation_type: "AddDerive".to_string(),
            target: "MyStruct".to_string(),
            changes: 1,
            mutation_data: Some(add_derive.to_serializable().to_json()),
            file_path: None,
            pre_state: None,
            post_state: None,
            affected_symbols: vec![],
        });

        // 4. mutation_dataなし(従来のlog_mutation経由) - NOT Replayable
        log.log(TxAction::MutationApplied {
            mutation_type: "Rename".to_string(),
            target: "legacy call".to_string(),
            changes: 1,
            mutation_data: None, // ← 問題点:従来のAPIはここがNone
            file_path: None,
            pre_state: None,
            post_state: None,
            affected_symbols: vec![],
        });

        let engine = ReplayEngine::new(&log);
        let analysis = engine.analyze();

        // 結果確認
        // Note: Only Rename is replayable (uses SymbolId::parse)
        // - AddFunction: NOT replayable (SymbolId cannot be deserialized, returns None)
        // - AddDerive: NOT replayable (SymbolId cannot be deserialized, returns None)
        // - Legacy: NOT replayable (no mutation_data)
        assert_eq!(analysis.total_mutations, 4);
        assert_eq!(analysis.replayable, 1); // Only Rename is replayable
        assert_eq!(analysis.missing_data, 1); // mutation_dataなし
        assert!(!analysis.is_fully_replayable()); // 完全Replayは不可

        // Replay可能率: 1/4 = 25%
        assert!((analysis.replayable_percentage() - 25.0).abs() < 0.1);
    }

    /// 検証2: Generic mutationはReplay不可能
    #[test]
    fn test_verify_generic_mutation_not_replayable() {
        use ryo_mutations::SerializableMutation;

        let mut log = TxLog::new();

        // Generic mutationをシミュレート
        let generic = SerializableMutation::Generic {
            mutation_type: "CustomMutation".to_string(),
            description: "Some custom operation".to_string(),
        };

        log.log(TxAction::MutationApplied {
            mutation_type: "CustomMutation".to_string(),
            target: "custom".to_string(),
            changes: 1,
            mutation_data: Some(generic.to_json()),
            file_path: None,
            pre_state: None,
            post_state: None,
            affected_symbols: vec![],
        });

        let engine = ReplayEngine::new(&log);
        let analysis = engine.analyze();

        assert_eq!(analysis.total_mutations, 1);
        assert_eq!(analysis.replayable, 0); // Generic → to_mutation() returns None
        assert!(!analysis.unreplayable_types.is_empty());
    }

    /// 検証3: 状態検証付きReplay
    #[test]
    fn test_verify_replay_with_state_verification() {
        use crate::storage::InMemoryStateStore;
        use ryo_mutations::ToSerializable;

        let mut state_store = InMemoryStateStore::new();

        // 初期状態を記録
        let initial_source = "fn foo() { println!(\"hello\"); }";
        let pre_state = state_store.store(initial_source);

        // Mutation適用後の期待状態
        let expected_source = "fn bar() { println!(\"hello\"); }";
        let post_state = state_store.store(expected_source);

        // ログ作成(状態付き)
        let mut log = TxLog::new();
        let rename = RenameMutation {
            symbol_id: dummy_symbol_id(),
            to: "bar".to_string(),
        };

        log.log(TxAction::MutationApplied {
            mutation_type: "Rename".to_string(),
            target: "foo -> bar".to_string(),
            changes: 1,
            mutation_data: Some(rename.to_serializable().to_json()),
            file_path: Some(std::path::PathBuf::from("test.rs")),
            pre_state: Some(pre_state.clone()),
            post_state: Some(post_state.clone()),
            affected_symbols: vec![],
        });

        let engine = ReplayEngine::new(&log);
        let analysis = engine.analyze();

        // 状態検証可能
        assert_eq!(analysis.with_pre_state, 1);
        assert_eq!(analysis.with_post_state, 1);
        assert!(analysis.can_verify());
    }

    /// 検証4: 実際のReplay実行(複数mutation連続適用)
    #[test]
    #[ignore = "V1 path disabled - Mutation::apply removed, needs V2 migration"]
    fn test_verify_sequential_replay() {
        use ryo_mutations::ToSerializable;

        let mut log = TxLog::new();

        // 1. foo → bar
        let rename1 = RenameMutation {
            symbol_id: dummy_symbol_id(),
            to: "bar".to_string(),
        };
        log.log(TxAction::MutationApplied {
            mutation_type: "Rename".to_string(),
            target: "foo -> bar".to_string(),
            changes: 1,
            mutation_data: Some(rename1.to_serializable().to_json()),
            file_path: None,
            pre_state: None,
            post_state: None,
            affected_symbols: vec![],
        });

        // 2. bar → baz
        let rename2 = RenameMutation {
            symbol_id: dummy_symbol_id(),
            to: "baz".to_string(),
        };
        log.log(TxAction::MutationApplied {
            mutation_type: "Rename".to_string(),
            target: "bar -> baz".to_string(),
            changes: 1,
            mutation_data: Some(rename2.to_serializable().to_json()),
            file_path: None,
            pre_state: None,
            post_state: None,
            affected_symbols: vec![],
        });

        // Replay実行
        let mut engine = ReplayEngine::new(&log);
        let mut file = PureFile::from_source("fn foo() { foo(); }").unwrap();

        let result = engine.replay_all(&mut file).unwrap();

        // 検証
        assert_eq!(result.mutations_applied, 2);
        let source = file.to_source().unwrap();
        assert!(source.contains("baz"));
        assert!(!source.contains("foo"));
        assert!(!source.contains("bar"));
    }

    /// 検証5: 現場問題の再現 - log_mutation()経由のログはReplay不可能
    #[test]
    fn test_verify_current_logger_issue() {
        use crate::txlog::TxLogger;
        use std::path::PathBuf;
        use std::thread;
        use std::time::Duration;

        // 現行のTxLoggerを使用
        let logger = TxLogger::start(PathBuf::from("/test"), 10);

        // 従来のlog_mutation() - mutation_dataなし
        logger.log_mutation("Rename", "foo -> bar", 5);

        thread::sleep(Duration::from_millis(10));
        let log = logger.finish();

        let engine = ReplayEngine::new(&log);
        let analysis = engine.analyze();

        // 問題点: log_mutation()はmutation_dataを記録しない
        assert_eq!(analysis.total_mutations, 1);
        assert_eq!(analysis.missing_data, 1);
        assert_eq!(analysis.replayable, 0);

        // これが修正すべき箇所
        // → log_mutation()にMutation自体を渡すAPIが必要
    }

    /// 検証6: 新API record_mutation()はReplay可能
    #[test]
    fn test_verify_new_record_mutation_api() {
        use crate::txlog::TxLogger;
        use std::path::PathBuf;
        use std::thread;
        use std::time::Duration;

        let logger = TxLogger::start(PathBuf::from("/test"), 10);

        // 新しいrecord_mutation() API - Replayable!
        let mutation = RenameMutation {
            symbol_id: dummy_symbol_id(),
            to: "bar".to_string(),
        };
        logger.record_mutation(&mutation, 5);

        thread::sleep(Duration::from_millis(10));
        let log = logger.finish();

        let engine = ReplayEngine::new(&log);
        let analysis = engine.analyze();

        // 新APIはmutation_dataを自動記録する
        assert_eq!(analysis.total_mutations, 1);
        assert_eq!(analysis.missing_data, 0);
        assert_eq!(analysis.replayable, 1);
        assert!(analysis.is_fully_replayable());
    }

    /// 検証7: 新旧API混在時の分析
    #[test]
    fn test_verify_mixed_api_usage() {
        use crate::txlog::TxLogger;
        use std::path::PathBuf;
        use std::thread;
        use std::time::Duration;

        let logger = TxLogger::start(PathBuf::from("/test"), 10);

        // 旧API (NOT replayable)
        logger.log_mutation("Rename", "legacy", 1);

        // 新API (REPLAYABLE)
        let mutation1 = RenameMutation {
            symbol_id: dummy_symbol_id(),
            to: "bar".to_string(),
        };
        logger.record_mutation(&mutation1, 2);

        // 新API with file path (REPLAYABLE)
        let mutation2 = RenameMutation {
            symbol_id: dummy_symbol_id(),
            to: "qux".to_string(),
        };
        logger.record_mutation_for_file(&mutation2, 3, "src/lib.rs");

        thread::sleep(Duration::from_millis(10));
        let log = logger.finish();

        let engine = ReplayEngine::new(&log);
        let analysis = engine.analyze();

        // 結果: 3 mutations, 2 replayable, 1 missing data
        assert_eq!(analysis.total_mutations, 3);
        assert_eq!(analysis.replayable, 2);
        assert_eq!(analysis.missing_data, 1);
        assert!(!analysis.is_fully_replayable());

        // Replay可能率: 66.67%
        assert!((analysis.replayable_percentage() - 66.67).abs() < 1.0);
    }
}