normalize-shadow 0.3.1

Shadow git history tracking for normalize edit operations
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
//! Shadow Git - automatic edit history tracking.
//!
//! Maintains a hidden git repository (`.normalize/shadow/`) that automatically
//! commits after each `normalize edit` operation, preserving full edit history.

use serde::{Deserialize, Serialize};
use std::path::{Path, PathBuf};
use std::process::Command;

/// A single entry in shadow git history.
#[derive(Debug, Clone, Serialize, schemars::JsonSchema)]
pub struct HistoryEntry {
    pub id: usize,
    pub hash: String,
    pub subject: String,
    pub operation: String,
    pub target: String,
    pub files: Vec<String>,
    pub message: Option<String>,
    pub workflow: Option<String>,
    pub git_head: String,
    pub timestamp: String,
}

/// Shadow git configuration.
#[derive(Debug, Clone, Deserialize, Serialize, Default, schemars::JsonSchema)]
#[serde(default)]
pub struct ShadowConfig {
    /// Whether shadow git is enabled. Default: true
    pub enabled: Option<bool>,
    /// Confirm before deleting symbols. Default: true
    pub warn_on_delete: Option<bool>,
}

impl ShadowConfig {
    pub fn enabled(&self) -> bool {
        self.enabled.unwrap_or(true)
    }

    pub fn warn_on_delete(&self) -> bool {
        self.warn_on_delete.unwrap_or(true)
    }
}

/// Information about an edit operation for shadow commit.
pub struct EditInfo {
    pub operation: String,
    pub target: String,
    pub files: Vec<PathBuf>,
    pub message: Option<String>,
    pub workflow: Option<String>,
}

/// Result of running a validation command in shadow worktree.
pub struct ValidationResult {
    pub success: bool,
    pub exit_code: Option<i32>,
    pub stdout: String,
    pub stderr: String,
}

/// Shadow git repository manager.
pub struct Shadow {
    /// Root of the project (where .normalize/ lives)
    root: PathBuf,
    /// Path to shadow git directory (.normalize/shadow/)
    shadow_dir: PathBuf,
    /// Path to shadow worktree (.normalize/shadow/worktree/)
    worktree: PathBuf,
}

impl Shadow {
    /// Create a new Shadow instance for a project root.
    pub fn new(root: &Path) -> Self {
        let shadow_dir = root.join(".normalize").join("shadow");
        let worktree = shadow_dir.join("worktree");
        Self {
            root: root.to_path_buf(),
            shadow_dir,
            worktree,
        }
    }

    /// Check if shadow git exists for this project.
    pub fn exists(&self) -> bool {
        self.shadow_dir.join(".git").exists()
    }

    /// Initialize shadow git repository if it doesn't exist.
    /// Called on first edit, not on `normalize init`.
    fn init(&self) -> Result<(), ShadowError> {
        if self.exists() {
            return Ok(());
        }

        // Create worktree directory (git init will create .git inside shadow_dir)
        std::fs::create_dir_all(&self.worktree)
            .map_err(|e| ShadowError::Init(format!("Failed to create shadow directory: {}", e)))?;

        // Initialize git repo with worktree in subdirectory
        // Use --separate-git-dir to put .git in shadow_dir while worktree is in worktree/
        let status = Command::new("git")
            .args([
                "init",
                "--quiet",
                &format!(
                    "--separate-git-dir={}",
                    self.shadow_dir.join(".git").display()
                ),
            ])
            .current_dir(&self.worktree)
            .status()
            .map_err(|e| ShadowError::Init(format!("Failed to run git init: {}", e)))?;

        if !status.success() {
            return Err(ShadowError::Init("git init failed".to_string()));
        }

        // Configure git user for commits (shadow-specific, doesn't affect user's git)
        let _ = Command::new("git")
            .args(["config", "user.email", "shadow@normalize.local"])
            .current_dir(&self.worktree)
            .status();
        let _ = Command::new("git")
            .args(["config", "user.name", "Normalize Shadow"])
            .current_dir(&self.worktree)
            .status();

        Ok(())
    }

    /// Get the current git HEAD of the real repository.
    fn get_real_git_head(&self) -> Option<String> {
        let output = Command::new("git")
            .args(["rev-parse", "--short", "HEAD"])
            .current_dir(&self.root)
            .output()
            .ok()?;

        if output.status.success() {
            Some(String::from_utf8_lossy(&output.stdout).trim().to_string())
        } else {
            None
        }
    }

    /// Copy a file to the shadow worktree, preserving relative path.
    fn copy_to_worktree(&self, file: &Path) -> Result<PathBuf, ShadowError> {
        let rel_path = file
            .strip_prefix(&self.root)
            .map_err(|_| ShadowError::Commit("File not under project root".to_string()))?;

        let dest = self.worktree.join(rel_path);

        // Create parent directories
        if let Some(parent) = dest.parent() {
            std::fs::create_dir_all(parent)
                .map_err(|e| ShadowError::Commit(format!("Failed to create directories: {}", e)))?;
        }

        // Copy file
        std::fs::copy(file, &dest)
            .map_err(|e| ShadowError::Commit(format!("Failed to copy file: {}", e)))?;

        Ok(rel_path.to_path_buf())
    }

    /// Record file state before an edit.
    /// Call this before applying the edit to capture "before" state.
    pub fn before_edit(&self, files: &[&Path]) -> Result<(), ShadowError> {
        self.init()?;

        for file in files {
            if file.exists() {
                self.copy_to_worktree(file)?;
            }
        }

        Ok(())
    }

    /// Record file state after an edit and commit.
    /// Call this after applying the edit to capture "after" state.
    pub fn after_edit(&self, info: &EditInfo) -> Result<(), ShadowError> {
        // Copy updated files to worktree
        for file in &info.files {
            if file.exists() {
                self.copy_to_worktree(file)?;
            }
        }

        // Stage all changes (run in worktree directory)
        let status = Command::new("git")
            .args(["add", "-A"])
            .current_dir(&self.worktree)
            .status()
            .map_err(|e| ShadowError::Commit(format!("Failed to stage changes: {}", e)))?;

        if !status.success() {
            return Err(ShadowError::Commit("git add failed".to_string()));
        }

        // Check if there are changes to commit
        let status = Command::new("git")
            .args(["diff", "--cached", "--quiet"])
            .current_dir(&self.worktree)
            .status()
            .map_err(|e| ShadowError::Commit(format!("Failed to check diff: {}", e)))?;

        if status.success() {
            // No changes to commit
            return Ok(());
        }

        // Build commit message
        let git_head = self
            .get_real_git_head()
            .unwrap_or_else(|| "none".to_string());
        let files_str: Vec<String> = info
            .files
            .iter()
            .filter_map(|f| f.strip_prefix(&self.root).ok())
            .map(|p| p.display().to_string())
            .collect();

        let mut commit_msg = format!("normalize edit: {} {}\n\n", info.operation, info.target);

        if let Some(ref msg) = info.message {
            commit_msg.push_str(&format!("Message: {}\n", msg));
        }
        if let Some(ref wf) = info.workflow {
            commit_msg.push_str(&format!("Workflow: {}\n", wf));
        }
        commit_msg.push_str(&format!("Operation: {}\n", info.operation));
        commit_msg.push_str(&format!("Target: {}\n", info.target));
        commit_msg.push_str(&format!("Files: {}\n", files_str.join(", ")));
        commit_msg.push_str(&format!("Git-HEAD: {}\n", git_head));

        // Commit
        let status = Command::new("git")
            .args(["commit", "-m", &commit_msg])
            .current_dir(&self.worktree)
            .status()
            .map_err(|e| ShadowError::Commit(format!("Failed to commit: {}", e)))?;

        if !status.success() {
            return Err(ShadowError::Commit("git commit failed".to_string()));
        }

        Ok(())
    }

    /// Get history of shadow edits.
    /// Returns list of edits in reverse chronological order (newest first).
    pub fn history(&self, file_filter: Option<&str>, limit: usize) -> Vec<HistoryEntry> {
        if !self.exists() {
            return Vec::new();
        }

        // Get git log with custom format
        // Use %x1e (record separator) between commits and %x1f (unit separator) between fields
        let mut args = vec![
            "log".to_string(),
            "--format=%H%x1f%s%x1f%b%x1f%aI%x1e".to_string(),
            format!("-{}", limit),
        ];

        // Filter by file if specified
        if let Some(file) = file_filter {
            args.push("--".to_string());
            args.push(file.to_string());
        }

        let output = Command::new("git")
            .args(&args)
            .current_dir(&self.worktree)
            .output();

        let output = match output {
            Ok(out) if out.status.success() => out,
            _ => return Vec::new(),
        };

        let stdout = String::from_utf8_lossy(&output.stdout);
        let mut entries = Vec::new();

        // Split by record separator (0x1e)
        let blocks: Vec<&str> = stdout
            .split('\x1e')
            .filter(|b| !b.trim().is_empty())
            .collect();
        let total = blocks.len();

        for (idx, block) in blocks.into_iter().enumerate() {
            // Parse the commit format: hash\x1fsubject\x1fbody\x1ftimestamp
            let parts: Vec<&str> = block.split('\x1f').collect();
            if parts.len() < 4 {
                continue;
            }

            let hash = parts[0].trim();
            let subject = parts[1].trim();
            let body = parts[2].trim();
            let timestamp = parts[3].trim();

            // Parse body for structured fields
            let mut operation = String::new();
            let mut target = String::new();
            let mut files = Vec::new();
            let mut message = None;
            let mut workflow = None;
            let mut git_head = String::new();

            for line in body.lines() {
                if let Some(val) = line.strip_prefix("Operation: ") {
                    operation = val.to_string();
                } else if let Some(val) = line.strip_prefix("Target: ") {
                    target = val.to_string();
                } else if let Some(val) = line.strip_prefix("Files: ") {
                    files = val.split(", ").map(String::from).collect();
                } else if let Some(val) = line.strip_prefix("Message: ") {
                    message = Some(val.to_string());
                } else if let Some(val) = line.strip_prefix("Workflow: ") {
                    workflow = Some(val.to_string());
                } else if let Some(val) = line.strip_prefix("Git-HEAD: ") {
                    git_head = val.to_string();
                }
            }

            entries.push(HistoryEntry {
                id: total - idx, // newest first, so first entry gets highest ID
                hash: hash.to_string(),
                subject: subject.to_string(),
                operation,
                target,
                files,
                message,
                workflow,
                git_head,
                timestamp: timestamp.to_string(),
            });
        }

        entries
    }

    /// Get diff for a specific commit.
    pub fn diff(&self, commit_ref: &str) -> Option<String> {
        if !self.exists() {
            return None;
        }

        let output = Command::new("git")
            .args(["show", "--format=", commit_ref])
            .current_dir(&self.worktree)
            .output()
            .ok()?;

        if output.status.success() {
            Some(String::from_utf8_lossy(&output.stdout).to_string())
        } else {
            None
        }
    }

    /// Get tree view of shadow history (shows all branches with graph).
    pub fn tree(&self, limit: usize) -> Option<String> {
        if !self.exists() {
            return None;
        }

        let output = Command::new("git")
            .args([
                "log",
                "--graph",
                "--all",
                "--oneline",
                "--decorate",
                &format!("-{}", limit),
            ])
            .current_dir(&self.worktree)
            .output()
            .ok()?;

        if output.status.success() {
            Some(String::from_utf8_lossy(&output.stdout).to_string())
        } else {
            None
        }
    }

    /// Get current checkpoint (last git commit in real repo when shadow was updated).
    pub fn checkpoint(&self) -> Option<String> {
        self.history(None, 1)
            .first()
            .map(|e| e.git_head.clone())
            .filter(|h| h != "none")
    }

    /// Run a validation command in the shadow worktree.
    /// Returns (success, stdout, stderr).
    /// Used by agents to test changes before applying to real files.
    pub fn validate(&self, cmd: &str, args: &[&str]) -> Result<ValidationResult, ShadowError> {
        if !self.exists() {
            return Err(ShadowError::Init("No shadow worktree exists".to_string()));
        }

        let output = Command::new(cmd)
            .args(args)
            .current_dir(&self.worktree)
            .output()
            .map_err(|e| ShadowError::Validation {
                message: format!("Failed to run {}: {}", cmd, e),
                exit_code: -1,
            })?;

        Ok(ValidationResult {
            success: output.status.success(),
            exit_code: output.status.code(),
            stdout: String::from_utf8_lossy(&output.stdout).to_string(),
            stderr: String::from_utf8_lossy(&output.stderr).to_string(),
        })
    }

    /// Apply pending shadow changes to the real worktree.
    /// Only call this after validation passes.
    /// Returns list of files that were updated.
    pub fn apply_to_real(&self) -> Result<Vec<PathBuf>, ShadowError> {
        if !self.exists() {
            return Err(ShadowError::Init("No shadow worktree exists".to_string()));
        }

        // Get list of changed files in shadow
        let output = Command::new("git")
            .args(["diff", "--name-only", "HEAD~1", "HEAD"])
            .current_dir(&self.worktree)
            .output()
            .map_err(|e| ShadowError::Validation {
                message: format!("git diff failed: {}", e),
                exit_code: -1,
            })?;

        if !output.status.success() {
            return Err(ShadowError::Validation {
                message: "Failed to get changed files".to_string(),
                exit_code: -1,
            });
        }

        let files: Vec<PathBuf> = String::from_utf8_lossy(&output.stdout)
            .lines()
            .map(|l| self.root.join(l))
            .collect();

        // Copy each file from shadow to real
        for file in &files {
            let rel = file.strip_prefix(&self.root).unwrap_or(file.as_path());
            let shadow_file = self.worktree.join(rel);
            if shadow_file.exists() {
                if let Some(parent) = file.parent() {
                    std::fs::create_dir_all(parent).map_err(|e| ShadowError::Validation {
                        message: format!("mkdir failed: {}", e),
                        exit_code: -1,
                    })?;
                }
                std::fs::copy(&shadow_file, file).map_err(|e| ShadowError::Validation {
                    message: format!("copy failed: {}", e),
                    exit_code: -1,
                })?;
            }
        }

        Ok(files)
    }

    /// Get the number of shadow commits (edits tracked).
    pub fn edit_count(&self) -> usize {
        if !self.exists() {
            return 0;
        }

        let output = Command::new("git")
            .args(["rev-list", "--count", "HEAD"])
            .current_dir(&self.worktree)
            .output();

        match output {
            Ok(out) if out.status.success() => String::from_utf8_lossy(&out.stdout)
                .trim()
                .parse()
                .unwrap_or(0),
            _ => 0,
        }
    }

    /// Prune shadow history, keeping only the last N commits.
    /// Returns the number of commits pruned.
    pub fn prune(&self, keep: usize) -> Result<usize, ShadowError> {
        if !self.exists() {
            return Err(ShadowError::Init("No shadow history exists".to_string()));
        }

        let total = self.edit_count();
        if total <= keep {
            return Ok(0);
        }

        let to_prune = total - keep;

        // Find the commit that will become the new root (the `keep`th commit from HEAD)
        let new_root_output = Command::new("git")
            .args(["rev-parse", &format!("HEAD~{}", keep - 1)])
            .current_dir(&self.worktree)
            .output()
            .map_err(|e| ShadowError::Init(format!("Failed to find root commit: {}", e)))?;

        if !new_root_output.status.success() {
            return Err(ShadowError::Init(
                "Failed to find commit to keep".to_string(),
            ));
        }

        let new_root = String::from_utf8_lossy(&new_root_output.stdout)
            .trim()
            .to_string();

        // Create a graft to make the new root appear as an initial commit
        let _ = Command::new("git")
            .args(["replace", "--graft", &new_root])
            .current_dir(&self.worktree)
            .output();

        // Use filter-branch to bake in the graft (rewrite history)
        let filter_result = Command::new("git")
            .args(["filter-branch", "--force", "--", "--all"])
            .current_dir(&self.worktree)
            .output();

        if let Err(e) = filter_result {
            return Err(ShadowError::Init(format!("Filter-branch failed: {}", e)));
        }

        // Clean up refs created by filter-branch
        let _ = Command::new("git")
            .args(["for-each-ref", "--format=%(refname)", "refs/original/"])
            .current_dir(&self.worktree)
            .output()
            .map(|out| {
                for refname in String::from_utf8_lossy(&out.stdout).lines() {
                    let _ = Command::new("git")
                        .args(["update-ref", "-d", refname])
                        .current_dir(&self.worktree)
                        .output();
                }
            });

        // Remove the replacement ref
        let _ = Command::new("git")
            .args(["replace", "-d", &new_root])
            .current_dir(&self.worktree)
            .output();

        // Run gc to actually free space
        let _ = Command::new("git")
            .args(["gc", "--prune=now", "--aggressive"])
            .current_dir(&self.worktree)
            .output();

        Ok(to_prune)
    }

    /// Undo the most recent edit (or specified number of edits).
    /// Returns information about what was undone.
    ///
    /// If `file_filter` is Some, only undo changes to files matching that path.
    /// If `force` is false, checks for external modifications first and fails
    /// if any files have been modified outside of normalize.
    ///
    /// If `cross_checkpoint` is false, refuses to undo past a git commit boundary.
    pub fn undo(
        &self,
        count: usize,
        file_filter: Option<&str>,
        cross_checkpoint: bool,
        dry_run: bool,
        force: bool,
    ) -> Result<Vec<UndoResult>, ShadowError> {
        if !self.exists() {
            return Err(ShadowError::Undo("No shadow history exists".to_string()));
        }

        let entries = self.history(None, count);
        if entries.is_empty() {
            return Err(ShadowError::Undo("No edits to undo".to_string()));
        }

        // Filter entries to only those affecting the specified file
        let entries: Vec<_> = if let Some(filter) = file_filter {
            entries
                .into_iter()
                .filter(|e| e.files.iter().any(|f| f.contains(filter) || f == filter))
                .collect()
        } else {
            entries
        };

        if entries.is_empty() {
            return Err(ShadowError::Undo(
                "No edits found matching the file filter".to_string(),
            ));
        }

        // Check for checkpoint boundaries (git commit changes) unless cross_checkpoint is set
        if !cross_checkpoint && entries.len() > 1 {
            let first_git_head = &entries[0].git_head;
            for entry in entries.iter().skip(1) {
                if entry.git_head != *first_git_head && entry.git_head != "none" {
                    return Err(ShadowError::Undo(format!(
                        "Cannot undo past checkpoint (git commit {}). Use --cross-checkpoint to override.",
                        entry.git_head
                    )));
                }
            }
        }

        // Check for external modifications unless force is set
        if !force && !dry_run {
            let conflicts = self.detect_conflicts(&entries);
            if !conflicts.is_empty() {
                let files_str = conflicts.join(", ");
                return Err(ShadowError::Undo(format!(
                    "Files modified externally since last edit: {}. Use --force to override.",
                    files_str
                )));
            }
        }

        let mut results = Vec::new();

        for entry in entries.iter().take(count) {
            // Filter files to only those matching the filter
            let files_to_undo: Vec<_> = if let Some(filter) = file_filter {
                entry
                    .files
                    .iter()
                    .filter(|f| f.contains(filter) || *f == filter)
                    .cloned()
                    .collect()
            } else {
                entry.files.clone()
            };

            if dry_run {
                // Also report conflicts in dry-run mode
                let conflicts = self.detect_conflicts(std::slice::from_ref(entry));
                results.push(UndoResult {
                    files: files_to_undo.iter().map(PathBuf::from).collect(),
                    undone_commit: entry.hash.clone(),
                    description: format!("{}: {}", entry.operation, entry.target),
                    conflicts,
                });
                continue;
            }

            // For each file in the commit, restore from the parent commit state
            let parent_ref = format!("{}^", entry.hash);
            self.restore_files_from_ref(&files_to_undo, &parent_ref)?;

            // Stage and commit the undo
            let add_status = Command::new("git")
                .args(["add", "-A"])
                .current_dir(&self.worktree)
                .status()
                .map_err(|e| ShadowError::Commit(format!("Failed to stage undo: {}", e)))?;
            if !add_status.success() {
                return Err(ShadowError::Commit(
                    "git add failed during undo".to_string(),
                ));
            }

            let undo_msg = format!(
                "normalize edit: undo {}\n\nOperation: undo\nTarget: {}\nUndone-Commit: {}\nFiles: {}\nGit-HEAD: {}\n",
                entry.target,
                entry.target,
                entry.hash,
                files_to_undo.join(", "),
                self.get_real_git_head()
                    .unwrap_or_else(|| "none".to_string())
            );

            let commit_status = Command::new("git")
                .args(["commit", "-m", &undo_msg, "--allow-empty"])
                .current_dir(&self.worktree)
                .status()
                .map_err(|e| ShadowError::Commit(format!("Failed to commit undo: {}", e)))?;
            if !commit_status.success() {
                return Err(ShadowError::Commit(
                    "git commit failed during undo".to_string(),
                ));
            }

            results.push(UndoResult {
                files: files_to_undo.iter().map(PathBuf::from).collect(),
                undone_commit: entry.hash.clone(),
                description: format!("{}: {}", entry.operation, entry.target),
                conflicts: vec![], // Already checked/forced above
            });
        }

        Ok(results)
    }

    /// Restore a set of files from a given git ref into both the real root and the worktree.
    /// Files that don't exist at `git_ref` are deleted; files that do are written.
    fn restore_files_from_ref(&self, files: &[String], git_ref: &str) -> Result<(), ShadowError> {
        for file_path in files {
            let worktree_file = self.worktree.join(file_path);
            let actual_file = self.root.join(file_path);

            let show_output = Command::new("git")
                .args(["show", &format!("{}:{}", git_ref, file_path)])
                .current_dir(&self.worktree)
                .output();

            match show_output {
                Ok(output) if output.status.success() => {
                    if let Some(parent) = actual_file.parent() {
                        let _ = std::fs::create_dir_all(parent);
                    }
                    std::fs::write(&actual_file, &output.stdout).map_err(|e| {
                        ShadowError::Undo(format!("Failed to write {}: {}", file_path, e))
                    })?;
                    if let Some(parent) = worktree_file.parent() {
                        let _ = std::fs::create_dir_all(parent);
                    }
                    let _ = std::fs::write(&worktree_file, &output.stdout);
                }
                _ => {
                    if actual_file.exists() {
                        std::fs::remove_file(&actual_file).map_err(|e| {
                            ShadowError::Undo(format!("Failed to delete {}: {}", file_path, e))
                        })?;
                    }
                    let _ = std::fs::remove_file(&worktree_file);
                }
            }
        }
        Ok(())
    }

    /// Detect files that have been modified externally since last normalize edit.
    /// Returns list of file paths that differ between actual filesystem and shadow git HEAD.
    fn detect_conflicts(&self, entries: &[HistoryEntry]) -> Vec<String> {
        let mut conflicts = Vec::new();

        for entry in entries {
            for file_path in &entry.files {
                let actual_file = self.root.join(file_path);

                // Get expected content from shadow git HEAD
                let show_output = Command::new("git")
                    .args(["show", &format!("HEAD:{}", file_path)])
                    .current_dir(&self.worktree)
                    .output();

                match show_output {
                    Ok(output) if output.status.success() => {
                        // File exists in shadow - compare with actual
                        if actual_file.exists() {
                            if let Ok(actual_content) = std::fs::read(&actual_file)
                                && actual_content != output.stdout
                            {
                                conflicts.push(file_path.clone());
                            }
                        } else {
                            // File was deleted externally
                            conflicts.push(file_path.clone());
                        }
                    }
                    _ => {
                        // File doesn't exist in shadow but might exist on disk
                        if actual_file.exists() {
                            conflicts.push(file_path.clone());
                        }
                    }
                }
            }
        }

        conflicts
    }

    /// Redo the most recently undone edit.
    /// Only works if the last operation was an undo.
    pub fn redo(&self) -> Result<UndoResult, ShadowError> {
        if !self.exists() {
            return Err(ShadowError::Undo("No shadow history exists".to_string()));
        }

        // Get the most recent entry to check if it's an undo
        let entries = self.history(None, 1);
        let latest = entries
            .first()
            .ok_or_else(|| ShadowError::Undo("No history to redo".to_string()))?;

        if latest.operation != "undo" {
            return Err(ShadowError::Undo(
                "Last operation was not an undo - nothing to redo".to_string(),
            ));
        }

        // Find the commit that was undone (from the undo commit message)
        let log_output = Command::new("git")
            .args(["log", "-1", "--format=%B", &latest.hash])
            .current_dir(&self.worktree)
            .output()
            .map_err(|e| ShadowError::Undo(format!("Failed to get log: {}", e)))?;

        let body = String::from_utf8_lossy(&log_output.stdout);
        let undone_hash = body
            .lines()
            .find_map(|line| line.strip_prefix("Undone-Commit: "))
            .ok_or_else(|| ShadowError::Undo("Cannot find undone commit reference".to_string()))?;

        // Get file list from the undone commit
        let files_output = Command::new("git")
            .args(["show", "--format=", "--name-only", undone_hash])
            .current_dir(&self.worktree)
            .output()
            .map_err(|e| ShadowError::Undo(format!("Failed to get files: {}", e)))?;

        let files: Vec<String> = String::from_utf8_lossy(&files_output.stdout)
            .lines()
            .filter(|l| !l.is_empty())
            .map(String::from)
            .collect();

        // For each file, restore from the undone commit state
        self.restore_files_from_ref(&files, undone_hash)?;

        // Stage and commit the redo
        let add_status = Command::new("git")
            .args(["add", "-A"])
            .current_dir(&self.worktree)
            .status()
            .map_err(|e| ShadowError::Commit(format!("Failed to stage redo: {}", e)))?;
        if !add_status.success() {
            return Err(ShadowError::Commit(
                "git add failed during redo".to_string(),
            ));
        }

        let redo_msg = format!(
            "normalize edit: redo {}\n\nOperation: redo\nTarget: {}\nRedone-Commit: {}\nFiles: {}\nGit-HEAD: {}\n",
            latest.target,
            latest.target,
            undone_hash,
            files.join(", "),
            self.get_real_git_head()
                .unwrap_or_else(|| "none".to_string())
        );

        let commit_status = Command::new("git")
            .args(["commit", "-m", &redo_msg, "--allow-empty"])
            .current_dir(&self.worktree)
            .status()
            .map_err(|e| ShadowError::Commit(format!("Failed to commit redo: {}", e)))?;
        if !commit_status.success() {
            return Err(ShadowError::Commit(
                "git commit failed during redo".to_string(),
            ));
        }

        Ok(UndoResult {
            files: files.iter().map(PathBuf::from).collect(),
            undone_commit: undone_hash.to_string(),
            description: format!("redo: {}", latest.target),
            conflicts: vec![], // Redo doesn't check for conflicts
        })
    }

    /// Jump to a specific commit in shadow history, restoring file state from that point.
    /// Can use full SHA, short SHA, or relative refs like HEAD~2.
    pub fn goto(
        &self,
        ref_str: &str,
        dry_run: bool,
        force: bool,
    ) -> Result<UndoResult, ShadowError> {
        if !self.exists() {
            return Err(ShadowError::Undo("No shadow history exists".to_string()));
        }

        // Resolve the ref to a full commit hash
        let rev_parse = Command::new("git")
            .args(["rev-parse", ref_str])
            .current_dir(&self.worktree)
            .output()
            .map_err(|e| ShadowError::Undo(format!("Failed to resolve ref: {}", e)))?;

        if !rev_parse.status.success() {
            return Err(ShadowError::Undo(format!(
                "Invalid ref '{}': not found in shadow history",
                ref_str
            )));
        }

        let target_hash = String::from_utf8_lossy(&rev_parse.stdout)
            .trim()
            .to_string();

        // Get files changed in the target commit
        let files_output = Command::new("git")
            .args(["show", "--format=", "--name-only", &target_hash])
            .current_dir(&self.worktree)
            .output()
            .map_err(|e| ShadowError::Undo(format!("Failed to get files: {}", e)))?;

        let files: Vec<String> = String::from_utf8_lossy(&files_output.stdout)
            .lines()
            .filter(|l| !l.is_empty())
            .map(String::from)
            .collect();

        // Get the commit message for description
        let log_output = Command::new("git")
            .args(["log", "-1", "--format=%s", &target_hash])
            .current_dir(&self.worktree)
            .output()
            .map_err(|e| ShadowError::Undo(format!("Failed to get log: {}", e)))?;

        let description = String::from_utf8_lossy(&log_output.stdout)
            .trim()
            .to_string();

        if dry_run {
            return Ok(UndoResult {
                files: files.iter().map(PathBuf::from).collect(),
                undone_commit: target_hash,
                description,
                conflicts: vec![],
            });
        }

        // Check for conflicts if not forcing
        if !force {
            // Create a fake HistoryEntry for conflict detection
            let fake_entry = HistoryEntry {
                id: 0,
                hash: target_hash.clone(),
                subject: description.clone(),
                operation: "goto".to_string(),
                target: ref_str.to_string(),
                files: files.clone(),
                message: None,
                workflow: None,
                git_head: String::new(),
                timestamp: String::new(),
            };
            let conflicts = self.detect_conflicts(&[fake_entry]);
            if !conflicts.is_empty() {
                let files_str = conflicts.join(", ");
                return Err(ShadowError::Undo(format!(
                    "Files modified externally: {}. Use --force to override.",
                    files_str
                )));
            }
        }

        // Restore files from target commit state
        for file_path in &files {
            let worktree_file = self.worktree.join(file_path);
            let actual_file = self.root.join(file_path);

            let show_output = Command::new("git")
                .args(["show", &format!("{}:{}", target_hash, file_path)])
                .current_dir(&self.worktree)
                .output();

            match show_output {
                Ok(output) if output.status.success() => {
                    if let Some(parent) = actual_file.parent() {
                        let _ = std::fs::create_dir_all(parent);
                    }
                    std::fs::write(&actual_file, &output.stdout).map_err(|e| {
                        ShadowError::Undo(format!("Failed to write {}: {}", file_path, e))
                    })?;
                    if let Some(parent) = worktree_file.parent() {
                        let _ = std::fs::create_dir_all(parent);
                    }
                    let _ = std::fs::write(&worktree_file, &output.stdout);
                }
                _ => {
                    // File doesn't exist in target commit
                    if actual_file.exists() {
                        std::fs::remove_file(&actual_file).map_err(|e| {
                            ShadowError::Undo(format!("Failed to delete {}: {}", file_path, e))
                        })?;
                    }
                    let _ = std::fs::remove_file(&worktree_file);
                }
            }
        }

        // Stage and commit the goto
        let add_status = Command::new("git")
            .args(["add", "-A"])
            .current_dir(&self.worktree)
            .status()
            .map_err(|e| ShadowError::Commit(format!("Failed to stage goto: {}", e)))?;
        if !add_status.success() {
            return Err(ShadowError::Commit(
                "git add failed during goto".to_string(),
            ));
        }

        let goto_msg = format!(
            "normalize edit: goto {}\n\nOperation: goto\nTarget: {}\nGoto-Commit: {}\nFiles: {}\nGit-HEAD: {}\n",
            ref_str,
            ref_str,
            target_hash,
            files.join(", "),
            self.get_real_git_head()
                .unwrap_or_else(|| "none".to_string())
        );

        let commit_status = Command::new("git")
            .args(["commit", "-m", &goto_msg, "--allow-empty"])
            .current_dir(&self.worktree)
            .status()
            .map_err(|e| ShadowError::Commit(format!("Failed to commit goto: {}", e)))?;
        if !commit_status.success() {
            return Err(ShadowError::Commit(
                "git commit failed during goto".to_string(),
            ));
        }

        Ok(UndoResult {
            files: files.iter().map(PathBuf::from).collect(),
            undone_commit: target_hash,
            description,
            conflicts: vec![],
        })
    }
}

/// Result of an undo operation.
pub struct UndoResult {
    /// Files that were modified by the undo
    pub files: Vec<PathBuf>,
    /// The commit that was undone
    pub undone_commit: String,
    /// Description of what was undone
    pub description: String,
    /// Files that have been modified externally (only populated in dry-run)
    pub conflicts: Vec<String>,
}

/// Shadow git errors.
#[derive(Debug, thiserror::Error)]
pub enum ShadowError {
    #[error("failed to initialize shadow worktree: {0}")]
    Init(String),
    #[error("failed to commit in shadow worktree: {0}")]
    Commit(String),
    #[error("failed to undo shadow operation: {0}")]
    Undo(String),
    #[error("validation failed: {message} (exit code {exit_code})")]
    Validation { message: String, exit_code: i32 },
}

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

    #[test]
    fn test_shadow_new() {
        // normalize-syntax-allow: rust/unwrap-in-impl - test code, panic is appropriate
        let dir = TempDir::new().unwrap();
        let shadow = Shadow::new(dir.path());

        assert!(!shadow.exists());
        assert_eq!(
            shadow.shadow_dir,
            dir.path().join(".normalize").join("shadow")
        );
    }

    #[test]
    fn test_shadow_init() {
        // normalize-syntax-allow: rust/unwrap-in-impl - test code, panic is appropriate
        let dir = TempDir::new().unwrap();
        let shadow = Shadow::new(dir.path());

        // Initialize as if it's the first edit
        // normalize-syntax-allow: rust/unwrap-in-impl - test code, panic is appropriate
        shadow.init().unwrap();

        assert!(shadow.exists());
        assert!(shadow.worktree.exists());
    }

    #[test]
    fn test_shadow_before_after_edit() {
        // normalize-syntax-allow: rust/unwrap-in-impl - test code, panic is appropriate
        let dir = TempDir::new().unwrap();

        // Create a test file
        let test_file = dir.path().join("test.rs");
        // normalize-syntax-allow: rust/unwrap-in-impl - test code, panic is appropriate
        std::fs::write(&test_file, "fn foo() {}").unwrap();

        let shadow = Shadow::new(dir.path());

        // Before edit
        // normalize-syntax-allow: rust/unwrap-in-impl - test code, panic is appropriate
        shadow.before_edit(&[&test_file]).unwrap();

        // Simulate edit
        // normalize-syntax-allow: rust/unwrap-in-impl - test code, panic is appropriate
        std::fs::write(&test_file, "fn bar() {}").unwrap();

        // After edit
        let info = EditInfo {
            operation: "replace".to_string(),
            target: "test.rs/foo".to_string(),
            files: vec![test_file.clone()],
            message: Some("Renamed foo to bar".to_string()),
            workflow: None,
        };
        // normalize-syntax-allow: rust/unwrap-in-impl - test code, panic is appropriate
        shadow.after_edit(&info).unwrap();

        assert_eq!(shadow.edit_count(), 1);
    }
}